跳到主要内容

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

提交记录
修改agent-vm.setup.sh+24 −12看文件
@@ -25,11 +25,13 @@ export DEBIAN_FRONTEND=noninteractive
2525# stdin (dpkg asking about a changed config file, an npm install script)
2626# would swallow the lines after it, which then never run.
2727apt_get() {
28删除: local status before=''
28新增: local status before='' retries=3 timeout=60
2929 if [[ "${CLAUDE_CAGE:-}" == 1 ]]; then
3030 before="$(awk '$1 == "oom_kill" {print $2}' /proc/vmstat)"
31新增: retries=1
32新增: timeout=15
3133 fi
32删除: if sudo env DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=60 -o Acquire::https::Timeout=60 "$@" </dev/null; then
34新增: if sudo env DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries="$retries" -o Acquire::http::Timeout="$timeout" -o Acquire::https::Timeout="$timeout" "$@" </dev/null; then
3335 return 0
3436 else
3537 status=$?
@@ -154,11 +156,12 @@ echo '$nrconf{restart} = '"'"'a'"'"';' | sudo tee /etc/needrestart/conf.d/no-pro
154156echo "Installing base packages..."
155157if [[ "${CLAUDE_CAGE:-}" == 1 ]]; then
156158 # This runs in the guest, through its configured DNS and proxy-only route.
157删除: echo "Checking guest DNS for Debian packages..."
159新增: package_host=$(. /etc/os-release; if [ "$ID" = ubuntu ]; then printf '%s' archive.ubuntu.com; else printf '%s' deb.debian.org; fi)
160新增: echo "Checking guest DNS for system packages..."
158161 if ! timeout 15 getent ahostsv4 mirrors.nju.edu.cn >/dev/null &&
159162 ! timeout 15 getent ahostsv4 mirrors.ustc.edu.cn >/dev/null &&
160删除: ! timeout 15 getent ahostsv4 deb.debian.org >/dev/null; then
161删除: echo 'Guest DNS could not resolve the Debian download sources. Check Cage Network & Proxy / DNS settings, apply and retry.' >&2
163新增: ! timeout 15 getent ahostsv4 "$package_host" >/dev/null; then
164新增: echo 'Guest DNS could not resolve the system download sources. Check Cage Network & Proxy / DNS settings, apply and retry.' >&2
162165 exit 1
163166 fi
164167fi
@@ -259,9 +262,11 @@ if [[ "$INSTALL_DOCKER" == "1" ]]; then
259262 # Install Docker from official repo (includes docker compose)
260263 echo "Installing Docker..."
261264 sudo install -m 0755 -d /etc/apt/keyrings
262删除: install_repository_key https://download.docker.com/linux/debian/gpg /etc/apt/keyrings/docker.asc
265新增: docker_distribution=$(. /etc/os-release && printf '%s' "$ID")
266新增: case "$docker_distribution" in debian|ubuntu) ;; *) echo "Unsupported Docker distribution: $docker_distribution" >&2; exit 1;; esac
267新增: install_repository_key "https://download.docker.com/linux/$docker_distribution/gpg" /etc/apt/keyrings/docker.asc
263268 sudo chmod a+r /etc/apt/keyrings/docker.asc
264删除: echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/debian $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
269新增: echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/$docker_distribution $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
265270 apt_get update
266271 # buildx and pigz are Recommends: `docker build` needs buildx, pigz speeds
267272 # up layer decompression. docker-ce-rootless-extras is left out: the user is
@@ -293,11 +298,17 @@ if [[ "$INSTALL_CHROMIUM" == "1" ]]; then
293298 # xauth: xvfb-run needs it, and it is only a Recommends of xvfb.
294299 # fonts-dejavu-core: with Liberation alone, fontconfig resolves the generic
295300 # sans-serif and serif to Liberation Mono.
296删除: chromium_packages=(chromium fonts-liberation fonts-dejavu-core xvfb xauth)
297删除: if [[ "${CLAUDE_CAGE:-}" == 1 ]]; then
298删除: cage_cache_chromium --no-install-recommends "${chromium_packages[@]}"
301新增: # Disposable browser contexts use the application locale's language defaults.
302新增: # Debian ships the non-English locale resources in this separate package.
303新增: if [[ "${CLAUDE_CAGE:-}" == 1 ]] && cage_is_ubuntu; then
304新增: cage_install_chromium
305新增: else
306新增: chromium_packages=(chromium chromium-l10n fonts-liberation fonts-dejavu-core xvfb xauth)
307新增: if [[ "${CLAUDE_CAGE:-}" == 1 ]]; then
308新增: cage_cache_chromium --no-install-recommends "${chromium_packages[@]}"
309新增: fi
310新增: apt_get install -y --no-install-recommends "${chromium_packages[@]}"
299311 fi
300删除: apt_get install -y --no-install-recommends "${chromium_packages[@]}"
301312 sudo ln -sf /usr/bin/chromium /usr/bin/google-chrome
302313 sudo ln -sf /usr/bin/chromium /usr/bin/google-chrome-stable
303314 sudo mkdir -p /opt/google/chrome
@@ -345,7 +356,8 @@ if [[ "$HAS_CLAUDE" == "1" ]]; then
345356 cat << 'JSON' | sudo tee /etc/claude-code/managed-settings.json > /dev/null
346357{
347358 "permissions": { "defaultMode": "bypassPermissions" },
348删除: "tui": "fullscreen"
359新增: "tui": "fullscreen",
360新增: "channelsEnabled": true
349361}
350362JSON
351363fi
修改cmd/cage-client/main.go+18 −1看文件
@@ -33,6 +33,12 @@ func run(args []string) error {
3333 fmt.Println("Cage remote client " + version.Version + "\nCommands: desktop --json, serve, prepare-update. Workloads run on the selected remote host.")
3434 return nil
3535 }
36新增: if args[0] == "verify-web-assets" {
37新增: if len(args) != 1 {
38新增: return errors.New("verify-web-assets does not accept arguments")
39新增: }
40新增: return workbench.VerifyWebAssets()
41新增: }
3642 config := os.Getenv(cage.ConfigEnv)
3743 if config == "" {
3844 home, err := os.UserHomeDir()
@@ -108,7 +114,12 @@ func run(args []string) error {
108114 return err
109115 }
110116 return printJSON(map[string]string{"status": "ok"}, nil)
111删除: case "upload-files", "browser-file":
117新增: case "share-project":
118新增: if len(args) != 6 || args[1] != "--json" || args[2] != "--connection" || args[3] == "" || (args[4] != "read" && args[4] != "write") {
119新增: return errors.New("share-project --json --connection ID read|write DIRECTORY")
120新增: }
121新增: return printJSON(workbench.ShareNativeCloudProject(config, args[3], args[5], args[4] == "read"))
122新增: case "clipboard-files", "upload-files", "browser-file":
112123 if len(args) < 4 || args[1] != "--json" {
113124 return errors.New("invalid file command")
114125 }
@@ -120,6 +131,12 @@ func run(args []string) error {
120131 connection = args[3]
121132 args = append(append([]string{}, args[:2]...), args[4:]...)
122133 }
134新增: if args[0] == "clipboard-files" {
135新增: if len(args) < 4 {
136新增: return errors.New("clipboard-files --json --connection ID send|receive PATH...")
137新增: }
138新增: return printJSON(workbench.ClipboardFilesForConnection(config, connection, args[2], args[3:]))
139新增: }
123140 if args[0] == "upload-files" {
124141 if len(args) < 5 {
125142 return errors.New("no selected files")
新增cmd/cage-guest-boot/main_windows.go+222 −0看文件
@@ -0,0 +1,222 @@
1新增://go:build windows
2新增:
3新增:// cage-guest-boot runs only as a guest-local Windows service. Winlogon owns
4新增:// authentication and its LSA secret. This service has no credential, network,
5新增:// screen, keyboard or session-control interface.
6新增:package main
7新增:
8新增:import (
9新增: "errors"
10新增: "os"
11新增: "strings"
12新增: "syscall"
13新增: "unsafe"
14新增:
15新增: "github.com/google/uuid"
16新增: "golang.org/x/sys/windows"
17新增: "golang.org/x/sys/windows/registry"
18新增: "golang.org/x/sys/windows/svc"
19新增:)
20新增:
21新增:const winlogon = `SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon`
22新增:const bootBase = `SOFTWARE\Cage\WorkbenchBoot\`
23新增:
24新增:var (
25新增: regCreate = windows.NewLazySystemDLL("advapi32.dll").NewProc("RegCreateKeyExW")
26新增: localGroups = windows.NewLazySystemDLL("netapi32.dll").NewProc("NetUserGetLocalGroups")
27新增: sessionInfo = windows.NewLazySystemDLL("wtsapi32.dll").NewProc("WTSQuerySessionInformationW")
28新增:)
29新增:
30新增:type bootService struct {
31新增: vm uuid.UUID
32新增: user string
33新增:}
34新增:
35新增:func read(key registry.Key, name string) string {
36新增: value, _, _ := key.GetStringValue(name)
37新增: return value
38新增:}
39新增:
40新增:func (b bootService) boundSID() (string, error) {
41新增: vm, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters`, registry.QUERY_VALUE)
42新增: if err != nil {
43新增: return "", err
44新增: }
45新增: defer vm.Close()
46新增: id, err := uuid.Parse(read(vm, "VirtualMachineId"))
47新增: if err != nil || id != b.vm {
48新增: return "", errors.New("wrong guest")
49新增: }
50新增: key, err := registry.OpenKey(registry.LOCAL_MACHINE, bootBase+b.vm.String(), registry.QUERY_VALUE)
51新增: if err != nil {
52新增: return "", err
53新增: }
54新增: defer key.Close()
55新增: sid := read(key, "SID")
56新增: if read(key, "VM") != b.vm.String() || read(key, "User") != b.user || !strings.HasPrefix(sid, "S-1-5-21-") {
57新增: return "", errors.New("unbound guest user")
58新增: }
59新增: return sid, nil
60新增:}
61新增:
62新增:// Require precisely the built-in Users group, including indirect memberships.
63新增:// Never arm an account which was renamed, replaced or made an administrator.
64新增:func (b bootService) standardUser(expected, host string) bool {
65新增: sid, _, kind, err := windows.LookupSID("", host+`\`+b.user)
66新增: if err != nil || kind != windows.SidTypeUser || sid.String() != expected {
67新增: return false
68新增: }
69新增: user, err := windows.UTF16PtrFromString(b.user)
70新增: if err != nil {
71新增: return false
72新增: }
73新增: var buffer *byte
74新增: var entries, total uint32
75新增: status, _, _ := localGroups.Call(0, uintptr(unsafe.Pointer(user)), 0, 1, uintptr(unsafe.Pointer(&buffer)), uintptr(0xffffffff), uintptr(unsafe.Pointer(&entries)), uintptr(unsafe.Pointer(&total)))
76新增: if buffer != nil {
77新增: defer windows.NetApiBufferFree(buffer)
78新增: }
79新增: if status != 0 || entries != 1 || total != 1 || buffer == nil {
80新增: return false
81新增: }
82新增: groupName := windows.UTF16PtrToString(*(**uint16)(unsafe.Pointer(buffer)))
83新增: groupSID, _, _, err := windows.LookupSID("", groupName)
84新增: return err == nil && groupSID.IsWellKnown(windows.WinBuiltinUsersSid)
85新增:}
86新增:
87新增:func (b bootService) configure(enable bool) error {
88新增: expected, err := b.boundSID()
89新增: if err != nil {
90新增: return err
91新增: }
92新增: key, err := registry.OpenKey(registry.LOCAL_MACHINE, winlogon, registry.QUERY_VALUE|registry.SET_VALUE)
93新增: if err != nil {
94新增: return err
95新增: }
96新增: defer key.Close()
97新增: host, err := os.Hostname()
98新增: if err != nil {
99新增: return err
100新增: }
101新增: if read(key, "AutoAdminLogon") == "1" && (!strings.EqualFold(read(key, "DefaultUserName"), b.user) || !strings.EqualFold(read(key, "DefaultDomainName"), host)) {
102新增: return errors.New("another logon policy exists")
103新增: }
104新增: if !enable {
105新增: return key.SetStringValue("AutoAdminLogon", "0")
106新增: }
107新增: if _, _, err := key.GetValue("DefaultPassword", nil); !errors.Is(err, registry.ErrNotExist) {
108新增: return errors.New("existing Winlogon password value")
109新增: }
110新增: if force := read(key, "ForceAutoLogon"); force != "" && force != "0" {
111新增: return errors.New("existing forced logon policy")
112新增: }
113新增: if !b.standardUser(expected, host) {
114新增: if strings.EqualFold(read(key, "DefaultUserName"), b.user) {
115新增: _ = key.SetStringValue("AutoAdminLogon", "0")
116新增: }
117新增: return errors.New("ordinary account required")
118新增: }
119新增: if err = key.SetStringValue("DefaultUserName", b.user); err != nil {
120新增: return err
121新增: }
122新增: if err = key.SetStringValue("DefaultDomainName", host); err != nil {
123新增: return err
124新增: }
125新增: // Arming is the final write; Winlogon reads the protected password itself.
126新增: return key.SetStringValue("AutoAdminLogon", "1")
127新增:}
128新增:
129新增:// The volatile key survives a service restart, but not a new boot. A service
130新增:// restart after a manual lock or logoff must never rearm the current boot.
131新增:func (b bootService) bootMarker() (registry.Key, error) {
132新增: path, _ := windows.UTF16PtrFromString(bootBase + b.vm.String() + `\CurrentBoot`)
133新增: var key windows.Handle
134新增: var disposition uint32
135新增: status, _, _ := regCreate.Call(uintptr(registry.LOCAL_MACHINE), uintptr(unsafe.Pointer(path)), 0, 0, 1, registry.QUERY_VALUE|registry.SET_VALUE, 0, uintptr(unsafe.Pointer(&key)), uintptr(unsafe.Pointer(&disposition)))
136新增: if status != 0 {
137新增: return 0, syscall.Errno(status)
138新增: }
139新增: return registry.Key(key), nil
140新增:}
141新增:
142新增:func signedIn() (bool, error) {
143新增: var sessions *windows.WTS_SESSION_INFO
144新增: var count uint32
145新增: if err := windows.WTSEnumerateSessions(0, 0, 1, &sessions, &count); err != nil {
146新增: return false, err
147新增: }
148新增: defer windows.WTSFreeMemory(uintptr(unsafe.Pointer(sessions)))
149新增: if count > 4096 {
150新增: return false, errors.New("invalid session count")
151新增: }
152新增: for _, s := range unsafe.Slice(sessions, count) {
153新增: if s.SessionID == 0 || s.State == windows.WTSListen || s.State == windows.WTSDown {
154新增: continue
155新增: }
156新增: var user *uint16
157新增: var size uint32
158新增: ok, _, err := sessionInfo.Call(0, uintptr(s.SessionID), 5, uintptr(unsafe.Pointer(&user)), uintptr(unsafe.Pointer(&size)))
159新增: if ok == 0 {
160新增: return false, err
161新增: }
162新增: present := user != nil && size >= 2 && *user != 0
163新增: windows.WTSFreeMemory(uintptr(unsafe.Pointer(user)))
164新增: if present {
165新增: return true, nil
166新增: }
167新增: }
168新增: return false, nil
169新增:}
170新增:
171新增:func (b bootService) Execute(_ []string, requests <-chan svc.ChangeRequest, reports chan<- svc.Status) (bool, uint32) {
172新增: reports <- svc.Status{State: svc.StartPending}
173新增: marker, err := b.bootMarker()
174新增: if err != nil {
175新增: return false, 1
176新增: }
177新增: defer marker.Close()
178新增: status := svc.Status{State: svc.Running, Accepts: svc.AcceptStop | svc.AcceptSessionChange | svc.AcceptPreShutdown}
179新增: reports <- status
180新增: used, _, markerErr := marker.GetIntegerValue("Consumed")
181新增: hasUser, probeError := signedIn()
182新增: if hasUser {
183新增: _ = marker.SetDWordValue("Consumed", 1)
184新增: }
185新增: _ = b.configure(used == 0 && (markerErr == nil || errors.Is(markerErr, registry.ErrNotExist)) && !hasUser && probeError == nil)
186新增: for request := range requests {
187新增: switch request.Cmd {
188新增: case svc.Interrogate:
189新增: reports <- status
190新增: case svc.SessionChange:
191新增: switch request.EventType {
192新增: case windows.WTS_SESSION_LOGON, windows.WTS_SESSION_LOGOFF, windows.WTS_SESSION_LOCK, windows.WTS_SESSION_UNLOCK:
193新增: _ = marker.SetDWordValue("Consumed", 1)
194新增: _ = b.configure(false)
195新增: }
196新增: case svc.PreShutdown:
197新增: // The SCM has committed to a real OS shutdown. Prepare the next
198新增: // boot before the registry hive is unloaded.
199新增: _ = b.configure(true)
200新增: reports <- svc.Status{State: svc.StopPending}
201新增: return false, 0
202新增: case svc.Stop:
203新增: _ = b.configure(false)
204新增: reports <- svc.Status{State: svc.StopPending}
205新增: return false, 0
206新增: }
207新增: }
208新增: return false, 0
209新增:}
210新增:func main() {
211新增: if len(os.Args) != 2 {
212新增: os.Exit(2)
213新增: }
214新增: id, err := uuid.Parse(os.Args[1])
215新增: if err != nil || id == uuid.Nil {
216新增: os.Exit(2)
217新增: }
218新增: b := bootService{vm: id, user: "Cage-" + strings.ReplaceAll(id.String(), "-", "")[:10]}
219新增: if err := svc.Run("Cage-Workbench-Boot-"+id.String(), b); err != nil {
220新增: os.Exit(1)
221新增: }
222新增:}
新增cmd/cage-guest-files/main.go+145 −0看文件
@@ -0,0 +1,145 @@
1新增:// cage-guest-files runs as the guest GUI agent's own user. File selections are
2新增:// transient stdin data, never host paths or commands selected by a web page.
3新增:package main
4新增:
5新增:import (
6新增: "encoding/binary"
7新增: "encoding/json"
8新增: "errors"
9新增: "fmt"
10新增: "io"
11新增: "os"
12新增: "path/filepath"
13新增:
14新增: "github.com/sylvinus/agent-vm/internal/clipboardfiles"
15新增:)
16新增:
17新增:func run(args []string, input io.Reader, output io.Writer) error {
18新增: if len(args) < 1 || len(args) > 2 {
19新增: return errors.New("guest file operation invalid")
20新增: }
21新增: if args[0] == "cache" && len(args) == 2 {
22新增: var request clipboardfiles.CacheRequest
23新增: if json.Unmarshal([]byte(args[1]), &request) != nil {
24新增: return errors.New("invalid clipboard cache request")
25新增: }
26新增: store, err := clipboardfiles.UserCacheStore()
27新增: if err != nil {
28新增: return err
29新增: }
30新增: result, err := store.Control(request)
31新增: if err != nil {
32新增: return err
33新增: }
34新增: return json.NewEncoder(output).Encode(result)
35新增: }
36新增: if args[0] == "save" {
37新增: if len(args) != 2 {
38新增: return errors.New("file name required")
39新增: }
40新增: path, err := clipboardfiles.Save(&framedInput{reader: input}, args[1])
41新增: if err != nil {
42新增: return err
43新增: }
44新增: return returnCachedPaths(output, []string{path})
45新增: }
46新增: if args[0] == "import" {
47新增: paths, err := clipboardfiles.Read(input)
48新增: if err != nil {
49新增: return err
50新增: }
51新增: return returnCachedPaths(output, paths)
52新增: }
53新增: var paths []string
54新增: if len(args) == 2 && args[1] != "--paths-stdin" {
55新增: if len(args[1]) > 1<<20 || json.Unmarshal([]byte(args[1]), &paths) != nil {
56新增: return errors.New("file selection invalid")
57新增: }
58新增: } else {
59新增: data, err := io.ReadAll(io.LimitReader(input, (1<<20)+1))
60新增: if err != nil || len(data) > 1<<20 || json.Unmarshal(data, &paths) != nil {
61新增: return errors.New("file selection invalid")
62新增: }
63新增: }
64新增: switch args[0] {
65新增: case "link-cached":
66新增: linked, err := clipboardfiles.LinkCachedFiles(paths)
67新增: if err != nil {
68新增: return err
69新增: }
70新增: return returnCachedPaths(output, linked)
71新增: case "export":
72新增: return clipboardfiles.Write(output, paths)
73新增: case "copy":
74新增: copied, err := clipboardfiles.Copy(paths)
75新增: if err != nil {
76新增: return err
77新增: }
78新增: return returnCachedPaths(output, copied)
79新增: default:
80新增: return errors.New("guest file operation invalid")
81新增: }
82新增:}
83新增:
84新增:func returnCachedPaths(output io.Writer, paths []string) error {
85新增: store, err := clipboardfiles.UserCacheStore()
86新增: if err != nil {
87新增: _ = os.RemoveAll(filepath.Dir(paths[0]))
88新增: return err
89新增: }
90新增: selection, err := store.Register(paths)
91新增: if err != nil {
92新增: _ = os.RemoveAll(filepath.Dir(paths[0]))
93新增: return err
94新增: }
95新增: if err := json.NewEncoder(output).Encode(selection); err != nil {
96新增: _ = store.Release(selection.ID)
97新增: return err
98新增: }
99新增: return nil
100新增:}
101新增:
102新增:// The zero-length frame confirms that the sender finished the file. A closed
103新增:// connection before that marker must not publish a truncated attachment.
104新增:type framedInput struct {
105新增: reader io.Reader
106新增: remaining uint32
107新增: ended bool
108新增:}
109新增:
110新增:func (f *framedInput) Read(buffer []byte) (int, error) {
111新增: if len(buffer) == 0 {
112新增: return 0, nil
113新增: }
114新增: if f.ended {
115新增: return 0, io.EOF
116新增: }
117新增: if f.remaining == 0 {
118新增: var header [4]byte
119新增: if _, err := io.ReadFull(f.reader, header[:]); err != nil {
120新增: return 0, io.ErrUnexpectedEOF
121新增: }
122新增: f.remaining = binary.LittleEndian.Uint32(header[:])
123新增: if f.remaining > 64<<10 {
124新增: return 0, errors.New("file frame exceeds limit")
125新增: }
126新增: if f.remaining == 0 {
127新增: f.ended = true
128新增: return 0, io.EOF
129新增: }
130新增: }
131新增: n, err := f.reader.Read(buffer[:min(len(buffer), int(f.remaining))])
132新增: f.remaining -= uint32(n)
133新增: if err == io.EOF {
134新增: err = io.ErrUnexpectedEOF
135新增: }
136新增: return n, err
137新增:}
138新增:
139新增:func main() {
140新增: if err := run(os.Args[1:], os.Stdin, os.Stdout); err != nil {
141新增: // Do not expose selected file names or OS error strings in agent logs.
142新增: fmt.Fprintln(os.Stderr, "Clipboard file transfer failed; check the selection, permissions and limits.")
143新增: os.Exit(1)
144新增: }
145新增:}
新增cmd/cage-guest-files/main_test.go+154 −0看文件
@@ -0,0 +1,154 @@
1新增:package main
2新增:
3新增:import (
4新增: "bytes"
5新增: "encoding/binary"
6新增: "encoding/json"
7新增: "io"
8新增: "os"
9新增: "path/filepath"
10新增: "strings"
11新增: "testing"
12新增:
13新增: "github.com/sylvinus/agent-vm/internal/clipboardfiles"
14新增:)
15新增:
16新增:type closedOutput struct{}
17新增:
18新增:func (closedOutput) Write([]byte) (int, error) { return 0, io.ErrClosedPipe }
19新增:
20新增:func TestGuestFileFailedReplyReleasesUnpublishedCopy(t *testing.T) {
21新增: isolateClipboardCache(t)
22新增: source := filepath.Join(t.TempDir(), "source.txt")
23新增: if err := os.WriteFile(source, []byte("retained source"), 0600); err != nil {
24新增: t.Fatal(err)
25新增: }
26新增: selection, _ := json.Marshal([]string{source})
27新增: if err := run([]string{"copy", "--paths-stdin"}, bytes.NewReader(selection), closedOutput{}); err == nil {
28新增: t.Fatal("closed output accepted a selection")
29新增: }
30新增: store, err := clipboardfiles.UserCacheStore()
31新增: if err != nil {
32新增: t.Fatal(err)
33新增: }
34新增: entries, err := os.ReadDir(store.Directory)
35新增: if err != nil || len(entries) != 1 || entries[0].Name() != ".lock" {
36新增: t.Fatal("an unpublished result retained its ownership receipt", err)
37新增: }
38新增: if data, err := os.ReadFile(source); err != nil || string(data) != "retained source" {
39新增: t.Fatal("source changed", err)
40新增: }
41新增:}
42新增:
43新增:func TestGuestFileSaveRequiresCompleteFrames(t *testing.T) {
44新增: isolateClipboardCache(t)
45新增: cache := t.TempDir()
46新增: t.Setenv("TMPDIR", cache)
47新增: t.Setenv("TEMP", cache)
48新增: t.Setenv("TMP", cache)
49新增: content := []byte{0, 255, 128, '\n'}
50新增: var wire bytes.Buffer
51新增: binary.Write(&wire, binary.LittleEndian, uint32(len(content)))
52新增: wire.Write(content)
53新增: truncated := append([]byte(nil), wire.Bytes()...)
54新增: binary.Write(&wire, binary.LittleEndian, uint32(0))
55新增: var output bytes.Buffer
56新增: if err := run([]string{"save", "图片 ' .bin"}, &wire, &output); err != nil {
57新增: t.Fatal(err)
58新增: }
59新增: var result struct {
60新增: Paths []string `json:"paths"`
61新增: }
62新增: if json.Unmarshal(output.Bytes(), &result) != nil || len(result.Paths) != 1 {
63新增: t.Fatal("saved file did not return its private path")
64新增: }
65新增: data, err := os.ReadFile(result.Paths[0])
66新增: if err != nil || !bytes.Equal(data, content) {
67新增: t.Fatal("saved bytes changed")
68新增: }
69新增: selection, _ := json.Marshal(result.Paths)
70新增: output.Reset()
71新增: if err := run([]string{"link-cached", "--paths-stdin"}, bytes.NewReader(selection), &output); err != nil {
72新增: t.Fatal(err)
73新增: }
74新增: var linked struct {
75新增: Paths []string `json:"paths"`
76新增: }
77新增: if json.Unmarshal(output.Bytes(), &linked) != nil || len(linked.Paths) != 1 {
78新增: t.Fatal("cache grouping did not return its private path")
79新增: }
80新增: sourceInfo, _ := os.Lstat(result.Paths[0])
81新增: linkedInfo, err := os.Lstat(linked.Paths[0])
82新增: if err != nil || !os.SameFile(sourceInfo, linkedInfo) {
83新增: t.Fatal("cache grouping copied or replaced file data")
84新增: }
85新增: if err := os.Remove(result.Paths[0]); err != nil {
86新增: t.Fatal(err)
87新增: }
88新增: data, err = os.ReadFile(linked.Paths[0])
89新增: if err != nil || !bytes.Equal(data, content) {
90新增: t.Fatal("removing the original upload lost the grouped attachment")
91新增: }
92新增: before, _ := os.ReadDir(cache)
93新增: if err := run([]string{"save", "partial.bin"}, bytes.NewReader(truncated), io.Discard); err == nil {
94新增: t.Fatal("missing completion frame was accepted")
95新增: }
96新增: after, _ := os.ReadDir(cache)
97新增: if len(after) != len(before) {
98新增: t.Fatal("failed save left a partial attachment")
99新增: }
100新增: for _, name := range []string{"../escape", "/absolute", "file:stream", ""} {
101新增: if err := run([]string{"save", name}, bytes.NewReader([]byte{0, 0, 0, 0}), io.Discard); err == nil {
102新增: t.Fatal("invalid filename accepted")
103新增: }
104新增: }
105新增:}
106新增:
107新增:func TestGuestFileOperationsUseStdinAndPreserveContent(t *testing.T) {
108新增: isolateClipboardCache(t)
109新增: root := t.TempDir()
110新增: path := filepath.Join(root, "资料.bin")
111新增: content := []byte{0, 255, 128, '\n'}
112新增: if err := os.WriteFile(path, content, 0600); err != nil {
113新增: t.Fatal(err)
114新增: }
115新增: selection, _ := json.Marshal([]string{path})
116新增: var wire bytes.Buffer
117新增: if err := run([]string{"export", "--paths-stdin"}, bytes.NewReader(selection), &wire); err != nil {
118新增: t.Fatal(err)
119新增: }
120新增: var output bytes.Buffer
121新增: if err := run([]string{"import"}, &wire, &output); err != nil {
122新增: t.Fatal(err)
123新增: }
124新增: var result struct {
125新增: Paths []string `json:"paths"`
126新增: }
127新增: if err := json.Unmarshal(output.Bytes(), &result); err != nil || len(result.Paths) != 1 {
128新增: t.Fatalf("import: %v", err)
129新增: }
130新增: defer os.RemoveAll(filepath.Dir(result.Paths[0]))
131新增: got, err := os.ReadFile(result.Paths[0])
132新增: if err != nil || !bytes.Equal(got, content) {
133新增: t.Fatalf("content changed: %v", err)
134新增: }
135新增: if result.Paths[0] == path {
136新增: t.Fatal("import reused source path")
137新增: }
138新增:}
139新增:
140新增:func isolateClipboardCache(t *testing.T) {
141新增: t.Helper()
142新增: directory := t.TempDir()
143新增: for _, name := range []string{"HOME", "USERPROFILE", "LOCALAPPDATA", "XDG_CACHE_HOME"} {
144新增: t.Setenv(name, directory)
145新增: }
146新增:}
147新增:
148新增:func TestGuestFileSelectionBoundsAndMissingSourceFail(t *testing.T) {
149新增: for _, input := range []string{`["/does/not/exist"]`, `[]`, `{}`, `[] {}`, strings.Repeat(" ", (1<<20)+1)} {
150新增: if err := run([]string{"copy", "--paths-stdin"}, strings.NewReader(input), io.Discard); err == nil {
151新增: t.Fatal("invalid selection succeeded")
152新增: }
153新增: }
154新增:}
新增cmd/cage-hyperv-manager/main_other.go+10 −0看文件
@@ -0,0 +1,10 @@
1新增://go:build !windows
2新增:
3新增:package main
4新增:
5新增:import (
6新增: "fmt"
7新增: "os"
8新增:)
9新增:
10新增:func main() { fmt.Fprintln(os.Stderr, "Windows host manager requires Windows."); os.Exit(1) }
新增cmd/cage-hyperv-manager/main_windows.go+69 −0看文件
@@ -0,0 +1,69 @@
1新增://go:build windows
2新增:
3新增:package main
4新增:
5新增:import (
6新增: "context"
7新增: "encoding/json"
8新增: "flag"
9新增: "fmt"
10新增: "github.com/google/uuid"
11新增: "github.com/sylvinus/agent-vm/internal/guestos"
12新增: "os"
13新增: "time"
14新增:)
15新增:
16新增:func main() {
17新增: if len(os.Args) < 2 {
18新增: os.Exit(2)
19新增: }
20新增: flags := flag.NewFlagSet("Cage.HyperVManager", flag.ContinueOnError)
21新增: flags.SetOutput(os.Stderr)
22新增: binding := flags.String("binding", "", "")
23新增: vm := flags.String("vm-id", "", "")
24新增: hostSID := flags.String("host-sid", "", "")
25新增: profile := flags.String("profile", "", "")
26新增: state := flags.String("state", "", "")
27新增: installation := flags.String("installation-id", "", "")
28新增: pipe := flags.String("pipe", "", "")
29新增: parentPID := flags.Uint("parent-pid", 0, "")
30新增: if flags.Parse(os.Args[2:]) != nil || flags.NArg() != 0 {
31新增: os.Exit(2)
32新增: }
33新增: var err error
34新增: enrollmentFlags := *profile != "" || *state != "" || *installation != "" || *pipe != "" || *parentPID != 0
35新增: switch os.Args[1] {
36新增: case "service":
37新增: if *binding == "" || *vm != "" || *hostSID != "" || enrollmentFlags {
38新增: os.Exit(2)
39新增: }
40新增: err = guestos.RunWindowsHostManagerService(*binding)
41新增: case "prepare":
42新增: id, parseErr := uuid.Parse(*vm)
43新增: if parseErr != nil || id == uuid.Nil || *hostSID == "" || *binding != "" || enrollmentFlags {
44新增: os.Exit(2)
45新增: }
46新增: ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
47新增: defer cancel()
48新增: var record guestos.WindowsHostManagerBinding
49新增: record, err = guestos.PrepareWindowsHostManagerBinding(ctx, id, *hostSID)
50新增: if err == nil {
51新增: err = json.NewEncoder(os.Stdout).Encode(record)
52新增: }
53新增: case "user-enrollment":
54新增: id, idErr := uuid.Parse(*vm)
55新增: install, installErr := uuid.Parse(*installation)
56新增: if idErr != nil || installErr != nil || id == uuid.Nil || install == uuid.Nil || *hostSID == "" || *profile == "" || *state == "" || *pipe == "" || *parentPID == 0 || *parentPID > 0xffffffff || *binding != "" {
57新增: os.Exit(2)
58新增: }
59新增: ctx, cancel := context.WithTimeout(context.Background(), 2*time.Hour)
60新增: defer cancel()
61新增: err = guestos.RunWindowsHostEnrollment(ctx, guestos.WindowsHostEnrollmentOptions{VMID: id, InstallationID: install, HostSID: *hostSID, Profile: *profile, State: *state, Pipe: *pipe, ParentPID: uint32(*parentPID)})
62新增: default:
63新增: os.Exit(2)
64新增: }
65新增: if err != nil {
66新增: fmt.Fprintln(os.Stderr, "Windows host manager action did not complete.")
67新增: os.Exit(1)
68新增: }
69新增:}
修改cmd/cage/container.go+1 −1看文件
@@ -119,7 +119,7 @@ func containerOperation(configPath string, args []string, cfg cage.Config) (bool
119119 return true, err
120120 }
121121 if needsServices {
122删除: if err := workbench.RunMaintenanceScript(ctx, configPath, cfg.StartScript(), os.Stdout, os.Stderr); err != nil {
122新增: if err := workbench.StartGuestServices(ctx, configPath, cfg, os.Stdout, os.Stderr); err != nil {
123123 return true, err
124124 }
125125 }
新增cmd/cage/guest_os.go+42 −0看文件
@@ -0,0 +1,42 @@
1新增:package main
2新增:
3新增:import (
4新增: "context"
5新增: "encoding/json"
6新增: "errors"
7新增: "flag"
8新增: "io"
9新增:
10新增: "github.com/google/uuid"
11新增:
12新增: "github.com/sylvinus/agent-vm/internal/guestos"
13新增:)
14新增:
15新增:func writeGuestOSInspection(ctx context.Context, args []string, w io.Writer) error {
16新增: flags := flag.NewFlagSet("guest-os", flag.ContinueOnError)
17新增: flags.SetOutput(io.Discard)
18新增: jsonOutput := flags.Bool("json", false, "")
19新增: var target uuid.UUID
20新增: flags.Func("vm-id", "", func(value string) error {
21新增: id, err := uuid.Parse(value)
22新增: if err != nil || id == uuid.Nil || target != uuid.Nil {
23新增: return errors.New("expected one non-empty Hyper-V VM GUID")
24新增: }
25新增: target = id
26新增: return nil
27新增: })
28新增: if err := flags.Parse(args); err != nil {
29新增: return err
30新增: }
31新增: if !*jsonOutput || flags.NArg() != 0 {
32新增: return errors.New("usage: cage guest-os --json [--vm-id GUID]")
33新增: }
34新增: if target == uuid.Nil {
35新增: return json.NewEncoder(w).Encode(guestos.Inspect(ctx))
36新增: }
37新增: result, err := guestos.InspectHyperV(ctx, target)
38新增: if err != nil {
39新增: return err
40新增: }
41新增: return json.NewEncoder(w).Encode(result)
42新增:}
新增cmd/cage/guest_os_test.go+30 −0看文件
@@ -0,0 +1,30 @@
1新增:package main
2新增:
3新增:import (
4新增: "bytes"
5新增: "runtime"
6新增: "strings"
7新增: "testing"
8新增:)
9新增:
10新增:func TestGuestOSVMIDRequiresExplicitValidTarget(t *testing.T) {
11新增: const valid = "ad2d0746-c50c-4dbd-a5f3-495ccfa4cbc2"
12新增: for _, args := range [][]string{
13新增: {"--json", "--vm-id", "this is not a GUID"},
14新增: {"--json", "--vm-id", "00000000-0000-0000-0000-000000000000"},
15新增: {"--vm-id", valid},
16新增: {"--json", "--vm-id", valid, "--vm-id", valid},
17新增: } {
18新增: var out bytes.Buffer
19新增: if err := writeGuestOSInspection(t.Context(), args, &out); err == nil || out.Len() != 0 {
20新增: t.Fatalf("unexpected guest inspection for %v: %v, %q", args, err, out.String())
21新增: }
22新增: }
23新增: if runtime.GOOS != "windows" {
24新增: var out bytes.Buffer
25新增: err := writeGuestOSInspection(t.Context(), []string{"--json", "--vm-id", valid}, &out)
26新增: if err == nil || !strings.Contains(err.Error(), "Windows") || out.Len() != 0 {
27新增: t.Fatalf("unexpected non-Windows lookup: %v, %q", err, out.String())
28新增: }
29新增: }
30新增:}
新增cmd/cage/mac_guest_darwin_arm64.go+105 −0看文件
@@ -0,0 +1,105 @@
1新增://go:build darwin && arm64 && cgo && !no_vz
2新增:
3新增:package main
4新增:
5新增:import (
6新增: "context"
7新增: "errors"
8新增: "flag"
9新增: "fmt"
10新增: "io"
11新增: "os"
12新增: "path/filepath"
13新增:
14新增: vzdriver "github.com/lima-vm/lima/v2/pkg/driver/vz"
15新增: "github.com/sylvinus/agent-vm/internal/guestos"
16新增: "github.com/sylvinus/agent-vm/internal/vm"
17新增:)
18新增:
19新增:func macGuestLoginAvailable() bool { return vzdriver.OffscreenView != nil }
20新增:
21新增:func runMacGuest(ctx context.Context, profile, state string, args []string) error {
22新增: if len(args) == 0 {
23新增: return errors.New("usage: cage guest-os macos create <absolute.ipsw> | bind <user> | start | stop")
24新增: }
25新增: lima, err := vm.NewLima(filepath.Join(state, "lima"), state)
26新增: if err != nil {
27新增: return err
28新增: }
29新增: const name = "mac"
30新增: switch args[0] {
31新增: case "update-components":
32新增: flags := flag.NewFlagSet("update-components", flag.ContinueOnError)
33新增: flags.SetOutput(io.Discard)
34新增: manifest := flags.String("manifest", "", "")
35新增: updateTools := flags.Bool("tools", false, "")
36新增: if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 || !filepath.IsAbs(*manifest) {
37新增: return errors.New("需要本次原生组件更新清单")
38新增: }
39新增: exe, err := os.Executable()
40新增: if err != nil {
41新增: return err
42新增: }
43新增: return guestos.MaintainMacOSComponents(ctx, profile, filepath.Join(filepath.Dir(exe), "guest-os"), *manifest, *updateTools, os.Stdout, os.Stderr)
44新增: case "install":
45新增: if len(args) != 1 {
46新增: return errors.New("unexpected install argument")
47新增: }
48新增: return installMacWorkbench(ctx, profile, state, lima)
49新增: case "create":
50新增: if len(args) != 2 {
51新增: return errors.New("supply the absolute path to an official macOS IPSW")
52新增: }
53新增: instances, err := lima.List(ctx)
54新增: if err != nil {
55新增: return err
56新增: }
57新增: switch {
58新增: case len(instances) == 0:
59新增: err = lima.CreateMacOSFromIPSW(ctx, name, args[1], vm.Settings{DiskGiB: 64}, os.Stderr)
60新增: case len(instances) == 1 && instances[0].Name == name:
61新增: if bound, loadErr := guestos.LoadMacOSProfile(profile); loadErr != nil || bound != nil {
62新增: return errors.New("this macOS guest already has a binding; use start")
63新增: }
64新增: err = lima.MatchMacOSInstallSource(ctx, name, args[1])
65新增: default:
66新增: return errors.New("create requires a dedicated macOS guest profile")
67新增: }
68新增: if err != nil {
69新增: return err
70新增: }
71新增: return lima.Start(ctx, name, os.Stderr)
72新增: case "bind":
73新增: if len(args) != 2 {
74新增: return errors.New("supply the ordinary guest account and its independently verified guest SSH host public key on stdin")
75新增: }
76新增: if err := lima.CheckMacOSGuest(ctx, name); err != nil {
77新增: return err
78新增: }
79新增: key, err := io.ReadAll(io.LimitReader(os.Stdin, 4097))
80新增: if err != nil || len(key) > 4096 {
81新增: return errors.New("could not read the guest host public key")
82新增: }
83新增: return guestos.BindMacOSProfile(profile, args[1], key)
84新增: case "start", "stop":
85新增: if len(args) != 1 {
86新增: return errors.New("unexpected macOS guest lifecycle argument")
87新增: }
88新增: m, err := guestos.LoadMacOSProfile(profile)
89新增: if err != nil {
90新增: return err
91新增: }
92新增: if m == nil {
93新增: return errors.New("this profile is not bound to a prepared macOS guest")
94新增: }
95新增: if args[0] == "stop" {
96新增: return lima.Stop(ctx, m.Instance)
97新增: }
98新增: if err := lima.CheckMacOSGuest(ctx, m.Instance); err != nil {
99新增: return err
100新增: }
101新增: return lima.Start(ctx, m.Instance, os.Stderr)
102新增: default:
103新增: return fmt.Errorf("unknown macOS guest command %q", args[0])
104新增: }
105新增:}
新增cmd/cage/mac_guest_download_darwin_arm64.go+105 −0看文件
@@ -0,0 +1,105 @@
1新增://go:build darwin && arm64 && cgo && !no_vz
2新增:
3新增:package main
4新增:
5新增:import (
6新增: "context"
7新增: "crypto/sha256"
8新增: "encoding/hex"
9新增: "errors"
10新增: "fmt"
11新增: "io"
12新增: "os"
13新增: "os/exec"
14新增: "time"
15新增:)
16新增:
17新增:// Keep the existing curl resume/retry behavior. Sampling the partial file also
18新增:// reports progress when curl's output is connected to the workbench log pipe.
19新增:func prepareMacRestoreMedia(ctx context.Context, media, url, digest string, total int64, out io.Writer) error {
20新增: if _, err := os.Stat(media); err == nil {
21新增: return verifyMacRestoreMedia(ctx, media, digest, out)
22新增: } else if !errors.Is(err, os.ErrNotExist) {
23新增: return err
24新增: }
25新增: partial := media + ".partial"
26新增: cmd := exec.CommandContext(ctx, "/usr/bin/curl", "--disable", "-fsSL", "--proto", "=https", "--proto-redir", "=https", "--retry", "2", "--connect-timeout", "15", "--speed-time", "90", "--speed-limit", "1024", "--continue-at", "-", url, "-o", partial)
27新增: cmd.Stderr = os.Stderr
28新增: report := func() {
29新增: var received int64
30新增: if info, err := os.Stat(partial); err == nil {
31新增: received = info.Size()
32新增: }
33新增: fmt.Fprintf(out, "CAGE_GUEST_BYTES macos download %d %d\n", received, total)
34新增: }
35新增: report()
36新增: if err := cmd.Start(); err != nil {
37新增: return err
38新增: }
39新增: done := make(chan error, 1)
40新增: go func() { done <- cmd.Wait() }()
41新增: ticker := time.NewTicker(time.Second)
42新增: defer ticker.Stop()
43新增: for {
44新增: select {
45新增: case <-ticker.C:
46新增: report()
47新增: case err := <-done:
48新增: report()
49新增: if ctx.Err() != nil {
50新增: return ctx.Err()
51新增: }
52新增: if err != nil {
53新增: return err
54新增: }
55新增: if err = verifyMacRestoreMedia(ctx, partial, digest, out); err != nil {
56新增: // Cancellation retains a complete archive for the next attempt.
57新增: if ctx.Err() == nil {
58新增: _ = os.Remove(partial)
59新增: }
60新增: return err
61新增: }
62新增: return os.Rename(partial, media)
63新增: }
64新增: }
65新增:}
66新增:
67新增:func verifyMacRestoreMedia(ctx context.Context, media, digest string, out io.Writer) error {
68新增: file, err := os.Open(media)
69新增: if err != nil {
70新增: return err
71新增: }
72新增: defer file.Close()
73新增: info, err := file.Stat()
74新增: if err != nil {
75新增: return err
76新增: }
77新增: var received int64
78新增: report := func() { fmt.Fprintf(out, "CAGE_GUEST_BYTES macos verify %d %d\n", received, info.Size()) }
79新增: report()
80新增: hash := sha256.New()
81新增: buffer := make([]byte, 4<<20)
82新增: last := time.Now()
83新增: for {
84新增: if err := ctx.Err(); err != nil {
85新增: return err
86新增: }
87新增: n, readErr := file.Read(buffer)
88新增: _, _ = hash.Write(buffer[:n])
89新增: received += int64(n)
90新增: if time.Since(last) >= time.Second || readErr == io.EOF {
91新增: report()
92新增: last = time.Now()
93新增: }
94新增: if readErr == io.EOF {
95新增: break
96新增: }
97新增: if readErr != nil {
98新增: return readErr
99新增: }
100新增: }
101新增: if hex.EncodeToString(hash.Sum(nil)) != digest {
102新增: return errors.New("Apple 下载校验失败,请重试。")
103新增: }
104新增: return nil
105新增:}
新增cmd/cage/mac_guest_download_darwin_arm64_test.go+132 −0看文件
@@ -0,0 +1,132 @@
1新增://go:build darwin && arm64 && cgo && !no_vz
2新增:
3新增:package main
4新增:
5新增:import (
6新增: "bytes"
7新增: "context"
8新增: "crypto/sha256"
9新增: "encoding/hex"
10新增: "encoding/pem"
11新增: "errors"
12新增: "fmt"
13新增: "net/http"
14新增: "net/http/httptest"
15新增: "os"
16新增: "path/filepath"
17新增: "strings"
18新增: "testing"
19新增: "time"
20新增:)
21新增:
22新增:func trustRestoreServer(t *testing.T, server *httptest.Server) {
23新增: t.Helper()
24新增: cert := filepath.Join(t.TempDir(), "ca.pem")
25新增: if err := os.WriteFile(cert, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: server.Certificate().Raw}), 0600); err != nil {
26新增: t.Fatal(err)
27新增: }
28新增: t.Setenv("CURL_CA_BUNDLE", cert)
29新增:}
30新增:
31新增:func TestMacRestoreDownloadResumesAndReportsVerification(t *testing.T) {
32新增: body := bytes.Repeat([]byte("restore-image"), 10000)
33新增: offset := len(body) / 3
34新增: server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
35新增: if r.Header.Get("Range") != fmt.Sprintf("bytes=%d-", offset) {
36新增: t.Errorf("missing resume offset: %s", r.Header.Get("Range"))
37新增: w.WriteHeader(400)
38新增: return
39新增: }
40新增: w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", offset, len(body)-1, len(body)))
41新增: w.WriteHeader(http.StatusPartialContent)
42新增: _, _ = w.Write(body[offset:])
43新增: }))
44新增: defer server.Close()
45新增: trustRestoreServer(t, server)
46新增: media := filepath.Join(t.TempDir(), "MacOS.ipsw")
47新增: if err := os.WriteFile(media+".partial", body[:offset], 0600); err != nil {
48新增: t.Fatal(err)
49新增: }
50新增: hash := sha256.Sum256(body)
51新增: var log bytes.Buffer
52新增: if err := prepareMacRestoreMedia(t.Context(), media, server.URL, hex.EncodeToString(hash[:]), int64(len(body)), &log); err != nil {
53新增: t.Fatal(err)
54新增: }
55新增: actual, err := os.ReadFile(media)
56新增: if err != nil || !bytes.Equal(actual, body) {
57新增: t.Fatalf("published media differs: %v", err)
58新增: }
59新增: if _, err := os.Stat(media + ".partial"); !errors.Is(err, os.ErrNotExist) {
60新增: t.Fatalf("partial file was not promoted: %v", err)
61新增: }
62新增: for _, event := range []string{fmt.Sprintf("CAGE_GUEST_BYTES macos download %d %d", offset, len(body)), fmt.Sprintf("CAGE_GUEST_BYTES macos verify 0 %d", len(body)), fmt.Sprintf("CAGE_GUEST_BYTES macos verify %d %d", len(body), len(body))} {
63新增: if !strings.Contains(log.String(), event) {
64新增: t.Fatalf("missing %q in %s", event, log.String())
65新增: }
66新增: }
67新增: log.Reset()
68新增: // A verified cached archive must not make another request to the server.
69新增: if err := prepareMacRestoreMedia(t.Context(), media, "https://invalid.invalid", hex.EncodeToString(hash[:]), int64(len(body)), &log); err != nil {
70新增: t.Fatal(err)
71新增: }
72新增: if strings.Contains(log.String(), "macos download") {
73新增: t.Fatal("cached archive was downloaded again")
74新增: }
75新增:}
76新增:
77新增:func TestMacRestoreCancelledDownloadKeepsPartial(t *testing.T) {
78新增: server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
79新增: _, _ = w.Write(bytes.Repeat([]byte("x"), 128<<10))
80新增: w.(http.Flusher).Flush()
81新增: <-r.Context().Done()
82新增: }))
83新增: defer server.Close()
84新增: trustRestoreServer(t, server)
85新增: media := filepath.Join(t.TempDir(), "MacOS.ipsw")
86新增: ctx, cancel := context.WithCancel(t.Context())
87新增: defer cancel()
88新增: done := make(chan error, 1)
89新增: go func() {
90新增: done <- prepareMacRestoreMedia(ctx, media, server.URL, strings.Repeat("0", 64), 1<<20, &bytes.Buffer{})
91新增: }()
92新增: deadline := time.After(5 * time.Second)
93新增: ticker := time.NewTicker(10 * time.Millisecond)
94新增: defer ticker.Stop()
95新增: for {
96新增: select {
97新增: case err := <-done:
98新增: t.Fatalf("download ended before cancellation: %v", err)
99新增: case <-deadline:
100新增: t.Fatal("download did not write partial bytes")
101新增: case <-ticker.C:
102新增: if info, err := os.Stat(media + ".partial"); err == nil && info.Size() > 0 {
103新增: cancel()
104新增: if err := <-done; !errors.Is(err, context.Canceled) {
105新增: t.Fatalf("wrong cancellation: %v", err)
106新增: }
107新增: if info, err := os.Stat(media + ".partial"); err != nil || info.Size() == 0 {
108新增: t.Fatalf("partial download lost: %v", err)
109新增: }
110新增: if _, err := os.Stat(media); !errors.Is(err, os.ErrNotExist) {
111新增: t.Fatalf("unverified media published: %v", err)
112新增: }
113新增: return
114新增: }
115新增: }
116新增: }
117新增:}
118新增:
119新增:func TestMacRestoreDigestFailureDoesNotPublishMedia(t *testing.T) {
120新增: server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("invalid restore")) }))
121新增: defer server.Close()
122新增: trustRestoreServer(t, server)
123新增: media := filepath.Join(t.TempDir(), "MacOS.ipsw")
124新增: if err := prepareMacRestoreMedia(t.Context(), media, server.URL, strings.Repeat("0", 64), 15, &bytes.Buffer{}); err == nil {
125新增: t.Fatal("invalid digest accepted")
126新增: }
127新增: for _, p := range []string{media, media + ".partial"} {
128新增: if _, err := os.Stat(p); !errors.Is(err, os.ErrNotExist) {
129新增: t.Fatalf("invalid media retained at %s: %v", p, err)
130新增: }
131新增: }
132新增:}
新增cmd/cage/mac_guest_install_darwin_arm64.go+178 −0看文件
@@ -0,0 +1,178 @@
1新增://go:build darwin && arm64 && cgo && !no_vz
2新增:
3新增:package main
4新增:
5新增:import (
6新增: "bytes"
7新增: "context"
8新增: "errors"
9新增: "fmt"
10新增: "io"
11新增: "os"
12新增: "os/exec"
13新增: "path/filepath"
14新增: "regexp"
15新增: "strings"
16新增: "time"
17新增:
18新增: "al.essio.dev/pkg/shellescape"
19新增: "github.com/sylvinus/agent-vm/internal/guestos"
20新增: "github.com/sylvinus/agent-vm/internal/vm"
21新增:)
22新增:
23新增:const appleImageURL = "https://updates.cdn-apple.com/2026SpringFCS/fullrestores/140-24263/B95838F0-6815-4F0B-A039-156526C081AD/UniversalMac_26.5.2_25F84_Restore.ipsw"
24新增:const appleImageDigest = "065abd295a1a456a46c1155217eab92ee95816520ec9aeed83f249f074f68a04"
25新增:const appleImageBytes int64 = 19769902281
26新增:
27新增:func installMacWorkbench(ctx context.Context, profile, state string, l *vm.Lima) error {
28新增: i, err := guestos.LoadInstallation(profile)
29新增: if err != nil || i == nil || i.System != guestos.MacOS {
30新增: return errors.New("缺少这台虚拟 Mac 的首次安装记录")
31新增: }
32新增: pw, err := io.ReadAll(io.LimitReader(os.Stdin, 257))
33新增: if err != nil || !guestos.ValidMacOSInstallPassword(string(pw)) {
34新增: return errors.New("客机初始密码需使用 8 至 256 个英文键盘可输入的字母、数字、空格或符号")
35新增: }
36新增: defer clear(pw)
37新增: if !macGuestLoginAvailable() {
38新增: return errors.New("此 Cage 构建缺少虚拟 Mac 登录组件")
39新增: }
40新增: exe, err := os.Executable()
41新增: if err != nil {
42新增: return err
43新增: }
44新增: kit := filepath.Join(filepath.Dir(exe), "guest-os")
45新增: components, err := guestos.RequiredNativeComponents(kit, guestos.MacOS)
46新增: if err != nil {
47新增: return err
48新增: }
49新增: componentStage, err := os.MkdirTemp("", "cage-install-components-")
50新增: if err != nil {
51新增: return err
52新增: }
53新增: defer os.RemoveAll(componentStage)
54新增: if err = guestos.WriteNativeComponentManifest(filepath.Join(componentStage, "native-components.json"), components); err != nil {
55新增: return err
56新增: }
57新增: cache := filepath.Join(state, "guest-media", i.System)
58新增: if err := os.MkdirAll(cache, 0700); err != nil {
59新增: return err
60新增: }
61新增: local := func(name string, args ...string) error {
62新增: cmd := exec.CommandContext(ctx, name, args...)
63新增: cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
64新增: return cmd.Run()
65新增: }
66新增: media := i.Media
67新增: if media == "" {
68新增: media = filepath.Join(cache, "MacOS.ipsw")
69新增: fmt.Fprintln(os.Stdout, "正在从 Apple 下载并校验 macOS 26.5.2(19.77 GB)…")
70新增: err = prepareMacRestoreMedia(ctx, media, appleImageURL, appleImageDigest, appleImageBytes, os.Stdout)
71新增: if err != nil {
72新增: return fmt.Errorf("Apple 恢复镜像下载失败:%w", err)
73新增: }
74新增: }
75新增: fmt.Fprintln(os.Stdout, "正在准备客机应用和开发工具…")
76新增: fmt.Fprintln(os.Stdout, "CAGE_GUEST_STAGE macos media")
77新增: if err := local("/bin/bash", filepath.Join(kit, "prepare-macos-media.sh"), cache); err != nil {
78新增: return fmt.Errorf("准备客机应用失败:%w", err)
79新增: }
80新增: fmt.Fprintln(os.Stdout, "正在恢复虚拟 Mac…")
81新增: fmt.Fprintln(os.Stdout, "CAGE_GUEST_STAGE macos restore")
82新增: if err := runMacGuest(ctx, profile, state, []string{"create", media}); err != nil {
83新增: return err
84新增: }
85新增: if err := l.CheckMacOSGuest(ctx, "mac"); err != nil {
86新增: return err
87新增: }
88新增: if err := guestos.PinMacOSInstallHostKey(profile); err != nil {
89新增: return err
90新增: }
91新增: provision, err := guestos.MacOSProvisionUser(profile)
92新增: if err != nil {
93新增: return err
94新增: }
95新增: ordinaryUser := "cage"
96新增: if provision != "cageprovision" {
97新增: return errors.New("此开发客机的置备身份不匹配")
98新增: }
99新增: adminPassword := " < /Users/" + provision + "/password"
100新增: args, err := guestos.MacOSSSHArgs(profile, provision)
101新增: if err != nil {
102新增: return err
103新增: }
104新增: guestCommand := func(opctx context.Context, script string) *exec.Cmd {
105新增: argv := append(append([]string{}, args...), "-T", "cage-macos", "--", "exec /bin/sh -ec "+shellescape.Quote(script))
106新增: cmd := exec.CommandContext(opctx, "/usr/bin/ssh", argv...)
107新增: cmd.Stderr = os.Stderr
108新增: return cmd
109新增: }
110新增: out, err := guestCommand(ctx, `umask 077; test "$(uname -s)" = Darwin; test "$(id -un)" = `+provision+`; mktemp -d /private/var/tmp/cage-install.XXXXXXXX`).Output()
111新增: remote := strings.TrimSpace(string(out))
112新增: if err != nil || !regexp.MustCompile(`^/private/var/tmp/cage-install\.[A-Za-z0-9]{8}$`).MatchString(remote) {
113新增: return errors.New("无法在已验证的虚拟 Mac 中准备安装目录")
114新增: }
115新增: defer func() {
116新增: clean, cancel := context.WithTimeout(context.Background(), 10*time.Second)
117新增: defer cancel()
118新增: _ = guestCommand(clean, `sudo -S -p '' /bin/rm -rf `+remote+adminPassword).Run()
119新增: }()
120新增: fmt.Fprintln(os.Stdout, "正在将开发组件送入已验证的离线虚拟 Mac…")
121新增: fmt.Fprintln(os.Stdout, "CAGE_GUEST_STAGE macos tools")
122新增: // Only the fixed subset of media is transferred. The IPSW stays on the host.
123新增: tar := exec.CommandContext(ctx, "/usr/bin/tar", "--no-mac-metadata", "-cf", "-", "-C", kit, ".", "-C", cache, "node.tgz", "editor.tgz", "playwright.tgz", "chrome.dmg", "claude.dmg", "cli", "macfuse.pkg", "-C", componentStage, "native-components.json")
124新增: tar.Env = append(os.Environ(), "COPYFILE_DISABLE=1")
125新增: tar.Stderr = os.Stderr
126新增: pipe, err := tar.StdoutPipe()
127新增: if err != nil {
128新增: return err
129新增: }
130新增: receiver := guestCommand(ctx, `umask 077; cd `+remote+`; /usr/bin/tar -xf -; mv macfuse.pkg project/macfuse.pkg`)
131新增: receiver.Stdin = pipe
132新增: if err = tar.Start(); err != nil {
133新增: return err
134新增: }
135新增: recvErr := receiver.Run()
136新增: _ = pipe.Close()
137新增: if err := errors.Join(recvErr, tar.Wait()); err != nil {
138新增: return fmt.Errorf("客机组件传输失败:%w", err)
139新增: }
140新增: // The staging directory belongs exclusively to the provisioning account.
141新增: // Before invoking the installer, root takes ownership and restricts access.
142新增: auth := guestCommand(ctx, `umask 077; cat > `+remote+`/login-input; sudo -S -p '' /usr/sbin/chown -R root:wheel `+remote+adminPassword)
143新增: auth.Stdin = io.MultiReader(bytes.NewReader(pw), strings.NewReader("\n"))
144新增: if err := auth.Run(); err != nil {
145新增: return errors.New("无法准备虚拟 Mac 账户")
146新增: }
147新增: cmd := guestCommand(ctx, `sudo -S -p '' /bin/sh -ec `+shellescape.Quote(`cd `+remote+`; exec 4<login-input; rm login-input; /usr/bin/perl ./native-component-manifest.pl source ./native-components.json .; /bin/bash ./provision-macos-workbench.sh `+remote+` `+i.ID.String()+` `+provision+` <&4; /usr/bin/perl ./native-component-manifest.pl publish ./native-components.json .`)+adminPassword)
148新增: cmd.Stdout = os.Stdout
149新增: if err := cmd.Run(); err != nil {
150新增: return fmt.Errorf("安装虚拟 Mac 应用失败,可在工作台继续安装:%w", err)
151新增: }
152新增: ordinary, err := guestos.MacOSSSHArgs(profile, ordinaryUser)
153新增: if err != nil {
154新增: return err
155新增: }
156新增: verify := exec.CommandContext(ctx, "/usr/bin/ssh", append(ordinary, "-T", "cage-macos", "--",
157新增: `test "$(id -un)" = `+ordinaryUser+` && test "$(uname -s)" = Darwin && ! id -Gn | /usr/bin/grep -qw admin`)...)
158新增: if err := verify.Run(); err != nil {
159新增: return errors.New("普通客机账户无法通过已验证的 SSH 通道连接,已保留安装进度")
160新增: }
161新增: key, err := guestos.MacOSInstallHostKey(profile)
162新增: if err != nil {
163新增: return err
164新增: }
165新增: // Remove the root-owned media before stopping. No user data is in this dir.
166新增: if err := guestCommand(ctx, `sudo -S -p '' /bin/rm -rf `+remote+adminPassword).Run(); err != nil {
167新增: return err
168新增: }
169新增: fmt.Fprintln(os.Stdout, "CAGE_GUEST_STAGE macos services")
170新增: if err := l.Stop(ctx, "mac"); err != nil {
171新增: return err
172新增: }
173新增: if err := guestos.BindNewMacOSProfile(profile, ordinaryUser, key, i.ID); err != nil {
174新增: return err
175新增: }
176新增: fmt.Fprintln(os.Stdout, "macOS 客机应用已安装,自动登录已准备。Cage 将继续完成首次授权。")
177新增: return nil
178新增:}
新增cmd/cage/mac_guest_other.go+14 −0看文件
@@ -0,0 +1,14 @@
1新增://go:build !darwin || !arm64 || !cgo || no_vz
2新增:
3新增:package main
4新增:
5新增:import (
6新增: "context"
7新增: "errors"
8新增:)
9新增:
10新增:func runMacGuest(context.Context, string, string, []string) error {
11新增: return errors.New("macOS guests require an Apple silicon Mac with Virtualization.framework")
12新增:}
13新增:
14新增:func macGuestLoginAvailable() bool { return false }
新增cmd/cage/mac_login_darwin_arm64.go+5 −0看文件
@@ -0,0 +1,5 @@
1新增://go:build darwin && arm64 && cgo && !no_vz
2新增:
3新增:package main
4新增:
5新增:import _ "github.com/sylvinus/agent-vm/internal/maclogin"
修改cmd/cage/main.go+119 −4看文件
@@ -3,6 +3,7 @@ package main
33import (
44 "context"
55 "encoding/json"
6新增: "errors"
67 "fmt"
78 "net/http"
89 "os"
@@ -18,6 +19,7 @@ import (
1819 "github.com/sylvinus/agent-vm/internal/cli"
1920 "github.com/sylvinus/agent-vm/internal/containerenv"
2021 "github.com/sylvinus/agent-vm/internal/diagnostics"
22新增: "github.com/sylvinus/agent-vm/internal/guestos"
2123 "github.com/sylvinus/agent-vm/internal/host"
2224 "github.com/sylvinus/agent-vm/internal/limaembed"
2325 "github.com/sylvinus/agent-vm/internal/managedproxy"
@@ -37,6 +39,8 @@ cage server-entry --json Issue a private SSH remote connection entry
3739cage container-configure --json Configure a Linux container from JSON stdin
3840cage init Create a private profile; add and select nodes in Cage settings
3941cage check Verify proxy transport (no VM required)
42新增:cage guest-os --json Check host prerequisites for a same-system guest
43新增: On Windows, add --vm-id GUID to inspect one Hyper-V VM
4044cage proxy-start Start Cage's bundled proxy core with the applied node
4145cage proxy-stop Stop Cage's core and close external networking
4246cage setup Build the isolated base VM through the specified proxy
@@ -85,6 +89,50 @@ func run() int {
8589 fmt.Print(help)
8690 return 0
8791 }
92新增: if args[0] == "verify-web-assets" {
93新增: if len(args) != 1 {
94新增: return 2
95新增: }
96新增: if err := workbench.VerifyWebAssets(); err != nil {
97新增: return fail(err)
98新增: }
99新增: return 0
100新增: }
101新增: if len(args) == 1 && (args[0] == "verify-macos-guest" || args[0] == "verify-macos-trial") {
102新增: if !macGuestLoginAvailable() {
103新增: return fail(fmt.Errorf("this helper was built without the virtual Mac login view"))
104新增: }
105新增: return 0
106新增: }
107新增: macGuestCommand := len(args) >= 2 && args[0] == "guest-os" && args[1] == "macos"
108新增: if args[0] == "guest-os" && !macGuestCommand {
109新增: ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
110新增: defer cancel()
111新增: if err := writeGuestOSInspection(ctx, args[1:], os.Stdout); err != nil {
112新增: return fail(err)
113新增: }
114新增: return 0
115新增: }
116新增: if args[0] == "verify-vm-assets" {
117新增: if len(args) != 1 {
118新增: return 2
119新增: }
120新增: dir, err := os.MkdirTemp("", "cage-vm-assets-")
121新增: if err != nil {
122新增: return fail(err)
123新增: }
124新增: defer os.RemoveAll(dir)
125新增: share, err := limaembed.WriteShare(dir)
126新增: if err != nil {
127新增: return fail(err)
128新增: }
129新增: if runtime.GOOS == "darwin" && runtime.GOARCH == "arm64" {
130新增: if _, err := share.GuestAgent("Darwin", "aarch64"); err != nil {
131新增: return fail(err)
132新增: }
133新增: }
134新增: return 0
135新增: }
88136 if err := host.ConfigureWindowsRuntime(); err != nil {
89137 return fail(err)
90138 }
@@ -99,6 +147,15 @@ func run() int {
99147 }
100148 store := diagnostics.New(filepath.Dir(path))
101149 diagnostics.SetDefault(store)
150新增: if args[0] == "windows-network-host" {
151新增: if len(args) != 1 {
152新增: return fail(fmt.Errorf("windows-network-host takes its bound configuration from the profile"))
153新增: }
154新增: if err := workbench.ServeWindowsPacketNetwork(path); err != nil {
155新增: return fail(err)
156新增: }
157新增: return 0
158新增: }
102159 if args[0] == "container-runtime" {
103160 if len(args) != 2 {
104161 return fail(fmt.Errorf("container-runtime prepare|start|stop|inspect"))
@@ -235,13 +292,37 @@ func run() int {
235292 return appupdate.Run(path, args[1:], os.Stdout)
236293 }
237294 connectionID := ""
238删除: if (args[0] == "upload-files" || args[0] == "browser-file") && len(args) >= 3 && args[2] == "--connection" {
295新增: if (args[0] == "clipboard-files" || args[0] == "upload-files" || args[0] == "browser-file" || args[0] == "share-project") && len(args) >= 3 && args[2] == "--connection" {
239296 if len(args) < 4 || args[3] == "" {
240297 return fail(fmt.Errorf("missing file connection identity"))
241298 }
242299 connectionID = args[3]
243300 args = append(append([]string{}, args[:2]...), args[4:]...)
244301 }
302新增: if args[0] == "clipboard-files" {
303新增: if len(args) < 4 || args[1] != "--json" {
304新增: return fail(fmt.Errorf("clipboard-files --json --connection ID send|receive PATH..."))
305新增: }
306新增: result, err := workbench.ClipboardFilesForConnection(workbench.DesktopHelperConfig(path, connectionID), connectionID, args[2], args[3:])
307新增: if err != nil {
308新增: _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"message": err.Error()})
309新增: return 1
310新增: }
311新增: _ = json.NewEncoder(os.Stdout).Encode(result)
312新增: return 0
313新增: }
314新增: if args[0] == "share-project" {
315新增: if connectionID == "" || len(args) != 4 || args[1] != "--json" || (args[2] != "read" && args[2] != "write") {
316新增: return fail(fmt.Errorf("share-project --json --connection ID read|write DIRECTORY"))
317新增: }
318新增: result, err := workbench.ShareNativeCloudProject(workbench.DesktopHelperConfig(path, connectionID), connectionID, args[3], args[2] == "read")
319新增: if err != nil {
320新增: _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"status": "error", "message": err.Error()})
321新增: return 1
322新增: }
323新增: _ = json.NewEncoder(os.Stdout).Encode(result)
324新增: return 0
325新增: }
245326 if args[0] == "upload-files" {
246327 if len(args) < 5 || args[1] != "--json" {
247328 return fail(fmt.Errorf("upload-files --json browser|desktop|terminal ID PATH..."))
@@ -380,6 +461,9 @@ func run() int {
380461 os.Unsetenv("CAGE_LIMA_CACHE_DIR")
381462 os.Unsetenv("CAGE_LOGICAL_LIMA_HOME")
382463 if !containerenv.Configured(profile) {
464新增: if err = guestos.RecoverWindowsStorage(context.Background(), profile); err != nil {
465新增: return fail(err)
466新增: }
383467 lease, location, err := cage.AcquireStorageUse(profile)
384468 if err != nil {
385469 return fail(err)
@@ -406,6 +490,14 @@ func run() int {
406490 if limaembed.Run(args) {
407491 return 0
408492 }
493新增: if macGuestCommand {
494新增: ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
495新增: defer cancel()
496新增: if err := runMacGuest(ctx, profile, state, args[2:]); err != nil {
497新增: return fail(err)
498新增: }
499新增: return 0
500新增: }
409501 if args[0] == "proxy-start" || args[0] == "proxy-stop" {
410502 if err := proxyCommand(args[0], filepath.Dir(path), cfg); err != nil {
411503 return fail(err)
@@ -477,7 +569,10 @@ func run() int {
477569 if err = os.WriteFile(filepath.Join(state, "setup.sh"), []byte(cage.GuestSetup), 0600); err != nil {
478570 return fail(err)
479571 }
480删除: memory, cpus := cage.ResourceLimits()
572新增: memory, cpus, resourceErr := cage.ConfiguredResourceLimits(path)
573新增: if resourceErr != nil {
574新增: return fail(resourceErr)
575新增: }
481576 args = append([]string{"setup", "--memory", fmt.Sprint(memory), "--cpus", fmt.Sprint(cpus), "--disk", "24", "--preinstall=node,python,chromium,claude,code-server"}, args[1:]...)
482577 }
483578 if args[0] == "up" || args[0] == "login" {
@@ -485,7 +580,7 @@ func run() int {
485580 if result != 0 {
486581 return result
487582 }
488删除: if err := workbench.RunMaintenanceScript(context.Background(), path, cfg.StartScript(), os.Stdout, os.Stderr); err != nil {
583新增: if err := workbench.StartGuestServices(context.Background(), path, cfg, os.Stdout, os.Stderr); err != nil {
489584 return fail(err)
490585 }
491586 fmt.Println("Cage local services are ready. Open Cage or run cage desktop to complete the required network checks. External networking stays closed until the workbench approves this VM; no local access password is required.")
@@ -518,7 +613,7 @@ func containerInstallScript(kind string) (string, error) {
518613 case "services":
519614 return cage.GuestSetup, nil
520615 case "tools":
521删除: script := "export CLAUDE_CAGE=1\n" + cage.ToolInstallPrelude()
616新增: script := "set -e\nexport CLAUDE_CAGE=1\n" + cage.APTBootstrapScript + "\n" + cage.ToolInstallPrelude()
522617 enabled := map[string]bool{"NODE": true, "PYTHON": true, "CHROMIUM": true, "CLAUDE": true, "CODE_SERVER": true}
523618 for _, name := range []string{"PYTHON", "NODE", "RUBY", "RUST", "GOLANG", "DOCKER", "CHROMIUM", "GH", "CLAUDE", "OPENCODE", "CODEX", "VIBE", "PI", "CODE_SERVER", "CODE_CLAUDE", "CODE_OPENCODE", "CODE_CODEX", "CODE_VIBE", "MCP_CHROME", "MCP_PLAYWRIGHT"} {
524619 value := "0"
@@ -579,6 +674,7 @@ func relay(configPath, kind string) int {
579674 } else {
580675 return 2
581676 }
677新增: configureRelayCommand(cmd)
582678 cmd.Env = append(os.Environ(), cage.ConfigEnv+"="+configPath)
583679 store := diagnostics.New(filepath.Dir(configPath))
584680 out := store.Stream(source, "info")
@@ -595,11 +691,13 @@ func relay(configPath, kind string) int {
595691 defer signal.Stop(signals)
596692 done := make(chan struct{})
597693 var wg sync.WaitGroup
694新增: var forwarded os.Signal
598695 wg.Add(1)
599696 go func() {
600697 defer wg.Done()
601698 select {
602699 case sig := <-signals:
700新增: forwarded = sig
603701 _ = cmd.Process.Signal(sig)
604702 case <-done:
605703 }
@@ -608,9 +706,26 @@ func relay(configPath, kind string) int {
608706 close(done)
609707 wg.Wait()
610708 if err != nil {
709新增: if expectedRelayStop(err, forwarded) {
710新增: diagnostics.Log("info", source, "process stopped on request")
711新增: return 0
712新增: }
611713 diagnostics.Log("error", source, "process exited: "+err.Error())
612714 return 1
613715 }
614716 diagnostics.Log("info", source, "process exited normally")
615717 return 0
616718}
719新增:
720新增:func expectedRelayStop(err error, forwarded os.Signal) bool {
721新增: signal, ok := forwarded.(syscall.Signal)
722新增: if !ok {
723新增: return false
724新增: }
725新增: var exit *exec.ExitError
726新增: if !errors.As(err, &exit) {
727新增: return false
728新增: }
729新增: status, ok := exit.Sys().(syscall.WaitStatus)
730新增: return ok && status.Signaled() && status.Signal() == signal || exit.ExitCode() == 128+int(signal)
731新增:}
修改cmd/cage/proxy.go+19 −4看文件
@@ -4,6 +4,7 @@ import (
44 "context"
55 "encoding/json"
66 "github.com/sylvinus/agent-vm/internal/cage"
7新增: "github.com/sylvinus/agent-vm/internal/guestos"
78 "github.com/sylvinus/agent-vm/internal/managedproxy"
89 "os"
910 "path/filepath"
@@ -45,7 +46,10 @@ func proxyCommand(command, profile string, cfg cage.Config) error {
4546 if err = managedproxy.Write(path, data); err != nil {
4647 return err
4748 }
48删除: files := managedGateFiles(profile)
49新增: files, err := managedGateFiles(profile)
50新增: if err != nil {
51新增: return err
52新增: }
4953 for _, file := range files {
5054 if client, e := cage.OpenGateClient(filepath.Dir(file)); e == nil {
5155 if _, e = client.Status(context.Background()); e == nil {
@@ -59,7 +63,10 @@ func proxyCommand(command, profile string, cfg cage.Config) error {
5963}
6064
6165func closeManagedGates(profile string) error {
62删除: files := managedGateFiles(profile)
66新增: files, err := managedGateFiles(profile)
67新增: if err != nil {
68新增: return err
69新增: }
6370 for _, file := range files {
6471 if client, e := cage.OpenGateClient(filepath.Dir(file)); e == nil {
6572 if _, e = client.Status(context.Background()); e == nil {
@@ -72,8 +79,16 @@ func closeManagedGates(profile string) error {
7279 return nil
7380}
7481
75删除:func managedGateFiles(profile string) []string {
82新增:func managedGateFiles(profile string) ([]string, error) {
7683 files, _ := filepath.Glob(filepath.Join(profile, "state", "lima", "*", "cage-gate.json"))
7784 containers, _ := filepath.Glob(filepath.Join(profile, "state", "container", "*", "cage-gate.json"))
78删除: return append(files, containers...)
85新增: files = append(files, containers...)
86新增: binding, err := guestos.LoadWindowsProfile(profile)
87新增: if err != nil {
88新增: return nil, err
89新增: }
90新增: if binding != nil {
91新增: files = append(files, filepath.Join(binding.InstanceDirectory, "cage-gate.json"))
92新增: }
93新增: return files, nil
7994}
新增cmd/cage/proxy_gate_test.go+45 −0看文件
@@ -0,0 +1,45 @@
1新增:package main
2新增:
3新增:import (
4新增: "os"
5新增: "path/filepath"
6新增: "testing"
7新增:
8新增: "github.com/google/uuid"
9新增: "github.com/sylvinus/agent-vm/internal/cage"
10新增: "github.com/sylvinus/agent-vm/internal/guestos"
11新增:)
12新增:
13新增:func TestProxyChangeClosesBoundWindowsGate(t *testing.T) {
14新增: profile := t.TempDir()
15新增: instance := t.TempDir()
16新增: binding := guestos.WindowsProfile{Version: 1, VMID: uuid.New(), GUIUserSID: "S-1-5-21-1-2-3-1001", InstanceDirectory: instance, RelayExecutable: filepath.Join(profile, "relay.exe"), PairingFile: filepath.Join(profile, "pairing.bin")}
17新增: if err := guestos.BindWindowsProfile(profile, binding); err != nil {
18新增: t.Fatal(err)
19新增: }
20新增: gate, err := cage.NewEgressGate(cage.DefaultConfig())
21新增: if err != nil {
22新增: t.Fatal(err)
23新增: }
24新增: stop, err := cage.StartGateControl(filepath.Join(profile, "config.json"), instance, gate)
25新增: if err != nil {
26新增: t.Fatal(err)
27新增: }
28新增: defer stop()
29新增: if err := closeManagedGates(profile); err != nil {
30新增: t.Fatal(err)
31新增: }
32新增: if gate.Status().Mode != cage.GateClosed || gate.Status().Reason != "代理核心停止或重启,等待重新检测" {
33新增: t.Fatal("CLI proxy lifecycle missed the bound Windows gate")
34新增: }
35新增:}
36新增:
37新增:func TestProxyChangeRejectsMalformedWindowsBinding(t *testing.T) {
38新增: profile := t.TempDir()
39新增: if err := os.WriteFile(guestos.WindowsProfilePath(profile), []byte(`{"version":1}`), 0600); err != nil {
40新增: t.Fatal(err)
41新增: }
42新增: if err := closeManagedGates(profile); err == nil {
43新增: t.Fatal("proxy mutation ignored an invalid native guest binding")
44新增: }
45新增:}
新增cmd/cage/relay_stop_test.go+32 −0看文件
@@ -0,0 +1,32 @@
1新增:package main
2新增:
3新增:import (
4新增: "os"
5新增: "os/exec"
6新增: "runtime"
7新增: "syscall"
8新增: "testing"
9新增:)
10新增:
11新增:func TestRelayRecognizesOnlyTheRequestedTermination(t *testing.T) {
12新增: if runtime.GOOS == "windows" {
13新增: t.Skip("POSIX signal fixture; Windows build is checked separately")
14新增: }
15新增: for _, tc := range []struct {
16新增: child string
17新增: forwarded os.Signal
18新增: want bool
19新增: }{
20新增: {"kill -TERM $$", syscall.SIGTERM, true},
21新增: {"exit 143", syscall.SIGTERM, true},
22新增: {"exit 143", nil, false},
23新增: {"kill -TERM $$", nil, false},
24新增: {"exit 7", syscall.SIGTERM, false},
25新增: {"kill -KILL $$", syscall.SIGTERM, false},
26新增: } {
27新增: err := exec.Command("sh", "-c", tc.child).Run()
28新增: if got := expectedRelayStop(err, tc.forwarded); got != tc.want {
29新增: t.Fatalf("child=%q signal=%v: got %t, want %t", tc.child, tc.forwarded, got, tc.want)
30新增: }
31新增: }
32新增:}
新增cmd/cage/relay_unix.go+7 −0看文件
@@ -0,0 +1,7 @@
1新增://go:build !windows
2新增:
3新增:package main
4新增:
5新增:import "os/exec"
6新增:
7新增:func configureRelayCommand(cmd *exec.Cmd) {}
新增cmd/cage/relay_windows.go+12 −0看文件
@@ -0,0 +1,12 @@
1新增:package main
2新增:
3新增:import (
4新增: "os/exec"
5新增: "syscall"
6新增:
7新增: "golang.org/x/sys/windows"
8新增:)
9新增:
10新增:func configureRelayCommand(cmd *exec.Cmd) {
11新增: cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: windows.CREATE_NO_WINDOW}
12新增:}
新增cmd/cage/relay_windows_test.go+34 −0看文件
@@ -0,0 +1,34 @@
1新增:package main
2新增:
3新增:import (
4新增: "fmt"
5新增: "os"
6新增: "os/exec"
7新增: "strings"
8新增: "testing"
9新增:
10新增: "golang.org/x/sys/windows"
11新增:)
12新增:
13新增:func TestRelayChildHasNoConsoleAndCapturesOutput(t *testing.T) {
14新增: executable, err := os.Executable()
15新增: if err != nil {
16新增: t.Fatal(err)
17新增: }
18新增: cmd := exec.Command(executable, "-test.run=^TestRelayConsoleChild$")
19新增: cmd.Env = append(os.Environ(), "CAGE_RELAY_CONSOLE_TEST=1")
20新增: configureRelayCommand(cmd)
21新增: output, err := cmd.CombinedOutput()
22新增: if err != nil || !strings.Contains(string(output), "console=0") || !strings.Contains(string(output), "stderr-captured") {
23新增: t.Fatalf("relay child: %s, %v", output, err)
24新增: }
25新增:}
26新增:
27新增:func TestRelayConsoleChild(t *testing.T) {
28新增: if os.Getenv("CAGE_RELAY_CONSOLE_TEST") != "1" {
29新增: return
30新增: }
31新增: window, _, _ := windows.NewLazySystemDLL("kernel32.dll").NewProc("GetConsoleWindow").Call()
32新增: fmt.Printf("console=%d\n", window)
33新增: fmt.Fprintln(os.Stderr, "stderr-captured")
34新增:}
修改go.mod+1 −0看文件
@@ -29,6 +29,7 @@ require (
2929 github.com/mattn/go-isatty v0.0.24
3030 github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58
3131 github.com/sirupsen/logrus v1.10.2
32新增: github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
3233 github.com/spf13/cobra v1.10.2
3334 golang.org/x/sys v0.48.0
3435 golang.org/x/term v0.46.0
修改go.sum+2 −0看文件
@@ -266,6 +266,8 @@ github.com/sethvargo/go-password v0.4.0 h1:eSidVKQw5C7CmTDAtH3RipBTSjdU1ZRxQaynD
266266github.com/sethvargo/go-password v0.4.0/go.mod h1:PO3nYHwUpcHPR0F9woy7a4abZPvzRuqJr0GaeIYTm3k=
267267github.com/sirupsen/logrus v1.10.2 h1:G2SED73/qrAu6YwbdxOD6peLkCBI3z7L+ykJFTXJBBo=
268268github.com/sirupsen/logrus v1.10.2/go.mod h1:SLEg8TqYulVKKfIGHldVp2K2aYz2DKSVBq4g/H5bR7Q=
269新增:github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0=
270新增:github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M=
269271github.com/spakin/netpbm v1.3.2 h1:ZAb16Sw/+b4QeO9NokEvejVvbrYdF6DdcYJe0dKONL0=
270272github.com/spakin/netpbm v1.3.2/go.mod h1:cVep9uXARFgAu2UU+0c+OE1J+eKmDN2hW0EN+tazkTA=
271273github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
新增internal/cage/apt-bootstrap.sh+40 −0看文件
@@ -0,0 +1,40 @@
1新增:#!/bin/sh
2新增:# Run as root before any dependency transaction. Keep the bootstrap independent
3新增:# of python3/curl and of archive mirrors that may have triggered APT's retry bug.
4新增:set -eu
5新增:. /etc/os-release
6新增:if [ "$ID" != debian ] || [ "${VERSION_ID:-}" != 13 ]; then
7新增: exit 0
8新增:fi
9新增:version=$(dpkg-query -W -f='${Version}' apt)
10新增:if dpkg --compare-versions "$version" ge 3.0.4; then
11新增: exit 0
12新增:fi
13新增:printf 'Updating Debian APT %s to a version with the delayed-item memory fix...\n' "$version"
14新增:stage=$(mktemp -d)
15新增:trap 'rm -rf "$stage"' EXIT
16新增:chmod 0755 "$stage"
17新增:mkdir -m 0755 "$stage/lists"
18新增:# HTTP also works in minimal images without a CA bundle. APT still requires the
19新增:# Debian archive signature and package hashes; no insecure options are enabled.
20新增:printf '%s\n' 'deb [signed-by=/usr/share/keyrings/debian-archive-keyring.gpg] http://deb.debian.org/debian-security trixie-security main' > "$stage/security.list"
21新增:apt_bootstrap_get() {
22新增: env DEBIAN_FRONTEND=noninteractive apt-get \
23新增: -o Acquire::Retries=0 -o Acquire::http::Timeout=15 -o Acquire::https::Timeout=15 \
24新增: -o DPkg::Lock::Timeout=60 -o APT::Update::Error-Mode=any \
25新增: -o Dir::Etc::sourcelist="$stage/security.list" -o Dir::Etc::sourceparts=- \
26新增: -o Dir::State::lists="$stage/lists" "$@" </dev/null
27新增:}
28新增:apt_bootstrap_get update
29新增:packages='apt libapt-pkg7.0'
30新增:if [ "$(dpkg-query -W -f='${Status}' apt-utils 2>/dev/null || true)" = 'install ok installed' ]; then
31新增: packages="$packages apt-utils"
32新增:fi
33新增:# The package names above are fixed, and --only-upgrade preserves optional tools.
34新增:apt_bootstrap_get install -y --only-upgrade --no-install-recommends $packages
35新增:version=$(dpkg-query -W -f='${Version}' apt)
36新增:if ! dpkg --compare-versions "$version" ge 3.0.4; then
37新增: printf 'APT is still %s; dependency installation stopped. Check the Debian security source and retry.\n' "$version" >&2
38新增: exit 1
39新增:fi
40新增:printf 'Debian APT %s is ready.\n' "$version"
新增internal/cage/apt_bootstrap_test.go+95 −0看文件
@@ -0,0 +1,95 @@
1新增:package cage
2新增:
3新增:import (
4新增: "os"
5新增: "os/exec"
6新增: "path/filepath"
7新增: "strings"
8新增: "testing"
9新增:)
10新增:
11新增:func TestAPTBootstrapUpgradeFailureAndRetry(t *testing.T) {
12新增: for _, mode := range []string{"current", "upgrade", "download-failure", "stale-candidate", "unconfigured", "no-utils"} {
13新增: t.Run(mode, func(t *testing.T) {
14新增: dir := t.TempDir()
15新增: version := "3.0.3"
16新增: if mode == "current" {
17新增: version = "3.0.4"
18新增: }
19新增: os.WriteFile(filepath.Join(dir, "version"), []byte(version), 0600)
20新增: os.WriteFile(filepath.Join(dir, "os-release"), []byte("ID=debian\nVERSION_ID=13\n"), 0600)
21新增: os.WriteFile(filepath.Join(dir, "sentinel"), []byte("personal data stays"), 0600)
22新增: commands := map[string]string{
23新增: "sudo": "#!/bin/sh\nexec \"$@\"\n",
24新增: "dpkg-query": `#!/bin/sh
25新增:case "$*" in
26新增: *apt-utils*)
27新增: case "$MODE" in no-utils) exit 1;; unconfigured) echo 'install ok unpacked';; *) echo 'install ok installed';; esac;;
28新增: *) cat "$FIXTURE/version";;
29新增:esac
30新增:`,
31新增: "dpkg": `#!/bin/sh
32新增:[ "$2" != 3.0.3 ]
33新增:`,
34新增: "apt-get": `#!/bin/sh
35新增:printf '%s\n' "$*" >> "$FIXTURE/requests"
36新增:case "$*" in
37新增: *Acquire::Retries=0*) ;; *) exit 92;;
38新增:esac
39新增:case "$*" in
40新增: *'install '*)
41新增: [ "$MODE" != download-failure ] || exit 100
42新增: [ "$MODE" = stale-candidate ] || echo 3.0.4 > "$FIXTURE/version";;
43新增:esac
44新增:`,
45新增: }
46新增: for name, body := range commands {
47新增: if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0755); err != nil {
48新增: t.Fatal(err)
49新增: }
50新增: }
51新增: script := strings.ReplaceAll(APTBootstrapScript, ". /etc/os-release", ". \"$FIXTURE/os-release\"")
52新增: run := func() ([]byte, error) {
53新增: cmd := exec.Command("sh", "-c", script+"\nprintf continued >> \"$FIXTURE/continued\"\n")
54新增: cmd.Env = append(os.Environ(), "PATH="+dir+":"+os.Getenv("PATH"), "FIXTURE="+dir, "MODE="+mode, "TMPDIR="+dir)
55新增: return cmd.CombinedOutput()
56新增: }
57新增: out, err := run()
58新增: requests, _ := os.ReadFile(filepath.Join(dir, "requests"))
59新增: fail := mode == "download-failure" || mode == "stale-candidate"
60新增: if fail {
61新增: if err == nil {
62新增: t.Fatalf("failure continued: %s", out)
63新增: }
64新增: if _, err := os.Stat(filepath.Join(dir, "continued")); !os.IsNotExist(err) {
65新增: t.Fatal("continued after failed bootstrap")
66新增: }
67新增: mode = "upgrade"
68新增: if out, err := run(); err != nil {
69新增: t.Fatalf("retry failed: %v %s", err, out)
70新增: }
71新增: } else if err != nil {
72新增: t.Fatalf("%v %s", err, out)
73新增: }
74新增: if mode == "current" && len(requests) != 0 {
75新增: t.Fatal("current version used network")
76新增: }
77新增: if strings.Contains(string(requests), "apt-utils") && (mode == "unconfigured" || mode == "no-utils") {
78新增: t.Fatal("upgraded uninstalled apt-utils")
79新增: }
80新增: if data, _ := os.ReadFile(filepath.Join(dir, "sentinel")); string(data) != "personal data stays" {
81新增: t.Fatal("personal data changed")
82新增: }
83新增: })
84新增: }
85新增:}
86新增:
87新增:func TestGuestInstallEntrypointsCheckAPTFirst(t *testing.T) {
88新增: for name, script := range map[string]string{"lima": DebianPrepareScript, "services": GuestSetup, "start": DefaultConfig().StartScript(), "tools": ToolsUpdateScript()} {
89新增: gate := strings.Index(script, "CAGE_APT_BOOTSTRAP")
90新增: install := strings.Index(script, "apt-get install")
91新增: if gate < 0 || (install >= 0 && gate > install) {
92新增: t.Fatalf("%s installs before APT check", name)
93新增: }
94新增: }
95新增:}
修改internal/cage/browser-agent.mjs+261 −43看文件
@@ -1,3 +1,4 @@
1新增:import { createTailnetClient } from "./tailnet-client.mjs";
12// Chromium is controlled through inherited pipes, never an exposed CDP port.
23import { spawn, execFile } from "node:child_process";
34import { promisify } from "node:util";
@@ -8,6 +9,9 @@ import http from "node:http";
89import { auditBrowser } from "./browser-audit.mjs";
910import { BrowserVault } from "./browser-vault.mjs";
1011import { LoginBrowser } from "./browser-login.mjs";
12新增:import { PrivateBrowser } from "./browser-private.mjs";
13新增:import { browserCookies } from "./browser-cookies.mjs";
14新增:import { BrowserExtensions, extensionUploadLimit } from "./browser-extensions.mjs";
1115import { BrowserClipboard } from "./browser-clipboard.mjs";
1216import { nativeInput } from "./native-input.mjs";
1317import { DownloadManager } from "./browser-downloads.mjs";
@@ -17,6 +21,7 @@ import { createHash, timingSafeEqual } from "node:crypto";
1721const config = JSON.parse(
1822 readFileSync("/etc/claude-cage/browser-control.json", "utf8"),
1923);
24新增:const displayScale = config.display_scale === 1.5 ? 1.5 : 2;
2025const selectionFile = "/home/cage-browser/workbench-state.json";
2126const homepageFile = "/home/cage-browser/homepage.json";
2227let homeURL = "https://www.bing.com/";
@@ -29,7 +34,7 @@ try {
2934} catch {}
3035function rememberSelection() {
3136 const tab = targets.get(activeId);
32删除: if (tab && !tab.login)
37新增: if (tab && !tab.login && !tab.incognito)
3338 try {
3439 writeFileSync(selectionFile, JSON.stringify({ url: tab.url }), {
3540 mode: 0o600,
@@ -39,24 +44,28 @@ function rememberSelection() {
3944const downloadPath = "/home/cage-browser/Downloads";
4045mkdirSync(downloadPath, { recursive: true });
4146const splitDirectory = "/usr/local/lib/cage-split";
47新增:const browserIdentity = readFileSync(`${splitDirectory}/browser-identity.js`, "utf8");
4248const extensionId = createHash("sha256").update(splitDirectory).digest("hex").slice(0, 32)
4349 .replace(/./g, c => String.fromCharCode(97 + parseInt(c, 16)));
4450const splitURL = `chrome-extension://${extensionId}/control.html`;
45删除:let splitView = null, splitSession, splitOpening, resizeTimer;
51新增:const settingsURL = `chrome-extension://${extensionId}/settings.html`;
52新增:const extensionRepairURL = "chrome://extensions/?cage-browser-controller";
53新增:const isSettingsTab = tab => tab.url === settingsURL || tab.url.startsWith(settingsURL + "#");
54新增:const publicURL = tab => isSettingsTab(tab) ? "cage://settings" + new URL(tab.url).hash : tab.url;
55新增:let splitView = null, splitSession, splitTarget, splitOpening, resizeTimer;
4656const favicons = new Map(), faviconRequests = new Map(), documents = new Map();
4757
4858function isBrowserTab(target) {
4959 return target.type === "page" && target.url !== splitURL &&
50删除: !target.url.startsWith("devtools://") && !auditContexts.has(target.browserContextId);
60新增: target.url !== extensionRepairURL &&
61新增: !target.url.startsWith("devtools://") && !auditExclusions.has(target.browserContextId) &&
62新增: !auditExclusions.has(target.targetId) && !auditExclusions.has(target.url);
5163}
5264
5365const flags = [
5466 `--load-extension=${splitDirectory}`,
5567 "--user-data-dir=/home/cage-browser/profile",
5668 "--remote-debugging-pipe",
57删除: // The pipe manages tabs for a human-operated browser. Keep it private while
58删除: // preventing its presence alone from enabling Blink's automation marker.
59删除: "--disable-blink-features=AutomationControlled",
6069 // Kiosk mode blocks Chromium's DevTools UI, including F12. Ordinary
6170 // fullscreen keeps the guest browser chrome hidden while allowing inspection.
6271 "--start-fullscreen",
@@ -66,11 +75,12 @@ const flags = [
6675 "--disable-quic",
6776 "--disable-session-crashed-bubble",
6877 "--window-size=1440,900",
69删除: "--force-device-scale-factor=2",
78新增: `--force-device-scale-factor=${displayScale}`,
7079 `--lang=${process.env.CAGE_LANGUAGE || "en-US"}`,
80新增: `--accept-lang=${process.env.CAGE_LANGUAGE || "en-US"}`,
7181];
72删除:if (!existsSync("/home/cage-browser/profile/Default/Sessions"))
73删除: flags.push(homeURL);
82新增:const freshProfile = !existsSync("/home/cage-browser/profile/Default/Sessions");
83新增:if (freshProfile) flags.push("about:blank");
7484const chrome = spawn("/usr/bin/chromium", flags, {
7585 stdio: ["ignore", "ignore", "inherit", "pipe", "pipe"],
7686});
@@ -81,12 +91,24 @@ let sequence = 0,
8191let shuttingDown = false;
8292const events = new Set();
8393let navigation = { id: "", back: false, forward: false }, navigationSequence = 0;
84删除:const auditContexts = new Set();
94新增:// Context IDs and unique blank-page URLs are registered before target creation.
95新增:const auditExclusions = new Set();
96新增:const auditCreations = new Set(), deferredTargetInfo = new Map();
8597const loginBrowser = new LoginBrowser(cdp);
98新增:const privateBrowser = new PrivateBrowser(cdp, downloadPath);
99新增:const browserExtensions = new BrowserExtensions({ directory: "/home/cage-browser", cdp, control: splitController, protectedID: extensionId });
86100const pending = new Map(),
87101 targets = new Map(),
88102 sessions = new Map();
89删除:const browserClipboard = new BrowserClipboard(cdp, ({ id, text, context }) => {
103新增:const closingTargets = new Map();
104新增:// Cross-process frames must be prepared before their first website script.
105新增:// Reuse clipboard's frame discovery without giving it identity-policy state.
106新增:function clipboardCDP(method, params, ...args) {
107新增: if (method === "Target.setAutoAttach")
108新增: params = { ...params, waitForDebuggerOnStart: true };
109新增: return cdp(method, params, ...args);
110新增:}
111新增:const browserClipboard = new BrowserClipboard(clipboardCDP, ({ id, text, context }) => {
90112 if (id !== activeId || !targets.has(id)) return;
91113 const payload = "event: clipboard\ndata: " + JSON.stringify({ id, text, context }) + "\n\n";
92114 for (const stream of events) stream.write(payload);
@@ -128,6 +150,40 @@ function cdp(method, params = {}, sessionId, timeout = 4500) {
128150 );
129151 });
130152}
153新增:
154新增:function updateTargetInfo(t) {
155新增: if (!isBrowserTab(t)) return;
156新增: const fresh = !targets.has(t.targetId);
157新增: targets.set(t.targetId, privateBrowser.tab(loginBrowser.tab(t, targets.get(t.targetId))));
158新增: if (fresh) void session(t.targetId).catch(() => {});
159新增: if (t.targetId === activeId) rememberSelection();
160新增: broadcastState();
161新增: if (!activeId) activeId = t.targetId;
162新增: if (ready && fresh && t.openerId)
163新增: void activate(t.targetId, true).catch(() => {});
164新增:}
165新增:
166新增:async function auditCDP(method, params, ...args) {
167新增: if (method !== "Target.createTarget" || params.browserContextId)
168新增: return cdp(method, params, ...args);
169新增: // Chromium initially announces a background tab as about:blank, before its
170新增: // diagnostic URL or creation reply. Delay classification until its ID is known.
171新增: let complete;
172新增: const creating = new Promise(resolve => { complete = resolve; });
173新增: auditCreations.add(creating);
174新增: try {
175新增: const result = await cdp(method, params, ...args);
176新增: auditExclusions.add(result.targetId);
177新增: return result;
178新增: } finally {
179新增: auditCreations.delete(creating);
180新增: if (!auditCreations.size) {
181新增: for (const t of deferredTargetInfo.values()) updateTargetInfo(t);
182新增: deferredTargetInfo.clear();
183新增: }
184新增: complete();
185新增: }
186新增:}
131187chrome.stdio[4].on("data", (chunk) => {
132188 buffer = Buffer.concat([buffer, chunk]);
133189 let end;
@@ -152,6 +208,16 @@ chrome.stdio[4].on("data", (chunk) => {
152208 }
153209 vault.event(event);
154210 const p = event.params || {};
211新增: if (event.method === "Target.attachedToTarget" && ["page", "iframe"].includes(p.targetInfo?.type) && p.waitingForDebugger) {
212新增: void (async () => {
213新增: try {
214新增: await cdp("Page.enable", {}, p.sessionId);
215新增: await cdp("Page.addScriptToEvaluateOnNewDocument", { source: browserIdentity, runImmediately: true }, p.sessionId);
216新增: } finally {
217新增: await cdp("Runtime.runIfWaitingForDebugger", {}, p.sessionId).catch(() => {});
218新增: }
219新增: })().catch(() => {});
220新增: }
155221 browserClipboard.event(event);
156222 if (event.sessionId === splitSession && event.method === "Runtime.bindingCalled" &&
157223 p.name === "cageFaviconChanged") refreshFavicon(p.payload);
@@ -174,19 +240,22 @@ chrome.stdio[4].on("data", (chunk) => {
174240 event.method === "Target.targetInfoChanged"
175241 ) {
176242 const t = p.targetInfo;
177删除: if (isBrowserTab(t)) {
178删除: const fresh = !targets.has(t.targetId);
179删除: targets.set(t.targetId, loginBrowser.tab(t, targets.get(t.targetId)));
180删除: if (fresh) void session(t.targetId).catch(() => {});
181删除: if (t.targetId === activeId) rememberSelection();
182删除: broadcastState();
183删除: if (!activeId) activeId = t.targetId;
184删除: if (ready && fresh && t.openerId)
185删除: void activate(t.targetId, true).catch(() => {});
186删除: }
243新增: if (auditCreations.size) deferredTargetInfo.set(t.targetId, t);
244新增: else updateTargetInfo(t);
187245 }
188246 if (event.method === "Target.targetDestroyed") {
247新增: auditExclusions.delete(p.targetId);
248新增: deferredTargetInfo.delete(p.targetId);
249新增: if (p.targetId === splitTarget) {
250新增: splitTarget = null; splitSession = null;
251新增: if (!shuttingDown) void mutate(async () => {
252新增: await cdp("Extensions.loadUnpacked", { path: splitDirectory });
253新增: await splitController();
254新增: }).catch(() => {});
255新增: }
256新增: closingTargets.get(p.targetId)?.();
189257 if (!targets.has(p.targetId)) continue;
258新增: const wasPrivate = targets.get(p.targetId).incognito;
190259 vault.remove(p.targetId);
191260 targets.delete(p.targetId);
192261 browserClipboard.detachTab(p.targetId);
@@ -197,11 +266,12 @@ chrome.stdio[4].on("data", (chunk) => {
197266 uploads.cancelTab(p.targetId);
198267 for (const [sid, tab] of uploadSessions) if (tab === p.targetId) uploadSessions.delete(sid);
199268 sessions.delete(p.targetId);
200删除: broadcastState();
269新增: if (wasPrivate) void mutate(() => privateBrowser.prune()).catch(() => {});
201270 if (activeId === p.targetId) {
202271 activeId = [...targets.keys()][0] || "";
203272 if (activeId) void activate(activeId).catch(() => {});
204273 }
274新增: broadcastState();
205275 }
206276 if (event.method === "Browser.downloadWillBegin")
207277 downloads.begin(p.guid, p.suggestedFilename);
@@ -246,6 +316,10 @@ async function session(id) {
246316 cdp("Target.attachToTarget", { targetId: id, flatten: true }).then(async (r) => {
247317 uploadSessions.set(r.sessionId, id);
248318 await cdp("Page.enable", {}, r.sessionId);
319新增: // Off-the-record contexts do not load the profile's extensions. Keep
320新增: // the same page identity there and on already-restored documents.
321新增: await cdp("Page.addScriptToEvaluateOnNewDocument", { source: browserIdentity }, r.sessionId);
322新增: await cdp("Runtime.evaluate", { expression: browserIdentity }, r.sessionId);
249323 await cdp("Page.setInterceptFileChooserDialog", { enabled: true }, r.sessionId);
250324 await browserClipboard.attach(r.sessionId, id).then(result => {
251325 if (result?.skipped.length) console.warn("Browser copy observer skipped a modified or replaced document; reload the page to enable copy buttons.");
@@ -280,15 +354,33 @@ function scheduleSplitMeasure() {
280354 }, 80);
281355}
282356
283删除:async function splitController() {
357新增:async function splitController(repair = false) {
358新增: if (repair) {
359新增: const previous = splitTarget;
360新增: splitTarget = null; splitSession = null;
361新增: if (previous) await cdp("Target.closeTarget", { targetId: previous }).catch(() => {});
362新增: }
284363 if (splitSession) return splitSession;
285364 if (splitOpening) return splitOpening;
286删除: splitOpening = openSplitController().finally(() => { splitOpening = null; });
365新增: splitOpening = (async () => {
366新增: const { extensions } = await cdp("Extensions.getExtensions").catch(() => ({ extensions: [] }));
367新增: if (repair || extensions.some(item => item.id === extensionId && !item.enabled)) {
368新增: const { targetId } = await cdp("Target.createTarget", { url: extensionRepairURL, hidden: true, background: true });
369新增: try {
370新增: const { sessionId } = await cdp("Target.attachToTarget", { targetId, flatten: true });
371新增: await cdp("Runtime.evaluate", { expression: `new Promise(resolve => document.readyState === 'complete' ? resolve() : addEventListener('load', resolve, {once:true}))`, awaitPromise: true }, sessionId);
372新增: const result = await cdp("Runtime.evaluate", { expression: `chrome.management.setEnabled(${JSON.stringify(extensionId)}, true).then(() => true)`, awaitPromise: true, returnByValue: true, userGesture: true }, sessionId);
373新增: if (result.exceptionDetails || result.result?.value !== true) throw new Error("浏览器组件未能恢复,请重启环境");
374新增: } finally { await cdp("Target.closeTarget", { targetId }).catch(() => {}); }
375新增: }
376新增: return openSplitController();
377新增: })().finally(() => { splitOpening = null; });
287378 return splitOpening;
288379}
289380
290381async function openSplitController() {
291382 const { targetId } = await cdp("Target.createTarget", { url: splitURL, hidden: true, background: true });
383新增: splitTarget = targetId;
292384 try {
293385 const { sessionId } = await cdp("Target.attachToTarget", { targetId, flatten: true });
294386 await cdp("Runtime.enable", {}, sessionId);
@@ -305,6 +397,7 @@ async function openSplitController() {
305397 for (const id of targets.keys()) refreshFavicon(id);
306398 return sessionId;
307399 } catch (error) {
400新增: if (splitTarget === targetId) splitTarget = null;
308401 await cdp("Target.closeTarget", { targetId }).catch(() => {});
309402 throw error;
310403 }
@@ -332,6 +425,12 @@ function refreshFavicon(id) {
332425async function setSplit({ left, right, id }) {
333426 if (left && (!targets.has(left) || !targets.has(right) || left === right ||
334427 ![left, right].includes(id))) throw new Error("Invalid split tabs");
428新增: if (left && targets.get(left).browserContextId !== targets.get(right).browserContextId)
429新增: throw new Error("不同浏览会话不能分屏");
430新增: if (left && (targets.get(left).incognito || targets.get(right).incognito))
431新增: throw new Error("无痕标签暂不支持双网页分屏");
432新增: if (left && [left, right].some(id => isSettingsTab(targets.get(id))))
433新增: throw new Error("设置页请在单个浏览器窗格内使用");
335434 const sid = await splitController();
336435 const result = await cdp("Runtime.evaluate", { awaitPromise: true, returnByValue: true,
337436 expression: `setCageSplit(${JSON.stringify(left || "")}, ${JSON.stringify(right || "")})`,
@@ -370,22 +469,52 @@ async function activate(id, focus = false) {
370469}
371470function checkedURL(value) {
372471 if (value === "about:blank") return value;
373删除: const u = new URL(value);
374删除: if (!["http:", "https:"].includes(u.protocol) || u.username || u.password)
375删除: throw new Error("Only HTTP(S) URLs are accepted");
376删除: return u.href;
472新增: if (/^https?:\/\//i.test(value)) {
473新增: const url = new URL(value);
474新增: if (url.username || url.password) throw new Error("Only HTTP(S) URLs without credentials are accepted");
475新增: return url.href;
476新增: }
477新增: if (value === "chrome://extensions/" || value === "chrome://settings/content" || value === "chrome://settings/clearBrowserData") return value;
478新增: if (/^chrome:\/\/extensions\/\?id=[a-p]{32}$/.test(value)) return value;
479新增: if (value === settingsURL || value.startsWith(settingsURL + "#")) return value;
480新增: throw new Error("Only HTTP(S) URLs and supported browser pages are accepted");
377481}
378删除:async function newTab(url = homeURL) {
482新增:async function newTab(url = homeURL, incognito = false) {
483新增: const address = checkedURL(url);
484新增: if (incognito) {
485新增: const result = await privateBrowser.open("about:blank", async tab => {
486新增: targets.set(tab.targetId, tab);
487新增: await activate(tab.targetId, true);
488新增: });
489新增: await cdp("Page.navigate", { url: address }, await session(result.id));
490新增: return result;
491新增: }
379492 const { targetId } = await cdp("Target.createTarget", {
380删除: url: checkedURL(url),
493新增: url: "about:blank",
381494 background: false,
382495 });
383496 // The response and discovery event may arrive in either order.
384497 if (!targets.has(targetId))
385删除: targets.set(targetId, { targetId, type: "page", url, title: "" });
498新增: targets.set(targetId, { targetId, type: "page", url: "about:blank", title: "" });
386499 await activate(targetId, true);
500新增: await cdp("Page.navigate", { url: address }, await session(targetId));
387501 return { id: targetId };
388502}
503新增:async function browserSettings(section = "general") {
504新增: if (!["general", "appearance", "privacy", "extensions", "about"].includes(section)) throw new Error("设置分类无效");
505新增: const url = settingsURL + "#" + section;
506新增: const existing = [...targets.values()].find(isSettingsTab);
507新增: if (existing) {
508新增: await cdp("Page.navigate", { url }, await session(existing.targetId));
509新增: existing.url = url;
510新增: await activate(existing.targetId, true);
511新增: return { id: existing.targetId, kind: "browser-settings", title: "设置", url: publicURL(existing) };
512新增: }
513新增: const result = await newTab(url);
514新增: const created = targets.get(result.id);
515新增: if (created) created.url = url;
516新增: return { ...result, kind: "browser-settings", title: "设置", url: "cage://settings#" + section };
517新增:}
389518async function editor(workspace = config.workspace, reload = false) {
390519 if (typeof workspace !== "string" || !workspace.startsWith("/")) throw new Error("Invalid workspace");
391520 const editorURL = `http://127.0.0.1:18080/?folder=${encodeURIComponent(workspace)}`;
@@ -437,10 +566,11 @@ async function restartEditor(workspace) {
437566 throw new Error("编辑器尚未恢复,请稍后重试。");
438567}
439568async function tabState() {
569新增: await Promise.allSettled([...auditCreations]);
440570 const { targetInfos } = await cdp("Target.getTargets");
441571 for (const tab of targetInfos)
442572 if (isBrowserTab(tab))
443删除: targets.set(tab.targetId, loginBrowser.tab(tab, targets.get(tab.targetId)));
573新增: targets.set(tab.targetId, privateBrowser.tab(loginBrowser.tab(tab, targets.get(tab.targetId))));
444574 await refreshNavigation();
445575 return publicState();
446576}
@@ -462,6 +592,7 @@ async function refreshNavigation() {
462592 }
463593}
464594function displayTitle(tab) {
595新增: if (isSettingsTab(tab)) return "设置";
465596 if (tab.login) return "账号授权";
466597 if (tab.url === "about:blank") return "新标签页";
467598 const title = tab.title;
@@ -488,11 +619,13 @@ function publicState() {
488619 uploads: uploads.snapshot(),
489620 tabs: [...targets.values()].map((t) => ({
490621 id: t.targetId,
622新增: incognito: Boolean(t.incognito),
623新增: login: Boolean(t.login),
491624 title: displayTitle(t),
492删除: url: t.url,
625新增: url: publicURL(t),
493626 document: documents.get(t.targetId) || "",
494627 favicon: favicons.get(t.targetId) || "",
495删除: kind: t.url.startsWith("http://127.0.0.1:18080/") ? "editor" : "web",
628新增: kind: isSettingsTab(t) ? "browser-settings" : t.url.startsWith("http://127.0.0.1:18080/") ? "editor" : "web",
496629 workspace: t.url.startsWith("http://127.0.0.1:18080/") ? new URL(t.url).searchParams.get("folder") || config.workspace : undefined,
497630 })),
498631 };
@@ -510,8 +643,8 @@ async function resizeDisplay(width, height) {
510643 if (
511644 !Number.isInteger(width) ||
512645 !Number.isInteger(height) ||
513删除: width < 320 ||
514删除: height < 480 ||
646新增: width < 160 * displayScale ||
647新增: height < 240 * displayScale ||
515648 width > 8192 ||
516649 height > 8192
517650 )
@@ -571,6 +704,10 @@ function pasteImage(png) {
571704 });
572705}
573706
707新增:const tailnet = createTailnetClient();
708新增:void tailnet.restore().catch(() => {});
709新增:process.once("exit", () => tailnet.close());
710新增:let phoneBrowser;
574711const server = http.createServer(async (req, res) => {
575712 res.setHeader("Cache-Control", "no-store");
576713 res.setHeader("Content-Type", "application/json");
@@ -589,6 +726,11 @@ const server = http.createServer(async (req, res) => {
589726 try {
590727 if (!ready) throw new Error("Browser is starting");
591728 const route = new URL(req.url, "http://localhost");
729新增: if (req.method === "POST" && route.pathname === "/extensions-upload") {
730新增: if (Number(req.headers["content-length"]) > extensionUploadLimit) throw new Error("扩展 ZIP 不能超过 32 MB");
731新增: res.end(JSON.stringify(await mutate(() => browserExtensions.upload(req))));
732新增: return;
733新增: }
592734 if (req.method === "POST" && route.pathname === "/upload-file") {
593735 if (Number(req.headers["content-length"]) > uploadLimit) throw new Error("每个文件不能超过 2 GB");
594736 res.end(JSON.stringify(await uploads.receive(route.searchParams.get("id"), route.searchParams.get("name"), req)));
@@ -632,9 +774,28 @@ const server = http.createServer(async (req, res) => {
632774 let text = "";
633775 for await (const chunk of req) {
634776 text += chunk;
635删除: if (text.length > (req.url === "/paste-image" ? 28 * 1024 * 1024 : 65536)) throw new Error("Request too large");
777新增: if (text.length > (req.url === "/paste-image" ? 28 * 1024 * 1024 : req.url === "/paste-text" ? 12 * 1024 * 1024 + 4096 : 65536)) throw new Error("Request too large");
636778 }
637779 const input = JSON.parse(text || "{}");
780新增: if (req.url === "/tailnet") { res.end(JSON.stringify(await tailnet.request(input))); return; }
781新增: if (["/phone-desktop/open", "/phone-desktop/frame", "/phone-desktop/action", "/phone-desktop/close"].includes(req.url)) {
782新增: const { phoneDesktop } = await import("./browser-phone-desktop.mjs");
783新增: try { res.end(JSON.stringify(await phoneDesktop(req.url.split("/").pop(), input))); }
784新增: catch (error) { res.writeHead(error.status || 503); res.end("{}"); }
785新增: return;
786新增: }
787新增: if (["/phone-browser/open", "/phone-browser/action", "/phone-browser/frame", "/phone-browser/close"].includes(req.url)) {
788新增: // Load only for a phone operation, keeping desktop startup independent.
789新增: const { PhoneBrowser } = await import("./browser-phone.mjs");
790新增: phoneBrowser ??= new PhoneBrowser();
791新增: try {
792新增: res.end(JSON.stringify(await phoneBrowser.run(req.url.slice("/phone-browser/".length), input)));
793新增: } catch (error) {
794新增: res.writeHead([403, 409, 410, 503].includes(error.status) ? error.status : 400);
795新增: res.end(JSON.stringify({ error: error.message }));
796新增: }
797新增: return;
798新增: }
638799 if (req.url === "/desktop-focus") {
639800 broadcastState(false, true);
640801 res.end('{"ok":true}');
@@ -657,7 +818,7 @@ const server = http.createServer(async (req, res) => {
657818 }
658819 if (req.url === "/audit") {
659820 if (typeof input.timezone !== "string" || input.timezone.length > 128) throw new Error("诊断时区无效");
660删除: res.end(JSON.stringify(await auditBrowser(cdp, auditContexts, input.network === true, input.timezone)));
821新增: res.end(JSON.stringify(await auditBrowser(auditCDP, auditExclusions, input.network === true, input.timezone)));
661822 return;
662823 }
663824 const result = await mutate(async () => {
@@ -669,6 +830,7 @@ const server = http.createServer(async (req, res) => {
669830 return loginBrowser.open(input.login, input.url, async tab => {
670831 if (!targets.has(tab.targetId)) targets.set(tab.targetId, loginBrowser.tab(tab));
671832 await activate(tab.targetId, true);
833新增: return session(tab.targetId);
672834 });
673835 }
674836 if (req.url === "/login-finish") {
@@ -689,9 +851,35 @@ const server = http.createServer(async (req, res) => {
689851 return { ok: true };
690852 }
691853 if (req.url === "/split") return setSplit(input);
854新增: if (req.url === "/settings") return browserSettings(input.mode || "general");
855新增: if (req.url === "/info") {
856新增: const { product, protocolVersion } = await cdp("Browser.getVersion");
857新增: return { product, protocolVersion };
858新增: }
859新增: if (req.url === "/extensions") {
860新增: const result = await browserExtensions.request(input);
861新增: if (input.mode === "options" && result.url) {
862新增: if (!result.url.startsWith(`chrome-extension://${input.id}/`)) throw new Error("扩展设置地址无效");
863新增: const { targetId } = await cdp("Target.createTarget", { url: result.url });
864新增: if (!targets.has(targetId)) targets.set(targetId, { targetId, type: "page", url: result.url });
865新增: await activate(targetId, true);
866新增: return { id: targetId, url: result.url, kind: "web", title: "扩展选项" };
867新增: }
868新增: return result;
869新增: }
870新增: if (req.url === "/internal-page") {
871新增: const destinations = { extensions: "chrome://extensions/", permissions: "chrome://settings/content", clear: "chrome://settings/clearBrowserData" };
872新增: let url = destinations[input.mode];
873新增: if (input.mode === "extensions" && input.id) {
874新增: if (!/^[a-p]{32}$/.test(input.id)) throw new Error("扩展标识无效");
875新增: url += "?id=" + input.id;
876新增: }
877新增: if (!url) throw new Error("内部页面无效");
878新增: return { ...await newTab(url), url, kind: "web", title: "浏览器设置" };
879新增: }
692880 if (req.url === "/resize")
693881 return resizeDisplay(input.width, input.height);
694删除: if (req.url === "/new") return newTab(input.url || undefined);
882新增: if (req.url === "/new") return newTab(input.url || undefined, input.incognito === true);
695883 if (req.url === "/editor") return editor(input.workspace || config.workspace);
696884 if (req.url === "/editor-restart") return restartEditor(input.workspace);
697885 if (req.url === "/ime") {
@@ -703,6 +891,7 @@ const server = http.createServer(async (req, res) => {
703891 const id = input.id || activeId;
704892 if (!targets.has(id)) throw new Error("Tab no longer exists");
705893 switch (req.url) {
894新增: case "/cookies": return browserCookies(cdp, session, { ...targets.get(id), url: publicURL(targets.get(id)) }, input);
706895 case "/copy-context": {
707896 if (!/^[a-f0-9]{32}$/.test(input.context || "") || id !== activeId)
708897 throw new Error("Copy target changed");
@@ -717,6 +906,14 @@ const server = http.createServer(async (req, res) => {
717906 if (input.id !== activeId) throw new Error("Image target changed");
718907 await pasteImage(input.png);
719908 break;
909新增: case "/paste-text": {
910新增: if (input.id !== activeId || typeof input.text !== "string" || Buffer.byteLength(input.text) > 2 * 1024 * 1024)
911新增: throw new Error("Input target or text is invalid");
912新增: const field = await nativeInput({ target: "browser", mode: "status" });
913新增: if (!field.available || field.context !== input.context || input.id !== activeId) throw new Error("Input target changed");
914新增: await cdp("Input.insertText", { text: input.text }, await session(id));
915新增: break;
916新增: }
720917 case "/insert-text":
721918 if (input.id !== activeId || typeof input.text !== "string" ||
722919 !input.text || Buffer.byteLength(input.text, "utf8") > 8192)
@@ -726,10 +923,22 @@ const server = http.createServer(async (req, res) => {
726923 case "/activate":
727924 await activate(id);
728925 break;
729删除: case "/close":
730删除: if (targets.size === 1) await newTab();
731删除: await cdp("Target.closeTarget", { targetId: id });
926新增: case "/close": {
927新增: const wasPrivate = targets.get(id).incognito;
928新增: let timer;
929新增: const closed = new Promise((resolve, reject) => {
930新增: closingTargets.set(id, resolve);
931新增: timer = setTimeout(() => reject(new Error("标签尚未关闭,请重试")), 4500);
932新增: });
933新增: // Keep consecutive close/new commands ordered after target destruction.
934新增: closed.catch(() => {});
935新增: try {
936新增: await cdp("Target.closeTarget", { targetId: id });
937新增: await closed;
938新增: if (wasPrivate) await privateBrowser.prune();
939新增: } finally { clearTimeout(timer); closingTargets.delete(id); }
732940 break;
941新增: }
733942 case "/navigate":
734943 await cdp(
735944 "Page.navigate",
@@ -766,7 +975,12 @@ const server = http.createServer(async (req, res) => {
766975});
767976server.listen(18500, "127.0.0.1");
768977(async () => {
769删除: await cdp("Browser.getVersion");
978新增: // A cold guest can spend several seconds initializing the sandbox and fonts.
979新增: // Keep ordinary commands bounded separately from this initial handshake.
980新增: await cdp("Browser.getVersion", {}, undefined, 30000);
981新增: // Website-created popups can run scripts before Cage activates them.
982新增: await cdp("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true,
983新增: flatten: true, filter: [{ type: "page" }, { exclude: true }] });
770984 await cdp("Target.setDiscoverTargets", { discover: true });
771985 const { targetInfos } = await cdp("Target.getTargets");
772986 for (const t of targetInfos)
@@ -783,6 +997,9 @@ server.listen(18500, "127.0.0.1");
783997 [...targets.keys()][0],
784998 );
785999 await setSplit({}).catch(() => {});
1000新增: await browserExtensions.restore();
1001新增: if (freshProfile && activeId)
1002新增: await cdp("Page.navigate", { url: homeURL }, await session(activeId));
7861003 ready = true;
7871004})().catch(error => {
7881005 console.error("Browser startup failed:", error.message);
@@ -791,6 +1008,7 @@ server.listen(18500, "127.0.0.1");
7911008process.on("SIGTERM", () => {
7921009 shuttingDown = true;
7931010 server.close();
1011新增: void phoneBrowser?.dispose();
7941012 cdp("Browser.close").catch(() => {});
7951013 setTimeout(() => process.exit(0), 2000).unref();
7961014});
修改internal/cage/browser-audit.mjs+44 −9看文件
@@ -1,15 +1,52 @@
1删除:// A hidden, disposable context avoids touching account tabs, browser cookies,
2删除:// focus or the visible tab strip while reading Chromium's actual settings.
1新增:import { randomUUID } from "node:crypto";
2新增:
3新增:// Read settings in a background blank page in the user profile, excluded from
4新增:// Cage's tab strip. Chromium's hidden-target path skips the profile's renderer
5新增:// preferences and reads UI-locale defaults even in the default context.
6新增:async function readBrowserSettings(cdp, exclusions, expectedTimezone) {
7新增: const url = `about:blank#cage-settings-${randomUUID()}`;
8新增: // Target events can arrive before the createTarget reply.
9新增: exclusions.add(url);
10新增: let targetId;
11新增: try {
12新增: ({ targetId } = await cdp("Target.createTarget", {
13新增: url, background: true, newWindow: false,
14新增: }));
15新增: const { sessionId } = await cdp("Target.attachToTarget", { targetId, flatten: true });
16新增: const response = await cdp("Runtime.evaluate", {
17新增: expression: `({timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
18新增: expected_timezone: new Intl.DateTimeFormat('en', {timeZone:${JSON.stringify(expectedTimezone)}}).resolvedOptions().timeZone,
19新增: language: navigator.language, languages: [...navigator.languages], platform: navigator.platform})`,
20新增: returnByValue: true,
21新增: }, sessionId);
22新增: if (response.exceptionDetails || !response.result?.value)
23新增: throw new Error("浏览器配置诊断未完成");
24新增: return response.result.value;
25新增: } finally {
26新增: if (targetId) {
27新增: try {
28新增: await cdp("Target.closeTarget", { targetId });
29新增: exclusions.delete(url);
30新增: } catch {
31新增: // Keep a page whose close failed excluded until the browser exits.
32新增: }
33新增: } else exclusions.delete(url);
34新增: }
35新增:}
36新增:
37新增:// Network probes retain a disposable context with no account cookies.
338export async function auditBrowser(
439 cdp,
5删除: auditContexts,
40新增: exclusions,
641 network,
742 expectedTimezone,
843) {
44新增: const settings = await readBrowserSettings(cdp, exclusions, expectedTimezone);
45新增: if (!network) return settings;
946 const { browserContextId } = await cdp("Target.createBrowserContext", {
1047 disposeOnDetach: true,
1148 });
12删除: auditContexts.add(browserContextId);
49新增: exclusions.add(browserContextId);
1350 let targetId;
1451 try {
1552 ({ targetId } = await cdp("Target.createTarget", {
@@ -56,9 +93,7 @@ export async function auditBrowser(
5693 if (!loaded) throw new Error("诊断页面尚未就绪");
5794 }
5895 const expression = `(async () => {
59删除: const result = {timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
60删除: expected_timezone: new Intl.DateTimeFormat('en', {timeZone:${JSON.stringify(expectedTimezone)}}).resolvedOptions().timeZone,
61删除: language: navigator.language, languages: [...navigator.languages], platform: navigator.platform};
96新增: const result = {};
6297 if (${network ? "true" : "false"}) {
6398 if (location.hostname !== '198.18.0.254') throw new Error('diagnostic navigation incomplete');
6499 try {
@@ -76,7 +111,7 @@ export async function auditBrowser(
76111 );
77112 if (response.exceptionDetails || !response.result?.value)
78113 throw new Error("浏览器诊断未完成");
79删除: return response.result.value;
114新增: return { ...settings, ...response.result.value };
80115 } finally {
81116 try {
82117 // Hidden targets are owned by the CDP connection, not the context's tab
@@ -84,7 +119,7 @@ export async function auditBrowser(
84119 // hidden page still references the context. Close it before disposal.
85120 if (targetId) await cdp("Target.closeTarget", { targetId });
86121 await cdp("Target.disposeBrowserContext", { browserContextId });
87删除: auditContexts.delete(browserContextId);
122新增: exclusions.delete(browserContextId);
88123 } catch {
89124 // If closing the page fails, leave its context alive and excluded from
90125 // user tabs. Disposing it anyway would recreate the browser crash.
修改internal/cage/browser-audit.test.mjs+66 −49看文件
@@ -2,30 +2,44 @@ import test from "node:test";
22import assert from "node:assert/strict";
33import { auditBrowser } from "./browser-audit.mjs";
44
5删除:function browser(failMethod) {
6删除: const contexts = new Set();
7删除: const excluded = new Set();
8删除: const pages = new Map();
9删除: let unsafeDisposal = false;
10删除: const observation = { timezone: "UTC", language: "en-US", platform: "Linux" };
11删除: const cdp = async (method, params) => {
12删除: if (method === failMethod) throw new Error("injected failure");
5新增:function browser(failMethod, failStage = "network") {
6新增: const contexts = new Set(), excluded = new Set(), pages = new Map(), calls = [];
7新增: let unsafeDisposal = false, stage = "settings";
8新增: const observation = { timezone: "UTC", language: "ja-JP", platform: "Linux" };
9新增: const cdp = async (method, params, sessionId) => {
10新增: if (method === "Target.createBrowserContext") stage = "network";
11新增: calls.push(method);
12新增: if (method === failMethod && stage === failStage && !params?.expression?.includes("document.readyState"))
13新增: throw new Error("injected failure");
1314 switch (method) {
1415 case "Target.createBrowserContext":
1516 contexts.add("audit-context");
1617 return { browserContextId: "audit-context" };
17删除: case "Target.createTarget":
18删除: assert.equal(params.hidden, true);
19删除: assert.ok(excluded.has(params.browserContextId));
20删除: pages.set("audit-page", params.browserContextId);
21删除: return { targetId: "audit-page" };
18新增: case "Target.createTarget": {
19新增: assert.equal(params.hidden, params.browserContextId ? true : undefined);
20新增: assert.equal(params.background, true);
21新增: assert.ok(excluded.has(params.browserContextId || params.url));
22新增: const targetId = params.browserContextId ? "network-page" : "settings-page";
23新增: pages.set(targetId, params.browserContextId || params.url);
24新增: return { targetId };
25新增: }
2226 case "Target.attachToTarget":
23删除: return { sessionId: "audit-session" };
27新增: return { sessionId: params.targetId + "-session" };
28新增: case "Page.navigate":
29新增: assert.equal(sessionId, "network-page-session", "only isolated pages navigate");
30新增: return {};
2431 case "Runtime.evaluate":
32新增: if (params.expression.includes("document.readyState")) return { result: { value: true } };
33新增: if (sessionId === "network-page-session") {
34新增: assert.ok(!params.expression.includes("navigator.language"));
35新增: return { result: { value: { network: { status: 200 } } } };
36新增: }
37新增: assert.equal(sessionId, "settings-page-session");
38新增: assert.ok(!params.expression.includes("document.cookie"));
2539 return { result: { value: observation } };
2640 case "Target.closeTarget":
27删除: // Disposal must await the close, not merely send both commands.
28删除: await new Promise((resolve) => setImmediate(resolve));
41新增: // Context disposal must wait for the page close to complete.
42新增: await new Promise(resolve => setImmediate(resolve));
2943 pages.delete(params.targetId);
3044 return { success: true };
3145 case "Target.disposeBrowserContext":
@@ -36,26 +50,18 @@ function browser(failMethod) {
3650 contexts.delete(params.browserContextId);
3751 return {};
3852 default:
39删除: throw new Error(`Unexpected command: ${method}`);
53新增: throw new Error("Unexpected command: " + method);
4054 }
4155 };
42删除: return {
43删除: cdp,
44删除: excluded,
45删除: contexts,
46删除: pages,
47删除: observation,
48删除: unsafe: () => unsafeDisposal,
49删除: };
56新增: return { cdp, excluded, contexts, pages, observation, calls, unsafe: () => unsafeDisposal };
5057}
5158
52删除:test("successful audits close their hidden pages before disposing contexts", async () => {
53删除: const b = browser();
59新增:test("successful audits close hidden pages before disposing network contexts", async () => {
5460 for (let i = 0; i < 3; i++) {
55删除: assert.deepEqual(
56删除: await auditBrowser(b.cdp, b.excluded, false, "UTC"),
57删除: b.observation,
58删除: );
61新增: const b = browser();
62新增: assert.deepEqual(await auditBrowser(b.cdp, b.excluded, true, "UTC"), {
63新增: ...b.observation, network: { status: 200 },
64新增: });
5965 assert.equal(b.unsafe(), false);
6066 assert.equal(b.pages.size, 0);
6167 assert.equal(b.contexts.size, 0);
@@ -63,29 +69,40 @@ test("successful audits close their hidden pages before disposing contexts", asy
6369 }
6470});
6571
66删除:for (const method of [
67删除: "Target.createTarget",
68删除: "Target.attachToTarget",
69删除: "Runtime.evaluate",
70删除:]) {
71删除: test(`${method} failure still releases the audit resources safely`, async () => {
72删除: const b = browser(method);
73删除: await assert.rejects(
74删除: auditBrowser(b.cdp, b.excluded, false, "UTC"),
75删除: /injected failure/,
76删除: );
77删除: assert.equal(b.unsafe(), false);
78删除: assert.equal(b.pages.size, 0);
79删除: assert.equal(b.contexts.size, 0);
80删除: assert.equal(b.excluded.size, 0);
81删除: });
72新增:for (const method of ["Target.createTarget", "Target.attachToTarget", "Runtime.evaluate"]) {
73新增: for (const stage of ["settings", "network"]) {
74新增: test(method + " failure in " + stage + " releases its audit resources", async () => {
75新增: const b = browser(method, stage);
76新增: await assert.rejects(auditBrowser(b.cdp, b.excluded, true, "UTC"), /injected failure/);
77新增: assert.equal(b.unsafe(), false);
78新增: assert.equal(b.pages.size, 0);
79新增: assert.equal(b.contexts.size, 0);
80新增: assert.equal(b.excluded.size, 0);
81新增: });
82新增: }
8283}
8384
84删除:test("a failed page close preserves its context and keeps it out of user tabs", async () => {
85新增:test("a failed network page close preserves its context and keeps it excluded", async () => {
8586 const b = browser("Target.closeTarget");
86删除: await auditBrowser(b.cdp, b.excluded, false, "UTC");
87新增: await auditBrowser(b.cdp, b.excluded, true, "UTC");
8788 assert.equal(b.unsafe(), false);
8889 assert.equal(b.pages.size, 1);
8990 assert.equal(b.contexts.size, 1);
9091 assert.equal(b.excluded.size, 1);
9192});
93新增:
94新增:test("settings-only monitoring reads the normal profile without a network context", async () => {
95新增: const b = browser();
96新增: assert.deepEqual(await auditBrowser(b.cdp, b.excluded, false, "UTC"), b.observation);
97新增: assert.equal(b.calls.includes("Target.createBrowserContext"), false);
98新增: assert.equal(b.calls.includes("Page.navigate"), false);
99新增: assert.equal(b.pages.size, 0);
100新增: assert.equal(b.excluded.size, 0);
101新增:});
102新增:
103新增:test("a settings page that cannot close stays excluded", async () => {
104新增: const b = browser("Target.closeTarget", "settings");
105新增: await auditBrowser(b.cdp, b.excluded, false, "UTC");
106新增: assert.equal(b.pages.size, 1);
107新增: assert.ok(b.excluded.has(b.pages.get("settings-page")));
108新增:});
新增internal/cage/browser-cookies.mjs+63 −0看文件
@@ -0,0 +1,63 @@
1新增:import { createHash } from "node:crypto";
2新增:
3新增:const key = cookie => createHash("sha256").update(JSON.stringify([
4新增: cookie.name, cookie.domain, cookie.path, cookie.partitionKey || null, Boolean(cookie.partitionKeyOpaque),
5新增:])).digest("hex");
6新增:const forHost = (cookie, hostname) => cookie.domain.startsWith(".")
7新增: ? hostname === cookie.domain.slice(1) || hostname.endsWith(cookie.domain)
8新增: : hostname === cookie.domain;
9新增:
10新增:export async function browserCookies(cdp, session, tab, input) {
11新增: if (!tab || tab.login) throw new Error("当前标签不可管理 Cookie");
12新增: if (input.url !== undefined && input.url !== tab.url) throw new Error("网页已切换,请重新打开 Cookie 管理");
13新增: const { mode = "list", scope = "site", query = "", page = 0 } = input;
14新增: if (!["list", "details", "delete", "clear"].includes(mode) || !["site", "all"].includes(scope) ||
15新增: typeof query !== "string" || query.length > 200 || !Number.isInteger(page) || page < 0)
16新增: throw new Error("Cookie 操作无效");
17新增: let hostname = "";
18新增: if (scope === "site") {
19新增: const url = new URL(tab.url);
20新增: if (!["http:", "https:"].includes(url.protocol)) throw new Error("当前页面没有网站 Cookie,请选择所有网站");
21新增: hostname = url.hostname;
22新增: }
23新增: const context = tab.browserContextId ? { browserContextId: tab.browserContextId } : {};
24新增: const read = async () => {
25新增: const { cookies } = await cdp("Storage.getCookies", context);
26新增: return cookies.filter(cookie => !hostname || forHost(cookie, hostname));
27新增: };
28新增: let cookies = await read();
29新增: const remove = async cookie => {
30新增: // Opaque partition keys cannot be addressed exactly by Network.deleteCookies.
31新增: if (cookie.partitionKeyOpaque) throw new Error("此 Cookie 的分区不可单独定位,请使用清空所有网站 Cookie");
32新增: await cdp("Network.deleteCookies", {
33新增: name: cookie.name, domain: cookie.domain, path: cookie.path,
34新增: ...(cookie.partitionKey ? { partitionKey: cookie.partitionKey } : {}),
35新增: }, await session(tab.targetId));
36新增: };
37新增: if (mode === "delete" || mode === "details") {
38新增: const cookie = cookies.find(cookie => key(cookie) === input.cookieKey);
39新增: if (!cookie) throw new Error("Cookie 已变化,请刷新列表");
40新增: if (mode === "details") return { value: cookie.value };
41新增: await remove(cookie);
42新增: cookies = await read();
43新增: } else if (mode === "clear") {
44新增: if (scope === "all") await cdp("Storage.clearCookies", context);
45新增: else {
46新增: if (cookies.some(cookie => cookie.partitionKeyOpaque)) throw new Error("此网站含不可单独定位的分区 Cookie,请使用清空所有网站 Cookie");
47新增: for (const cookie of cookies) await remove(cookie);
48新增: }
49新增: cookies = await read();
50新增: }
51新增: const search = query.toLowerCase();
52新增: cookies = cookies.filter(cookie => `${cookie.domain}\n${cookie.name}`.toLowerCase().includes(search))
53新增: .sort((a, b) => a.domain.localeCompare(b.domain) || a.name.localeCompare(b.name) || a.path.localeCompare(b.path));
54新增: const current = Math.min(page, Math.max(0, Math.ceil(cookies.length / 50) - 1));
55新增: return { total: cookies.length, page: current, hostname, incognito: Boolean(tab.incognito),
56新增: cookies: cookies.slice(current * 50, (current + 1) * 50).map(({ value, ...cookie }) => ({
57新增: key: key(cookie), name: cookie.name, domain: cookie.domain, path: cookie.path,
58新增: expires: cookie.expires, session: cookie.session, secure: cookie.secure, httpOnly: cookie.httpOnly,
59新增: sameSite: cookie.sameSite || "", partitionKey: cookie.partitionKey,
60新增: partitionKeyOpaque: Boolean(cookie.partitionKeyOpaque), size: cookie.size,
61新增: })),
62新增: };
63新增:}
新增internal/cage/browser-cookies.test.mjs+45 −0看文件
@@ -0,0 +1,45 @@
1新增:import assert from 'node:assert/strict';
2新增:import test from 'node:test';
3新增:import { browserCookies } from './browser-cookies.mjs';
4新增:import { BrowserVault } from './browser-vault.mjs';
5新增:
6新增:const tab = { targetId: 'tab', url: 'https://sub.example.test/page', browserContextId: 'private-context', incognito: true };
7新增:const cookie = (domain, extra = {}) => ({ name: 'session', value: 'fixture-secret', domain, path: '/', expires: -1, session: true, ...extra });
8新增:
9新增:test('site scope includes parent domain cookies and excludes host-only parent and lookalikes', async () => {
10新增: const calls = [];
11新增: const cdp = async (method, params) => {
12新增: calls.push({ method, params });
13新增: return { cookies: [cookie('.example.test'), cookie('example.test'), cookie('sub.example.test'), cookie('.notexample.test'), cookie('other.example.test')] };
14新增: };
15新增: const result = await browserCookies(cdp, async () => 'sid', tab, { mode: 'list', scope: 'site' });
16新增: assert.deepEqual(result.cookies.map(cookie => cookie.domain), ['.example.test', 'sub.example.test']);
17新增: assert.equal(result.incognito, true);
18新增: assert.ok(result.cookies.every(cookie => !('value' in cookie)));
19新增: assert.deepEqual(calls, [{ method: 'Storage.getCookies', params: { browserContextId: 'private-context' } }]);
20新增:});
21新增:
22新增:test('opaque partitions refuse site-wide and individual deletion before any mutation', async () => {
23新增: const calls = [];
24新增: const cdp = async method => { calls.push(method); return { cookies: [cookie('sub.example.test'), cookie('sub.example.test', { partitionKeyOpaque: true })] }; };
25新增: const data = await browserCookies(cdp, async () => 'sid', tab, { mode: 'list', scope: 'site' });
26新增: await assert.rejects(browserCookies(cdp, async () => 'sid', tab, { mode: 'delete', scope: 'site', cookieKey: data.cookies.find(cookie => cookie.partitionKeyOpaque).key }), /分区/);
27新增: await assert.rejects(browserCookies(cdp, async () => 'sid', tab, { mode: 'clear', scope: 'site' }), /分区/);
28新增: assert.ok(calls.every(method => method === 'Storage.getCookies'));
29新增:});
30新增:
31新增:test('stale page or authorization tabs cannot reach cookie storage', async () => {
32新增: const cdp = () => { throw new Error('must not contact cookie storage'); };
33新增: await assert.rejects(browserCookies(cdp, null, tab, { mode: 'clear', scope: 'all', url: 'https://previous.test/' }), /网页已切换/);
34新增: await assert.rejects(browserCookies(cdp, null, { ...tab, login: true }, { mode: 'list', scope: 'all' }), /不可管理/);
35新增:});
36新增:
37新增:test('vault never attaches credential observers to private or authorization tabs', async () => {
38新增: for (const mode of ['incognito', 'login']) {
39新增: const vault = new BrowserVault({ cdp: () => { throw new Error('must not install credential observer'); }, active: () => 'tab', tab: () => ({ [mode]: true }) });
40新增: await vault.attach('tab', 'sid');
41新增: assert.equal(vault.sessions.size, 0);
42新增: await vault.request({ action: 'status', lease: 'f'.repeat(64), tab: 'tab' });
43新增: await assert.rejects(vault.request({ action: 'fill', lease: 'f'.repeat(64), tab: 'tab' }), /网页已切换/);
44新增: }
45新增:});
新增internal/cage/browser-extension-archive.py+55 −0看文件
@@ -0,0 +1,55 @@
1新增:"""Extract a user-selected extension ZIP into a newly created staging directory."""
2新增:import json
3新增:import pathlib
4新增:import stat
5新增:import re
6新增:import sys
7新增:import zipfile
8新增:
9新增:archive, destination = map(pathlib.Path, sys.argv[1:])
10新增:with zipfile.ZipFile(archive) as source:
11新增: entries = source.infolist()
12新增: if len(entries) > 3000 or sum(item.file_size for item in entries) > 128 * 1024 * 1024:
13新增: raise ValueError('扩展解压后不能超过 128 MB 或 3000 个文件')
14新增: for item in entries:
15新增: path = pathlib.PurePosixPath(item.filename)
16新增: if not item.filename or '\\' in item.filename or '\x00' in item.filename or path.is_absolute() or '..' in path.parts or ':' in path.parts[0]:
17新增: raise ValueError('扩展包包含不安全的文件路径')
18新增: if stat.S_ISLNK(item.external_attr >> 16) or item.flag_bits & 1:
19新增: raise ValueError('扩展包不能包含符号链接或加密文件')
20新增: if item.file_size > 32 * 1024 * 1024:
21新增: raise ValueError('扩展包中的单个文件不能超过 32 MB')
22新增: source.extractall(destination)
23新增:manifest_path = destination / 'manifest.json'
24新增:if not manifest_path.is_file():
25新增: candidates = list(destination.glob('*/manifest.json'))
26新增: if len(candidates) != 1:
27新增: raise ValueError('扩展包需要在根目录或单层文件夹内包含 manifest.json')
28新增: manifest_path = candidates[0]
29新增:if manifest_path.stat().st_size > 1024 * 1024:
30新增: raise ValueError('扩展配置过大')
31新增:manifest = json.loads(manifest_path.read_text(encoding='utf-8-sig'))
32新增:if re.fullmatch(r'[A-Za-z0-9_-]{1,32}', str(manifest.get('default_locale', ''))):
33新增: messages_path = manifest_path.parent / '_locales' / manifest['default_locale'] / 'messages.json'
34新增: if messages_path.is_file() and messages_path.stat().st_size < 1024 * 1024:
35新增: messages = json.loads(messages_path.read_text(encoding='utf-8-sig'))
36新增: for field in ('name', 'description'):
37新增: value = manifest.get(field, '')
38新增: if isinstance(value, str) and value.startswith('__MSG_') and value.endswith('__'):
39新增: manifest[field] = messages.get(value[6:-2], {}).get('message', value)
40新增:if manifest.get('manifest_version') != 3:
41新增: raise ValueError('仅支持 Manifest V3 的 Chromium 扩展')
42新增:if not isinstance(manifest.get('name'), str) or not manifest['name'] or not isinstance(manifest.get('version'), str):
43新增: raise ValueError('扩展缺少名称或版本')
44新增:permissions = manifest.get('permissions', [])
45新增:hosts = manifest.get('host_permissions', [])
46新增:# Content scripts can read matched pages without a separate host_permissions list.
47新增:for script in manifest.get('content_scripts', []):
48新增: hosts = hosts + script.get('matches', [])
49新增:if not all(isinstance(items, list) and len(items) <= 300 and all(isinstance(value, str) and len(value) <= 2048 for value in items) for items in [permissions, hosts]):
50新增: raise ValueError('扩展权限声明无效')
51新增:print(json.dumps({'relative': str(manifest_path.parent.relative_to(destination)),
52新增: 'name': manifest['name'][:200], 'version': manifest['version'][:100],
53新增: 'description': str(manifest.get('description', ''))[:1000],
54新增: 'key': str(manifest.get('key', ''))[:8192],
55新增: 'permissions': list(dict.fromkeys(permissions)), 'hostPermissions': list(dict.fromkeys(hosts))}, ensure_ascii=False))
新增internal/cage/browser-extensions.mjs+146 −0看文件
@@ -0,0 +1,146 @@
1新增:import { mkdirSync, readFileSync, writeFileSync, renameSync, rmSync } from 'node:fs';
2新增:import { join } from 'node:path';
3新增:import { randomUUID, createHash } from 'node:crypto';
4新增:import { execFile } from 'node:child_process';
5新增:import { promisify } from 'node:util';
6新增:import { fileURLToPath } from 'node:url';
7新增:const run = promisify(execFile);
8新增:const extensionID = /^[a-p]{32}$/;
9新增:const idFor = value => createHash('sha256').update(value).digest('hex').slice(0, 32)
10新增: .replace(/./g, char => String.fromCharCode(97 + parseInt(char, 16)));
11新增:export const extensionUploadLimit = 32 << 20;
12新增:
13新增:export class BrowserExtensions {
14新增: constructor({ directory, cdp, control, protectedID, extractArchive, idForPath = idFor }) {
15新增: this.root = join(directory, 'extensions');
16新增: this.cdp = cdp; this.control = control; this.protectedID = protectedID;
17新增: this.idForPath = idForPath;
18新增: this.extractArchive = extractArchive || (async (archive, destination) => {
19新增: const { stdout } = await run('/usr/bin/python3', [fileURLToPath(new URL('./browser-extension-archive.py', import.meta.url)), archive, destination], { maxBuffer: 1 << 20, timeout: 15000 });
20新增: return JSON.parse(stdout);
21新增: });
22新增: this.records = new Map(); this.pending = new Map();
23新增: mkdirSync(join(this.root, 'packages'), { recursive: true, mode: 0o700 });
24新增: rmSync(join(this.root, 'staging'), { recursive: true, force: true });
25新增: mkdirSync(join(this.root, 'staging'), { mode: 0o700 });
26新增: try {
27新增: for (const entry of JSON.parse(readFileSync(join(this.root, 'registry.json'), 'utf8'))) {
28新增: if (extensionID.test(entry.id) && /^[a-f0-9-]{36}$/.test(entry.package) &&
29新增: typeof entry.relative === 'string' && entry.relative !== '..' && /^[^/\\]+$/.test(entry.relative))
30新增: this.records.set(entry.id, entry);
31新增: }
32新增: } catch {}
33新增: }
34新增: persist() {
35新增: const temporary = join(this.root, 'registry.json.tmp');
36新增: writeFileSync(temporary, JSON.stringify([...this.records.values()]), { mode: 0o600 });
37新增: renameSync(temporary, join(this.root, 'registry.json'));
38新增: }
39新增: path(entry) { return join(this.root, 'packages', entry.package, entry.relative); }
40新增: async management(input) {
41新增: const evaluate = async repair => this.cdp('Runtime.evaluate', {
42新增: expression: `manageCageExtensions(${JSON.stringify(input)})`, awaitPromise: true,
43新增: returnByValue: true, userGesture: true,
44新增: }, await this.control(repair), 15000);
45新增: let response;
46新增: try { response = await evaluate(false); }
47新增: catch { response = await evaluate(true); }
48新增: if (response.exceptionDetails && /not defined|context|session/i.test(response.exceptionDetails.exception?.description || response.exceptionDetails.text || '')) response = await evaluate(true);
49新增: if (response.exceptionDetails || !response.result?.value) throw new Error('扩展操作未完成,请重试或打开 Chromium 扩展管理');
50新增: return response.result.value;
51新增: }
52新增: async restore() {
53新增: for (const entry of this.records.values()) {
54新增: if (!entry.enabled) continue;
55新增: try {
56新增: const { id } = await this.cdp('Extensions.loadUnpacked', { path: this.path(entry) });
57新增: if (id !== entry.id) throw new Error('扩展标识已变化');
58新增: entry.error = '';
59新增: } catch { entry.error = '扩展未能加载,请检查扩展文件或重新安装'; }
60新增: }
61新增: }
62新增: async upload(stream) {
63新增: if (this.pending.size >= 4) throw new Error('请先安装或取消之前选择的扩展');
64新增: const token = randomUUID(), directory = join(this.root, 'staging', token), archive = directory + '.zip';
65新增: const chunks = []; let size = 0;
66新增: try {
67新增: for await (const chunk of stream) {
68新增: size += chunk.length;
69新增: if (size > extensionUploadLimit) throw new Error('扩展 ZIP 不能超过 32 MB');
70新增: chunks.push(chunk);
71新增: }
72新增: writeFileSync(archive, Buffer.concat(chunks), { mode: 0o600 });
73新增: mkdirSync(directory, { mode: 0o700 });
74新增: const entry = await this.extractArchive(archive, directory);
75新增: this.pending.set(token, { ...entry, directory });
76新增: return { session: token, name: entry.name, version: entry.version, description: entry.description,
77新增: permissions: entry.permissions, hostPermissions: entry.hostPermissions };
78新增: } catch (error) {
79新增: rmSync(directory, { recursive: true, force: true });
80新增: throw new Error(error.stderr?.trim().split('\n').at(-1)?.replace(/^ValueError: /, '') || error.message);
81新增: } finally { rmSync(archive, { force: true }); }
82新增: }
83新增: async request(input) {
84新增: const mode = input.mode || 'list';
85新增: if (mode === 'cancel' || mode === 'install') {
86新增: const entry = this.pending.get(input.session);
87新增: if (!entry) throw new Error('扩展选择已过期,请重新选择 ZIP');
88新增: if (mode === 'cancel') {
89新增: rmSync(entry.directory, { recursive: true, force: true }); this.pending.delete(input.session);
90新增: return { ok: true };
91新增: }
92新增: const packageID = input.session, directory = join(this.root, 'packages', packageID);
93新增: if (input.target && this.records.size && [...this.records.values()].some(item => item.source === input.target)) throw new Error('此本机扩展已经导入');
94新增: const expectedID = entry.key ? idFor(Buffer.from(entry.key, 'base64')) : this.idForPath(join(directory, entry.relative));
95新增: if (expectedID === this.protectedID || this.records.has(expectedID)) throw new Error('此扩展已经安装,请先移除原有版本');
96新增: renameSync(entry.directory, directory); this.pending.delete(input.session);
97新增: let id, inserted = false;
98新增: try {
99新增: if (input.enabled === false) id = expectedID;
100新增: else ({ id } = await this.cdp('Extensions.loadUnpacked', { path: join(directory, entry.relative) }));
101新增: if (id === this.protectedID || this.records.has(id)) throw new Error('此扩展标识已存在');
102新增: const { directory: unused, key: publicKey, ...metadata } = entry;
103新增: this.records.set(id, { ...metadata, id, package: packageID, enabled: input.enabled !== false,
104新增: ...(typeof input.target === 'string' && /^[a-f0-9]{32}:[a-p]{32}$/.test(input.target) ? { source: input.target } : {}),
105新增: });
106新增: inserted = true;
107新增: this.persist();
108新增: } catch (error) {
109新增: if (inserted) this.records.delete(id);
110新增: if (id && id !== this.protectedID && !this.records.has(id)) await this.cdp('Extensions.uninstall', { id }).catch(() => {});
111新增: rmSync(directory, { recursive: true, force: true }); throw error;
112新增: }
113新增: return this.request({ mode: 'list' });
114新增: }
115新增: if (!['list', 'enable', 'disable', 'remove', 'options'].includes(mode)) throw new Error('扩展操作无效');
116新增: if (mode !== 'list' && (!extensionID.test(input.id || '') || input.id === this.protectedID)) throw new Error('扩展标识无效');
117新增: const record = this.records.get(input.id);
118新增: if (mode === 'enable' && record) {
119新增: const loaded = await this.cdp('Extensions.loadUnpacked', { path: this.path(record) });
120新增: if (loaded.id !== input.id) {
121新增: await this.cdp('Extensions.uninstall', { id: loaded.id }).catch(() => {});
122新增: throw new Error('扩展标识已变化,请重新安装');
123新增: }
124新增: }
125新增: if (mode === 'remove') {
126新增: if (!record) return { native: true, id: input.id };
127新增: const installed = (await this.management({ mode: 'list' })).items.some(item => item.id === input.id);
128新增: if (installed) await this.cdp('Extensions.uninstall', { id: input.id });
129新增: this.records.delete(input.id);
130新增: try { this.persist(); } catch (error) { this.records.set(input.id, record); throw error; }
131新增: rmSync(join(this.root, 'packages', record.package), { recursive: true, force: true });
132新增: } else if (mode !== 'list') {
133新增: const result = await this.management({ mode, id: input.id });
134新增: if (mode === 'options') return result;
135新增: if (record) { record.enabled = mode === 'enable'; record.error = ''; this.persist(); }
136新增: }
137新增: const { items } = await this.management({ mode: 'list' });
138新增: const byID = new Map(items.map(item => [item.id, { ...item, managed: this.records.has(item.id) }]));
139新增: for (const entry of this.records.values()) {
140新增: if (!byID.has(entry.id)) byID.set(entry.id, { ...entry, enabled: false, managed: true, optionsUrl: '' });
141新增: if (entry.source) byID.get(entry.id).source = entry.source;
142新增: if (entry.error) byID.get(entry.id).error = entry.error;
143新增: }
144新增: return { items: [...byID.values()].map(({ directory, package: path, relative, ...entry }) => entry) };
145新增: }
146新增:}
新增internal/cage/browser-extensions.test.mjs+26 −0看文件
@@ -0,0 +1,26 @@
1新增:import assert from 'node:assert/strict';
2新增:import test from 'node:test';
3新增:import { execFileSync } from 'node:child_process';
4新增:import { mkdtemp, access, rm } from 'node:fs/promises';
5新增:import { join } from 'node:path';
6新增:import { tmpdir } from 'node:os';
7新增:import { Readable } from 'node:stream';
8新增:import { BrowserExtensions } from './browser-extensions.mjs';
9新增:
10新增:for (const kind of ['traversal', 'symlink', 'legacy']) test(`extension ZIP refuses ${kind} before installation`, async () => {
11新增: const root = await mkdtemp(join(tmpdir(), 'cage-extension-archive-'));
12新增: try {
13新增: const bytes = execFileSync('uv', ['run', '--no-project', 'python', '-c', `import io,json,stat,sys,zipfile
14新增:b=io.BytesIO()
15新增:with zipfile.ZipFile(b,'w') as z:
16新增: z.writestr('manifest.json',json.dumps({'manifest_version':2 if sys.argv[1]=='legacy' else 3,'name':'Fixture','version':'1.0'}))
17新增: if sys.argv[1]=='traversal':z.writestr('../outside','blocked')
18新增: if sys.argv[1]=='symlink':
19新增: link=zipfile.ZipInfo('link');link.create_system=3;link.external_attr=(stat.S_IFLNK|0o777)<<16;z.writestr(link,'/etc/passwd')
20新增:sys.stdout.buffer.write(b.getvalue())`, kind], { stdio: ['ignore', 'pipe', 'ignore'] });
21新增: const manager = new BrowserExtensions({ directory: root, cdp: () => { throw new Error('must not install rejected ZIP'); }, control: null, protectedID: 'a'.repeat(32) });
22新增: await assert.rejects(manager.upload(Readable.from([bytes])), /路径|符号链接|Manifest V3/);
23新增: assert.equal(manager.pending.size, 0);
24新增: await assert.rejects(access(join(root, 'extensions/staging/outside')));
25新增: } finally { await rm(root, { recursive: true, force: true }); }
26新增:});
修改internal/cage/browser-login.mjs+3 −2看文件
@@ -28,8 +28,9 @@ export class LoginBrowser {
2828 expiry.unref();
2929 this.contexts.set(browserContextId, { login, expiry });
3030 try {
31删除: const { targetId } = await this.cdp("Target.createTarget", { browserContextId, url: url.href, newWindow: true });
32删除: await activate({ targetId, browserContextId, type: "page", url: url.href });
31新增: const { targetId } = await this.cdp("Target.createTarget", { browserContextId, url: "about:blank", newWindow: true });
32新增: const sessionId = await activate({ targetId, browserContextId, type: "page", url: url.href });
33新增: await this.cdp("Page.navigate", { url: url.href }, sessionId);
3334 return { id: targetId };
3435 } catch {
3536 await this.close(browserContextId);
修改internal/cage/browser-login.test.mjs+7 −2看文件
@@ -5,9 +5,13 @@ import { LoginBrowser } from "./browser-login.mjs";
55test("login redirects and popups stay private, closing one login leaves the other open", async () => {
66 const closed = [];
77 let contexts = 0;
8删除: const browser = new LoginBrowser(async (method, params) => {
8新增: const browser = new LoginBrowser(async (method, params, sessionId) => {
99 if (method === "Target.createBrowserContext") return { browserContextId: String(++contexts) };
10删除: if (method === "Target.createTarget") return { targetId: "tab-" + params.browserContextId };
10新增: if (method === "Target.createTarget") {
11新增: assert.equal(params.url, "about:blank", "login must be prepared before navigation");
12新增: return { targetId: "tab-" + params.browserContextId };
13新增: }
14新增: if (method === "Page.navigate") assert.equal(sessionId, "prepared-page");
1115 if (method === "Target.disposeBrowserContext") closed.push(params.browserContextId);
1216 });
1317 const page = { url: "https://claude.ai/oauth/authorize?state=secret", title: "secret" };
@@ -15,6 +19,7 @@ test("login redirects and popups stay private, closing one login leaves the othe
1519 for (const id of ["a", "b"]) {
1620 await browser.open(id.repeat(24), page.url, async tab => {
1721 assert.equal(browser.tab(tab).url, "https://claude.ai");
22新增: return "prepared-page";
1823 });
1924 }
2025 const popup = { ...page, targetId: "popup", browserContextId: "1", url: "http://localhost:9123/callback?code=secret" };
新增internal/cage/browser-phone-desktop.mjs+33 −0看文件
@@ -0,0 +1,33 @@
1新增:// The fixed sudo helper checks the host-minted lease and drops privileges
2新增:// before attaching a phone view to the existing desktop application.
3新增:import { spawn } from "node:child_process";
4新增:
5新增:export async function phoneDesktop(op, input) {
6新增: const child = spawn("/usr/bin/sudo", ["-n", "/usr/local/lib/cage-phone-desktop/control.py"],
7新增: { stdio: ["pipe", "pipe", "ignore"] });
8新增: let size = 0;
9新增: const chunks = [];
10新增: const timeout = setTimeout(() => child.kill("SIGKILL"), 12500);
11新增: try {
12新增: const output = await new Promise((resolve, reject) => {
13新增: child.on("error", reject);
14新增: child.stdout.on("data", chunk => {
15新增: size += chunk.length;
16新增: if (size > 3600000) child.kill("SIGKILL");
17新增: else chunks.push(chunk);
18新增: });
19新增: child.stdin.on("error", () => {});
20新增: child.once("close", code => {
21新增: if (code !== 0 || !size || size > 3600000) reject(new Error("手机 Desktop 服务不可用"));
22新增: else resolve(Buffer.concat(chunks));
23新增: });
24新增: child.stdin.end(JSON.stringify({ ...input, op }) + "\n");
25新增: });
26新增: const result = JSON.parse(output);
27新增: if (result.status) {
28新增: const status = [400, 403, 409, 410, 412, 501, 503].includes(result.status) ? result.status : 503;
29新增: throw Object.assign(new Error("手机 Desktop 操作未完成"), { status });
30新增: }
31新增: return result;
32新增: } finally { clearTimeout(timeout); }
33新增:}
新增internal/cage/browser-phone-network.mjs+115 −0看文件
@@ -0,0 +1,115 @@
1新增:// Chromium's own loopback bypass is disabled. Pin each connection to the
2新增:// checked IPv4 from the guest resolver, including redirects and subresources.
3新增:// The guest's existing Cage network gate still controls these sockets.
4新增:import { resolve4 } from "node:dns/promises";
5新增:import { once } from "node:events";
6新增:import net from "node:net";
7新增:import { networkInterfaces } from "node:os";
8新增:
9新增:const reserved = new net.BlockList();
10新增:for (const [address, prefix] of [
11新增: ["0.0.0.0", 8], ["10.0.0.0", 8], ["100.64.0.0", 10],
12新增: ["127.0.0.0", 8], ["169.254.0.0", 16], ["172.16.0.0", 12],
13新增: ["192.0.0.0", 24], ["192.0.2.0", 24], ["192.88.99.0", 24],
14新增: ["192.168.0.0", 16], ["198.18.0.0", 15], ["198.51.100.0", 24],
15新增: ["203.0.113.0", 24], ["224.0.0.0", 3],
16新增:]) reserved.addSubnet(address, prefix);
17新增:
18新增:function publicIPv4(ip) {
19新增: return net.isIPv4(ip) && !reserved.check(ip);
20新增:}
21新增:
22新增:function publicName(name) {
23新增: if (net.isIP(name)) return publicIPv4(name);
24新增: return name.length <= 253 && name.includes(".") &&
25新增: !/(^|\.)(localhost|local|internal|home\.arpa)$/.test(name) &&
26新增: name.split(".").every(label => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(label));
27新增:}
28新增:
29新增:export function phoneError(status, message) {
30新增: return Object.assign(new Error(message), { status });
31新增:}
32新增:
33新增:export function webAddress(value) {
34新增: if (typeof value !== "string" || value.length > 16384) throw new Error("请输入有效的网址");
35新增: let url;
36新增: try { url = new URL(value); } catch { throw new Error("请输入有效的网址"); }
37新增: if (!["http:", "https:"].includes(url.protocol) || url.username || url.password ||
38新增: !publicName(url.hostname.toLowerCase().replace(/\.$/, ""))) {
39新增: throw phoneError(403, "手机浏览器仅支持公网 HTTP 或 HTTPS 网址");
40新增: }
41新增: return url.href;
42新增:}
43新增:
44新增:async function internetSocket(name, port) {
45新增: if (!publicName(name)) throw new Error("非公网地址");
46新增: const ips = net.isIPv4(name) ? [name] : await resolve4(name);
47新增: const local = new Set(Object.values(networkInterfaces()).flat().map(info => info.address));
48新增: if (!ips.length || !ips.every(ip => publicIPv4(ip) && !local.has(ip))) throw new Error("非公网地址");
49新增: const socket = net.createConnection({ host: ips[0], port, family: 4 });
50新增: socket.setTimeout(12000, () => socket.destroy(new Error("连接超时")));
51新增: await once(socket, "connect");
52新增: socket.setTimeout(0);
53新增: socket.removeAllListeners("timeout");
54新增: return socket;
55新增:}
56新增:
57新增:// Only SOCKS5 CONNECT is implemented. UDP, BIND, and IPv6 are refused.
58新增:export async function startPhoneProxy(connect = internetSocket) {
59新增: const sockets = new Set();
60新增: const server = net.createServer({ pauseOnConnect: true }, client => {
61新增: sockets.add(client);
62新增: client.once("close", () => sockets.delete(client));
63新增: client.on("error", () => client.destroy());
64新增: client.setTimeout(15000, () => client.destroy());
65新增: async function handshake() {
66新增: const reader = client.iterator({ destroyOnReturn: false });
67新增: let buffer = Buffer.alloc(0);
68新增: async function take(length) {
69新增: while (buffer.length < length) {
70新增: const next = await reader.next();
71新增: if (next.done) throw new Error("连接中断");
72新增: buffer = Buffer.concat([buffer, next.value]);
73新增: }
74新增: const head = buffer.subarray(0, length);
75新增: buffer = buffer.subarray(length);
76新增: return head;
77新增: }
78新增: let remote;
79新增: try {
80新增: const [version, methodCount] = await take(2);
81新增: if (version !== 5 || !(await take(methodCount)).includes(0)) throw new Error("协议不支持");
82新增: client.write(Buffer.from([5, 0]));
83新增: const [nextVersion, command, zero, family] = await take(4);
84新增: if (nextVersion !== 5 || command !== 1 || zero !== 0 || ![1, 3].includes(family)) throw new Error("协议不支持");
85新增: const name = family === 1 ? [...await take(4)].join(".") :
86新增: (await take((await take(1))[0])).toString("latin1").toLowerCase().replace(/\.$/, "");
87新增: const port = (await take(2)).readUInt16BE();
88新增: if (!port || !publicName(name)) throw new Error("目标不可用");
89新增: remote = await connect(name, port);
90新增: remote.on("error", () => client.destroy());
91新增: if (client.destroyed) throw new Error("连接已关闭");
92新增: sockets.add(remote);
93新增: remote.once("close", () => { sockets.delete(remote); client.destroy(); });
94新增: client.once("close", () => remote.destroy());
95新增: await reader.return();
96新增: client.setTimeout(0);
97新增: client.write(Buffer.from([5, 0, 0, 1, 0, 0, 0, 0, 0, 0]));
98新增: if (buffer.length) remote.write(buffer);
99新增: client.pipe(remote);
100新增: remote.pipe(client);
101新增: } catch {
102新增: remote?.destroy();
103新增: client.destroy();
104新增: }
105新增: }
106新增: void handshake();
107新增: });
108新增: server.maxConnections = 128;
109新增: server.listen(0, "127.0.0.1");
110新增: await once(server, "listening");
111新增: return {
112新增: port: server.address().port,
113新增: close() { server.close(); for (const socket of sockets) socket.destroy(); },
114新增: };
115新增:}
新增internal/cage/browser-phone.mjs+309 −0看文件
@@ -0,0 +1,309 @@
1新增:// One displayed page and private debugging pipe per active phone browser.
2新增:// The desktop process, its targets and its profile are never attached here.
3新增:import { spawn } from "node:child_process";
4新增:import { createHash } from "node:crypto";
5新增:import { mkdir, readFile, writeFile, rename } from "node:fs/promises";
6新增:import { join } from "node:path";
7新增:import { phoneError, startPhoneProxy, webAddress } from "./browser-phone-network.mjs";
8新增:
9新增:const idleTimeout = 2 * 60 * 1000;
10新增:const validID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
11新增:const keys = new Map([
12新增: ["Enter", 13], ["Tab", 9], ["Escape", 27], ["Backspace", 8], ["Delete", 46],
13新增: ["ArrowLeft", 37], ["ArrowUp", 38], ["ArrowRight", 39], ["ArrowDown", 40],
14新增:]);
15新增:
16新增:function dimensions({ width, height }) {
17新增: if (!Number.isInteger(width) || width < 240 || width > 1440 ||
18新增: !Number.isInteger(height) || height < 160 || height > 1600) throw new Error("手机视口大小无效");
19新增: return { width, height };
20新增:}
21新增:
22新增:class BrowserPipe {
23新增: constructor(binary, args) {
24新增: this.calls = new Map();
25新增: this.sequence = 0;
26新增: this.process = spawn(binary, args, { stdio: ["ignore", "ignore", "ignore", "pipe", "pipe"] });
27新增: this.closed = new Promise(resolve => this.process.once("close", resolve));
28新增: let buffered = [];
29新增: const disconnected = () => {
30新增: this.dead = true;
31新增: for (const call of this.calls.values()) call.reject(phoneError(410, "远程浏览器已关闭"));
32新增: this.calls.clear();
33新增: this.process.kill();
34新增: };
35新增: this.process.on("error", disconnected);
36新增: this.process.once("exit", disconnected);
37新增: for (const stream of this.process.stdio.slice(3)) stream.on("error", disconnected);
38新增: this.process.stdio[4].on("data", data => {
39新增: let end;
40新增: while ((end = data.indexOf(0)) !== -1) {
41新增: buffered.push(data.subarray(0, end));
42新增: let event;
43新增: try { event = JSON.parse(Buffer.concat(buffered)); } catch { disconnected(); return; }
44新增: data = data.subarray(end + 1);
45新增: buffered = [];
46新增: if (!event.id) { this.onEvent?.(event); continue; }
47新增: const call = this.calls.get(event.id);
48新增: if (!call) continue;
49新增: this.calls.delete(event.id);
50新增: if (event.error) call.reject(new Error("Chromium 暂时无法完成此操作"));
51新增: else call.resolve(event.result);
52新增: }
53新增: if (data.length) buffered.push(data);
54新增: });
55新增: }
56新增: async send(method, params = {}, sessionId) {
57新增: if (this.dead) throw phoneError(410, "远程浏览器已关闭");
58新增: const id = ++this.sequence;
59新增: let timer;
60新增: try {
61新增: return await new Promise((resolve, reject) => {
62新增: // The first CDP command includes macOS Chrome's cold process startup.
63新增: let timeout = method === "Page.navigate" || method === "Page.navigateToHistoryEntry" ? 12000 : 4500;
64新增: if (method === "Target.getTargets" && process.platform === "darwin") timeout = 75000;
65新增: timer = setTimeout(() => reject(new Error("远程浏览器操作超时")), timeout);
66新增: this.calls.set(id, { resolve, reject });
67新增: this.process.stdio[3].write(JSON.stringify({ id, method, params, sessionId }) + "\0");
68新增: });
69新增: } finally { clearTimeout(timer); this.calls.delete(id); }
70新增: }
71新增: async close() {
72新增: if (!this.dead) void this.send("Browser.close").catch(() => {});
73新增: const timeout = setTimeout(() => this.process.kill("SIGKILL"), 1800);
74新增: try { await this.closed; } finally { clearTimeout(timeout); }
75新增: }
76新增:}
77新增:
78新增:// Executed in an isolated world in the current top-level document. A password
79新增:// only enters the page through Input.insertText; no field value is inspected.
80新增:const inspectFocus = `(() => {
81新增: let node = document.activeElement;
82新增: while (node?.shadowRoot?.activeElement) node = node.shadowRoot.activeElement;
83新增: const input = node instanceof HTMLInputElement;
84新增: const editable = node && !node.readOnly && !node.disabled &&
85新增: (node.isContentEditable || node instanceof HTMLTextAreaElement ||
86新增: (input && ["text","email","search","url","tel","password","number"].includes(node.type)));
87新增: if (!editable) return { focus: "", password: false };
88新增: const ids = globalThis.cageInputs ??= new WeakMap();
89新增: if (!ids.has(node)) ids.set(node, String(globalThis.cageSequence = (globalThis.cageSequence || 0) + 1));
90新增: return { focus: ids.get(node), password: input && node.type === "password" };
91新增:})()`;
92新增:
93新增:async function saveLanguage(profile, language) {
94新增: const directory = join(profile, "Default");
95新增: await mkdir(directory, { recursive: true, mode: 0o700 });
96新增: const file = join(directory, "Preferences");
97新增: let settings = {};
98新增: try { settings = JSON.parse(await readFile(file, "utf8")); }
99新增: catch (error) { if (error.code !== "ENOENT") throw new Error("手机浏览器资料暂时无法读取"); }
100新增: settings.intl ??= {};
101新增: settings.intl.accept_languages = language;
102新增: settings.intl.selected_languages = language;
103新增: const next = file + ".phone-next";
104新增: await writeFile(next, JSON.stringify(settings), { mode: 0o600 });
105新增: await rename(next, file);
106新增:}
107新增:
108新增:export class PhoneBrowser {
109新增: constructor({ binary = "/usr/bin/chromium", directory = "/home/cage-browser/phone-profiles",
110新增: language = process.env.CAGE_LANGUAGE || "en-US", connect, pipeFactory } = {}) {
111新增: this.binary = binary;
112新增: this.directory = directory;
113新增: this.language = language;
114新增: this.connect = connect;
115新增: this.pipeFactory = pipeFactory ?? ((binary, args) => new BrowserPipe(binary, args));
116新增: this.queue = Promise.resolve();
117新增: this.pending = 0;
118新增: }
119新增: run(operation, input, signal) {
120新增: // Serialize screenshot/context checks with all layout and input changes.
121新增: if (this.pending >= 12) return Promise.reject(new Error("手机浏览器正在处理上一项操作"));
122新增: this.pending++;
123新增: const task = this.queue.then(() => this.perform(operation, input, signal));
124新增: this.queue = task.catch(() => {}).finally(() => { this.pending--; });
125新增: return task;
126新增: }
127新增: async perform(operation, input, signal) {
128新增: if (!input || !validID.test(input.id)) throw new Error("手机浏览器会话无效");
129新增: if (operation === "open") {
130新增: const size = dimensions(input);
131新增: if (typeof input.profile !== "string" || !/^[a-f0-9]{64}$/.test(input.profile)) throw new Error("手机浏览器资料无效");
132新增: const url = input.url ? webAddress(input.url) : "";
133新增: if (!this.session) {
134新增: try { await this.open(input.id, input.profile, size, url, signal); }
135新增: catch (error) {
136新增: if (error.status === 403 || error.status === 409) throw error;
137新增: throw phoneError(503, "客机浏览器暂时无法启动,请稍后重新打开");
138新增: }
139新增: }
140新增: else if (input.profile !== this.session.profile) throw phoneError(409, "另一部手机正在使用浏览器");
141新增: }
142新增: const s = this.session;
143新增: if (!s || s.id !== input.id) throw phoneError(410, "手机浏览器会话已结束,请重新打开");
144新增: clearTimeout(this.timer);
145新增: this.timer = setTimeout(() => { void this.run("close", { id: s.id }).catch(() => {}); }, idleTimeout).unref();
146新增: if (operation === "open") return { id: s.id };
147新增: if (operation === "frame") return this.frame(s, input.after);
148新增: if (operation === "action") {
149新增: await this.action(s, input);
150新增: if (input.return_frame === true) {
151新增: // Navigation can invalidate the screenshot context after the input was
152新增: // delivered. Acknowledge the input so the phone retries only the frame.
153新增: try { return await this.frame(s); } catch { return { id: s.id }; }
154新增: }
155新增: } else if (operation === "close") await this.dispose(s);
156新增: else throw new Error("未知的手机浏览器操作");
157新增: return { id: input.id };
158新增: }
159新增: async open(id, profile, size, url, signal) {
160新增: const data = join(this.directory, profile);
161新增: await saveLanguage(data, this.language);
162新增: const proxy = await startPhoneProxy(this.connect);
163新增: let pipe;
164新增: try { pipe = await this.pipeFactory(this.binary, [
165新增: "--headless=new", "--disable-extensions", "--disable-quic", "--disable-background-networking",
166新增: "--no-first-run", "--no-default-browser-check", "--disable-session-crashed-bubble",
167新增: "--disable-sync", "--disable-dev-shm-usage", "--remote-debugging-pipe",
168新增: "--force-webrtc-ip-handling-policy=disable_non_proxied_udp",
169新增: "--proxy-server=socks5://127.0.0.1:" + proxy.port, "--proxy-bypass-list=<-loopback>",
170新增: "--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1",
171新增: "--lang=" + this.language, "--accept-lang=" + this.language, "--user-data-dir=" + data, "about:blank",
172新增: ]); } catch (error) { proxy.close(); throw error; }
173新增: const s = { id, profile, ...size, pipe, proxy };
174新增: this.session = s;
175新增: let stopping;
176新增: const stop = () => { stopping ??= this.dispose(s); };
177新增: signal?.addEventListener("abort", stop, { once: true });
178新增: pipe.closed.then(() => {
179新增: proxy.close();
180新增: if (this.session === s) { this.session = null; clearTimeout(this.timer); }
181新增: });
182新增: try {
183新增: signal?.throwIfAborted();
184新增: const { targetInfos } = await pipe.send("Target.getTargets");
185新增: const target = targetInfos.find(t => t.type === "page" && t.url === "about:blank");
186新增: if (!target) throw phoneError(503, "客机浏览器尚未就绪,请稍后重新打开");
187新增: s.targetId = target.targetId;
188新增: const { sessionId } = await pipe.send("Target.attachToTarget", { targetId: target.targetId, flatten: true });
189新增: s.send = (method, params) => pipe.send(method, params, sessionId);
190新增: pipe.onEvent = ({ method, params, sessionId: src }) => {
191新增: if (method === "Target.targetCreated" && params.targetInfo.type === "page" && params.targetInfo.targetId !== target.targetId)
192新增: void pipe.send("Target.closeTarget", { targetId: params.targetInfo.targetId }).catch(() => {});
193新增: if (src === sessionId && method === "Page.javascriptDialogOpening")
194新增: void s.send("Page.handleJavaScriptDialog", { accept: false }).catch(() => {});
195新增: };
196新增: await pipe.send("Target.setDiscoverTargets", { discover: true });
197新增: await pipe.send("Browser.setDownloadBehavior", { behavior: "deny" });
198新增: await s.send("Page.enable");
199新增: // Some sites select their layout on the first HTTP request. Device
200新增: // metrics alone still send Chromium's desktop UA and mobile hint.
201新增: const { userAgent } = await pipe.send("Browser.getVersion");
202新增: const platform = process.platform === "darwin" ? "macOS" : process.platform === "win32" ? "Windows" : "Linux";
203新增: await s.send("Emulation.setUserAgentOverride", {
204新增: userAgent: userAgent.replace(" Safari/", " Mobile Safari/"),
205新增: // Chromium supplies its own brands and full versions when omitted.
206新增: userAgentMetadata: { platform, platformVersion: "", architecture: "", model: "", mobile: true, formFactors: ["Mobile"] },
207新增: });
208新增: await s.send("Page.setInterceptFileChooserDialog", { enabled: true });
209新增: await this.resize(s, size);
210新增: await s.send("Emulation.setTouchEmulationEnabled", { enabled: true, maxTouchPoints: 1 });
211新增: if (url) await s.send("Page.navigate", { url });
212新增: } catch (error) { await (stopping ?? this.dispose(s)); throw error; }
213新增: finally { signal?.removeEventListener("abort", stop); }
214新增: }
215新增: async dispose(s = this.session) {
216新增: if (!s) return;
217新增: clearTimeout(this.timer);
218新增: s.proxy.close();
219新增: await s.pipe.close();
220新增: if (this.session === s) this.session = null;
221新增: }
222新增: async resize(s, size) {
223新增: // Keep the page in phone CSS pixels, with enough image pixels for legible
224新增: // text. Cap the raster size so a tablet frame still fits the paired link.
225新增: const density = Math.max(1, Math.min(2, Math.sqrt(2_000_000 / (size.width * size.height))));
226新增: await s.send("Emulation.setDeviceMetricsOverride", { ...size, screenWidth: size.width, screenHeight: size.height,
227新增: deviceScaleFactor: density, mobile: true });
228新增: Object.assign(s, size);
229新增: }
230新增: async document(s) {
231新增: const [{ frameTree: { frame } }, { cssVisualViewport: viewport }] = await Promise.all([
232新增: s.send("Page.getFrameTree"), s.send("Page.getLayoutMetrics"),
233新增: ]);
234新增: const failed = frame.url === "chrome-error://chromewebdata/";
235新增: const url = frame.url === "about:blank" ? "" : webAddress(failed ? frame.unreachableUrl : frame.url + (frame.urlFragment || ""));
236新增: const token = createHash("sha256").update(JSON.stringify([frame.loaderId, url, s.width, s.height,
237新增: viewport.scale, viewport.offsetX, viewport.offsetY])).digest("hex");
238新增: return { url, token, failed, scale: viewport.scale, frameId: frame.id, loaderId: frame.loaderId };
239新增: }
240新增: async focus(s, { frameId, loaderId }) {
241新增: const { executionContextId } = await s.send("Page.createIsolatedWorld", { frameId, worldName: "CagePhone" });
242新增: const result = await s.send("Runtime.evaluate", { expression: inspectFocus, contextId: executionContextId, returnByValue: true });
243新增: const field = result.result.value;
244新增: if (!field?.focus) return { focus: "", password: false };
245新增: // Opening the phone keyboard changes the frame geometry, but the same
246新增: // DOM input and its draft remain valid until the document or focus changes.
247新增: const token = createHash("sha256").update(JSON.stringify([frameId, loaderId, field.focus])).digest("hex");
248新增: return { focus: token, password: field.password };
249新增: }
250新增: async frame(s, previousTag) {
251新增: const before = await this.document(s);
252新增: const [picture, info, focus] = await Promise.all([
253新增: s.send("Page.captureScreenshot", { format: "jpeg", quality: 70, captureBeyondViewport: false }),
254新增: s.pipe.send("Target.getTargetInfo", { targetId: s.targetId }),
255新增: before.failed ? { focus: "", password: false } : this.focus(s, before),
256新增: ]);
257新增: const after = await this.document(s);
258新增: if (before.token !== after.token) throw phoneError(409, "页面正在切换,请重新读取画面");
259新增: if (!picture.data || picture.data.length > 2500000) throw new Error("远程画面过大,请减小视口");
260新增: const metadata = { id: s.id, url: after.url, title: info.targetInfo.title.slice(0, 512), width: s.width,
261新增: height: s.height, document: after.token, ...focus };
262新增: const tag = createHash("sha256").update(JSON.stringify(metadata)).update(picture.data, "ascii").digest("hex").slice(0, 32);
263新增: if (previousTag === tag) return { id: s.id, frame_tag: tag, unchanged: true };
264新增: return { ...metadata, frame_tag: tag, image: picture.data };
265新增: }
266新增: async action(s, input) {
267新增: const { type } = input;
268新增: if (type === "resize") return this.resize(s, dimensions(input));
269新增: if (type === "navigate") return s.send("Page.navigate", { url: webAddress(input.url) });
270新增: const doc = await this.document(s);
271新增: if (doc.token !== input.document) throw phoneError(409, "页面已切换,请重新读取画面");
272新增: if (type === "back" || type === "forward") {
273新增: const history = await s.send("Page.getNavigationHistory");
274新增: const entry = history.entries[history.currentIndex + (type === "back" ? -1 : 1)];
275新增: if (entry) { if (entry.url !== "about:blank") webAddress(entry.url); await s.send("Page.navigateToHistoryEntry", { entryId: entry.id }); }
276新增: return;
277新增: }
278新增: if (type === "reload") return s.send("Page.reload");
279新增: if (doc.failed) throw new Error("网页加载失败,请检查地址或重新载入");
280新增: if (type === "text" || type === "key") {
281新增: if (type === "text" || input.key === "Enter" || input.focus) {
282新增: const actual = await this.focus(s, doc);
283新增: if (!actual.focus || actual.focus !== input.focus) throw phoneError(409, "输入框已改变,请重新点选");
284新增: }
285新增: if (type === "text") {
286新增: if (typeof input.text !== "string" || !input.text || Buffer.byteLength(input.text) > 8192) throw new Error("输入文字无效");
287新增: return s.send("Input.insertText", { text: input.text });
288新增: }
289新增: const code = keys.get(input.key);
290新增: if (!code) throw new Error("按键不受支持");
291新增: const key = { key: input.key, code: input.key, windowsVirtualKeyCode: code };
292新增: await s.send("Input.dispatchKeyEvent", { ...key, type: "keyDown", ...(input.key === "Enter" ? { text: "\r" } : {}) });
293新增: await s.send("Input.dispatchKeyEvent", { ...key, type: "keyUp" });
294新增: return;
295新增: }
296新增: if (!Number.isFinite(input.x) || !Number.isFinite(input.y) ||
297新增: input.x < 0 || input.y < 0 || input.x >= s.width || input.y >= s.height) throw new Error("触点不在当前画面内");
298新增: // CDP takes CSS coordinates; pages without a viewport meta tag can
299新增: // render a 980px layout scaled down into a 390px phone image.
300新增: const x = input.x / doc.scale, y = input.y / doc.scale;
301新增: if (type === "tap") {
302新增: await s.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: [{ x, y }] });
303新增: await s.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] });
304新增: } else if (type === "scroll") {
305新增: if (![input.dx, input.dy].every(n => Number.isFinite(n) && Math.abs(n) <= 3200)) throw new Error("滚动距离无效");
306新增: await s.send("Input.dispatchMouseEvent", { type: "mouseWheel", x, y, deltaX: input.dx / doc.scale, deltaY: input.dy / doc.scale });
307新增: } else throw new Error("未知的浏览器动作");
308新增: }
309新增:}
新增internal/cage/browser-phone.test.mjs+210 −0看文件
@@ -0,0 +1,210 @@
1新增:import assert from "node:assert/strict";
2新增:import { once } from "node:events";
3新增:import { mkdtemp, rm, writeFile } from "node:fs/promises";
4新增:import http from "node:http";
5新增:import net from "node:net";
6新增:import { tmpdir } from "node:os";
7新增:import { join } from "node:path";
8新增:import { randomUUID } from "node:crypto";
9新增:import { setTimeout as delay } from "node:timers/promises";
10新增:import test from "node:test";
11新增:import { PhoneBrowser } from "./browser-phone.mjs";
12新增:import { webAddress } from "./browser-phone-network.mjs";
13新增:import { pathToFileURL } from "node:url";
14新增:import { playwrightPhonePipe } from "../../scripts/guest-os/windows-phone-browser.mjs";
15新增:
16新增:test("phone navigation accepts public web URLs", () => {
17新增: for (const url of ["file:///tmp/file", "chrome://settings", "http://2130706433", "http://10.0.0.1",
18新增: "http://localhost./", "http://db.internal", "http://[::1]", "https://user:[email protected]"]) {
19新增: assert.throws(() => webAddress(url));
20新增: }
21新增: assert.equal(webAddress("https://example.org/path"), "https://example.org/path");
22新增:});
23新增:
24新增:test("a failed Chromium launch reports an unavailable browser and releases the session", async t => {
25新增: const directory = await mkdtemp(join(tmpdir(), "cage-phone-launch-"));
26新增: t.after(() => rm(directory, { recursive: true, force: true }));
27新增: const phone = new PhoneBrowser({ binary: join(directory, "missing-browser"), directory });
28新增: const id = randomUUID();
29新增: await assert.rejects(phone.run("open", { id, profile: "a".repeat(64), width: 390, height: 640 }), { status: 503 });
30新增: await assert.rejects(phone.run("frame", { id }), { status: 410 });
31新增: await writeFile(join(directory, "b".repeat(64)), "not a profile directory");
32新增: await assert.rejects(phone.run("open", { id, profile: "b".repeat(64), width: 390, height: 640 }), { status: 503 });
33新增:});
34新增:
35新增:// CAGE_TEST_CHROMIUM points at an installed, sandboxed Chromium. Only the
36新增:// fixture hostname is mapped to loopback; Chromium uses the production SOCKS
37新增:// listener, including its denial of requests for private literal addresses.
38新增:test("real phone Chromium routes, resizes, types, and keeps paired profiles separate",
39新增: { skip: !process.env.CAGE_TEST_CHROMIUM }, async t => {
40新增: const directory = await mkdtemp(join(tmpdir(), "cage-phone-browser-"));
41新增: t.after(() => rm(directory, { recursive: true, force: true }));
42新增: const seen = [];
43新增: let acceptLanguage;
44新增: const site = http.createServer((req, res) => {
45新增: seen.push(req.url);
46新增: if (req.url === "/remember" || req.url === "/restored") acceptLanguage = req.headers["accept-language"];
47新增: if (req.url === "/private") {
48新增: res.writeHead(302, { Location: `http://127.0.0.1:${site.address().port}/forbidden` });
49新增: return res.end();
50新增: }
51新增: if (req.url === "/private-ws") {
52新增: res.setHeader("Content-Type", "text/html; charset=utf-8");
53新增: return res.end(`<meta name="viewport" content="width=device-width,initial-scale=1"><script>
54新增: const socket=new WebSocket('ws://127.0.0.1:${site.address().port}/forbidden-ws');
55新增: document.title=JSON.stringify([innerWidth,innerHeight,'ws-attempted']);
56新增: </script>`);
57新增: }
58新增: if (req.url === "/remember") res.setHeader("Set-Cookie", "state=known; Path=/; Max-Age=3600");
59新增: res.setHeader("Content-Type", "text/html; charset=utf-8");
60新增: if (req.url === "/wide") return res.end(`<style>body{margin:0}input{position:absolute;left:450px;top:40px;width:200px;height:48px}</style>
61新增: <input><script>onload = () => document.title = JSON.stringify([innerWidth,visualViewport.scale]);</script>`);
62新增: res.end(`<meta name="viewport" content="width=device-width,initial-scale=1">
63新增: <style>body{margin:0;height:320vh}input{display:block;width:200px;height:50px}</style>
64新增: <input aria-label="draft"><input type=password aria-label="password">
65新增: <script>
66新增: const show = () => document.title = JSON.stringify([innerWidth, innerHeight,
67新增: document.querySelector("input").value, document.cookie, scrollY, navigator.maxTouchPoints, navigator.language, Intl.DateTimeFormat().resolvedOptions().timeZone, devicePixelRatio]);
68新增: oninput = onresize = onscroll = show; show();
69新增: </script>`);
70新增: });
71新增: site.listen(0, "127.0.0.1");
72新增: site.on("upgrade", (request, socket) => { seen.push(request.url); socket.destroy(); });
73新增: await once(site, "listening");
74新增: t.after(() => site.close());
75新增: const chromium = process.env.CAGE_TEST_PHONE_PLAYWRIGHT ? (await import(pathToFileURL(process.env.CAGE_TEST_PHONE_PLAYWRIGHT))).chromium : null;
76新增: const browser = new PhoneBrowser({
77新增: directory, binary: process.env.CAGE_TEST_CHROMIUM, language: "ja-JP",
78新增: connect: async (name, port) => {
79新增: if (name !== "phone.example" || port !== site.address().port) throw new Error("fixture denies destination");
80新增: const socket = net.connect({ host: "127.0.0.1", port });
81新增: await once(socket, "connect");
82新增: return socket;
83新增: },
84新增: ...(chromium ? { pipeFactory: (binary, args) => playwrightPhonePipe(chromium, binary, args) } : {}),
85新增: });
86新增: t.after(() => browser.dispose());
87新增: let id = randomUUID();
88新增: const url = `http://phone.example:${site.address().port}`;
89新增: const open = (profile, path = "/") => browser.run("open", { id, profile, url: url + path, width: 390, height: 750 });
90新增: const action = (type, extra) => browser.run("action", { id, type, ...extra });
91新增: async function read(check = () => true) {
92新增: let latest;
93新增: for (let i = 0; i < 25; i++) {
94新增: try { latest = await browser.run("frame", { id }); }
95新增: catch (error) { if (error.status !== 409) throw error; await delay(50); continue; }
96新增: if (latest.title.startsWith("[") && check(JSON.parse(latest.title), latest)) return latest;
97新增: await delay(50);
98新增: }
99新增: throw new Error("expected frame missing: " + latest?.title);
100新增: }
101新增: async function settled(frame) {
102新增: // Chromium can paint the page after the DOM already has its new title.
103新增: for (let i = 0; i < 20; i++) {
104新增: const next = await browser.run("frame", { id, after: frame.frame_tag });
105新增: if (next.unchanged) {
106新增: assert.deepEqual(next, { id, frame_tag: frame.frame_tag, unchanged: true });
107新增: return frame;
108新增: }
109新增: frame = next;
110新增: await delay(50);
111新增: }
112新增: throw new Error("static page never produced an unchanged frame");
113新增: }
114新增: assert.deepEqual(await open("a".repeat(64), "/remember"), { id });
115新增: let page = await read(([w, h, , cookie, , touch]) => w === 390 && h === 750 && cookie === "state=known" && touch >= 1);
116新增: assert.equal(JSON.parse(page.title)[6], "ja-JP");
117新增: assert.equal(JSON.parse(page.title)[8], 2);
118新增: assert.match(acceptLanguage, /^ja-JP/i);
119新增: if (process.env.TZ) assert.equal(JSON.parse(page.title)[7], Intl.DateTimeFormat().resolvedOptions().timeZone);
120新增: assert.ok(Buffer.from(page.image, "base64").subarray(0, 2).equals(Buffer.from([255, 216])));
121新增: assert.match(page.frame_tag, /^[a-f0-9]{32}$/);
122新增: page = await settled(page);
123新增: const initialTag = page.frame_tag;
124新增: page = await action("tap", { x: 60, y: 25, document: page.document, return_frame: true });
125新增: assert.ok(page.focus && page.image);
126新增: assert.notEqual(page.frame_tag, initialTag);
127新增: const old = { document: page.document, focus: page.focus };
128新增: assert.deepEqual(await action("text", { ...old, text: "你好 Cage" }), { id });
129新增: page = await read(([, , value]) => value === "你好 Cage");
130新增: const capture = browser.frame;
131新增: browser.frame = async () => { throw new Error("frame changed after text input"); };
132新增: try {
133新增: assert.deepEqual(await action("text", { ...old, text: "!", return_frame: true }), { id });
134新增: } finally { browser.frame = capture; }
135新增: await read(([, , value]) => value === "你好 Cage!");
136新增: await action("resize", { width: 390, height: 400 });
137新增: page = await read(([, h]) => h === 400);
138新增: assert.equal(page.focus, old.focus);
139新增: assert.notEqual(page.document, old.document);
140新增: await action("text", { focus: old.focus, document: page.document, text: "✓" });
141新增: page = await read(([, , value]) => value === "你好 Cage!✓");
142新增: await action("tap", { x: 60, y: 75, document: page.document });
143新增: await read((_, frame) => frame.password && frame.focus !== old.focus);
144新增: await assert.rejects(action("text", { document: page.document, focus: old.focus, text: "stale" }), /输入框已改变/);
145新增: await action("scroll", { x: 100, y: 280, dx: 0, dy: 200, document: page.document });
146新增: await read(([, , , , y]) => y > 0);
147新增: await action("resize", { width: 750, height: 390 });
148新增: await read(([w, h]) => w === 750 && h === 390);
149新增: await assert.rejects(action("tap", { x: 30, y: 30, document: old.document }), /页面已切换/);
150新增: await action("navigate", { url: url + "/next" });
151新增: page = await read();
152新增: await action("tap", { x: 60, y: 25, document: page.document });
153新增: page = await read((_, frame) => Boolean(frame.focus));
154新增: assert.notEqual(page.focus, old.focus);
155新增: await assert.rejects(action("text", { document: page.document, focus: old.focus, text: "stale" }), /输入框已改变/);
156新增: await action("resize", { width: 390, height: 750 });
157新增: await action("navigate", { url: url + "/wide" });
158新增: page = await read(([w, scale]) => w >= 980 && scale < 1);
159新增: const scale = JSON.parse(page.title)[1];
160新增: await action("tap", { x: 550 * scale, y: 65 * scale, document: page.document });
161新增: await read((_, frame) => Boolean(frame.focus));
162新增: await action("navigate", { url: url + "/private" }).catch(() => {});
163新增: await delay(250);
164新增: assert.equal(seen.includes("/forbidden"), false);
165新增: await action("navigate", { url: url + "/private-ws" });
166新增: await read(([, , status]) => status === "ws-attempted");
167新增: await delay(200);
168新增: assert.equal(seen.includes("/forbidden-ws"), false, "a WebSocket bypassed the public-only proxy");
169新增: await browser.run("close", { id });
170新增: browser.language = "fr-FR";
171新增: id = randomUUID(); await open("a".repeat(64), "/restored");
172新增: page = await read(([, , , cookie]) => cookie === "state=known");
173新增: assert.equal(JSON.parse(page.title)[6], "fr-FR");
174新增: assert.match(acceptLanguage, /^fr-FR/i);
175新增: await browser.run("close", { id });
176新增: id = randomUUID(); await open("b".repeat(64));
177新增: await read(([, , , cookie]) => cookie === "");
178新增: // A secure fixture varies the initial HTML by Chromium's request headers,
179新增: // just as mobile sites do. Fulfill the request before it leaves the test.
180新增: const s = browser.session;
181新增: const originalOnEvent = s.pipe.onEvent;
182新增: const { product } = await s.pipe.send("Browser.getVersion");
183新增: const major = product.split("/")[1].split(".")[0];
184新增: s.pipe.onEvent = event => {
185新增: originalOnEvent(event);
186新增: if (event.method !== "Fetch.requestPaused") return;
187新增: const { request, requestId } = event.params;
188新增: const headers = Object.fromEntries(Object.entries(request.headers).map(([k, v]) => [k.toLowerCase(), v]));
189新增: const mobile = headers["sec-ch-ua-mobile"] === "?1" && headers["user-agent"].includes(" Mobile ") &&
190新增: headers["sec-ch-ua"]?.includes(`"Chromium";v="${major}"`);
191新增: const html = `<meta name="viewport" content="width=device-width,initial-scale=1">
192新增: <style>body{margin:0} form{width:${mobile ? "95%" : "768px"}}</style>
193新增: <form><input></form><script>document.title=JSON.stringify([innerWidth, document.forms[0].offsetWidth,
194新增: navigator.userAgentData.mobile,navigator.language]);</script>`;
195新增: void s.send("Fetch.fulfillRequest", { requestId, responseCode: 200, responseHeaders: [{ name: "Content-Type", value: "text/html" }],
196新增: body: Buffer.from(html).toString("base64") });
197新增: };
198新增: await s.send("Fetch.enable", { patterns: [{ urlPattern: "https://phone.example/*" }] });
199新增: await action("navigate", { url: "https://phone.example/search" });
200新增: page = await read(([w, form, mobile]) => w === 390 && form <= w && mobile === true);
201新增: assert.equal(JSON.parse(page.title)[3], "fr-FR");
202新增: page = await settled(page);
203新增: // A change to the title alone must invalidate the conditional frame.
204新增: await s.send("Runtime.evaluate", { expression: 'document.title = "new title"' });
205新增: const renamed = await browser.run("frame", { id, after: page.frame_tag });
206新增: assert.equal(renamed.title, "new title");
207新增: assert.equal(renamed.image, page.image);
208新增: assert.notEqual(renamed.frame_tag, page.frame_tag);
209新增: await browser.run("close", { id });
210新增: });
新增internal/cage/browser-private.mjs+43 −0看文件
@@ -0,0 +1,43 @@
1新增:// All user-created private tabs share one off-the-record Chromium context.
2新增:// Login and diagnostic contexts have independent owners.
3新增:export class PrivateBrowser {
4新增: constructor(cdp, downloadPath) {
5新增: this.cdp = cdp;
6新增: this.downloadPath = downloadPath;
7新增: this.context = "";
8新增: }
9新增:
10新增: tab(raw) {
11新增: return { ...raw, incognito: Boolean(this.context && raw.browserContextId === this.context) };
12新增: }
13新增:
14新增: async open(url, activate) {
15新增: await this.prune();
16新增: if (!this.context) {
17新增: const { browserContextId } = await this.cdp("Target.createBrowserContext", { disposeOnDetach: true });
18新增: this.context = browserContextId;
19新增: }
20新增: try {
21新增: await this.cdp("Browser.setDownloadBehavior", {
22新增: browserContextId: this.context, behavior: "allowAndName",
23新增: downloadPath: this.downloadPath, eventsEnabled: true,
24新增: });
25新增: const { targetId } = await this.cdp("Target.createTarget", {
26新增: browserContextId: this.context, url, newWindow: true,
27新增: });
28新增: await activate(this.tab({ targetId, browserContextId: this.context, type: "page", url }));
29新增: return { id: targetId, incognito: true };
30新增: } catch (error) {
31新增: await this.prune();
32新增: throw error;
33新增: }
34新增: }
35新增:
36新增: async prune() {
37新增: if (!this.context) return;
38新增: const { targetInfos } = await this.cdp("Target.getTargets");
39新增: if (targetInfos.some(tab => tab.type === "page" && tab.browserContextId === this.context)) return;
40新增: await this.cdp("Target.disposeBrowserContext", { browserContextId: this.context });
41新增: this.context = "";
42新增: }
43新增:}
修改internal/cage/browser-vault.mjs+4 −4看文件
@@ -91,7 +91,7 @@ export class BrowserVault {
9191 for (const [id, item] of this.pending) if (this.now() >= item.expires) this.pending.delete(id);
9292 }
9393 async attach(tab, sid) {
94删除: if (this.tab(tab)?.login) return;
94新增: if (this.tab(tab)?.login || this.tab(tab)?.incognito) return;
9595 const entry = { tab, sid, top: "", contexts: new Map() };
9696 this.sessions.set(sid, entry);
9797 await this.cdp("Runtime.enable", {}, sid);
@@ -120,7 +120,7 @@ export class BrowserVault {
120120 if (event.method !== "Runtime.bindingCalled" || p.name !== binding ||
121121 entry.contexts.get(p.executionContextId) !== entry.top) return;
122122 this.prune();
123删除: if (!this.lease || entry.tab !== this.active() || this.tab(entry.tab)?.login || p.payload.length > 16000) return;
123新增: if (!this.lease || entry.tab !== this.active() || (this.tab(entry.tab)?.login || this.tab(entry.tab)?.incognito) || p.payload.length > 16000) return;
124124 try {
125125 const value = JSON.parse(p.payload);
126126 const origin = new URL(value.origin).origin;
@@ -173,7 +173,7 @@ export class BrowserVault {
173173 v.lease = ${JSON.stringify(this.lease)}; v.deadline = Date.now() + 6500;
174174 return {origin: location.origin, document: v.document};
175175 })()`);
176删除: if (value && entry.tab === input.tab && entry.tab === this.active() && !this.tab(entry.tab)?.login)
176新增: if (value && entry.tab === input.tab && entry.tab === this.active() && !(this.tab(entry.tab)?.login || this.tab(entry.tab)?.incognito))
177177 Object.assign(result, value);
178178 } catch {}
179179 }));
@@ -189,7 +189,7 @@ export class BrowserVault {
189189 if (input.action === "dismiss") { this.pending.delete(input.candidate); return { ok: true }; }
190190 if (input.action === "fill") {
191191 const entry = [...this.sessions.values()].find(value => value.tab === input.tab);
192删除: if (!entry || input.tab !== this.active() || this.tab(input.tab)?.login) throw new Error("当前网页已切换");
192新增: if (!entry || input.tab !== this.active() || (this.tab(input.tab)?.login || this.tab(input.tab)?.incognito)) throw new Error("当前网页已切换");
193193 const filled = await this.evaluate(entry, `globalThis.cageVault?.fill(${JSON.stringify(input)}) === true`);
194194 if (filled) this.usernames.set(entry.tab, { origin: input.origin, username: input.username, expires: this.now() + 120000 });
195195 if (!filled) throw new Error("未找到可填写的登录框,或页面已变化");
新增internal/cage/browser_language_test.go+118 −0看文件
@@ -0,0 +1,118 @@
1新增:package cage
2新增:
3新增:import (
4新增: "encoding/json"
5新增: "os"
6新增: "os/exec"
7新增: "path/filepath"
8新增: "strings"
9新增: "testing"
10新增:)
11新增:
12新增:func TestBrowserLanguagePackageMigration(t *testing.T) {
13新增: start := strings.Index(guestStart, "if ! cage_is_ubuntu")
14新增: if start < 0 {
15新增: t.Fatal("existing guests have no language package migration")
16新增: }
17新增: end := strings.Index(guestStart[start:], "\nfi\n")
18新增: if end < 0 {
19新增: t.Fatal("unterminated migration")
20新增: }
21新增: script := "set -euo pipefail\ncage_is_ubuntu() { [ \"$MODE\" = ubuntu ]; }\n" + guestStart[start:start+end+4] + "\nprintf continued\n"
22新增: for _, mode := range []string{"installed", "ubuntu", "missing", "update-failure", "install-failure"} {
23新增: t.Run(mode, func(t *testing.T) {
24新增: dir := t.TempDir()
25新增: commands := map[string]string{
26新增: "dpkg-query": "#!/bin/sh\nif [ \"$MODE\" = installed ] || [ -f \"$FIXTURE/installed\" ]; then printf 'install ok installed'; else exit 1; fi\n",
27新增: "sudo": "#!/bin/sh\nexec \"$@\"\n",
28新增: "apt-get": `#!/bin/sh
29新增:set -eu
30新增:[ "$DEBIAN_FRONTEND" = noninteractive ]
31新增:[ "$APT_CONFIG" = "$FIXTURE/apt.conf" ]
32新增:printf '%s\n' "$*" >> "$FIXTURE/requests"
33新增:case "$1" in
34新增: update) [ "$MODE" != update-failure ];;
35新增: install)
36新增: [ "$MODE" != install-failure ] || exit 100
37新增: [ "$*" = 'install -y --no-install-recommends chromium-l10n' ]
38新增: touch "$FIXTURE/installed";;
39新增: *) exit 91;;
40新增:esac
41新增:`,
42新增: }
43新增: for name, body := range commands {
44新增: if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0755); err != nil {
45新增: t.Fatal(err)
46新增: }
47新增: }
48新增: run := func() ([]byte, error) {
49新增: cmd := exec.Command("bash", "-c", script)
50新增: cmd.Env = append(os.Environ(), "PATH="+dir+":"+os.Getenv("PATH"), "FIXTURE="+dir, "MODE="+mode, "CAGE_APT_CONFIG="+filepath.Join(dir, "apt.conf"))
51新增: return cmd.CombinedOutput()
52新增: }
53新增: out, err := run()
54新增: failed := strings.HasSuffix(mode, "failure")
55新增: if (err != nil) != failed || strings.Contains(string(out), "continued") == failed {
56新增: t.Fatalf("migration %s: %v %s", mode, err, out)
57新增: }
58新增: requests, _ := os.ReadFile(filepath.Join(dir, "requests"))
59新增: if (mode == "installed" || mode == "ubuntu") && len(requests) != 0 {
60新增: t.Fatal("installed language package triggered network access")
61新增: }
62新增: if mode == "update-failure" && strings.Contains(string(requests), "install") {
63新增: t.Fatal("installation continued after failed package index update")
64新增: }
65新增: if mode == "missing" {
66新增: if out, err := run(); err != nil {
67新增: t.Fatalf("second startup: %v %s", err, out)
68新增: }
69新增: again, _ := os.ReadFile(filepath.Join(dir, "requests"))
70新增: if string(again) != string(requests) {
71新增: t.Fatal("second startup reinstalled language package")
72新增: }
73新增: }
74新增: })
75新增: }
76新增:}
77新增:
78新增:func TestBrowserLanguagePreferencesReplaceStaleSelection(t *testing.T) {
79新增: if _, err := exec.LookPath("python3"); err != nil {
80新增: t.Skip("guest Python interpreter unavailable")
81新增: }
82新增: start := strings.Index(guestStart, "import json, os\nfrom pathlib import Path\np = Path.home()")
83新增: if start < 0 {
84新增: t.Fatal("browser preference writer not found")
85新增: }
86新增: end := strings.Index(guestStart[start:], "\nPYCODE")
87新增: script := strings.Replace(guestStart[start:start+end], "Path.home()", `Path(os.environ["FIXTURE"])`, 1)
88新增: dir := t.TempDir()
89新增: profile := filepath.Join(dir, "profile", "Default")
90新增: if err := os.MkdirAll(profile, 0700); err != nil {
91新增: t.Fatal(err)
92新增: }
93新增: prefs := filepath.Join(profile, "Preferences")
94新增: if err := os.WriteFile(prefs, []byte(`{"intl":{"accept_languages":"en-US","selected_languages":"en-US"},"unrelated":{"keep":true}}`), 0600); err != nil {
95新增: t.Fatal(err)
96新增: }
97新增: for _, language := range []string{"zh-TW", "fr-FR", "en-US"} {
98新增: cmd := exec.Command("python3", "-c", script)
99新增: cmd.Env = append(os.Environ(), "FIXTURE="+dir, "CAGE_LANGUAGE="+language)
100新增: if out, err := cmd.CombinedOutput(); err != nil {
101新增: t.Fatalf("%v %s", err, out)
102新增: }
103新增: data, err := os.ReadFile(prefs)
104新增: if err != nil {
105新增: t.Fatal(err)
106新增: }
107新增: var settings struct {
108新增: Intl map[string]string `json:"intl"`
109新增: Unrelated map[string]bool `json:"unrelated"`
110新增: }
111新增: if err := json.Unmarshal(data, &settings); err != nil {
112新增: t.Fatal(err)
113新增: }
114新增: if settings.Intl["accept_languages"] != language || settings.Intl["selected_languages"] != language || !settings.Unrelated["keep"] {
115新增: t.Fatalf("preference update lost language or unrelated settings: %s", data)
116新增: }
117新增: }
118新增:}
修改internal/cage/chromium-download.py+17 −9看文件
@@ -4,7 +4,6 @@ import os
44import subprocess
55import sys
66from pathlib import Path
7删除:from urllib.parse import urlsplit
87
98# Older or minimal container images can still use their normal apt-get install.
109try:
@@ -16,9 +15,7 @@ except ImportError:
1615 sys.exit(0)
1716
1817
19删除:MIRRORS = ("https://mirrors.nju.edu.cn/debian-security/", "https://mirrors.ustc.edu.cn/debian-security/")
2018SECURITY_LIST = Path("/etc/apt/mirrors/debian-security.list")
21删除:OFFICIAL = ("https://deb.debian.org/debian-security/", "https://security.debian.org/debian-security/")
2219
2320
2421def stock_security_uri(uri):
@@ -27,10 +24,21 @@ def stock_security_uri(uri):
2724 if uri.startswith("mirror+file:" + str(SECURITY_LIST) + "/"):
2825 if not SECURITY_LIST.is_file():
2926 return False
30删除: return SECURITY_LIST.read_text().strip().rstrip("/") + "/" in OFFICIAL
31删除: site = urlsplit(uri)
32删除: return (site.scheme in ("http", "https") and site.netloc in ("deb.debian.org", "security.debian.org")
33删除: and site.path.startswith("/debian-security/"))
27新增: return SECURITY_LIST.read_text().startswith("# Cage managed Debian mirrors\n")
28新增: return False
29新增:
30新增:
31新增:def security_mirrors():
32新增: if not SECURITY_LIST.is_file():
33新增: return []
34新增: lines = SECURITY_LIST.read_text().splitlines()
35新增: if not lines or lines[0] != "# Cage managed Debian mirrors":
36新增: return []
37新增: # Reuse only mirrors selected by the bounded reachability probe. Explicit
38新增: # official preference and custom sources never cause hidden mirror requests.
39新增: allowed = ("https://mirrors.nju.edu.cn/debian-security/", "https://mirrors.ustc.edu.cn/debian-security/")
40新增: return [parts[0].rstrip("/") + "/" for line in lines[1:]
41新增: if (parts := line.split()) and parts[0].rstrip("/") + "/" in allowed]
3442
3543
3644class Progress(AcquireProgress):
@@ -54,7 +62,7 @@ def fetch(package, version, target):
5462 hashes = apt_pkg.HashStringList()
5563 hashes.append(apt_pkg.HashString("SHA256", version.sha256))
5664 partial = target.parent / "partial" / (target.name + ".cage")
57删除: for mirror in MIRRORS:
65新增: for mirror in security_mirrors():
5866 print(f"Downloading {package} {version.version} from {mirror}", flush=True)
5967 progress = Progress(package, version.size)
6068 acquire = apt_pkg.Acquire(progress)
@@ -84,7 +92,7 @@ def prefetch(install_options):
8492 cache = apt.Cache()
8593 archives = Path(apt_pkg.config.find_dir("Dir::Cache::archives"))
8694 apt_pkg.config.set("Acquire::Retries", "0")
87删除: apt_pkg.config.set("Acquire::https::Timeout", "60")
95新增: apt_pkg.config.set("Acquire::https::Timeout", "15")
8896 with apt_pkg.FileLock(str(archives / "lock")):
8997 for line in plan.splitlines():
9098 if not line.startswith("'"):
修改internal/cage/claude-account.py+282 −21看文件
@@ -1,6 +1,6 @@
11#!/usr/bin/python3
22"""Launch the official guest CLI and export only its subscription status fields."""
3删除:import fcntl
3新增:import runpy
44from datetime import datetime
55import hashlib
66import json
@@ -9,22 +9,42 @@ from pathlib import Path
99import re
1010import shutil
1111import signal
12新增:import socket
13新增:import stat
1214import subprocess
1315import sys
1416import tempfile
1517import time
1618
1719
20新增:if os.name == "nt":
21新增: platform_path = Path(__file__).with_name("windows_cli_platform.py")
22新增: if not platform_path.exists():
23新增: platform_path = Path(__file__).parent.parent / "workbench/windows_cli_platform.py"
24新增: _platform = runpy.run_path(platform_path)
25新增: fcntl = _platform["FileLock"]
26新增:else:
27新增: import fcntl
28新增:
1829SHIM = "/usr/local/lib/cage-claude-bin"
19删除:OPEN = "/usr/local/bin/cage-open"
30新增:OPEN = "/usr/local/libexec/cage-cli/bin/cage-open" if sys.platform == "darwin" else "/usr/local/bin/cage-open"
2031HELPER = "/usr/local/bin/cage-claude-account"
2132DEFAULT = "default"
2233
2334
35新增:def shared_root():
36新增: return Path(os.environ["CAGE_CLI_SHARED_ROOT"]) if os.name == "nt" else Path.home() / ".local/share/cage/claude-shared"
37新增:
38新增:
39新增:class SharedResourceConflict(ValueError):
40新增: pass
41新增:
42新增:
2443def profile(account_id):
2544 if account_id != DEFAULT and not re.fullmatch("[0-9a-f]{24}", account_id):
2645 raise ValueError("invalid account ID")
27删除: return Path.home() / ".local/share/cage/claude-accounts" / account_id
46新增: root = Path(os.environ["CAGE_CLI_ACCOUNT_ROOT"]) if os.name == "nt" else Path.home() / ".local/share/cage/claude-accounts"
47新增: return root / account_id
2848
2949
3050def config_directory(base):
@@ -36,6 +56,8 @@ def cli_environment(base):
3656 # Executing the real binary must never recurse into the terminal's claude shim.
3757 path = [p for p in env.get("PATH", os.defpath).split(os.pathsep) if p and p != SHIM]
3858 env["PATH"] = os.pathsep.join([str(Path.home() / ".local/bin"), *path])
59新增: if sys.platform == "darwin" and Path("/usr/local/libexec/cage-cli/bin/claude").is_file():
60新增: env["PATH"] = "/usr/local/libexec/cage-cli/bin:/usr/local/bin:" + env["PATH"]
3961 if base.name == DEFAULT:
4062 # Let Claude resolve its normal ~/.claude.json and ~/.claude itself.
4163 # Preserve provider variables: an API-authenticated shell is not a
@@ -49,9 +71,9 @@ def cli_environment(base):
4971 return env
5072
5173
52删除:def identity(binary, env, cwd, settings=(), timeout=10):
74新增:def identity(binary, env, cwd, settings=(), timeout=10, pass_fds=()):
5375 result = subprocess.run([binary, *settings, "auth", "status"], cwd=cwd, env=env, timeout=timeout,
54删除: stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
76新增: stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, pass_fds=pass_fds)
5577 # Exit code 1 with JSON is the CLI's documented logged-out response. Any
5678 # other failure (including missing JSON) must not sign a known user out.
5779 data = json.loads(result.stdout)
@@ -287,8 +309,15 @@ def query_usage(binary, env, base, expected):
287309def has_status_line(base):
288310 # Preserve existing user, project and managed status lines, including an
289311 # explicit disable. If a settings file is unreadable, defer to Claude.
290删除: paths = [config_directory(base) / "settings.json", Path("/etc/claude-code/managed-settings.json")]
291删除: paths.extend(Path("/etc/claude-code/managed-settings.d").glob("*.json"))
312新增: if os.name == "nt":
313新增: policy = Path(os.environ.get("ProgramFiles", "C:/Program Files")) / "ClaudeCode"
314新增: elif sys.platform == "darwin":
315新增: policy = Path("/Library/Application Support/ClaudeCode")
316新增: else:
317新增: policy = Path("/etc/claude-code")
318新增: paths = [config_directory(base) / "settings.json", policy / "managed-settings.json"]
319新增: if os.name != "nt":
320新增: paths.extend((policy / "managed-settings.d").glob("*.json"))
292321 for folder in (Path.cwd(), *Path.cwd().parents):
293322 paths += [folder / ".claude/settings.json", folder / ".claude/settings.local.json"]
294323 for path in paths:
@@ -318,7 +347,197 @@ def settings_flags(args):
318347 return flags
319348
320349
321删除:def main(args):
350新增:def shared_profile_resources(base):
351新增: """Share local customizations; credentials, synced skills and history stay private."""
352新增: config = config_directory(base)
353新增: common = Path.home() / ".claude"
354新增: common.mkdir(mode=0o700, parents=True, exist_ok=True)
355新增: if config == common:
356新增: return
357新增: lock_dir = shared_root()
358新增: lock_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
359新增: with (lock_dir / "resources.lock").open("a") as lock:
360新增: fcntl.flock(lock, fcntl.LOCK_EX)
361新增: conflict = "账号的技能或指令与共用资料同名冲突,请先核对 ~/.claude 中的对应文件;原文件已保留"
362新增: def check(local, shared):
363新增: if (local.is_symlink() or os.name == "nt" and local.is_junction()):
364新增: if local.resolve() != shared.resolve():
365新增: raise SharedResourceConflict(conflict)
366新增: elif local.exists() and shared.exists():
367新增: if local.is_dir() and shared.is_dir():
368新增: for child in local.iterdir():
369新增: check(child, shared / child.name)
370新增: elif not (local.is_file() and shared.is_file() and local.read_bytes() == shared.read_bytes()):
371新增: raise SharedResourceConflict(conflict)
372新增: def merge(local, shared):
373新增: if (local.is_symlink() or os.name == "nt" and local.is_junction()):
374新增: if local.resolve() == shared.resolve():
375新增: return
376新增: raise SharedResourceConflict(conflict)
377新增: if local.exists():
378新增: if local.is_dir() and shared.is_dir():
379新增: for child in list(local.iterdir()):
380新增: merge(child, shared / child.name)
381新增: if child.is_symlink():
382新增: child.unlink()
383新增: local.rmdir()
384新增: elif not shared.exists():
385新增: shared.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
386新增: local.rename(shared)
387新增: elif local.is_file() and shared.is_file() and local.read_bytes() == shared.read_bytes():
388新增: # Keep a recoverable copy before replacing a local resource.
389新增: backup = lock_dir / "backups" / base.name / local.relative_to(config)
390新增: backup.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
391新增: if not backup.exists():
392新增: shutil.copy2(local, backup)
393新增: local.unlink()
394新增: else:
395新增: # Never choose which conflicting instruction or skill wins.
396新增: raise SharedResourceConflict(conflict)
397新增: if not shared.exists():
398新增: if local.name in ("CLAUDE.md", "AGENTS.md"):
399新增: shared.touch(mode=0o600)
400新增: else:
401新增: shared.mkdir(mode=0o700, parents=True, exist_ok=True)
402新增: local.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
403新增: if os.name == "nt":
404新增: _platform["resource_link"](local, shared)
405新增: else:
406新增: local.symlink_to(shared, target_is_directory=shared.is_dir())
407新增: # claude.ai downloads skills into skills/synced. Keep that subtree
408新增: # account-specific; link only locally installed skill entries.
409新增: local, shared = config / "skills", common / "skills"
410新增: local.mkdir(mode=0o700, parents=True, exist_ok=True)
411新增: shared.mkdir(mode=0o700, parents=True, exist_ok=True)
412新增: names = {p.name for folder in (local, shared) for p in folder.iterdir()} - {"synced"}
413新增: resources = [(config / name, common / name) for name in
414新增: ("commands", "agents", "rules", "agent-memory", "CLAUDE.md", "AGENTS.md")]
415新增: resources += [(local / name, shared / name) for name in sorted(names)]
416新增: # Validate every resource before moving any of them. A late conflict
417新增: # must leave the account's existing directory layout usable.
418新增: for source, destination in resources:
419新增: check(source, destination)
420新增: for source, destination in resources:
421新增: if source.exists() and not source.is_symlink():
422新增: backup = lock_dir / "backups" / base.name / source.relative_to(config)
423新增: if backup.exists():
424新增: backup = backup.with_name(backup.name + "-" + str(time.time_ns()))
425新增: backup.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
426新增: if source.is_dir():
427新增: shutil.copytree(source, backup, symlinks=True)
428新增: else:
429新增: shutil.copy2(source, backup)
430新增: merge(source, destination)
431新增:
432新增:
433新增:def shared_launch_arguments(base, args, settings_fd=None):
434新增: """Apply a stable project memory location without sharing auth/settings files."""
435新增: lock_dir = shared_root()
436新增: lock_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
437新增: with (lock_dir / "resources.lock").open("a") as lock:
438新增: fcntl.flock(lock, fcntl.LOCK_EX)
439新增: return shared_launch_arguments_locked(base, args, settings_fd)
440新增:
441新增:
442新增:def shared_launch_arguments_locked(base, args, settings_fd):
443新增: directory = Path.cwd().resolve()
444新增: try:
445新增: git = subprocess.run(["git", "rev-parse", "--path-format=absolute", "--git-common-dir"],
446新增: cwd=directory, capture_output=True, text=True, timeout=2)
447新增: if git.returncode == 0:
448新增: common_git = Path(git.stdout.strip())
449新增: if common_git.name == ".git":
450新增: directory = common_git.parent.resolve()
451新增: except (OSError, subprocess.SubprocessError):
452新增: pass
453新增: key = re.sub(r"[^a-zA-Z0-9]", "-", str(directory))
454新增: if len(key) > 180:
455新增: key = key[:140] + "-" + hashlib.sha256(str(directory).encode()).hexdigest()[:32]
456新增: memory = Path.home() / ".claude/projects" / key / "memory"
457新增: own_memory = config_directory(base) / "projects" / key / "memory"
458新增: memory.mkdir(mode=0o700, parents=True, exist_ok=True)
459新增: # Retain pre-existing account notes. Colliding files remain in their
460新增: # original directory and block automatic consolidation until reviewed.
461新增: if own_memory != memory and own_memory.exists() and not (own_memory.is_symlink() or os.name == "nt" and own_memory.is_junction()):
462新增: sources = [source for source in own_memory.rglob("*") if source.is_file()]
463新增: for source in sources:
464新增: destination = memory / source.relative_to(own_memory)
465新增: if destination.exists() and (not destination.is_file() or destination.read_bytes() != source.read_bytes()):
466新增: raise SharedResourceConflict("账号的项目记忆与共用记忆冲突,原记忆已保留,请先核对")
467新增: for source in sources:
468新增: if source.is_file():
469新增: destination = memory / source.relative_to(own_memory)
470新增: if destination.exists() and destination.read_bytes() != source.read_bytes():
471新增: raise SharedResourceConflict("账号的项目记忆与共用记忆冲突,原记忆已保留,请先核对")
472新增: destination.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
473新增: if not destination.exists():
474新增: shutil.copy2(source, destination)
475新增: backup = shared_root() / "backups" / base.name / "projects" / key / "memory"
476新增: backup.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
477新增: if backup.exists():
478新增: backup = backup.with_name(backup.name + "-" + str(time.time_ns()))
479新增: own_memory.rename(backup)
480新增: if os.name == "nt":
481新增: _platform["resource_link"](own_memory, memory)
482新增: else:
483新增: own_memory.symlink_to(memory, target_is_directory=True)
484新增: settings = {"autoMemoryDirectory": str(memory)}
485新增: # Only local behavior is shared. Never copy env, apiKeyHelper, login/org
486新增: # constraints, OAuth metadata, or account-synced remote configuration.
487新增: common_settings = json_file(Path.home() / ".claude/settings.json")
488新增: shared_keys = {"model", "permissions", "hooks", "statusLine", "attribution", "language",
489新增: "effortLevel", "alwaysThinkingEnabled", "includeCoAuthoredBy", "respectGitignore",
490新增: "spinnerTipsEnabled", "outputStyle", "disableAllHooks", "includeGitInstructions",
491新增: "theme", "skipDangerousModePermissionPrompt", "tui", "autoMemoryEnabled"}
492新增: if isinstance(common_settings, dict):
493新增: settings.update({key: value for key, value in common_settings.items() if key in shared_keys})
494新增: # Respect an explicit memory location in existing user/project settings.
495新增: paths = [Path.home() / ".claude/settings.json", config_directory(base) / "settings.json"]
496新增: for parent in reversed((Path.cwd(), *Path.cwd().parents)):
497新增: paths += [parent / ".claude/settings.json", parent / ".claude/settings.local.json"]
498新增: for path in paths:
499新增: stored = json_file(path)
500新增: if path != Path.home() / ".claude/settings.json" and isinstance(stored, dict):
501新增: # Let the CLI's normal profile/project precedence decide these
502新增: # values. A shared default must not turn into a command-line override.
503新增: for key in shared_keys & stored.keys():
504新增: settings.pop(key, None)
505新增: if isinstance(stored, dict) and "autoMemoryDirectory" in stored:
506新增: settings["autoMemoryDirectory"] = stored["autoMemoryDirectory"]
507新增: result, iterator = [], iter(args)
508新增: for arg in iterator:
509新增: if arg == "--":
510新增: result += [arg, *iterator]
511新增: break
512新增: if arg == "--settings" or arg.startswith("--settings="):
513新增: value = next(iterator) if arg == "--settings" else arg.split("=", 1)[1]
514新增: supplied = json.loads(value) if value.lstrip().startswith("{") else json.loads(Path(value).read_text())
515新增: settings.update(supplied)
516新增: else:
517新增: result.append(arg)
518新增: data = json.dumps(settings, separators=(",", ":")).encode()
519新增: if settings_fd is not None:
520新增: # Mobile launch deliberately keeps settings in an anonymous file.
521新增: # Sharing local defaults must not persist its provider material.
522新增: with os.fdopen(os.dup(settings_fd), "r+b") as snapshot:
523新增: snapshot.seek(0)
524新增: snapshot.truncate()
525新增: snapshot.write(data)
526新增: snapshot.flush()
527新增: snapshot.seek(0)
528新增: return ["--settings", "/dev/fd/" + str(settings_fd), *result]
529新增: folder = base / "launch-settings"
530新增: folder.mkdir(mode=0o700, parents=True, exist_ok=True)
531新增: path = folder / (hashlib.sha256(data).hexdigest() + ".json")
532新增: if not path.exists():
533新增: with tempfile.NamedTemporaryFile(dir=folder, delete=False) as stream:
534新增: stream.write(data)
535新增: temporary = stream.name
536新增: os.replace(temporary, path)
537新增: return ["--settings", str(path), *result]
538新增:
539新增:
540新增:def main(args, *, mobile_settings_fd=None, verify_mobile=None):
322541 mode, account_id, *rest = args
323542 if mode == "quotas":
324543 result = {}
@@ -348,7 +567,7 @@ def main(args):
348567 print(json.dumps(changed_identity() if mode == "usage" else {"logged_in": False}))
349568 return 0
350569 raise ValueError("not the default subscription configuration")
351删除: binary = shutil.which("claude", path=env["PATH"])
570新增: binary = os.environ.get("CAGE_CLI_BINARY") if os.name == "nt" else shutil.which("claude", path=env["PATH"])
352571 if not binary:
353572 raise ValueError("Claude is not installed")
354573 if mode == "usage":
@@ -371,42 +590,84 @@ def main(args):
371590 print(json.dumps(summary))
372591 return 0
373592 if mode == "login":
374删除: env.update(BROWSER=OPEN, CAGE_CLAUDE_LOGIN=account_id)
593新增: env.update(CAGE_CLAUDE_LOGIN=account_id)
594新增: if os.name != "nt":
595新增: env["BROWSER"] = OPEN
375596 # Set the handler before spawning so SSH/window closure also disposes
376597 # the ephemeral browser and its cookies.
377598 def interrupted(_signum, _frame):
378599 raise KeyboardInterrupt()
379删除: signal.signal(signal.SIGHUP, interrupted)
600新增: if hasattr(signal, "SIGHUP"):
601新增: signal.signal(signal.SIGHUP, interrupted)
380602 signal.signal(signal.SIGTERM, interrupted)
381603 try:
382604 (base / "quota.json").unlink(missing_ok=True)
383删除: return subprocess.call([binary, "auth", "login", "--claudeai"], cwd=Path.home(), env=env)
605新增: return subprocess.call([binary, "auth", "login", *([] if os.name == "nt" else ["--claudeai"])], cwd=Path.home(), env=env)
384606 finally:
385删除: subprocess.run([OPEN, "--finish-login"], env=env, timeout=8, check=False,
386删除: stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
607新增: if os.name != "nt":
608新增: subprocess.run([OPEN, "--finish-login"], env=env, timeout=8, check=False,
609新增: stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
387610 if mode == "run":
611新增: shared_profile_resources(base)
612新增: if not settings_flags(rest) and not has_status_line(base):
613新增: rest = ["--settings", json.dumps({"statusLine": {"type": "command", "command": f"{HELPER} statusline {account_id}"}}), *rest]
614新增: rest = shared_launch_arguments(base, rest, mobile_settings_fd)
388615 # Profile/project settings can override inherited authentication. Check
389616 # the actual CLI method in the project before launching the conversation.
390617 options = settings_flags(rest)
391删除: if not expected or subject(identity(binary, env, Path.cwd(), options)) != expected:
618新增: # A mobile turn verifies and executes with the same anonymous settings
619新增: # snapshot. Keep its descriptor open across the auth-status child.
620新增: pass_fds = () if mobile_settings_fd is None else (mobile_settings_fd,)
621新增: reading = identity(binary, env, Path.cwd(), options, pass_fds=pass_fds) if expected else None
622新增: if not expected or subject(reading) != expected:
392623 print("此项目未使用所选 Claude 订阅。请检查项目配置和账号登录状态。", file=sys.stderr)
393624 return 1
394删除: flags = []
395删除: if not options and not has_status_line(base):
396删除: settings = {"statusLine": {"type": "command", "command": f"{HELPER} statusline {account_id}"}}
397删除: flags = ["--settings", json.dumps(settings, separators=(",", ":"))]
625新增: if mobile_settings_fd is not None:
626新增: verify_mobile(reading)
627新增: os.lseek(mobile_settings_fd, 0, os.SEEK_SET)
398628 # The private profile is ready. Claude and its tools must create files
399629 # in the shared project using the user's usual umask.
400630 os.umask(original_umask)
401删除: os.execve(binary, [binary, *flags, *rest], env)
631新增: if os.name == "nt":
632新增: return subprocess.call([binary, *rest], env=env)
633新增: os.execve(binary, [binary, *rest], env)
402634 raise ValueError("unknown operation")
403635
404636
637新增:def macos_open(args):
638新增: login = os.environ.get("CAGE_CLAUDE_LOGIN", "")
639新增: if len(args) != 1 or not re.fullmatch("[0-9a-f]{24}", login):
640新增: return 2
641新增: finish = args[0] == "--finish-login"
642新增: data = {"action": "login-finish" if finish else "login-open", "login": login}
643新增: if not finish:
644新增: from urllib.parse import urlsplit
645新增: url = urlsplit(args[0])
646新增: if len(args[0]) > 8192 or url.scheme != "https" or url.username or url.password or url.hostname not in (
647新增: "claude.ai", "claude.com", "console.anthropic.com", "platform.claude.com", "platform.anthropic.com"):
648新增: return 2
649新增: data["url"] = args[0]
650新增: address = Path.home() / "Library/Application Support/Cage/Login/open.sock"
651新增: owner = address.lstat()
652新增: if not stat.S_ISSOCK(owner.st_mode) or owner.st_uid != os.getuid() or owner.st_mode & 0o077:
653新增: return 1
654新增: with socket.socket(socket.AF_UNIX) as client:
655新增: client.settimeout(12)
656新增: client.connect(str(address))
657新增: client.sendall(json.dumps(data).encode())
658新增: client.shutdown(socket.SHUT_WR)
659新增: with client.makefile("rb") as reply:
660新增: return 0 if reply.read(4) == b"OK" else 1
661新增:
662新增:
405663if __name__ == "__main__":
406664 try:
407删除: sys.exit(main(sys.argv[1:]))
665新增: sys.exit(macos_open(sys.argv[1:]) if sys.platform == "darwin" and Path(sys.argv[0]).name == "cage-open" else main(sys.argv[1:]))
408666 except KeyboardInterrupt:
409667 sys.exit(130)
668新增: except SharedResourceConflict as error:
669新增: print(str(error), file=sys.stderr)
670新增: sys.exit(1)
410671 except (OSError, ValueError, subprocess.SubprocessError, TypeError):
411672 # No raw CLI output, paths, credentials or callback URLs go to logs.
412673 print("无法读取 Claude 订阅状态或启动官方 CLI,请检查环境组件与登录状态。", file=sys.stderr)
修改internal/cage/claude-account.test.py+72 −2看文件
@@ -30,11 +30,14 @@ class ClaudeAccountTests(unittest.TestCase):
3030 # Emulate the documented status shape of the official CLI. Its response
3131 # deliberately includes fields that must never cross the guest boundary.
3232 fake.write_text("""#!/bin/sh
33新增:original_settings="$2"
34新增:if [ "$1" = --settings ]; then shift 2; fi
3335if [ "$1" = auth ] && [ "$2" = status ]; then
3436 method=claude.ai; if [ -n "$ANTHROPIC_API_KEY" ]; then method=api_key; fi
3537 printf '{"configDirectory":"%s","authMethod":"%s","apiProvider":"%s","loggedIn":true,"email":"%s","orgId":"test-org","subscriptionType":"pro","access_token":"must-not-appear"}' "${TEST_CONFIG_RESULT:-${CLAUDE_CONFIG_DIR:-$HOME/.claude}}" "$method" "${TEST_PROVIDER:-firstParty}" "$TEST_EMAIL"
3638 exit 0
3739fi
40新增:if [ -n "$original_settings" ]; then printf '%s\\n' --settings "$original_settings"; fi
3841printf '%s\\n' "$@"
3942""")
4043 fake.chmod(0o700)
@@ -97,12 +100,12 @@ printf '%s\\n' "$@"
97100 def test_cli_arguments_and_existing_statusline(self):
98101 args = self.run_helper("run", FIRST, "--model", "sonnet").stdout.splitlines()
99102 self.assertEqual(args[-2:], ["--model", "sonnet"])
100删除: self.assertIn("statusline " + FIRST, json.loads(args[1])["statusLine"]["command"])
103新增: self.assertIn("autoMemoryDirectory", json.loads(Path(args[1]).read_text()))
101104 config = self.home / ".local/share/cage/claude-accounts" / FIRST / "config"
102105 original = '{"statusLine":{"type":"command","command":"my-original-status"}}'
103106 (config / "settings.json").write_text(original)
104107 args = self.run_helper("run", FIRST, "--model", "sonnet").stdout.splitlines()
105删除: self.assertEqual(args, ["--model", "sonnet"])
108新增: self.assertEqual(args[-2:], ["--model", "sonnet"])
106109 self.assertEqual((config / "settings.json").read_text(), original)
107110
108111 def test_default_reuses_the_existing_configuration_and_pin(self):
@@ -134,6 +137,73 @@ printf '%s\\n' "$@"
134137 unknown = self.run_helper("snapshot", "default", env={**self.env, "TEST_CONFIG_RESULT": str(self.home / "different")}, check=False)
135138 self.assertNotEqual(unknown.returncode, 0)
136139
140新增: def test_local_skills_instructions_and_memory_share_without_credentials(self):
141新增: with patch.dict(os.environ,self.env,clear=True),patch.object(helper.Path,"cwd",return_value=self.home):
142新增: common=self.home/".claude"
143新增: (common/"skills/local-skill").mkdir(parents=True)
144新增: (common/"skills/local-skill/SKILL.md").write_text("local instructions")
145新增: (common/"skills/synced").mkdir()
146新增: (common/"skills/synced/remote.md").write_text("account-specific download")
147新增: (common/"CLAUDE.md").write_text("global preferences")
148新增: for account in (FIRST,SECOND):
149新增: base=helper.profile(account);config=helper.config_directory(base);config.mkdir(parents=True)
150新增: (config/".credentials.json").write_text(account)
151新增: helper.shared_profile_resources(base)
152新增: self.assertEqual((config/"skills/local-skill/SKILL.md").read_text(),"local instructions")
153新增: self.assertFalse((config/"skills/synced").exists())
154新增: self.assertEqual((config/"CLAUDE.md").read_text(),"global preferences")
155新增: flags=helper.shared_launch_arguments(base,["--model","sonnet"])
156新增: memory=Path(json.loads(Path(flags[1]).read_text())["autoMemoryDirectory"])
157新增: if account==FIRST:(memory/"MEMORY.md").write_text("project learning")
158新增: self.assertEqual((memory/"MEMORY.md").read_text(),"project learning")
159新增: self.assertEqual((config/".credentials.json").read_text(),account)
160新增: (common/"skills/local-skill/SKILL.md").write_text("updated once")
161新增: self.assertEqual((helper.config_directory(helper.profile(FIRST))/"skills/local-skill/SKILL.md").read_text(),"updated once")
162新增:
163新增: def test_conflicting_shared_resource_preserves_both_versions(self):
164新增: with patch.dict(os.environ,self.env,clear=True):
165新增: base=helper.profile(FIRST);config=helper.config_directory(base);config.mkdir(parents=True)
166新增: common=self.home/".claude";common.mkdir()
167新增: (common/"CLAUDE.md").write_text("global")
168新增: (config/"CLAUDE.md").write_text("account")
169新增: (config/"commands").mkdir()
170新增: (config/"commands/keep.md").write_text("retain the original layout on conflict")
171新增: with self.assertRaises(ValueError):helper.shared_profile_resources(base)
172新增: self.assertEqual((common/"CLAUDE.md").read_text(),"global")
173新增: self.assertEqual((config/"CLAUDE.md").read_text(),"account")
174新增: self.assertFalse((config/"commands").is_symlink())
175新增: self.assertEqual((config/"commands/keep.md").read_text(),"retain the original layout on conflict")
176新增: failure=self.run_helper("run",FIRST,check=False)
177新增: self.assertIn("同名冲突",failure.stderr)
178新增:
179新增: def test_existing_project_memory_is_backed_up_and_remains_shared(self):
180新增: with patch.dict(os.environ,self.env,clear=True),patch.object(helper.Path,"cwd",return_value=self.home):
181新增: base=helper.profile(FIRST)
182新增: key=helper.re.sub(r"[^a-zA-Z0-9]","-",str(self.home.resolve()))
183新增: original=helper.config_directory(base)/"projects"/key/"memory"
184新增: original.mkdir(parents=True)
185新增: (original/"MEMORY.md").write_text("account learning")
186新增: flags=helper.shared_launch_arguments(base,[])
187新增: memory=Path(json.loads(Path(flags[1]).read_text())["autoMemoryDirectory"])
188新增: self.assertEqual((memory/"MEMORY.md").read_text(),"account learning")
189新增: self.assertTrue(original.is_symlink())
190新增: backup=self.home/".local/share/cage/claude-shared/backups"/FIRST/"projects"/key/"memory/MEMORY.md"
191新增: self.assertEqual(backup.read_text(),"account learning")
192新增: self.assertTrue(Path(flags[1]).is_relative_to(base))
193新增:
194新增: def test_mobile_settings_remain_anonymous_when_adding_shared_defaults(self):
195新增: with patch.dict(os.environ,self.env,clear=True),patch.object(helper.Path,"cwd",return_value=self.home),tempfile.TemporaryFile() as snapshot:
196新增: snapshot.write(json.dumps({"env":{"ANTHROPIC_AUTH_TOKEN":"fixture-private"}}).encode())
197新增: snapshot.flush()
198新增: snapshot.seek(0)
199新增: base=helper.profile(FIRST)
200新增: flags=helper.shared_launch_arguments(base,["--settings","/dev/fd/"+str(snapshot.fileno())],snapshot.fileno())
201新增: self.assertEqual(flags,["--settings","/dev/fd/"+str(snapshot.fileno())])
202新增: settings=json.load(snapshot)
203新增: self.assertEqual(settings["env"]["ANTHROPIC_AUTH_TOKEN"],"fixture-private")
204新增: self.assertIn("autoMemoryDirectory",settings)
205新增: self.assertFalse((base/"launch-settings").exists())
206新增:
137207 def test_cancel_login_closes_browser_even_when_cli_fails(self):
138208 env = {**self.env}
139209 with patch.dict(os.environ, env, clear=True), patch.object(helper, "OPEN", "/bin/true"), \
修改internal/cage/claude-desktop-install.sh+1 −1看文件
@@ -12,7 +12,7 @@ printf '正在准备安装依赖…\n'
1212sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get -o DPkg::Lock::Timeout=60 update </dev/null
1313# Satisfy the vendor's kde-cli-tools | ... | libglib2.0-bin dependency before
1414# resolving Claude, so apt does not pull in a KDE/Qt desktop toolchain.
15删除:sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get -o DPkg::Lock::Timeout=60 install -y --no-install-recommends ca-certificates curl gnupg dbus-x11 xauth x11-utils x11-xserver-utils tigervnc-standalone-server tigervnc-scraping-server tigervnc-tools openbox gnome-keyring gcr bubblewrap socat openssh-client libglib2.0-bin ibus ibus-gtk3 gir1.2-ibus-1.0 python3-gi </dev/null
15新增:sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get -o DPkg::Lock::Timeout=60 install -y --no-install-recommends ca-certificates curl gnupg dbus-x11 xauth x11-utils x11-xserver-utils tigervnc-standalone-server tigervnc-scraping-server tigervnc-tools openbox gnome-keyring gcr bubblewrap socat openssh-client libglib2.0-bin ibus ibus-gtk3 gir1.2-ibus-1.0 gir1.2-gtk-3.0 python3-gi python3-pil python3-xlib xsettingsd </dev/null
1616temporary=$(mktemp -d)
1717trap 'rm -rf "$temporary"' EXIT
1818printf '正在验证 Anthropic 安装源…\n'
修改internal/cage/claude-desktop-session.sh+32 −3看文件
@@ -45,8 +45,35 @@ for i in $(seq 1 50); do
4545done
4646keyring_unlocked || { echo '无法解锁已有密钥环,登录数据未修改。' >&2; exit 1; }
4747touch "$XDG_RUNTIME_DIR/keyring-ready"
48删除:# RemoteView displays two framebuffer pixels per CSS pixel, as for Chromium.
49删除:# Scale the application's layout too so controls retain their intended size.
48新增:# Record the running application's density for clients that reconnect later.
49新增:display_scale=2
50新增:if [[ -r /etc/claude-cage/display-scale && $(< /etc/claude-cage/display-scale) == 1.5 ]]; then
51新增: display_scale=1.5
52新增:fi
53新增:printf '%s\n' "$display_scale" > "$XDG_RUNTIME_DIR/display-scale"
54新增:printf '%s\n' "$display_scale" > "$XDG_RUNTIME_DIR/base-display-scale"
55新增:scale_args=(--force-device-scale-factor="$display_scale")
56新增:if command -v xsettingsd >/dev/null; then
57新增: dpi=$(awk -v scale="$display_scale" 'BEGIN {printf "%.0f", scale * 96 * 1024}')
58新增: # Cage owns the embedded app's window controls; keep its native buttons hidden.
59新增: printf 'Xft/DPI %s\nGdk/WindowScalingFactor 1\nGdk/UnscaledDPI %s\nGtk/DecorationLayout ":"\n' "$dpi" "$dpi" > "$XDG_RUNTIME_DIR/xsettings.conf"
60新增: xsettingsd --config="$XDG_RUNTIME_DIR/xsettings.conf" &
61新增: printf '%s\n' "$!" > "$XDG_RUNTIME_DIR/xsettings.pid"
62新增: /usr/bin/python3 - <<'CAGE_DESKTOP_DPI_READY'
63新增:import time
64新增:from Xlib import display
65新增:connection = display.Display()
66新增:selection = connection.intern_atom('_XSETTINGS_S0')
67新增:for attempt in range(60):
68新增: if connection.get_selection_owner(selection):
69新增: break
70新增: time.sleep(.05)
71新增:else:
72新增: raise RuntimeError('Desktop display settings unavailable')
73新增:connection.close()
74新增:CAGE_DESKTOP_DPI_READY
75新增: scale_args=()
76新增:fi
5077/usr/local/bin/cage-desktop-files &
5178files_pid=$!
5279for i in $(seq 1 100); do
@@ -56,7 +83,9 @@ for i in $(seq 1 100); do
5683done
5784test -S "$XDG_RUNTIME_DIR/files.sock"
5885export GTK_USE_PORTAL=1
59删除:/usr/local/bin/cage-input-session claude-desktop --force-device-scale-factor=2 --xdg-portal-required-version=3 &
86新增:# Openbox is not auto-detected as a libsecret desktop by Electron. Select the
87新增:# unlocked keyring explicitly so OAuth tokens survive application restarts.
88新增:/usr/local/bin/cage-input-session claude-desktop "${scale_args[@]}" --password-store=gnome-libsecret --xdg-portal-required-version=3 &
6089app_pid=$!
6190# The service becomes ready only after the application has opened a window.
6291for i in $(seq 1 200); do
修改internal/cage/claude_desktop.go+1 −1看文件
@@ -32,7 +32,7 @@ func ClaudeDesktopInstallScript() string {
3232// Provisioning is independent of the browser and never restarts it. Desktop
3333// services are deliberately not enabled at boot: the user opens the app.
3434func ClaudeDesktopProvisionScript() string {
35删除: return "set -euo pipefail\n" + nativeInputScript() + fileInputScript() +
35新增: return "set -euo pipefail\n" + sharedClipboardScript() + nativeInputScript() + fileInputScript() +
3636 "sudo install -d -m 0755 /etc/claude-cage\n" +
3737 "sudo tee /usr/local/bin/cage-claude-session >/dev/null <<'CAGE_CLAUDE_SESSION'\n" + claudeDesktopSession + "\nCAGE_CLAUDE_SESSION\n" +
3838 "sudo tee /usr/local/bin/cage-claude-open >/dev/null <<'CAGE_CLAUDE_OPEN'\n" + claudeDesktopOpen + "\nCAGE_CLAUDE_OPEN\n" +
修改internal/cage/debian-mirrors.sh+49 −14看文件
@@ -1,16 +1,51 @@
11#!/bin/sh
2删除:# The Debian cloud image uses separate lists for its archive and security
3删除:# updates. Replace only the stock archive list, preserving customized sources.
4删除:if [ -f /etc/apt/mirrors/debian.list ] && [ "$(cat /etc/apt/mirrors/debian.list)" = "https://deb.debian.org/debian" ]; then
5删除: sudo sh -eu <<'CAGE_DEBIAN_MIRRORS'
6删除:list=/etc/apt/mirrors/debian.list
7删除:stage=$(mktemp "$list.XXXXXX")
8删除:trap 'rm -f "$stage"' EXIT
9删除:printf '%s\tpriority:%s\n' \
10删除: https://mirrors.nju.edu.cn/debian 1 \
11删除: https://mirrors.ustc.edu.cn/debian 2 \
12删除: https://deb.debian.org/debian 3 > "$stage"
13删除:chmod 0644 "$stage"
14删除:mv -f "$stage" "$list"
15删除:CAGE_DEBIAN_MIRRORS
2新增:# Only stock and Cage-owned lists are managed. Custom lists and direct URIs
3新增:# remain under the user's control. The preference survives guest cloning.
4新增:sudo env APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" sh -se <<'CAGE_DEBIAN_MIRRORS'
5新增:set -eu
6新增:preference=auto
7新增:if [ -f /etc/claude-cage/debian-mirror ]; then
8新增: preference=$(cat /etc/claude-cage/debian-mirror)
169fi
10新增:case "$preference" in
11新增: auto|official) ;;
12新增: *) echo 'Invalid /etc/claude-cage/debian-mirror: use auto or official.' >&2; exit 1;;
13新增:esac
14新增:for repository in debian debian-security; do
15新增: list="/etc/apt/mirrors/$repository.list"
16新增: [ -f "$list" ] || continue
17新增: content=$(cat "$list")
18新增: official="https://deb.debian.org/$repository"
19新增: old=$(printf '%s\tpriority:%s\n' "https://mirrors.nju.edu.cn/$repository" 1 "https://mirrors.ustc.edu.cn/$repository" 2 "$official" 3)
20新增: case "$content" in
21新增: "$official"|"$old"|'# Cage managed Debian mirrors'*) ;;
22新增: *) continue;;
23新增: esac
24新增: stage=$(mktemp "$list.XXXXXX")
25新增: probe=$(mktemp)
26新增: trap 'rm -f "$stage" "$probe"' EXIT
27新增: printf '# Cage managed Debian mirrors\n' > "$stage"
28新增: suite=$(. /etc/os-release; printf '%s' "${VERSION_CODENAME:-trixie}")
29新增: [ "$repository" != debian-security ] || suite="$suite-security"
30新增: priority=0
31新增: if [ "$preference" = auto ]; then
32新增: for mirror in "https://mirrors.nju.edu.cn/$repository" "https://mirrors.ustc.edu.cn/$repository"; do
33新增: rm -f "$probe"
34新增: if timeout 8 /usr/lib/apt/apt-helper -o Acquire::Retries=0 \
35新增: -o Acquire::http::Timeout=5 -o Acquire::https::Timeout=5 \
36新增: download-file "$mirror/dists/$suite/InRelease" "$probe" >/dev/null 2>&1; then
37新增: priority=$((priority + 1))
38新增: printf '%s\tpriority:%s\n' "$mirror" "$priority" >> "$stage"
39新增: else
40新增: printf 'Debian mirror unavailable; using the next source: %s\n' "$mirror"
41新增: fi
42新增: done
43新增: fi
44新增: priority=$((priority + 1))
45新增: printf '%s\tpriority:%s\n' "$official" "$priority" >> "$stage"
46新增: chmod 0644 "$stage"
47新增: mv -f "$stage" "$list"
48新增: rm -f "$probe"
49新增: trap - EXIT
50新增:done
51新增:CAGE_DEBIAN_MIRRORS
新增internal/cage/debian_mirrors_test.go+114 −0看文件
@@ -0,0 +1,114 @@
1新增:package cage
2新增:
3新增:import (
4新增: "os"
5新增: "os/exec"
6新增: "path/filepath"
7新增: "strings"
8新增: "testing"
9新增:)
10新增:
11新增:func TestDebianMirrorFailureFallbackAndPreference(t *testing.T) {
12新增: old := "https://mirrors.nju.edu.cn/debian\tpriority:1\nhttps://mirrors.ustc.edu.cn/debian\tpriority:2\nhttps://deb.debian.org/debian\tpriority:3\n"
13新增: for _, mode := range []string{"reachable", "bookworm", "tls-failure", "nju-failure", "official", "custom", "old", "reboot", "invalid"} {
14新增: t.Run(mode, func(t *testing.T) {
15新增: dir := t.TempDir()
16新增: mirrors := filepath.Join(dir, "mirrors")
17新增: os.MkdirAll(mirrors, 0755)
18新增: list := filepath.Join(mirrors, "debian.list")
19新增: content := "https://deb.debian.org/debian\n"
20新增: if mode == "custom" {
21新增: content = "https://custom.invalid/debian\n"
22新增: }
23新增: if mode == "old" {
24新增: content = old
25新增: }
26新增: if mode == "reboot" {
27新增: content = "# Cage managed Debian mirrors\nhttps://deb.debian.org/debian\tpriority:1\n"
28新增: }
29新增: os.WriteFile(list, []byte(content), 0644)
30新增: os.WriteFile(filepath.Join(mirrors, "debian-security.list"), []byte("https://deb.debian.org/debian-security\n"), 0644)
31新增: preference := filepath.Join(dir, "preference")
32新增: if mode == "official" || mode == "invalid" {
33新增: os.WriteFile(preference, []byte(mode+"\n"), 0644)
34新增: }
35新增: for name, body := range map[string]string{
36新增: "sudo": "#!/bin/sh\nexec \"$@\"\n",
37新增: "apt-helper": `#!/bin/sh
38新增:printf '%s\n' "$*" >> "$FIXTURE/probes"
39新增:[ "$MODE" != tls-failure ] || exit 1
40新增:case "$*" in *mirrors.nju*) [ "$MODE" != nju-failure ] || exit 1;; esac
41新增:exit 0
42新增:`,
43新增: "timeout": "#!/bin/sh\nshift\nexec \"$@\"\n",
44新增: } {
45新增: os.WriteFile(filepath.Join(dir, name), []byte(body), 0755)
46新增: }
47新增: script := strings.ReplaceAll(DebianMirrorsScript, "/etc/apt/mirrors", mirrors)
48新增: script = strings.ReplaceAll(script, "/etc/claude-cage/debian-mirror", preference)
49新增: script = strings.ReplaceAll(script, "/usr/lib/apt/apt-helper", filepath.Join(dir, "apt-helper"))
50新增: suite := "trixie"
51新增: if mode == "bookworm" {
52新增: suite = "bookworm"
53新增: }
54新增: osRelease := filepath.Join(dir, "os-release")
55新增: if err := os.WriteFile(osRelease, []byte("VERSION_CODENAME="+suite+"\n"), 0644); err != nil {
56新增: t.Fatal(err)
57新增: }
58新增: script = strings.ReplaceAll(script, "/etc/os-release", osRelease)
59新增: run := func() ([]byte, error) {
60新增: cmd := exec.Command("sh", "-c", script)
61新增: cmd.Env = append(os.Environ(), "PATH="+dir+":"+os.Getenv("PATH"), "FIXTURE="+dir, "MODE="+mode)
62新增: return cmd.CombinedOutput()
63新增: }
64新增: out, err := run()
65新增: if mode == "invalid" {
66新增: if err == nil {
67新增: t.Fatal("invalid preference accepted")
68新增: }
69新增: return
70新增: }
71新增: if err != nil {
72新增: t.Fatalf("%v %s", err, out)
73新增: }
74新增: data, _ := os.ReadFile(list)
75新增: got := string(data)
76新增: switch mode {
77新增: case "custom":
78新增: if got != content {
79新增: t.Fatal("custom source overwritten")
80新增: }
81新增: case "official", "tls-failure":
82新增: if strings.Contains(got, "mirrors.") || !strings.Contains(got, "deb.debian.org") {
83新增: t.Fatal(got)
84新增: }
85新增: case "nju-failure":
86新增: if strings.Contains(got, "mirrors.nju") || !strings.Contains(got, "mirrors.ustc") {
87新增: t.Fatal(got)
88新增: }
89新增: default:
90新增: if !strings.Contains(got, "mirrors.nju") {
91新增: t.Fatal(got)
92新增: }
93新增: }
94新增: if mode == "official" {
95新增: if probes, _ := os.ReadFile(filepath.Join(dir, "probes")); len(probes) > 0 {
96新增: t.Fatal("official preference contacted mirrors")
97新增: }
98新增: }
99新增: if mode == "reachable" || mode == "bookworm" {
100新增: probes, err := os.ReadFile(filepath.Join(dir, "probes"))
101新增: if err != nil || !strings.Contains(string(probes), "/dists/"+suite+"/InRelease") || !strings.Contains(string(probes), "/dists/"+suite+"-security/InRelease") {
102新增: t.Fatalf("wrong distribution probes: %s, %v", probes, err)
103新增: }
104新增: }
105新增: if out, err := run(); err != nil {
106新增: t.Fatalf("repeat: %v %s", err, out)
107新增: }
108新增: after, _ := os.ReadFile(list)
109新增: if string(after) != got {
110新增: t.Fatal("preference changed on repeated setup")
111新增: }
112新增: })
113新增: }
114新增:}
修改internal/cage/desktop-downloads.py+11 −0看文件
@@ -62,6 +62,17 @@ class Downloads:
6262 return [{key: value for key, value in item.items() if key not in ('sourceName', 'complete')}
6363 for item in reversed(list(self.records.values()))]
6464
65新增: def host_visible_path(self, path):
66新增: """Translate retained SaveFile staging locations to the published file."""
67新增: with self.lock:
68新增: for item in self.records.values():
69新增: source = self.source(item)
70新增: if path in (str(source), str(source.parent)):
71新增: if item['state'] != 'saved':
72新增: raise ValueError('文件尚未保存完成,请稍后重试')
73新增: return item['path'] if path == str(source) else str(Path(item['path']).parent)
74新增: return path
75新增:
6576 def begin(self, name):
6677 if not valid_name(name):
6778 raise ValueError('下载文件名无效')
修改internal/cage/desktop-downloads.test.py+3 −0看文件
@@ -67,6 +67,9 @@ class DesktopDownloadsTests(unittest.TestCase):
6767 self.assertEqual(item['name'], 'video (1).mp4')
6868 self.assertEqual(Path(item['path']).read_bytes(), b'export')
6969 self.assertEqual((self.workspace / 'Downloads' / 'video.mp4').read_bytes(), b'original')
70新增: self.assertEqual(self.manager.host_visible_path(str(target)), item['path'])
71新增: self.assertEqual(self.manager.host_visible_path(str(target.parent)), str(Path(item['path']).parent))
72新增: self.assertEqual(self.manager.host_visible_path('/etc/passwd'), '/etc/passwd')
7073
7174 def test_cancel_discards_partial_and_empty_download_completes_by_rename(self):
7275 target = Path(self.manager.begin('canceled.mp4'))
修改internal/cage/desktop-files.py+115 −17看文件
@@ -13,14 +13,26 @@ import socketserver
1313import subprocess
1414import sys
1515import threading
16新增:import time
1617import uuid
17删除:from urllib.parse import parse_qs, urlsplit
18新增:from urllib.parse import parse_qs, unquote, urlsplit
1819
1920LIMIT = 2 * 1024 ** 3
2021PORTAL = 'org.freedesktop.portal.FileChooser'
2122ROOT = '/org/freedesktop/portal/desktop'
2223
2324
25新增:def image_context():
26新增: result = subprocess.run(['/usr/local/bin/cage-native-input', '--request'],
27新增: input=b'{"mode":"status"}\n', stdout=subprocess.PIPE,
28新增: stderr=subprocess.DEVNULL, check=True, timeout=4)
29新增: value = json.loads(result.stdout)
30新增: context = value.get('context', '')
31新增: if value.get('available') is not True or not re.fullmatch('[a-f0-9]{32}', context):
32新增: raise ValueError('图片接收位置尚未聚焦,请点击输入框后重试')
33新增: return context
34新增:
35新增:
2436class Broker:
2537 def __init__(self, directory, deliver=lambda request, paths: None, downloads=None):
2638 self.directory = Path(directory)
@@ -31,23 +43,71 @@ class Broker:
3143 self.lock = threading.RLock()
3244
3345 def start(self, kind='paste', multiple=True, **metadata):
34删除: if kind not in ('paste', 'drop', 'chooser', 'save'):
46新增: if kind not in ('paste', 'drop', 'image', 'chooser', 'save', 'open'):
3547 raise ValueError('文件传递方式无效')
48新增: if kind == 'image':
49新增: metadata['image_context'] = image_context()
50新增: multiple = False
3651 with self.lock:
3752 if len(self.requests) >= 32:
3853 raise ValueError('请先完成已打开的文件窗口')
3954 key = str(uuid.uuid4())
4055 self.requests[key] = dict(id=key, kind=kind, multiple=multiple,
41删除: files=[], busy=False, **metadata)
56新增: files=[], busy=False, created=time.monotonic(), **metadata)
4257 return {'id': key}
4358
4459 def snapshot(self):
4560 with self.lock:
61新增: for key, request in list(self.requests.items()):
62新增: if request['kind'] == 'open' and time.monotonic() - request['created'] > 60:
63新增: self.complete_open(key, '本机文件操作已超时,请重新打开')
4664 return {'uploads': [dict(id=r['id'], multiple=r['multiple'],
4765 title=r.get('title', ''), target='desktop',
4866 directory=r.get('directory', False))
4967 for r in self.requests.values() if r['kind'] == 'chooser'],
50删除: 'downloads': self.downloads.snapshot() if self.downloads else []}
68新增: 'downloads': self.downloads.snapshot() if self.downloads else [],
69新增: 'opens': [{'id': r['id']} for r in self.requests.values()
70新增: if r['kind'] == 'open' and not r['busy']]}
71新增:
72新增: def open_path(self, path, action='open', **metadata):
73新增: if action not in ('open', 'reveal') or not isinstance(path, str) or not path or '\x00' in path:
74新增: raise ValueError('文件打开请求无效')
75新增: if path.startswith('file:'):
76新增: uri = urlsplit(path)
77新增: if uri.scheme != 'file' or uri.netloc not in ('', 'localhost') or uri.query or uri.fragment:
78新增: raise ValueError('请选择本机项目中的文件')
79新增: path = unquote(uri.path, errors='strict')
80新增: if not Path(path).is_absolute():
81新增: raise ValueError('文件打开请求需要绝对路径')
82新增: path = str(Path(path).resolve(strict=True))
83新增: return self.start('open', False, path=path, action=action, **metadata)
84新增:
85新增: def claim_open(self, key):
86新增: with self.lock:
87新增: request = self.requests.get(key)
88新增: if not request or request['kind'] != 'open' or request['busy']:
89新增: return {'handled': True}
90新增: if time.monotonic() - request['created'] > 60:
91新增: self.complete_open(key, '本机文件操作已超时,请重新打开')
92新增: return {'handled': True}
93新增: request['busy'] = True
94新增: path = request['path']
95新增: if self.downloads:
96新增: try:
97新增: path = self.downloads.host_visible_path(path)
98新增: except ValueError as error:
99新增: return {'error': str(error)}
100新增: return {'id': key, 'path': path, 'action': request['action']}
101新增:
102新增: def complete_open(self, key, error=''):
103新增: with self.lock:
104新增: request = self.requests.get(key)
105新增: if not request or request['kind'] != 'open':
106新增: return {'ok': True}
107新增: del self.requests[key]
108新增: if request.get('handle'):
109新增: self.deliver(request, None if error else [])
110新增: return {'ok': True}
51111
52112 def get(self, key):
53113 if key not in self.requests:
@@ -96,7 +156,7 @@ class Broker:
96156 def finish(self, key):
97157 with self.lock:
98158 request = self.get(key)
99删除: if request['busy'] or not request['files']:
159新增: if request['kind'] == 'image' or request['busy'] or not request['files']:
100160 raise ValueError('请先选择并传递文件')
101161 request['busy'] = True
102162 try:
@@ -111,6 +171,20 @@ class Broker:
111171 self.cancel(key)
112172 raise
113173
174新增: def finish_image(self, key):
175新增: with self.lock:
176新增: request = self.get(key)
177新增: if request['kind'] != 'image' or request['busy'] or len(request['files']) != 1:
178新增: raise ValueError('图片没有完整收到')
179新增: request['busy'] = True
180新增: try:
181新增: if image_context() != request['image_context']:
182新增: raise ValueError('图片接收位置已变化,请重新粘贴')
183新增: paste_files(request['files'], expected_context=request['image_context'])
184新增: return {'ok': True}
185新增: finally:
186新增: self.cancel(key)
187新增:
114188 def cancel(self, key, respond=True):
115189 with self.lock:
116190 request = self.requests.pop(key, None)
@@ -193,6 +267,8 @@ class Handler(BaseHTTPRequestHandler):
193267 result = broker.start(value.get('kind', 'paste'))
194268 elif route.path == '/finish':
195269 result = broker.finish(value.get('id', ''))
270新增: elif route.path == '/finish-image':
271新增: result = broker.finish_image(value.get('id', ''))
196272 elif route.path == '/cancel':
197273 key = value.get('id', '')
198274 if not re.fullmatch(r'[0-9a-f-]{36}', key):
@@ -200,6 +276,12 @@ class Handler(BaseHTTPRequestHandler):
200276 result = broker.cancel(key)
201277 elif route.path == '/directory':
202278 result = broker.choose_directory(value.get('id', ''), value.get('path', ''))
279新增: elif route.path == '/open':
280新增: result = broker.open_path(value.get('path', ''), value.get('action', 'open'))
281新增: elif route.path == '/open-claim':
282新增: result = broker.claim_open(value.get('id', ''))
283新增: elif route.path == '/open-complete':
284新增: result = broker.complete_open(value.get('id', ''), value.get('error', ''))
203285 elif route.path == '/download-retry' and broker.downloads:
204286 result = broker.downloads.retry(value.get('id', ''))
205287 else:
@@ -373,14 +455,14 @@ class Portal:
373455 self.unregister(self.connection, object_id)
374456
375457 def deliver(self, request, paths):
376删除: if request['kind'] not in ('chooser', 'save'):
458新增: if request['kind'] not in ('chooser', 'save', 'open'):
377459 paste_files(paths)
378460 return
379461 entries = []
380删除: if paths is not None:
462新增: if paths is not None and request['kind'] != 'open':
381463 uris = self.array('s', [self.new_string(Path(path).as_uri().encode()) for path in paths])
382464 entries.append(self.new_entry(self.new_string(b'uris'), self.new_variant(uris)))
383删除: response = self.tuple(self.new_uint(0 if paths is not None else 1), self.array('{sv}', entries))
465新增: response = self.tuple(self.new_uint(0 if paths is not None else (2 if request['kind'] == 'open' else 1)), self.array('{sv}', entries))
384466 if not self.emit(self.connection, request['sender'].encode(), request['handle'].encode(),
385467 b'org.freedesktop.portal.Request', b'Response', response, None):
386468 raise ValueError('原文件窗口已关闭')
@@ -390,10 +472,11 @@ class Portal:
390472 bind(self.glib, 'g_main_loop_run', None, C.c_void_p)(self.loop)
391473
392474
393删除:def paste_files(paths):
475新增:def paste_files(paths, expected_context=None):
394476 process = subprocess.Popen([sys.executable, __file__, '--clipboard'], stdin=subprocess.PIPE,
395477 stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
396删除: process.stdin.write(json.dumps(paths).encode())
478新增: value = paths if expected_context is None else dict(paths=paths, image_context=expected_context)
479新增: process.stdin.write(json.dumps(value).encode())
397480 process.stdin.close()
398481 try:
399482 ready, _, _ = select.select([process.stdout], [], [], 10)
@@ -405,7 +488,7 @@ def paste_files(paths):
405488 process.stdout.close()
406489
407490
408删除:def clipboard(paths):
491新增:def clipboard(paths, expected_context=None):
409492 gtk, gdk, glib = (C.CDLL(name) for name in ('libgtk-3.so.0', 'libgdk-3.so.0', 'libglib-2.0.so.0'))
410493 p = C.c_void_p
411494 if not bind(gtk, 'gtk_init_check', C.c_int, p, p)(None, None):
@@ -421,9 +504,18 @@ def clipboard(paths):
421504 _fields_ = [('target', C.c_char_p), ('flags', C.c_uint), ('info', C.c_uint)]
422505 provide_type = C.CFUNCTYPE(None, p, p, C.c_uint, p)
423506 clear_type = C.CFUNCTYPE(None, p, p)
424删除: names = [b'text/uri-list', b'x-special/gnome-copied-files']
425删除: uris = [Path(path).as_uri() for path in paths]
426删除: payloads = [('\r\n'.join(uris) + '\r\n').encode(), ('copy\n' + '\n'.join(uris)).encode()]
507新增: if expected_context is not None:
508新增: if len(paths) != 1 or image_context() != expected_context:
509新增: raise ValueError('图片接收位置已变化,请重新粘贴')
510新增: with open(paths[0], 'rb') as image:
511新增: data = image.read(20 * 1024 * 1024 + 1)
512新增: if len(data) > 20 * 1024 * 1024 or not data.startswith(b'\x89PNG\r\n\x1a\n'):
513新增: raise ValueError('PNG 图片无效')
514新增: names, payloads = [b'image/png'], [data]
515新增: else:
516新增: names = [b'text/uri-list', b'x-special/gnome-copied-files']
517新增: uris = [Path(path).as_uri() for path in paths]
518新增: payloads = [('\r\n'.join(uris) + '\r\n').encode(), ('copy\n' + '\n'.join(uris)).encode()]
427519 buffers = [C.create_string_buffer(data) for data in payloads]
428520 acknowledged = False
429521 @stop_type
@@ -441,12 +533,14 @@ def clipboard(paths):
441533 @clear_type
442534 def clear(_clipboard, _data):
443535 timeout(10000, stop, None)
444删除: targets = (Target * 2)(*(Target(name, 0, index) for index, name in enumerate(names)))
536新增: targets = (Target * len(names))(*(Target(name, 0, index) for index, name in enumerate(names)))
445537 get = bind(gtk, 'gtk_clipboard_get', p, p)
446538 own = bind(gtk, 'gtk_clipboard_set_with_data', C.c_int, p, C.POINTER(Target), C.c_uint, provide_type, clear_type, p)
447删除: if not own(get(atom(b'CLIPBOARD')), targets, 2, provide, clear, None):
539新增: if not own(get(atom(b'CLIPBOARD')), targets, len(names), provide, clear, None):
448540 raise RuntimeError('clipboard unavailable')
449541 flush()
542新增: if expected_context is not None and image_context() != expected_context:
543新增: raise ValueError('图片接收位置已变化,请重新粘贴')
450544 subprocess.run(['xdotool', 'key', '--clearmodifiers', 'ctrl+v'], check=True,
451545 stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=3)
452546 timeout(120000, stop, None)
@@ -470,7 +564,11 @@ def main():
470564 raise
471565 return
472566 if sys.argv[1:] == ['--clipboard']:
473删除: clipboard(json.load(sys.stdin))
567新增: value = json.load(sys.stdin)
568新增: if isinstance(value, dict):
569新增: clipboard(value['paths'], value['image_context'])
570新增: else:
571新增: clipboard(value)
474572 return
475573 runtime = Path(os.environ['XDG_RUNTIME_DIR'])
476574 directory = runtime / 'uploads'
修改internal/cage/desktop-files.test.py+127 −0看文件
@@ -1,8 +1,13 @@
11import importlib.util
22import io
3新增:import os
34from pathlib import Path
5新增:import subprocess
6新增:import sys
47import tempfile
8新增:import threading
59import unittest
10新增:from unittest.mock import patch
611
712spec = importlib.util.spec_from_file_location('desktop_files', Path(__file__).with_name('desktop-files.py'))
813files = importlib.util.module_from_spec(spec)
@@ -53,6 +58,27 @@ class FileBrokerTests(unittest.TestCase):
5358 with self.assertRaisesRegex(ValueError, 'target closed'): self.broker.finish(key)
5459 self.assertFalse((Path(self.temp.name) / key).exists())
5560
61新增: def test_image_preparation_retains_focus_and_releases_received_bytes(self):
62新增: context = 'a' * 32
63新增: received = []
64新增: def paste(paths, expected_context=None):
65新增: received.append((Path(paths[0]).read_bytes(), expected_context))
66新增: with patch.object(files, 'image_context', lambda: context), patch.object(files, 'paste_files', paste):
67新增: key = self.broker.start('image')['id']
68新增: self.broker.receive(key, 'image.png', [b'PNG fixture'])
69新增: with self.assertRaises(ValueError):
70新增: self.broker.finish(key)
71新增: self.broker.finish_image(key)
72新增: self.assertEqual(received, [(b'PNG fixture', 'a' * 32)])
73新增: self.assertFalse((Path(self.temp.name) / key).exists())
74新增: key = self.broker.start('image')['id']
75新增: self.broker.receive(key, 'image.png', [b'old image'])
76新增: context = 'b' * 32
77新增: with self.assertRaisesRegex(ValueError, '接收位置已变化'):
78新增: self.broker.finish_image(key)
79新增: self.assertEqual(len(received), 1)
80新增: self.assertFalse((Path(self.temp.name) / key).exists())
81新增:
5682 def test_directory_selection_returns_live_directory_without_copying(self):
5783 project = Path(self.temp.name) / '项目 #+%'
5884 project.mkdir()
@@ -73,6 +99,107 @@ class FileBrokerTests(unittest.TestCase):
7399 key = self.broker.start('chooser')['id']
74100 with self.assertRaises(ValueError): self.broker.choose_directory(key, str(project))
75101
102新增: def test_local_file_uri_and_relative_folder_become_single_use_requests(self):
103新增: document = Path(self.temp.name) / '报告 #+%.docx'
104新增: document.write_bytes(b'document')
105新增: key = self.broker.open_path(document.as_uri(), 'reveal')['id']
106新增: self.assertEqual(self.broker.snapshot()['opens'], [{'id': key}])
107新增: # Two native windows must not launch the same action twice.
108新增: results = []
109新增: threads = [threading.Thread(target=lambda: results.append(self.broker.claim_open(key))) for _ in range(2)]
110新增: for thread in threads: thread.start()
111新增: for thread in threads: thread.join()
112新增: self.assertEqual(sum(r.get('handled', False) for r in results), 1)
113新增: self.assertIn({'id': key, 'path': str(document.resolve()), 'action': 'reveal'}, results)
114新增: self.broker.complete_open(key)
115新增: self.assertEqual(self.broker.snapshot()['opens'], [])
116新增: self.assertEqual(self.broker.claim_open(key), {'handled': True})
117新增: for path in ['', 'file://remote-host/etc/passwd', document.as_uri() + '?invalid', 'https://example.com']:
118新增: with self.assertRaises((ValueError, OSError)):
119新增: self.broker.open_path(path)
120新增:
121新增: def test_portal_failure_timeout_and_close_release_requests(self):
122新增: chooser = self.broker.start('chooser')['id']
123新增: self.broker.complete_open(chooser)
124新增: self.assertIn(chooser, self.broker.requests)
125新增: self.broker.cancel(chooser)
126新增: key = self.broker.open_path(self.temp.name, 'reveal', handle='/request/test')['id']
127新增: self.broker.claim_open(key)
128新增: self.broker.complete_open(key, 'permission denied')
129新增: self.assertIsNone(self.delivered[-1][1])
130新增: key = self.broker.open_path(self.temp.name, handle='/request/timeout')['id']
131新增: self.broker.requests[key]['created'] -= 61
132新增: self.assertEqual(self.broker.snapshot()['opens'], [])
133新增: self.assertNotIn(key, self.broker.requests)
134新增: self.assertIsNone(self.delivered[-1][1])
135新增:
136新增:
137新增:@unittest.skipUnless(sys.platform == 'linux' and os.environ.get('DBUS_SESSION_BUS_ADDRESS'),
138新增: 'requires an isolated Linux D-Bus session')
139新增:class DesktopFileDBusTests(unittest.TestCase):
140新增: def test_real_filemanager_portal_fd_and_xdg_open(self):
141新增: import gi
142新增: gi.require_version('Gio', '2.0')
143新增: from gi.repository import Gio, GLib
144新增: with tempfile.TemporaryDirectory() as directory:
145新增: root = Path(directory)
146新增: document = root / 'Word 报告 #+%.docx'
147新增: document.write_bytes(b'generated document')
148新增: broker = files.Broker(root / 'uploads')
149新增: portal = files.Portal(broker)
150新增: broker.deliver = portal.deliver
151新增: threading.Thread(target=portal.run, daemon=True).start()
152新增: client = Gio.DBusConnection.new_for_address_sync(os.environ['DBUS_SESSION_BUS_ADDRESS'],
153新增: Gio.DBusConnectionFlags.AUTHENTICATION_CLIENT | Gio.DBusConnectionFlags.MESSAGE_BUS_CONNECTION, None, None)
154新增: responses, received = [], threading.Event()
155新增: def response(_connection, _sender, _path, _interface, _signal, parameters):
156新增: responses.append(parameters.unpack())
157新增: received.set()
158新增: client.signal_subscribe(None, 'org.freedesktop.portal.Request', 'Response', None, None,
159新增: Gio.DBusSignalFlags.NONE, response)
160新增: client.call_sync('org.freedesktop.FileManager1', '/org/freedesktop/FileManager1',
161新增: 'org.freedesktop.FileManager1', 'ShowItems', GLib.Variant('(ass)', ([document.as_uri()], '')),
162新增: None, Gio.DBusCallFlags.NONE, 5000, None)
163新增: key = broker.snapshot()['opens'][0]['id']
164新增: self.assertEqual(broker.claim_open(key)['path'], str(document))
165新增: broker.complete_open(key)
166新增:
167新增: for failure in (False, True):
168新增: descriptors = Gio.UnixFDList.new()
169新增: with document.open('rb') as source:
170新增: index = descriptors.append(source.fileno())
171新增: result, _ = client.call_with_unix_fd_list_sync('org.freedesktop.portal.Desktop', files.ROOT,
172新增: 'org.freedesktop.portal.OpenURI', 'OpenDirectory',
173新增: GLib.Variant('(sha{sv})', ('', index, {'handle_token': GLib.Variant('s', 'reveal_' + str(failure))})),
174新增: GLib.VariantType.new('(o)'), Gio.DBusCallFlags.NONE, 5000, descriptors, None)
175新增: key = broker.snapshot()['opens'][0]['id']
176新增: request = broker.claim_open(key)
177新增: self.assertEqual(request['path'], str(document))
178新增: self.assertEqual(request['action'], 'reveal')
179新增: self.assertEqual(broker.requests[key]['handle'], result.unpack()[0])
180新增: received.clear()
181新增: broker.complete_open(key, 'test denied' if failure else '')
182新增: self.assertTrue(received.wait(5))
183新增: self.assertEqual(responses[-1], (2 if failure else 0, {}))
184新增:
185新增: # Run the actual shell and Python entry points against their private
186新增: # Unix socket. This also exercises Electron's relative `.` fallback.
187新增: socket = Path('/run/cage-desktop/files.sock')
188新增: server = files.FileServer(str(socket), files.Handler)
189新增: server.broker = broker
190新增: threading.Thread(target=server.serve_forever, daemon=True).start()
191新增: try:
192新增: for argument, want in ((document.as_uri(), str(document)), ('.', str(root))):
193新增: subprocess.run(['sh', str(Path(__file__).with_name('guest-open.sh').resolve()), argument],
194新增: cwd=root, check=True, timeout=10)
195新增: key = broker.snapshot()['opens'][0]['id']
196新增: self.assertEqual(broker.claim_open(key)['path'], want)
197新增: broker.complete_open(key)
198新增: finally:
199新增: server.shutdown()
200新增: server.server_close()
201新增: socket.unlink(missing_ok=True)
202新增:
76203
77204if __name__ == '__main__':
78205 unittest.main()
修改internal/cage/exit_policy.go+3 −125看文件
@@ -1,128 +1,6 @@
11package cage
22
3删除:import (
4删除: "errors"
5删除: "net/netip"
6删除: "regexp"
7删除: "strings"
8删除:)
3新增:import "github.com/sylvinus/agent-vm/internal/exitpolicy"
94
10删除:// ExitPolicy is user configuration. Its anchor survives checks and restarts;
11删除:// observations must never silently replace a configured address or region.
12删除:type ExitPolicy struct {
13删除: Mode string `json:"mode"`
14删除: Scope string `json:"scope"`
15删除: IP string `json:"ip,omitempty"`
16删除: CountryCode string `json:"country_code,omitempty"`
17删除: Region string `json:"region,omitempty"`
18删除: City string `json:"city,omitempty"`
19删除:}
20删除:
21删除:type ExitLocation struct{ IP, CountryCode, Region, City string }
22删除:
23删除:func (p ExitPolicy) Normalized() ExitPolicy {
24删除: if p.Mode == "" {
25删除: p.Mode = "dynamic"
26删除: }
27删除: if p.Scope == "" {
28删除: p.Scope = "country"
29删除: }
30删除: p.IP = strings.TrimSpace(p.IP)
31删除: p.CountryCode = strings.ToUpper(strings.TrimSpace(p.CountryCode))
32删除: p.Region = strings.Join(strings.Fields(p.Region), " ")
33删除: p.City = strings.Join(strings.Fields(p.City), " ")
34删除: return p
35删除:}
36删除:
37删除:func (p ExitPolicy) Validate() error {
38删除: p = p.Normalized()
39删除: if p.Mode != "static" && p.Mode != "dynamic" {
40删除: return errors.New("请选择静态或动态 IP")
41删除: }
42删除: if p.Scope != "any" && p.Scope != "country" && p.Scope != "city" {
43删除: return errors.New("请选择动态 IP 的允许范围")
44删除: }
45删除: if p.IP != "" {
46删除: ip, err := netip.ParseAddr(p.IP)
47删除: if err != nil || !ip.Is4() || !ip.IsGlobalUnicast() || ip.IsPrivate() {
48删除: return errors.New("固定出口应填写公网 IPv4 地址")
49删除: }
50删除: }
51删除: if p.CountryCode != "" && !regexp.MustCompile(`^[A-Z]{2}$`).MatchString(p.CountryCode) {
52删除: return errors.New("国家或地区代码应为两个字母,例如 US")
53删除: }
54删除: if len(p.Region) > 120 || len(p.City) > 120 {
55删除: return errors.New("地区名称过长")
56删除: }
57删除: return nil
58删除:}
59删除:
60删除:func (p ExitPolicy) NeedsBinding() bool {
61删除: p = p.Normalized()
62删除: if p.Mode == "static" {
63删除: return p.IP == ""
64删除: }
65删除: return p.Scope != "any" && (p.CountryCode == "" || p.Scope == "city" && (p.Region == "" || p.City == ""))
66删除:}
67删除:
68删除:// BindMissing is used only for a previously unconfigured anchor. It leaves
69删除:// existing values intact, including when the new observation violates them.
70删除:func (p ExitPolicy) BindMissing(location ExitLocation) ExitPolicy {
71删除: p = p.Normalized()
72删除: if p.Mode == "static" && p.IP == "" {
73删除: p.IP = location.IP
74删除: }
75删除: if p.Mode == "dynamic" && p.Scope != "any" {
76删除: if p.CountryCode == "" {
77删除: p.CountryCode = location.CountryCode
78删除: }
79删除: if p.Scope == "city" && strings.EqualFold(p.CountryCode, location.CountryCode) {
80删除: if p.Region == "" {
81删除: p.Region = location.Region
82删除: }
83删除: if p.City == "" {
84删除: p.City = location.City
85删除: }
86删除: }
87删除: }
88删除: return p.Normalized()
89删除:}
90删除:
91删除:func (p ExitPolicy) Evaluate(ip string, location *ExitLocation) (CheckState, string) {
92删除: p = p.Normalized()
93删除: if err := p.Validate(); err != nil {
94删除: return CheckUnknown, err.Error()
95删除: }
96删除: observed, err := netip.ParseAddr(ip)
97删除: if err != nil || !observed.Is4() || !observed.IsGlobalUnicast() || observed.IsPrivate() {
98删除: return CheckUnknown, "尚未取得有效的检测出口"
99删除: }
100删除: if p.NeedsBinding() {
101删除: return CheckUnknown, "尚未绑定出口规则,请在设置中确认检测到的 IP 或地区"
102删除: }
103删除: if p.Mode == "static" {
104删除: if p.IP != observed.String() {
105删除: return CheckFailed, "检测出口已偏离绑定的静态 IP"
106删除: }
107删除: return CheckPassed, "检测出口与绑定的静态 IP 一致"
108删除: }
109删除: if p.Scope == "any" {
110删除: return CheckPassed, "动态 IP 不限制地区,流量仍须经指定代理"
111删除: }
112删除: if location == nil || location.IP != observed.String() || location.CountryCode == "" {
113删除: return CheckUnknown, "无法取得当前出口的国家或地区,不能确认允许范围"
114删除: }
115删除: if !strings.EqualFold(p.CountryCode, location.CountryCode) {
116删除: return CheckFailed, "检测出口超出允许的国家或地区"
117删除: }
118删除: if p.Scope == "country" {
119删除: return CheckPassed, "检测出口位于允许的国家或地区"
120删除: }
121删除: if location.Region == "" || location.City == "" {
122删除: return CheckUnknown, "当前位置缺少州、省或城市,不能确认城市范围"
123删除: }
124删除: if !strings.EqualFold(p.Region, strings.Join(strings.Fields(location.Region), " ")) || !strings.EqualFold(p.City, strings.Join(strings.Fields(location.City), " ")) {
125删除: return CheckFailed, "检测出口超出允许的城市范围"
126删除: }
127删除: return CheckPassed, "检测出口位于允许的城市及其所属州、省"
128删除:}
5新增:type ExitPolicy = exitpolicy.Policy
6新增:type ExitLocation = exitpolicy.Location
修改internal/cage/exit_policy_test.go+20 −3看文件
@@ -7,6 +7,8 @@ func TestExitPolicyStaticAndGeographicChanges(t *testing.T) {
77 city := ExitPolicy{Mode: "dynamic", Scope: "city"}.BindMissing(base)
88 country := city
99 country.Scope = "country"
10新增: region := city
11新增: region.Scope, region.City = "region", ""
1012 static := ExitPolicy{Mode: "static"}.BindMissing(base)
1113 for _, tc := range []struct {
1214 name string
@@ -15,13 +17,18 @@ func TestExitPolicyStaticAndGeographicChanges(t *testing.T) {
1517 want CheckState
1618 }{
1719 {"same IP", static, base, CheckPassed},
18删除: {"static changes", static, ExitLocation{IP: "1.1.1.1"}, CheckFailed},
20新增: {"static changes", static, ExitLocation{IP: "1.1.1.1", CountryCode: "US"}, CheckFailed},
1921 {"same city new IP", city, ExitLocation{IP: "1.1.1.1", CountryCode: "US", Region: "california", City: "Los Angeles"}, CheckPassed},
2022 {"city moves", city, ExitLocation{IP: "1.1.1.1", CountryCode: "US", Region: "California", City: "San Jose"}, CheckFailed},
2123 {"same name different state", city, ExitLocation{IP: "1.1.1.1", CountryCode: "US", Region: "Texas", City: "Los Angeles"}, CheckFailed},
2224 {"country allows city change", country, ExitLocation{IP: "1.1.1.1", CountryCode: "US", Region: "New York", City: "New York"}, CheckPassed},
2325 {"country moves", country, ExitLocation{IP: "1.1.1.1", CountryCode: "JP", Region: "Tokyo", City: "Tokyo"}, CheckFailed},
2426 {"missing city", city, ExitLocation{IP: "1.1.1.1", CountryCode: "US", Region: "California"}, CheckUnknown},
27新增: {"region allows city change", region, ExitLocation{IP: "1.1.1.1", CountryCode: "US", Region: "california", City: "San Jose"}, CheckPassed},
28新增: {"region does not require city", region, ExitLocation{IP: "1.1.1.1", CountryCode: "US", Region: "California"}, CheckPassed},
29新增: {"region changes", region, ExitLocation{IP: "1.1.1.1", CountryCode: "US", Region: "Texas"}, CheckFailed},
30新增: {"region country changes", region, ExitLocation{IP: "1.1.1.1", CountryCode: "CA", Region: "California"}, CheckFailed},
31新增: {"region evidence missing", region, ExitLocation{IP: "1.1.1.1", CountryCode: "US"}, CheckUnknown},
2532 } {
2633 t.Run(tc.name, func(t *testing.T) {
2734 got, _ := tc.policy.Evaluate(tc.location.IP, &tc.location)
@@ -36,8 +43,8 @@ func TestExitPolicyStaticAndGeographicChanges(t *testing.T) {
3643 if got, _ := country.Evaluate("1.1.1.1", nil); got != CheckUnknown {
3744 t.Fatal("missing geography was accepted")
3845 }
39删除: if got, _ := (ExitPolicy{Mode: "dynamic", Scope: "any"}).Evaluate("1.1.1.1", nil); got != CheckPassed {
40删除: t.Fatal("unrestricted dynamic mode incorrectly required geography")
46新增: if got, _ := (ExitPolicy{Mode: "dynamic", Scope: "any"}).Evaluate("1.1.1.1", nil); got != CheckUnknown {
47新增: t.Fatal("unrestricted dynamic mode bypassed mandatory country evidence")
4148 }
4249 if changed := static.BindMissing(ExitLocation{IP: "1.1.1.1"}); changed.IP != static.IP {
4350 t.Fatal("recheck silently rebound static IP")
@@ -45,4 +52,14 @@ func TestExitPolicyStaticAndGeographicChanges(t *testing.T) {
4552 if changed := city.BindMissing(ExitLocation{CountryCode: "JP", Region: "Tokyo", City: "Tokyo"}); changed != city {
4653 t.Fatal("recheck silently rebound city")
4754 }
55新增: boundRegion := (ExitPolicy{Mode: "dynamic", Scope: "region"}).BindMissing(base)
56新增: if boundRegion.NeedsBinding() || boundRegion.Region != base.Region || boundRegion.City != "" {
57新增: t.Fatalf("region binding: %+v", boundRegion)
58新增: }
59新增: if changed := boundRegion.BindMissing(ExitLocation{CountryCode: "US", Region: "Texas"}); changed != boundRegion {
60新增: t.Fatal("recheck silently rebound region")
61新增: }
62新增: if !(ExitPolicy{Mode: "dynamic", Scope: "region", CountryCode: "JP"}).NeedsBinding() {
63新增: t.Fatal("region without an anchor accepted")
64新增: }
4865}
修改internal/cage/gate.go+16 −14看文件
@@ -38,20 +38,21 @@ type GateCounters struct {
3838}
3939
4040type GateStatus struct {
41删除: Epoch uint64 `json:"epoch"`
42删除: PolicyVerified bool `json:"policy_verified"`
43删除: Policy string `json:"policy"`
44删除: RunID string `json:"run_id"`
45删除: CheckID string `json:"check_id,omitempty"`
46删除: CheckStartedAt time.Time `json:"check_started_at,omitempty"`
47删除: Configuration string `json:"configuration"`
48删除: Mode string `json:"mode"`
49删除: Fault bool `json:"fault"`
50删除: Until time.Time `json:"until"`
51删除: Reason string `json:"reason,omitempty"`
52删除: Counters GateCounters `json:"counters"`
53删除: Connections int `json:"connections"`
54删除: Report *SafetyReport `json:"report,omitempty"`
41新增: IPv6LinkProbeCheck string `json:"ipv6_link_probe_check,omitempty"`
42新增: Epoch uint64 `json:"epoch"`
43新增: PolicyVerified bool `json:"policy_verified"`
44新增: Policy string `json:"policy"`
45新增: RunID string `json:"run_id"`
46新增: CheckID string `json:"check_id,omitempty"`
47新增: CheckStartedAt time.Time `json:"check_started_at,omitempty"`
48新增: Configuration string `json:"configuration"`
49新增: Mode string `json:"mode"`
50新增: Fault bool `json:"fault"`
51新增: Until time.Time `json:"until"`
52新增: Reason string `json:"reason,omitempty"`
53新增: Counters GateCounters `json:"counters"`
54新增: Connections int `json:"connections"`
55新增: Report *SafetyReport `json:"report,omitempty"`
5556}
5657
5758// EgressGate is owned by the hostagent, not by the guest or browser UI.
@@ -212,6 +213,7 @@ func (g *EgressGate) BeginCheck() error {
212213 g.mu.Lock()
213214 connections := g.transitionLocked(GateChecking, false, "关键检查进行中")
214215 g.state.CheckID = hex.EncodeToString(id[:])
216新增: g.state.IPv6LinkProbeCheck = ""
215217 g.state.CheckStartedAt = time.Now()
216218 g.probeRequests = 0
217219 g.armLocked(3 * time.Minute)
新增internal/cage/gate_ipv6.go+37 −0看文件
@@ -0,0 +1,37 @@
1新增:package cage
2新增:
3新增:import (
4新增: "bytes"
5新增: "encoding/binary"
6新增: "net/netip"
7新增:)
8新增:
9新增:const MacIPv6ProbePort = 49417
10新增:const MacIPv6ProbePrefix = "Cage IPv6 link probe v1 "
11新增:
12新增:// ObserveDroppedIPv6 is called at the actual VM switch, before forwarding,
13新增:// only when its instantiated network stack has no IPv6 protocol. Validate the
14新增:// complete datagram; ambient NDP, stale checks or another VM cannot attest it.
15新增:func (g *EgressGate) ObserveDroppedIPv6(packet []byte) {
16新增: if len(packet) < 48 || packet[0]>>4 != 6 || packet[6] != 17 || packet[7] != 1 {
17新增: return
18新增: }
19新增: n := int(binary.BigEndian.Uint16(packet[4:6]))
20新增: if n+40 != len(packet) || n != int(binary.BigEndian.Uint16(packet[44:46])) || binary.BigEndian.Uint16(packet[42:44]) != MacIPv6ProbePort || binary.BigEndian.Uint16(packet[46:48]) == 0 {
21新增: return
22新增: }
23新增: src := netip.AddrFrom16([16]byte(packet[8:24]))
24新增: dst := netip.AddrFrom16([16]byte(packet[24:40]))
25新增: if !src.IsLinkLocalUnicast() || dst != netip.MustParseAddr("ff02::2") || !bytes.HasPrefix(packet[48:], []byte(MacIPv6ProbePrefix)) {
26新增: return
27新增: }
28新增: g.mu.Lock()
29新增: defer g.mu.Unlock()
30新增: if g.state.Mode != GateChecking || !g.validLocked(g.epoch) || g.state.CheckID == "" {
31新增: return
32新增: }
33新增: want := MacIPv6ProbePrefix + g.state.RunID + " " + g.state.CheckID
34新增: if string(packet[48:]) == want {
35新增: g.state.IPv6LinkProbeCheck = g.state.CheckID
36新增: }
37新增:}
新增internal/cage/gate_ipv6_test.go+49 −0看文件
@@ -0,0 +1,49 @@
1新增:package cage
2新增:
3新增:import (
4新增: "encoding/binary"
5新增: "net/netip"
6新增: "testing"
7新增:)
8新增:
9新增:func TestMacIPv6DropRequiresThisCheckingInstance(t *testing.T) {
10新增: g := fixtureGate(t)
11新增: if err := g.BeginCheck(); err != nil {
12新增: t.Fatal(err)
13新增: }
14新增: s := g.Status()
15新增: payload := []byte(MacIPv6ProbePrefix + s.RunID + " " + s.CheckID)
16新增: packet := make([]byte, 48+len(payload))
17新增: packet[0] = 0x60
18新增: packet[6] = 17
19新增: packet[7] = 1
20新增: binary.BigEndian.PutUint16(packet[4:6], uint16(8+len(payload)))
21新增: a := netip.MustParseAddr("fe80::1").As16()
22新增: copy(packet[8:24], a[:])
23新增: a = netip.MustParseAddr("ff02::2").As16()
24新增: copy(packet[24:40], a[:])
25新增: binary.BigEndian.PutUint16(packet[42:44], MacIPv6ProbePort)
26新增: binary.BigEndian.PutUint16(packet[44:46], uint16(8+len(payload)))
27新增: packet[47] = 1
28新增: copy(packet[48:], payload)
29新增: for _, position := range []int{0, 5, 6, 7, 8, 24, 42, 45, 48, len(packet) - 1} {
30新增: wrong := append([]byte(nil), packet...)
31新增: wrong[position] ^= 0xff
32新增: g.ObserveDroppedIPv6(wrong)
33新增: if g.Status().IPv6LinkProbeCheck != "" {
34新增: t.Fatalf("unrelated datagram accepted (byte %d)", position)
35新增: }
36新增: }
37新增: g.ObserveDroppedIPv6(packet)
38新增: if g.Status().IPv6LinkProbeCheck != s.CheckID {
39新增: t.Fatal("matching received datagram not recorded")
40新增: }
41新增: g.Close("reset")
42新增: if err := g.BeginCheck(); err != nil {
43新增: t.Fatal(err)
44新增: }
45新增: g.ObserveDroppedIPv6(packet)
46新增: if g.Status().IPv6LinkProbeCheck != "" {
47新增: t.Fatal("replayed earlier check")
48新增: }
49新增:}
修改internal/cage/gate_probe.go+9 −3看文件
@@ -15,6 +15,8 @@ import (
1515 "time"
1616
1717 "github.com/miekg/dns"
18新增: "github.com/sylvinus/agent-vm/internal/diagnostics"
19新增: "github.com/sylvinus/agent-vm/internal/usererror"
1820)
1921
2022// ProbeExitIP sends a fixed request through the configured proxy. It does not
@@ -35,14 +37,18 @@ func probeExitIP(ctx context.Context, e *Egress) (string, error) {
3537 req.Header.Set("User-Agent", "Cage-network-check/1")
3638 resp, err := client.Do(req)
3739 if err != nil {
38删除: return "", errors.New("无法经指定代理读取检测出口")
40新增: diagnostics.Log("warn", "exit-probe", fmt.Sprintf("exit query transport: %v", err))
41新增: return "", usererror.Wrap("通过所选代理查询出口 IP", err, "请检查网络与代理中的节点是否可用,再重新检测;未能确认出口时,外网保持关闭。")
3942 }
4043 defer resp.Body.Close()
4144 var data struct {
4245 IP string `json:"ip"`
4346 }
44删除: if resp.StatusCode != 200 || json.NewDecoder(io.LimitReader(resp.Body, 4096)).Decode(&data) != nil {
45删除: return "", errors.New("出口检测服务没有返回有效结果")
47新增: if resp.StatusCode != 200 {
48新增: return "", fmt.Errorf("查询出口 IP 失败:检测服务返回 HTTP %d。请检查所选代理,稍后重新检测;外网保持关闭。", resp.StatusCode)
49新增: }
50新增: if json.NewDecoder(io.LimitReader(resp.Body, 4096)).Decode(&data) != nil {
51新增: return "", errors.New("查询出口 IP 失败:检测服务没有返回有效的 IP 记录。请更换可用节点或稍后重新检测;外网保持关闭。")
4652 }
4753 ip, err := netip.ParseAddr(data.IP)
4854 if err != nil || !ip.Is4() || !ip.IsGlobalUnicast() || ip.IsPrivate() {
修改internal/cage/gate_test.go+1 −0看文件
@@ -64,6 +64,7 @@ func TestSafetyReportRequiresCompleteCurrentEvidence(t *testing.T) {
6464 "missing evidence": func(r *SafetyReport) { r.Checks[0].Evidence = "" },
6565 "duplicate": func(r *SafetyReport) { r.Checks = append(r.Checks, r.Checks[0]) },
6666 "old VM": func(r *SafetyReport) { r.RunID = "old-run" },
67新增: "old country policy": func(r *SafetyReport) { r.Policy = "cage-safety/2" },
6768 "other configuration": func(r *SafetyReport) { r.Configuration = "other" },
6869 "expired": func(r *SafetyReport) { r.CreatedAt = time.Now().Add(-25 * time.Hour) },
6970 } {
修改internal/cage/guest-services.sh+15 −6看文件
@@ -3,14 +3,23 @@
33if systemctl is-active --quiet cage-webvnc; then
44 sudo systemctl stop cage-webvnc
55fi
6删除:if ! command -v X0tigervnc >/dev/null || ! command -v Xtigervnc >/dev/null || ! command -v openbox >/dev/null || ! command -v xrandr >/dev/null || ! command -v xdotool >/dev/null || ! command -v ibus-daemon >/dev/null || ! /usr/bin/python3 -c 'import gi; gi.require_version("IBus", "1.0")' 2>/dev/null; then
7删除: sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get install -y --no-install-recommends tigervnc-standalone-server tigervnc-scraping-server tigervnc-tools openbox x11-xserver-utils xdotool libgtk-3-0 ibus ibus-gtk3 gir1.2-ibus-1.0 python3-gi
6新增:if ! command -v X0tigervnc >/dev/null || ! command -v Xtigervnc >/dev/null || ! command -v openbox >/dev/null || ! command -v xrandr >/dev/null || ! command -v xdotool >/dev/null || ! command -v ibus-daemon >/dev/null || ! /usr/bin/python3 -c 'import gi; gi.require_version("IBus", "1.0"); gi.require_version("Gtk", "3.0")' 2>/dev/null; then
7新增: sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get install -y --no-install-recommends tigervnc-standalone-server tigervnc-scraping-server tigervnc-tools openbox x11-xserver-utils xdotool libgtk-3-0 ibus ibus-gtk3 gir1.2-ibus-1.0 gir1.2-gtk-3.0 python3-gi
88fi
9新增:cage_novnc_root=/usr/share/novnc
10新增:if cage_is_ubuntu; then
11新增: cage_install_ubuntu_novnc
12新增: cage_novnc_root=/usr/local/share/cage-novnc
13新增:fi
14新增:sudo install -d -m 0755 /usr/local/share
15新增:sudo ln -sfn "$cage_novnc_root" /usr/local/share/cage-webvnc
916sudo install -d -m 0755 /etc/claude-cage /usr/local/lib
1017# New website passwords belong to the host vault. Keep existing browser data.
11删除:sudo install -d -m 0755 /etc/chromium/policies/managed
12删除:printf '%s\n' '{"PasswordManagerEnabled":false}' | sudo tee /etc/chromium/policies/managed/cage-password-vault.json >/dev/null
13删除:sudo chmod 0644 /etc/chromium/policies/managed/cage-password-vault.json
18新增:cage_browser_policy_dir=/etc/chromium/policies/managed
19新增:if cage_is_ubuntu; then cage_browser_policy_dir=/etc/opt/chrome_for_testing/policies/managed; fi
20新增:sudo install -d -m 0755 "$cage_browser_policy_dir"
21新增:printf '%s\n' '{"PasswordManagerEnabled":false}' | sudo tee "$cage_browser_policy_dir/cage-password-vault.json" >/dev/null
22新增:sudo chmod 0644 "$cage_browser_policy_dir/cage-password-vault.json"
1423sudo tee /usr/local/bin/cage-editor-start >/dev/null <<'SCRIPT'
1524#!/bin/sh
1625set -eu
@@ -113,7 +122,7 @@ Requires=cage-vnc.service
113122After=cage-vnc.service
114123[Service]
115124User=cage-browser
116删除:ExecStart=/usr/local/bin/cage-log-run /usr/bin/websockify --web=/usr/share/novnc 127.0.0.1:16080 127.0.0.1:15900
125新增:ExecStart=/usr/local/bin/cage-log-run /usr/bin/websockify --web=/usr/local/share/cage-webvnc 127.0.0.1:16080 127.0.0.1:15900
117126LogNamespace=cage
118127Restart=on-failure
119128UNIT
修改internal/cage/guest-start.sh+17 −10看文件
@@ -14,12 +14,23 @@ fi
1414sudo install -d -o cage-browser -g cage-browser -m 0700 /home/cage-browser/.vnc
1515cat "$HOME/.config/claude-cage/browser-password" | sudo -u cage-browser sh -c 'umask 077; tigervncpasswd -f > "$HOME/.vnc/passwd"'
1616sudo systemctl stop cage-browser || true
17新增:# Existing images may predate the explicit locale dependency. The scoped
18新增:# maintenance channel can install it while business networking stays closed.
19新增:if ! cage_is_ubuntu && ! dpkg-query -W -f='${Status}' chromium-l10n 2>/dev/null | grep -qx 'install ok installed'; then
20新增: sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get update </dev/null
21新增: sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get install -y --no-install-recommends chromium-l10n </dev/null
22新增:fi
1723# Publish per-VM control credentials for the browser process and SSH owner only.
18删除:sudo env CAGE_WORKSPACE="$PWD" CAGE_USER_HOME="$HOME" python3 - <<'PYCONTROL'
24新增:sudo env CAGE_DISPLAY_SCALE="${CAGE_DISPLAY_SCALE:-2}" CAGE_WORKSPACE="$PWD" CAGE_USER_HOME="$HOME" python3 - <<'PYCONTROL'
1925import json, os, secrets, grp
2026from pathlib import Path
2127p=Path('/etc/claude-cage/browser-control.json')
2228d=json.loads(p.read_text()) if p.exists() else {'token':secrets.token_hex(32)}
29新增:scale = 1.5 if os.environ['CAGE_DISPLAY_SCALE'] == '1.5' else 2
30新增:d['display_scale'] = scale
31新增:scale_file = Path('/etc/claude-cage/display-scale')
32新增:scale_file.write_text(str(scale) + '\n')
33新增:scale_file.chmod(0o644)
2334d['workspace']=os.environ['CAGE_WORKSPACE']
2435yaml=Path(os.environ['CAGE_USER_HOME']) / '.config/claude-cage/code-server.yaml'
2536d['editorPassword']=next(line.split(':',1)[1].strip() for line in yaml.read_text().splitlines() if line.startswith('password:'))
@@ -34,7 +45,10 @@ p = Path.home() / "profile/Default/Preferences"
3445p.parent.mkdir(parents=True, exist_ok=True)
3546d = json.loads(p.read_text()) if p.exists() else {}
3647d.setdefault("intl", {})["accept_languages"] = os.environ["CAGE_LANGUAGE"]
48新增:d["intl"]["selected_languages"] = os.environ["CAGE_LANGUAGE"]
3749d.setdefault("translate", {})["enabled"] = False
50新增:d["credentials_enable_service"] = False
51新增:d.setdefault("profile", {})["password_manager_enabled"] = False
3852p.write_text(json.dumps(d))
3953PYCODE
4054sudo systemctl reset-failed cage-display cage-window-manager cage-browser cage-vnc cage-webvnc 2>/dev/null || true
@@ -54,12 +68,5 @@ if ! systemctl is-active --quiet cage-editor.service; then
5468 sudo /usr/local/bin/cage-editor-migrate
5569 sudo systemctl start cage-editor.service
5670fi
57删除:for i in $(seq 1 30); do
58删除: if curl --noproxy '*' -fsS http://127.0.0.1:18080/healthz >/dev/null 2>&1 && curl --noproxy '*' -fsS http://127.0.0.1:16080/vnc.html >/dev/null 2>&1; then
59删除: printf 'Cage services ready. Timezone=%s Locale=%s Browser=%s\n' "$CAGE_TZ" "$CAGE_LOCALE" "$CAGE_LANGUAGE"
60删除: exit 0
61删除: fi
62删除: sleep 1
63删除:done
64删除:echo 'Cage web services did not become ready. Inspect systemctl status cage-browser and the editor log.' >&2
65删除:exit 1
71新增:sudo python3 /usr/local/lib/cage-wait-services.py
72新增:printf 'Cage services ready. Timezone=%s Locale=%s Browser=%s\n' "$CAGE_TZ" "$CAGE_LOCALE" "$CAGE_LANGUAGE"
新增internal/cage/guest-wait-services.py+32 −0看文件
@@ -0,0 +1,32 @@
1新增:import json
2新增:import time
3新增:import urllib.error
4新增:import urllib.request
5新增:from pathlib import Path
6新增:
7新增:
8新增:def wait(config_path='/etc/claude-cage/browser-control.json', endpoints=None, timeout=60):
9新增: token = json.loads(Path(config_path).read_text())['token']
10新增: endpoints = endpoints or (
11新增: ('http://127.0.0.1:18080/healthz', False),
12新增: ('http://127.0.0.1:16080/vnc.html', False),
13新增: ('http://127.0.0.1:18500/health', True),
14新增: )
15新增: opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
16新增: deadline = time.monotonic() + timeout
17新增: while time.monotonic() < deadline:
18新增: try:
19新增: for address, browser in endpoints:
20新增: headers = {'Authorization': 'Bearer ' + token} if browser else {}
21新增: request = urllib.request.Request(address, headers=headers)
22新增: with opener.open(request, timeout=2) as response:
23新增: if browser and json.loads(response.read(1024)).get('ready') is not True:
24新增: raise ValueError('Browser is starting')
25新增: return
26新增: except (OSError, ValueError, urllib.error.URLError):
27新增: time.sleep(1)
28新增: raise SystemExit('Cage browser, editor or display service did not become ready. Inspect the guest service logs and retry.')
29新增:
30新增:
31新增:if __name__ == '__main__':
32新增: wait()
修改internal/cage/guest.go+68 −10看文件
@@ -16,9 +16,22 @@ import (
1616//go:embed guest-setup.sh
1717var guestDependencies string
1818
19新增://go:embed tailnet-client.mjs
20新增:var tailnetClient string
21新增:
22新增:func tailnetClientScript() string {
23新增: return "sudo tee /usr/local/lib/tailnet-client.mjs >/dev/null <<'CAGE_TAILNET_CLIENT'\n" + tailnetClient + "\nCAGE_TAILNET_CLIENT\n"
24新增:}
25新增:
26新增://go:embed ubuntu-browser.sh
27新增:var ubuntuBrowser string
28新增:
1929//go:embed guest-services.sh
2030var guestServices string
2131
32新增://go:embed guest-wait-services.py
33新增:var guestWaitServices string
34新增:
2235//go:embed claude-account.py
2336var claudeAccountHelper string
2437
@@ -51,6 +64,24 @@ var browserVault string
5164//go:embed browser-agent.mjs
5265var browserAgent string
5366
67新增://go:embed browser-phone.mjs
68新增:var phoneBrowser string
69新增:
70新增://go:embed browser-phone-network.mjs
71新增:var phoneBrowserNetwork string
72新增:
73新增://go:embed browser-private.mjs
74新增:var browserPrivate string
75新增:
76新增://go:embed browser-cookies.mjs
77新增:var browserCookies string
78新增:
79新增://go:embed browser-extensions.mjs
80新增:var browserExtensions string
81新增:
82新增://go:embed browser-extension-archive.py
83新增:var browserExtensionArchive string
84新增:
5485//go:embed browser-clipboard.mjs
5586var browserClipboard string
5687
@@ -60,18 +91,26 @@ var splitManifest string
6091//go:embed split-extension/control.html
6192var splitPage string
6293
94新增://go:embed split-extension/settings.html
95新增:var browserSettingsPage string
96新增:
6397//go:embed split-extension/control.js
6498var splitControl string
6599
100新增://go:embed split-extension/browser-identity.js
101新增:var browserIdentity string
102新增:
66103func splitExtensionScript() string {
67104 return "sudo install -d -m 0755 /usr/local/lib/cage-split\n" +
68105 "sudo tee /usr/local/lib/cage-split/manifest.json >/dev/null <<'CAGE_MANIFEST'\n" + splitManifest + "\nCAGE_MANIFEST\n" +
69106 "sudo tee /usr/local/lib/cage-split/control.html >/dev/null <<'CAGE_HTML'\n" + splitPage + "\nCAGE_HTML\n" +
70删除: "sudo tee /usr/local/lib/cage-split/control.js >/dev/null <<'CAGE_CONTROL'\n" + splitControl + "\nCAGE_CONTROL\n"
107新增: "sudo tee /usr/local/lib/cage-split/settings.html >/dev/null <<'CAGE_SETTINGS_HTML'\n" + browserSettingsPage + "\nCAGE_SETTINGS_HTML\n" +
108新增: "sudo tee /usr/local/lib/cage-split/control.js >/dev/null <<'CAGE_CONTROL'\n" + splitControl + "\nCAGE_CONTROL\n" +
109新增: "sudo tee /usr/local/lib/cage-split/browser-identity.js >/dev/null <<'CAGE_IDENTITY'\n" + browserIdentity + "\nCAGE_IDENTITY\n"
71110}
72111
73112func browserClipboardScript() string {
74删除: return "sudo tee /usr/local/lib/browser-clipboard.mjs >/dev/null <<'CAGE_BROWSER_CLIPBOARD'\n" + browserClipboard + "\nCAGE_BROWSER_CLIPBOARD\n"
113新增: return sharedClipboardScript() + "sudo tee /usr/local/lib/browser-clipboard.mjs >/dev/null <<'CAGE_BROWSER_CLIPBOARD'\n" + browserClipboard + "\nCAGE_BROWSER_CLIPBOARD\n"
75114}
76115
77116//go:embed browser-audit.mjs
@@ -95,6 +134,10 @@ var imageInput string
95134//go:embed desktop-files.py
96135var desktopFiles string
97136
137新增:// DesktopFileReceiver shares the same bounded attachment writer with native
138新增:// guests. Its --save-file mode uses only Python's standard library.
139新增:func DesktopFileReceiver() string { return desktopFiles }
140新增:
98141//go:embed desktop-downloads.py
99142var desktopDownloads string
100143
@@ -124,8 +167,13 @@ func imageInputScript() string {
124167 return nativeInputScript() + fileInputScript() + "\nsudo tee /usr/local/bin/cage-image-input >/dev/null <<'CAGE_IMAGE_INPUT'\n" + imageInput + "\nCAGE_IMAGE_INPUT\nsudo chmod 0755 /usr/local/bin/cage-image-input\n"
125168}
126169
170新增:func phoneBrowserScript() string {
171新增: return "\nsudo tee /usr/local/lib/browser-phone.mjs >/dev/null <<'CAGE_PHONE_BROWSER'\n" + phoneBrowser + "\nCAGE_PHONE_BROWSER\n" +
172新增: "sudo tee /usr/local/lib/browser-phone-network.mjs >/dev/null <<'CAGE_PHONE_NETWORK'\n" + phoneBrowserNetwork + "\nCAGE_PHONE_NETWORK\n"
173新增:}
174新增:
127175func browserServices() string {
128删除: return "\nsudo tee /usr/local/lib/browser-vault.mjs >/dev/null <<'CAGE_BROWSER_VAULT'\n" + browserVault + "\nCAGE_BROWSER_VAULT\n" + guestMemory + "\n" + guestDiagnostics() + guestAudio + "\n" + guestOpenScript() + splitExtensionScript() + browserClipboardScript() + imageInputScript() + "\nsudo tee /usr/local/lib/browser-uploads.mjs >/dev/null <<'CAGE_BROWSER_UPLOADS'\n" + browserUploads + "\nCAGE_BROWSER_UPLOADS\n" + guestServices + "\nsudo tee /usr/local/lib/browser-downloads.mjs >/dev/null <<'CAGE_BROWSER_DOWNLOADS'\n" + browserDownloads + "\nCAGE_BROWSER_DOWNLOADS\n" + "\nsudo tee /usr/local/bin/cage-editor-migrate >/dev/null <<'CAGE_EDITOR_MIGRATE'\n" + editorMigrate + "\nCAGE_EDITOR_MIGRATE\nsudo chmod 0755 /usr/local/bin/cage-editor-migrate\n" + "\nsudo tee /usr/local/lib/browser-audit.mjs >/dev/null <<'CAGE_BROWSER_AUDIT'\n" + browserAudit + "\nCAGE_BROWSER_AUDIT\n" + "\nsudo tee /usr/local/lib/cage-browser-agent.mjs >/dev/null <<'CAGE_BROWSER_AGENT'\n" + browserAgent + "\nCAGE_BROWSER_AGENT\n" + "sudo tee /usr/local/bin/cage-save-download >/dev/null <<'CAGE_DOWNLOAD_HELPER'\n" + saveDownload + "\nCAGE_DOWNLOAD_HELPER\nsudo chmod 0755 /usr/local/bin/cage-save-download\nprintf 'cage-browser ALL=(root) NOPASSWD: /usr/local/bin/cage-save-download *\\n' | sudo tee /etc/sudoers.d/cage-download >/dev/null\nsudo chmod 0440 /etc/sudoers.d/cage-download\n" + "\nsudo python3 - <<'CAGE_NOVNC_PATCH'\n" + novncPatch + "\nCAGE_NOVNC_PATCH\n" + "\nsudo tee /usr/share/novnc/cage-clipboard.js >/dev/null <<'CAGE_CLIPBOARD_JS'\n" + clipboardJS + "\nCAGE_CLIPBOARD_JS\n" + `sudo python3 - <<'PYCODE'
176新增: return "sudo tee /usr/local/lib/cage-wait-services.py >/dev/null <<'CAGE_WAIT_SERVICES'\n" + guestWaitServices + "\nCAGE_WAIT_SERVICES\n" + toolVersions + "\n" + guestTools + "\n" + ubuntuBrowser + "\n" + tailnetClientScript() + PhoneDesktopProvisionScript() + phoneBrowserScript() + "\nsudo tee /usr/local/lib/browser-extensions.mjs >/dev/null <<'CAGE_BROWSER_EXTENSIONS'\n" + browserExtensions + "\nCAGE_BROWSER_EXTENSIONS\n" + "\nsudo tee /usr/local/lib/browser-extension-archive.py >/dev/null <<'CAGE_EXTENSION_ARCHIVE'\n" + browserExtensionArchive + "\nCAGE_EXTENSION_ARCHIVE\n" + "\nsudo tee /usr/local/lib/browser-private.mjs >/dev/null <<'CAGE_BROWSER_PRIVATE'\n" + browserPrivate + "\nCAGE_BROWSER_PRIVATE\n" + "\nsudo tee /usr/local/lib/browser-cookies.mjs >/dev/null <<'CAGE_BROWSER_COOKIES'\n" + browserCookies + "\nCAGE_BROWSER_COOKIES\n" + "\nsudo tee /usr/local/lib/browser-vault.mjs >/dev/null <<'CAGE_BROWSER_VAULT'\n" + browserVault + "\nCAGE_BROWSER_VAULT\n" + guestMemory + "\n" + guestDiagnostics() + guestAudio + "\n" + guestOpenScript() + splitExtensionScript() + browserClipboardScript() + imageInputScript() + "\nsudo tee /usr/local/lib/browser-uploads.mjs >/dev/null <<'CAGE_BROWSER_UPLOADS'\n" + browserUploads + "\nCAGE_BROWSER_UPLOADS\n" + guestServices + "\nsudo tee /usr/local/lib/browser-downloads.mjs >/dev/null <<'CAGE_BROWSER_DOWNLOADS'\n" + browserDownloads + "\nCAGE_BROWSER_DOWNLOADS\n" + "\nsudo tee /usr/local/bin/cage-editor-migrate >/dev/null <<'CAGE_EDITOR_MIGRATE'\n" + editorMigrate + "\nCAGE_EDITOR_MIGRATE\nsudo chmod 0755 /usr/local/bin/cage-editor-migrate\n" + "\nsudo tee /usr/local/lib/browser-audit.mjs >/dev/null <<'CAGE_BROWSER_AUDIT'\n" + browserAudit + "\nCAGE_BROWSER_AUDIT\n" + "\nsudo tee /usr/local/lib/cage-browser-agent.mjs >/dev/null <<'CAGE_BROWSER_AGENT'\n" + browserAgent + "\nCAGE_BROWSER_AGENT\n" + "sudo tee /usr/local/bin/cage-save-download >/dev/null <<'CAGE_DOWNLOAD_HELPER'\n" + saveDownload + "\nCAGE_DOWNLOAD_HELPER\nsudo chmod 0755 /usr/local/bin/cage-save-download\nprintf 'cage-browser ALL=(root) NOPASSWD: /usr/local/bin/cage-save-download *\\n' | sudo tee /etc/sudoers.d/cage-download >/dev/null\nsudo chmod 0440 /etc/sudoers.d/cage-download\n" + "\nsudo python3 - \"$cage_novnc_root\" <<'CAGE_NOVNC_PATCH'\n" + novncPatch + "\nCAGE_NOVNC_PATCH\n" + "\nsudo tee \"$cage_novnc_root/cage-clipboard.js\" >/dev/null <<'CAGE_CLIPBOARD_JS'\n" + clipboardJS + "\nCAGE_CLIPBOARD_JS\n" + `sudo python3 - <<'PYCODE'
129177from pathlib import Path
130178import re
131179p = Path("/usr/share/novnc/vnc.html")
@@ -141,7 +189,7 @@ PYCODE
141189`
142190}
143191
144删除:var GuestSetup = guestDependencies + "\n" + browserServices()
192新增:var GuestSetup = APTBootstrapScript + "\n" + guestDependencies + "\n" + browserServices()
145193
146194//go:embed editor-theme.json
147195var editorTheme string
@@ -161,11 +209,21 @@ var guestTools string
161209//go:embed debian-mirrors.sh
162210var DebianMirrorsScript string
163211
212新增://go:embed apt-bootstrap.sh
213新增:var aptBootstrap string
214新增:
215新增:// APTBootstrapScript preserves the temporary maintenance proxy through sudo.
216新增:var APTBootstrapScript = "set -e\nsudo env APT_CONFIG=\"${CAGE_APT_CONFIG:-/dev/null}\" sh -se <<'CAGE_APT_BOOTSTRAP'\n" + aptBootstrap + "\nCAGE_APT_BOOTSTRAP\n"
217新增:
218新增:// DebianPrepareScript runs before Lima's own dependency installation as well
219新增:// as Cage setup. Its version check also covers previously created guests.
220新增:var DebianPrepareScript = "#!/bin/sh\n" + APTBootstrapScript + "\n" + DebianMirrorsScript
221新增:
164222//go:embed chromium-download.py
165223var chromiumDownload string
166224
167225func ToolInstallPrelude() string {
168删除: return toolVersions + "\n" + guestTools + `
226新增: return toolVersions + "\n" + guestTools + "\n" + ubuntuBrowser + `
169227cage_cache_chromium() {
170228 local status=0
171229 sudo env APT_CONFIG="${CAGE_APT_CONFIG:-}" CAGE_SETUP_PROGRESS="${CAGE_SETUP_PROGRESS:-}" /usr/bin/python3 -I - "$@" <<'CAGE_CHROMIUM_DOWNLOAD' || status=$?
@@ -178,7 +236,7 @@ CAGE_CHROMIUM_DOWNLOAD
178236}
179237
180238func RequiredToolVersions() map[string]string {
181删除: result := map[string]string{"chromium": "Debian security repository"}
239新增: result := map[string]string{"chromium": "Debian security repository / Ubuntu Chrome for Testing"}
182240 for _, line := range strings.Split(toolVersions, "\n") {
183241 key, value, ok := strings.Cut(line, "=")
184242 if !ok {
@@ -197,11 +255,11 @@ func RequiredToolVersions() map[string]string {
197255}
198256
199257func ToolsUpdateScript() string {
200删除: return "set -euo pipefail\nexport PATH=\"$HOME/.local/bin:$PATH\"\n" + ToolInstallPrelude() + `
258新增: return "set -euo pipefail\nexport PATH=\"$HOME/.local/bin:$PATH\"\n" + `
201259sudo env DEBIAN_FRONTEND=noninteractive dpkg --configure -a </dev/null
260新增:` + APTBootstrapScript + ToolInstallPrelude() + `
202261sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get update </dev/null
203删除:cage_cache_chromium --only-upgrade chromium
204删除:sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get install -y --only-upgrade chromium </dev/null
262新增:cage_install_chromium
205263cage_install_tool mise
206264cage_install_tool code-server
207265cage_install_tool claude
@@ -219,7 +277,7 @@ func (c Config) StartScript() string {
219277}
220278
221279func componentStartScript() string {
222删除: return claudeAccountScript() + browserServices() + "\nsudo tee /etc/claude-cage/editor-theme.json >/dev/null <<'CAGE_EDITOR_THEME'\n" + editorTheme + "\nCAGE_EDITOR_THEME\nif systemctl is-active --quiet cage-editor.service; then sudo systemctl stop cage-editor.service; fi\n" + guestStart
280新增: return APTBootstrapScript + "\n" + claudeAccountScript() + browserServices() + "\nsudo tee /etc/claude-cage/editor-theme.json >/dev/null <<'CAGE_EDITOR_THEME'\n" + editorTheme + "\nCAGE_EDITOR_THEME\nif systemctl is-active --quiet cage-editor.service; then sudo systemctl stop cage-editor.service; fi\n" + guestStart
223281}
224282
225283func markGuestStart(body string) string {
新增internal/cage/guest_readiness_test.go+60 −0看文件
@@ -0,0 +1,60 @@
1新增:package cage
2新增:
3新增:import (
4新增: "context"
5新增: "encoding/json"
6新增: "fmt"
7新增: "net/http"
8新增: "net/http/httptest"
9新增: "os"
10新增: "os/exec"
11新增: "path/filepath"
12新增: "sync/atomic"
13新增: "testing"
14新增: "time"
15新增:)
16新增:
17新增:func TestGuestReadinessWaitsForAuthenticatedBrowser(t *testing.T) {
18新增: python, err := exec.LookPath("python3")
19新增: if err != nil {
20新增: t.Skip("Python unavailable")
21新增: }
22新增: var browserRequests, proxyRequests atomic.Int32
23新增: server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
24新增: if r.URL.Path != "/browser" {
25新增: _, _ = fmt.Fprint(w, "ready")
26新增: return
27新增: }
28新增: if r.Header.Get("Authorization") != "Bearer fixture-token" {
29新增: w.WriteHeader(401)
30新增: return
31新增: }
32新增: if browserRequests.Add(1) < 3 {
33新增: w.WriteHeader(503)
34新增: return
35新增: }
36新增: _, _ = fmt.Fprint(w, `{"ready":true}`)
37新增: }))
38新增: defer server.Close()
39新增: proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { proxyRequests.Add(1); w.WriteHeader(502) }))
40新增: defer proxy.Close()
41新增: dir := t.TempDir()
42新增: script, config := filepath.Join(dir, "wait.py"), filepath.Join(dir, "browser.json")
43新增: if err := os.WriteFile(script, []byte(guestWaitServices), 0600); err != nil {
44新增: t.Fatal(err)
45新增: }
46新增: if err := os.WriteFile(config, []byte(`{"token":"fixture-token"}`), 0600); err != nil {
47新增: t.Fatal(err)
48新增: }
49新增: endpoints, _ := json.Marshal([][]any{{server.URL + "/editor", false}, {server.URL + "/vnc", false}, {server.URL + "/browser", true}})
50新增: ctx, cancel := context.WithTimeout(t.Context(), 15*time.Second)
51新增: defer cancel()
52新增: cmd := exec.CommandContext(ctx, python, "-c", `import runpy,sys,json;runpy.run_path(sys.argv[1])['wait'](sys.argv[2],json.loads(sys.argv[3]),timeout=10)`, script, config, string(endpoints))
53新增: cmd.Env = append(os.Environ(), "http_proxy="+proxy.URL, "HTTP_PROXY="+proxy.URL, "no_proxy=", "NO_PROXY=")
54新增: if output, err := cmd.CombinedOutput(); err != nil {
55新增: t.Fatalf("readiness: %v %s", err, output)
56新增: }
57新增: if browserRequests.Load() < 3 || proxyRequests.Load() != 0 {
58新增: t.Fatalf("premature or proxied readiness: browser=%d proxy=%d", browserRequests.Load(), proxyRequests.Load())
59新增: }
60新增:}
修改internal/cage/native-ime-session.sh+1 −0看文件
@@ -7,6 +7,7 @@ if ! command -v ibus-daemon >/dev/null || ! /usr/bin/python3 -c 'import gi; gi.r
77fi
88umask 077
99input_root="$HOME/.cache/cage-input"
10新增:if [ "${CAGE_PHONE_DESKTOP_INPUT:-}" = 1 ]; then input_root=/run/cage-phone-desktop/input; fi
1011mkdir -p "$input_root"
1112chmod 700 "$input_root"
1213export IBUS_ADDRESS="unix:path=$input_root/bus"
修改internal/cage/native-ime.py+28 −5看文件
@@ -7,7 +7,8 @@ import re
77import socket
88import sys
99
10删除:directory = Path.home() / '.cache' / 'cage-input'
10新增:directory = (Path('/run/cage-phone-desktop/input') if os.environ.get('CAGE_PHONE_DESKTOP_INPUT') == '1'
11新增: else Path.home() / '.cache' / 'cage-input')
1112socket_path = directory / 'input.sock'
1213limit = 32768
1314
@@ -155,9 +156,13 @@ if not bus.is_connected():
155156
156157class Factory(IBus.Factory):
157158 def do_create_engine(self, name):
158删除: engine = Engine(connection=bus.get_connection(),
159删除: object_path='/org/freedesktop/IBus/Cage/' + str(len(engines)),
160删除: has_focus_id=True)
159新增: options = dict(connection=bus.get_connection(),
160新增: object_path='/org/freedesktop/IBus/Cage/' + str(len(engines)))
161新增: # Ubuntu 22.04's IBus uses the original per-context focus signals.
162新增: # Newer IBus can reuse engines and supplies the explicit focus ID.
163新增: if IBus.Engine.find_property('has-focus-id') is not None:
164新增: options['has_focus_id'] = True
165新增: engine = Engine(**options)
161166 engines.append(engine)
162167 return engine
163168
@@ -191,6 +196,21 @@ def utf16_index(text, offset):
191196def apply(value):
192197 engine = active
193198 mode = value.get('mode')
199新增: if mode in ('phone-status', 'phone-text', 'phone-char') and os.environ.get('CAGE_PHONE_DESKTOP_INPUT') == '1':
200新增: if engine is None or not engine.reachable or not engine.context:
201新增: return {'available': False}
202新增: password = engine.purpose in (8, 9)
203新增: if mode == 'phone-status':
204新增: return {'available': True, 'context': engine.context, 'password': password}
205新增: text = value.get('text', '')
206新增: if engine.context != value.get('context') or not isinstance(text, str) or not text:
207新增: return {'available': False}
208新增: if mode == 'phone-text' and (password or len(text.encode()) > 8192):
209新增: return {'available': False}
210新增: if mode == 'phone-char' and (len(text) != 1 or not (' ' <= text <= '~')):
211新增: return {'available': False}
212新增: engine.commit_text(IBus.Text.new_from_string(text))
213新增: return {'available': True}
194214 if mode == 'status':
195215 if engine is not None and engine.session and value.get('session') == engine.session:
196216 engine.updated = time.monotonic()
@@ -272,7 +292,10 @@ class Handler(socketserver.StreamRequestHandler):
272292
273293 def probe():
274294 engine = active
275删除: if probe_ready and value.get('mode') in ('status', 'begin') and engine is not None and engine.purpose not in (8, 9):
295新增: desktop_probe = (os.environ.get('CAGE_PHONE_DESKTOP_INPUT') == '1' and
296新增: value.get('mode') in ('phone-status', 'phone-text', 'phone-char'))
297新增: ordinary_probe = value.get('mode') in ('status', 'begin') and engine is not None and engine.purpose not in (8, 9)
298新增: if probe_ready and engine is not None and (desktop_probe or ordinary_probe):
276299 engine.probing = True
277300 engine.probe_seen = False
278301 subprocess.Popen(['xdotool', 'key', '--delay', '0', 'F24'],
修改internal/cage/novnc-patch.py+3 −2看文件
@@ -85,10 +85,10 @@ replace_once(' clipboardPasteFrom(text) {', ''' // Cage: serialize the cli
8585 RFB.messages.clientFence(this._sock, (1 << 31) | 1, id);
8686 });
8787 if (this._rfbConnectionState !== 'connected') throw new Error('Input disconnected');
88删除: return action();
88新增: return action((...key) => this._cageSendKey(...key));
8989 }
9090
91删除: cagePasteContent(content, pasteImage, valid) {
91新增: cagePasteContent(content, pasteImage, valid, pasteText) {
9292 // Reserve the queue before asynchronous host clipboard/image decoding.
9393 // Keep a rejection handler attached even if an earlier input fails.
9494 const pending = Promise.resolve(content).then(value => ({value}), error => ({error}));
@@ -97,6 +97,7 @@ replace_once(' clipboardPasteFrom(text) {', ''' // Cage: serialize the cli
9797 if (error) throw error;
9898 if (!valid()) throw new Error('Input target changed');
9999 if (value.png || value.files || value.fileSelection) return this._cageRunInput(() => pasteImage(value));
100新增: if (pasteText) return this._cageRunInput(() => pasteText(value.text || ''));
100101 return this._cagePasteText(value.text || '');
101102 });
102103 }
新增internal/cage/phone-desktop/control.py+132 −0看文件
@@ -0,0 +1,132 @@
1新增:#!/usr/bin/python3
2新增:"""Attach an authenticated phone view to the desktop application's display."""
3新增:import fcntl
4新增:import json
5新增:import math
6新增:import os
7新增:from pathlib import Path
8新增:import pwd
9新增:import re
10新增:import socket
11新增:import subprocess
12新增:import sys
13新增:
14新增:STATE = Path('/run/cage-phone-desktop-owner')
15新增:RUNTIME = Path('/run/cage-phone-desktop')
16新增:TOOLS = '/usr/local/lib/cage-phone-desktop'
17新增:UNIT = 'cage-phone-desktop.service'
18新增:
19新增:
20新增:class Failure(Exception):
21新增: def __init__(self, status):
22新增: self.status = status
23新增:
24新增:
25新增:def command(*args, timeout=10):
26新增: return subprocess.run(args, check=True, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
27新增: stderr=subprocess.DEVNULL, timeout=timeout).stdout
28新增:
29新增:
30新增:def unit_state():
31新增: return command('systemctl', 'show', UNIT, '-p', 'ActiveState', '--value').strip()
32新增:
33新增:
34新增:def stop():
35新增: if unit_state() not in (b'inactive', b'failed'):
36新增: command('systemctl', 'stop', UNIT, timeout=20)
37新增: # A collected inactive transient unit often no longer exists.
38新增: if unit_state() == b'failed':
39新增: command('systemctl', 'reset-failed', UNIT)
40新增:
41新增:
42新增:def launch(request, record):
43新增: if not Path('/usr/bin/claude-desktop').is_file():
44新增: raise Failure(501)
45新增: ident = request['id']
46新增: w, h = request['width'], request['height']
47新增: pixel_ratio = request.get('pixel_ratio', 0)
48新增: if type(pixel_ratio) not in (int, float) or not math.isfinite(pixel_ratio) or (pixel_ratio != 0 and not 1 <= pixel_ratio <= 8):
49新增: raise Failure(400)
50新增: if type(w) is not int or type(h) is not int or not (240 <= w <= 1440 and 160 <= h <= 1600):
51新增: raise Failure(400)
52新增: desktop = command('systemctl', 'show', 'cage-claude-desktop.service', '-p', 'ActiveState', '--value').strip()
53新增: if desktop != b'active' or not Path('/run/cage-desktop/keyring-ready').exists():
54新增: raise Failure(412)
55新增: owner = {'id': ident, 'mode': 'shared'}
56新增: state = unit_state()
57新增: if record.exists() and json.loads(record.read_bytes()) == owner and state in (b'active', b'activating'):
58新增: return
59新增: stop()
60新增: user = pwd.getpwnam('cage')
61新增: args = ['systemd-run', '--quiet', '--collect', '--unit=' + UNIT, '--service-type=exec',
62新增: '--working-directory=' + user.pw_dir, '--uid=' + user.pw_name, '--gid=' + str(user.pw_gid)]
63新增: # This unit owns only capture and input. Closing it leaves Desktop running.
64新增: for prop in ['RuntimeDirectory=cage-phone-desktop',
65新增: 'RuntimeDirectoryMode=0700', 'UMask=0077', 'KillMode=control-group', 'TimeoutStopSec=8',
66新增: 'ProtectSystem=strict', 'ProtectHome=read-only',
67新增: 'ReadWritePaths=/run/cage-desktop',
68新增: 'ExecStopPost=' + TOOLS + '/session.sh --restore',
69新增: 'BindsTo=cage-claude-desktop.service', 'After=cage-claude-desktop.service',
70新增: 'StandardOutput=null', 'StandardError=null']:
71新增: args.append('--property=' + prop)
72新增: for name, value in [('HOME', user.pw_dir), ('CAGE_PHONE_ID', ident), ('CAGE_PHONE_WIDTH', w), ('CAGE_PHONE_HEIGHT', h),
73新增: ('CAGE_PHONE_PIXEL_RATIO', pixel_ratio)]:
74新增: args.append('--setenv=' + name + '=' + str(value))
75新增: command(*args, TOOLS + '/session.sh')
76新增: temporary = record.with_suffix('.new')
77新增: temporary.write_text(json.dumps(owner))
78新增: os.replace(temporary, record)
79新增:
80新增:
81新增:def main():
82新增: os.umask(0o077)
83新增: if os.geteuid() or len(sys.argv) != 1:
84新增: raise Failure(403)
85新增: raw = sys.stdin.buffer.readline(65537)
86新增: if len(raw) > 65536:
87新增: raise Failure(400)
88新增: req = json.loads(raw)
89新增: if not re.fullmatch('[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}', req.get('id', '')):
90新增: raise Failure(400)
91新增: if req.get('op') not in ('open', 'frame', 'action', 'close'):
92新增: raise Failure(400)
93新增: STATE.mkdir(mode=0o700, exist_ok=True)
94新增: record = STATE / 'owner'
95新增: with open(STATE / 'lock', 'a+b') as lock:
96新增: fcntl.flock(lock, fcntl.LOCK_EX)
97新增: if req['op'] == 'open':
98新增: launch(req, record)
99新增: return {'id': req['id']}
100新增: owner = json.loads(record.read_bytes()) if record.exists() else {}
101新增: if owner.get('id') != req['id'] or owner.get('mode') != 'shared':
102新增: raise Failure(410)
103新增: if req['op'] == 'close':
104新增: stop()
105新增: record.unlink(missing_ok=True)
106新增: return {'id': req['id']}
107新增: if unit_state() not in (b'active', b'activating'):
108新增: raise Failure(503)
109新增: user = pwd.getpwnam('cage')
110新增: os.setgroups([])
111新增: os.setgid(user.pw_gid)
112新增: os.setuid(user.pw_uid)
113新增: with socket.socket(socket.AF_UNIX) as channel:
114新增: channel.settimeout(8)
115新增: try:
116新增: channel.connect(str(RUNTIME / 'view.sock'))
117新增: except (FileNotFoundError, ConnectionRefusedError):
118新增: raise Failure(409)
119新增: channel.sendall(raw)
120新增: reply = channel.makefile('rb').readline(3600001)
121新增: if not reply or len(reply) > 3600000:
122新增: raise Failure(503)
123新增: return json.loads(reply)
124新增:
125新增:
126新增:if __name__ == '__main__':
127新增: try:
128新增: print(json.dumps(main(), separators=(',', ':')))
129新增: except Failure as error:
130新增: print(json.dumps({'status': error.status}))
131新增: except Exception:
132新增: print('{"status":503}')
新增internal/cage/phone-desktop/handler.desktop+6 −0看文件
@@ -0,0 +1,6 @@
1新增:[Desktop Entry]
2新增:Type=Application
3新增:Name=Claude
4新增:Exec=/usr/local/lib/cage-phone-desktop/xdg-open %u
5新增:Terminal=false
6新增:MimeType=x-scheme-handler/claude;
新增internal/cage/phone-desktop/network.mjs+4 −0看文件
@@ -0,0 +1,4 @@
1新增:import { writeFile } from "node:fs/promises";
2新增:import { startPhoneProxy } from "/usr/local/lib/browser-phone-network.mjs";
3新增:const proxy = await startPhoneProxy();
4新增:await writeFile(process.env.XDG_RUNTIME_DIR + "/proxy", String(proxy.port), { mode: 0o600 });
新增internal/cage/phone-desktop/openbox.xml+7 −0看文件
@@ -0,0 +1,7 @@
1新增:<?xml version="1.0" encoding="UTF-8"?>
2新增:<openbox_config xmlns="http://openbox.org/3.4/rc">
3新增: <focus><focusNew>yes</focusNew><followMouse>no</followMouse></focus>
4新增: <desktops><number>1</number></desktops>
5新增: <keyboard/><mouse/>
6新增: <applications><application type="normal"><decor>no</decor><maximized>yes</maximized></application></applications>
7新增:</openbox_config>
新增internal/cage/phone-desktop/session.sh+5 −0看文件
@@ -0,0 +1,5 @@
1新增:#!/bin/bash
2新增:set -eu
3新增:export DISPLAY=:78 XAUTHORITY=/run/cage-desktop/Xauthority
4新增:export XDG_RUNTIME_DIR=/run/cage-phone-desktop
5新增:exec /usr/bin/python3 /usr/local/lib/cage-phone-desktop/view.py "$@"
新增internal/cage/phone-desktop/test_control.py+58 −0看文件
@@ -0,0 +1,58 @@
1新增:"""Regression checks for the phone window geometry and host mount specification."""
2新增:import json
3新增:import unittest
4新增:from types import SimpleNamespace
5新增:from unittest.mock import Mock
6新增:
7新增:from Xlib import Xutil
8新增:import control
9新增:from view import View, dimensions, fitted_window
10新增:
11新增:
12新增:class PhoneWindowTests(unittest.TestCase):
13新增: def test_viewport_matches_electron_dpi_even_while_typing(self):
14新增: for size, expected in [((390, 672), (585, 1008)), ((672, 390), (1008, 585)),
15新增: ((390, 242), (585, 363))]:
16新增: self.assertEqual(dimensions(*size), expected)
17新增:
18新增: def test_only_verified_maximized_window_relaxes_desktop_minimum(self):
19新增: # A mobile display of 585px starts with the actual Claude Electron
20新增: # minimum 900x600, which Openbox honors until this hint is lowered.
21新增: from view import Failure
22新增: view = View.__new__(View)
23新增: view.size = (390, 672)
24新增: view.root = Mock()
25新增: view.conn = Mock()
26新增: view.conn.intern_atom.side_effect = lambda name: name
27新增: view.values = lambda w, k: [12] if w is view.root else [
28新增: '_NET_WM_STATE_MAXIMIZED_VERT', '_NET_WM_STATE_MAXIMIZED_HORZ']
29新增: real = Mock()
30新增: real.get_geometry.return_value = SimpleNamespace(width=900, height=1008)
31新增: hints = dict(flags=Xutil.PMinSize, min_width=900, min_height=600, win_gravity=10)
32新增: real.get_wm_normal_hints.return_value = SimpleNamespace(**hints, _data=hints)
33新增: real.get_wm_transient_for.return_value = None
34新增: view.window = lambda _: real
35新增: view.role = lambda _: ''
36新增: with self.assertRaises(Failure):
37新增: view.active()
38新增: real.set_wm_normal_hints.assert_not_called()
39新增: view.role = lambda _: 'desktop'
40新增: with self.assertRaises(Failure):
41新增: view.active()
42新增: real.set_wm_normal_hints.assert_called_once_with(**{**hints, 'min_width': 585})
43新增:
44新增: def test_nonmaximized_dialog_uses_matching_picture_and_input_geometry(self):
45新增: ratio, left, top = fitted_window((390, 672), SimpleNamespace(width=600, height=300))
46新增: self.assertEqual((150 * ratio + left, 150 * ratio + top), (97.5, 336))
47新增:
48新增: def test_existing_project_mounts_use_literal_guest_paths_in_transient_unit(self):
49新增: mounts = ('25 11 0:88 / /opt/QA\\040%h rw - fuse.sshfs :/qa rw\n'
50新增: '27 11 0:89 / /Users/A\\134B rw - virtiofs data rw\n'
51新增: '29 11 0:90 / /home rw - ext4 /dev/vda1 rw\n')
52新增: shares = control.host_shares(mounts)
53新增: self.assertEqual(shares, ['/Users/A\\B', '/opt/QA %h'])
54新增: self.assertEqual(json.loads(control.unit_path(shares[1])), '-/opt/QA %h')
55新增:
56新增:
57新增:if __name__ == '__main__':
58新增: unittest.main()
新增internal/cage/phone-desktop/view.py+427 −0看文件
@@ -0,0 +1,427 @@
1新增:#!/usr/bin/python3
2新增:"""Window-only capture and shared input for the existing Claude Desktop."""
3新增:import base64
4新增:import fcntl
5新增:import hashlib
6新增:import io
7新增:import json
8新增:import math
9新增:import os
10新增:from pathlib import Path
11新增:import secrets
12新增:import signal
13新增:import socket
14新增:import socketserver
15新增:import subprocess
16新增:import sys
17新增:import time
18新增:
19新增:from PIL import Image
20新增:from Xlib import X, XK, Xutil, display, error
21新增:from Xlib.ext import composite, xtest
22新增:
23新增:
24新增:class Failure(Exception):
25新增: def __init__(self, status):
26新增: self.status = status
27新增:
28新增:
29新增:def run(*args):
30新增: return subprocess.check_output(args, stdin=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=3).decode()
31新增:
32新增:
33新增:layout_file = Path('/run/cage-phone-desktop/layout.json')
34新增:
35新增:
36新增:def display_scale():
37新增: path = Path('/run/cage-desktop/display-scale')
38新增: value = float(path.read_text()) if path.exists() else 2
39新增: if not math.isfinite(value) or not 1 <= value <= 8:
40新增: raise Failure(503)
41新增: return value
42新增:
43新增:
44新增:def set_display_scale(value):
45新增: dpi = round(value * 96 * 1024)
46新增: config = Path('/run/cage-desktop/xsettings.conf')
47新增: temporary = config.with_suffix('.new')
48新增: temporary.write_text(f'Xft/DPI {dpi}\nGdk/WindowScalingFactor 1\nGdk/UnscaledDPI {dpi}\nGtk/DecorationLayout ":"\n')
49新增: temporary.replace(config)
50新增: pid = int(Path('/run/cage-desktop/xsettings.pid').read_text())
51新增: if Path(f'/proc/{pid}/comm').read_text().strip() != 'xsettingsd':
52新增: raise Failure(503)
53新增: os.kill(pid, signal.SIGHUP)
54新增: Path('/run/cage-desktop/display-scale').write_text(str(value) + '\n')
55新增:
56新增:
57新增:def encode_frame(image):
58新增: # Preserve fine text and colored edges at native resolution. Detailed
59新增: # images fall back within the existing mobile response-size limit.
60新增: while True:
61新增: for quality in (92, 82, 68, 50):
62新增: buffer = io.BytesIO()
63新增: image.save(buffer, format='JPEG', quality=quality, subsampling=0)
64新增: if buffer.tell() <= 1900000:
65新增: return buffer.getvalue(), image.size
66新增: ratio = min(.85, math.sqrt(1900000 / buffer.tell()) * .95)
67新增: image = image.resize((max(1, round(image.width * ratio)), max(1, round(image.height * ratio))),
68新增: Image.Resampling.LANCZOS)
69新增:
70新增:
71新增:def save_layout(layout):
72新增: temporary = layout_file.with_suffix('.new')
73新增: temporary.write_text(json.dumps(layout))
74新增: temporary.replace(layout_file)
75新增:
76新增:
77新增:def display_size(width, height):
78新增: name = f'cage-phone-{width}x{height}'
79新增: modes = run('xrandr', '--query')
80新增: if name not in modes:
81新增: run('xrandr', '--newmode', name, f'{(width+32)*(height+8)*60/1000000:.3f}',
82新增: *[str(v) for v in (width, width+8, width+16, width+32, height, height+1, height+2, height+8)], '+HSync', '-VSync')
83新增: run('xrandr', '--addmode', 'VNC-0', name)
84新增: run('xrandr', '--output', 'VNC-0', '--mode', name)
85新增: for line in modes.splitlines():
86新增: fields = line.split()
87新增: if fields and fields[0].startswith('cage-phone-') and fields[0] != name:
88新增: run('xrandr', '--delmode', 'VNC-0', fields[0])
89新增: run('xrandr', '--rmmode', fields[0])
90新增:
91新增:
92新增:def restore_layout():
93新增: if not layout_file.exists():
94新增: return
95新增: with open('/run/cage-desktop/resize.lock', 'a') as lock:
96新增: fcntl.flock(lock, fcntl.LOCK_EX)
97新增: layout = json.loads(layout_file.read_text())
98新增: if 'scale' in layout and Path('/run/cage-desktop/xsettings.pid').exists():
99新增: set_display_scale(layout['scale'])
100新增: conn = display.Display()
101新增: for wid, saved in layout['minimums'].items():
102新增: try:
103新增: win = conn.create_resource_object('window', int(wid))
104新增: pid = win.get_full_property(conn.intern_atom('_NET_WM_PID'), X.AnyPropertyType)
105新增: hints = win.get_wm_normal_hints()
106新增: if pid is not None and list(pid.value) == [saved['pid']] and hints:
107新增: values = dict(hints._data)
108新增: values.update(min_width=saved['width'], min_height=saved['height'])
109新增: win.set_wm_normal_hints(**values)
110新增: except error.XError:
111新增: # A closed window has no minimum size to restore.
112新增: continue
113新增: conn.sync()
114新增: width, height = layout['width'], layout['height']
115新增: pending = Path('/run/cage-desktop/desktop-size')
116新增: if pending.exists():
117新增: width, height = map(int, pending.read_text().split())
118新增: display_size(width, height)
119新增: layout_file.unlink()
120新增: conn.close()
121新增:
122新增:
123新增:def fitted_window(size, window):
124新增: """Phone CSS rectangle actually occupied by the remote window."""
125新增: ratio = min(size[0] / window.width, size[1] / window.height)
126新增: return ratio, (size[0] - window.width * ratio) / 2, (size[1] - window.height * ratio) / 2
127新增:
128新增:
129新增:def native_input(payload):
130新增: with socket.socket(socket.AF_UNIX) as conn:
131新增: conn.settimeout(2)
132新增: conn.connect(str(Path.home() / '.cache/cage-input/input.sock'))
133新增: conn.sendall(json.dumps(payload).encode() + b'\n')
134新增: return json.loads(conn.makefile('rb').readline(32769))
135新增:
136新增:
137新增:def token(*parts):
138新增: return hashlib.sha256(json.dumps(parts, separators=(',', ':')).encode()).hexdigest()
139新增:
140新增:
141新增:class View:
142新增: def __init__(self):
143新增: self.conn = display.Display()
144新增: self.root = self.conn.screen().root
145新增: self.id = os.environ['CAGE_PHONE_ID']
146新增: self.generation = secrets.token_hex(16)
147新增: self.redirected = set()
148新增: self.size = None
149新增: self.pixels = None
150新增: self.scale = display_scale()
151新增: self.dynamic_scale = Path('/run/cage-desktop/xsettings.pid').exists()
152新增: self.requested_scale = self.scale
153新增: self.scale_ready = 0
154新增: self.resize(int(os.environ['CAGE_PHONE_WIDTH']), int(os.environ['CAGE_PHONE_HEIGHT']),
155新增: float(os.environ.get('CAGE_PHONE_PIXEL_RATIO', '0')))
156新增: self.last = time.monotonic()
157新增:
158新增: def resize(self, w, h, pixel_ratio=0):
159新增: if type(w) is not int or type(h) is not int or not (240 <= w <= 1440 and 160 <= h <= 1600):
160新增: raise Failure(400)
161新增: self.size = (w, h)
162新增: if type(pixel_ratio) not in (int, float) or not math.isfinite(pixel_ratio) or (pixel_ratio != 0 and not 1 <= pixel_ratio <= 8):
163新增: raise Failure(400)
164新增: if pixel_ratio:
165新增: self.requested_scale = pixel_ratio
166新增: self.fit_display()
167新增:
168新增: def fit_display(self):
169新增: with open('/run/cage-desktop/resize.lock', 'a') as lock:
170新增: fcntl.flock(lock, fcntl.LOCK_EX)
171新增: geometry = self.root.get_geometry()
172新增: current = (geometry.width, geometry.height)
173新增: if layout_file.exists():
174新增: layout = json.loads(layout_file.read_text())
175新增: # Older computer clients can still resize directly. Preserve
176新增: # their latest size for restoration when the phone detaches.
177新增: if self.pixels is not None and current != self.pixels:
178新增: layout.update(width=current[0], height=current[1])
179新增: save_layout(layout)
180新增: else:
181新增: minimums = {}
182新增: for wid in self.values(self.root, '_NET_CLIENT_LIST'):
183新增: win = self.window(wid)
184新增: if self.role(win) != 'desktop':
185新增: continue
186新增: hints = win.get_wm_normal_hints()
187新增: if hints and hints.flags & Xutil.PMinSize:
188新增: minimums[str(win.id)] = {'width':hints.min_width, 'height':hints.min_height,
189新增: 'pid':int(self.values(win, '_NET_WM_PID')[0])}
190新增: save_layout({'width':current[0], 'height':current[1], 'scale':self.scale, 'minimums':minimums})
191新增: scale = min(self.requested_scale, 8192 / max(self.size)) if self.dynamic_scale else self.scale
192新增: if scale != self.scale:
193新增: set_display_scale(scale)
194新增: self.scale = scale
195新增: self.scale_ready = time.monotonic() + .2
196新增: pixels = tuple(round(value * self.scale) for value in self.size)
197新增: if current != pixels:
198新增: display_size(*pixels)
199新增: self.pixels = pixels
200新增:
201新增: def fit_window(self, win, geometry):
202新增: width, height = self.pixels
203新增: if geometry.width <= width and geometry.height <= height:
204新增: return
205新增: hints = win.get_wm_normal_hints()
206新增: if not hints or not hints.flags & Xutil.PMinSize or win.get_wm_transient_for():
207新增: return
208新增: if hints.min_width <= width and hints.min_height <= height:
209新增: return
210新增: layout = json.loads(layout_file.read_text())
211新增: wid = str(win.id)
212新增: if wid not in layout['minimums']:
213新增: layout['minimums'][wid] = {'width':hints.min_width, 'height':hints.min_height,
214新增: 'pid':int(self.values(win, '_NET_WM_PID')[0])}
215新增: save_layout(layout)
216新增: values = dict(hints._data)
217新增: values.update(min_width=min(width, hints.min_width), min_height=min(height, hints.min_height))
218新增: win.set_wm_normal_hints(**values)
219新增: self.conn.sync()
220新增: raise Failure(409)
221新增:
222新增: def values(self, win, name):
223新增: result = win.get_full_property(self.conn.intern_atom(name), X.AnyPropertyType)
224新增: return result.value if result is not None else []
225新增:
226新增: def window(self, wid):
227新增: return self.conn.create_resource_object('window', int(wid))
228新增:
229新增: def role(self, win):
230新增: pid = self.values(win, '_NET_WM_PID')
231新增: if len(pid) != 1 or win.get_attributes().map_state != X.IsViewable:
232新增: return ''
233新增: process = Path('/proc') / str(int(pid[0]))
234新增: try:
235新增: if process.stat().st_uid != os.getuid():
236新增: return ''
237新增: exe = os.readlink(process / 'exe')
238新增: except OSError:
239新增: return ''
240新增: klass = {s.lower() for s in (win.get_wm_class() or ())}
241新增: if klass & {'com.anthropic.claude','claude','claude-desktop'}:
242新增: if exe == '/usr/lib/claude-desktop/claude-desktop':
243新增: return 'desktop'
244新增: return ''
245新增:
246新增: def active(self):
247新增: ids = self.values(self.root, '_NET_ACTIVE_WINDOW')
248新增: if not len(ids) or not ids[0]:
249新增: raise Failure(409)
250新增: win = self.window(ids[0])
251新增: role = self.role(win)
252新增: if not role:
253新增: raise Failure(409)
254新增: g = win.get_geometry()
255新增: self.fit_window(win, g)
256新增: document = token(self.generation, win.id, role, *self.size, g.width, g.height)
257新增: return win, role, g, document
258新增:
259新增: def focus(self, win, role):
260新增: try:
261新增: value = native_input({'mode': 'status'})
262新增: except (OSError, ValueError):
263新增: value = {}
264新增: ctx = value.get('context', '')
265新增: if not value.get('available') or not ctx:
266新增: return '', False, ''
267新增: return token(self.generation, win.id, ctx), False, ctx
268新增:
269新增: def snapshot(self):
270新增: self.fit_display()
271新增: if time.monotonic() < self.scale_ready:
272新增: raise Failure(409)
273新增: win, role, g, document = self.active()
274新增: if not (0 < g.width <= 8192 and 0 < g.height <= 8192):
275新增: raise Failure(409)
276新增: # An offscreen pixmap contains only the verified application's window.
277新增: # A foreign tooltip, dialog or another app cannot appear in the frame.
278新增: if win.id not in self.redirected:
279新增: win.composite_redirect_window(composite.RedirectAutomatic)
280新增: self.redirected.add(win.id)
281新增: self.conn.sync()
282新增: pixmap = win.composite_name_window_pixmap()
283新增: try:
284新增: raw = pixmap.get_image(0, 0, g.width, g.height, X.ZPixmap, 0xffffffff)
285新增: if raw.depth not in (24, 32):
286新增: raise Failure(503)
287新增: image = Image.frombytes('RGB', (g.width, g.height), raw.data, 'raw', 'BGRX')
288新增: finally:
289新增: pixmap.free()
290新增: ratio, left, top = fitted_window(self.size, g)
291新增: density = min(self.scale, 1 / ratio)
292新增: canvas = Image.new('RGB', (max(1, round(self.size[0] * density)),
293新增: max(1, round(self.size[1] * density))), '#181818')
294新增: image.thumbnail((max(1, round(g.width * ratio * density)), max(1, round(g.height * ratio * density))),
295新增: Image.Resampling.LANCZOS)
296新增: canvas.paste(image, (round(left * density), round(top * density)))
297新增: encoded, encoded_size = encode_frame(canvas)
298新增: focus, password, _ = self.focus(win, role)
299新增: if document != self.active()[3]:
300新增: raise Failure(409)
301新增: return {'id': self.id, 'width': self.size[0], 'height': self.size[1], 'document': document,
302新增: 'image': base64.b64encode(encoded).decode(), 'focus': focus, 'password': password,
303新增: 'pixel_width':encoded_size[0], 'pixel_height':encoded_size[1],
304新增: 'pixel_ratio':self.scale, 'requested_pixel_ratio':self.requested_scale,
305新增: 'pixel_ratio_control':self.dynamic_scale,
306新增: 'window': role, 'title': 'Claude Desktop', 'shared': True}
307新增:
308新增: def switch(self, role):
309新增: for wid in reversed(self.values(self.root, '_NET_CLIENT_LIST_STACKING')):
310新增: if self.role(self.window(wid)) == role:
311新增: run('xdotool', 'windowactivate', '--sync', str(int(wid)))
312新增: return
313新增: raise Failure(409)
314新增:
315新增: def action(self, req):
316新增: kind = req.get('type')
317新增: if kind == 'resize':
318新增: self.resize(req.get('width'), req.get('height'), req.get('pixel_ratio', 0))
319新增: return
320新增: win, role, geometry, document = self.active()
321新增: if document != req.get('document'):
322新增: raise Failure(409)
323新增: if kind in ('desktop', 'login'):
324新增: self.switch(kind)
325新增: return
326新增: key = req.get('key', '')
327新增: ctx = None
328新增: if kind == 'text' or (kind == 'key' and (req.get('focus') or key == 'Enter' or len(key) == 1)):
329新增: focus, password, ctx = self.focus(win, role)
330新增: if not focus or req.get('focus') != focus or (password and kind == 'text'):
331新增: raise Failure(409)
332新增: if kind == 'text' or (kind == 'key' and len(key) == 1):
333新增: value = req.get('text') if kind == 'text' else key
334新增: if not isinstance(value, str) or not value or len(value.encode()) > 8192:
335新增: raise Failure(400)
336新增: if kind == 'key' and (role != 'login' or not (' ' <= key <= '~')):
337新增: raise Failure(400)
338新增: if document != self.active()[3]:
339新增: raise Failure(409)
340新增: session = secrets.token_hex(16)
341新增: result = native_input({'mode': 'begin', 'context': ctx, 'session': session, 'sequence': 0})
342新增: if result.get('available'):
343新增: result = native_input({'mode': 'commit', 'session': session, 'sequence': 1, 'text': value})
344新增: if not result.get('available'):
345新增: raise Failure(409)
346新增: return
347新增: # Hold the server only for short X11 checks and event dispatch. Do not
348新增: # invoke subprocesses or IBus while the server is grabbed.
349新增: self.conn.grab_server()
350新增: try:
351新增: if document != self.active()[3]:
352新增: raise Failure(409)
353新增: if kind == 'key':
354新增: names = {'Enter':'Return', 'Tab':'Tab', 'Escape':'Escape', 'Backspace':'BackSpace', 'Delete':'Delete',
355新增: 'ArrowLeft':'Left', 'ArrowRight':'Right', 'ArrowUp':'Up', 'ArrowDown':'Down'}
356新增: if key not in names:
357新增: raise Failure(400)
358新增: code = self.conn.keysym_to_keycode(XK.string_to_keysym(names[key]))
359新增: if not code:
360新增: raise Failure(400)
361新增: xtest.fake_input(self.conn, X.KeyPress, code)
362新增: xtest.fake_input(self.conn, X.KeyRelease, code)
363新增: return
364新增: if kind not in ('tap', 'scroll'):
365新增: raise Failure(400)
366新增: x, y = req.get('x'), req.get('y')
367新增: if not all(type(n) in (int, float) and math.isfinite(n) and 0 <= n < bound for n, bound in zip((x,y), self.size)):
368新增: raise Failure(400)
369新增: ratio, left, top = fitted_window(self.size, geometry)
370新增: wx, wy = (x - left) / ratio, (y - top) / ratio
371新增: if not (0 <= wx < geometry.width and 0 <= wy < geometry.height):
372新增: raise Failure(409)
373新增: p = self.root.translate_coords(win, int(wx), int(wy))
374新增: xtest.fake_input(self.conn, X.MotionNotify, x=p.x, y=p.y)
375新增: current = self.root
376新增: while current.id != win.id:
377新增: current = current.query_pointer().child
378新增: if not current:
379新增: raise Failure(409)
380新增: buttons = [1]
381新增: if kind == 'scroll':
382新增: dx, dy = req.get('dx'), req.get('dy')
383新增: if not all(type(n) in (int, float) and math.isfinite(n) and abs(n) <= 3200 for n in (dx,dy)):
384新增: raise Failure(400)
385新增: buttons = []
386新增: for delta, neg, pos in [(dx,6,7), (dy,4,5)]:
387新增: if delta:
388新增: buttons.extend([neg if delta < 0 else pos] * min(20, max(1, round(abs(delta)/50))))
389新增: for button in buttons:
390新增: xtest.fake_input(self.conn, X.ButtonPress, button)
391新增: xtest.fake_input(self.conn, X.ButtonRelease, button)
392新增: finally:
393新增: self.conn.ungrab_server()
394新增: self.conn.sync()
395新增:
396新增:
397新增:class Handler(socketserver.StreamRequestHandler):
398新增: def handle(self):
399新增: self.request.settimeout(7)
400新增: try:
401新增: req = json.loads(self.rfile.readline(65537))
402新增: if req.get('id') != view.id:
403新增: raise Failure(410)
404新增: view.last = time.monotonic()
405新增: if req.get('op') == 'frame':
406新增: result = view.snapshot()
407新增: elif req.get('op') == 'action':
408新增: view.action(req)
409新增: result = {'id': view.id}
410新增: else:
411新增: raise Failure(400)
412新增: except Failure as error:
413新增: result = {'status': error.status}
414新增: except Exception:
415新增: result = {'status': 409}
416新增: self.wfile.write(json.dumps(result, separators=(',', ':')).encode() + b'\n')
417新增:
418新增:
419新增:if __name__ == '__main__':
420新增: if sys.argv[1:] == ['--restore']:
421新增: restore_layout()
422新增: sys.exit(0)
423新增: view = View()
424新增: with socketserver.UnixStreamServer(str(Path(os.environ['XDG_RUNTIME_DIR'])/'view.sock'), Handler) as server:
425新增: server.timeout = 3
426新增: while time.monotonic() - view.last < 120:
427新增: server.handle_request()
新增internal/cage/phone-desktop/xdg-open+31 −0看文件
@@ -0,0 +1,31 @@
1新增:#!/usr/bin/python3
2新增:import os
3新增:from pathlib import Path
4新增:import sys
5新增:from urllib.parse import urlsplit
6新增:
7新增:def launch():
8新增: if len(sys.argv) != 2 or os.environ.get('DISPLAY') != ':79' or os.environ.get('XDG_RUNTIME_DIR') != '/run/cage-phone-desktop':
9新增: return 1
10新增: value = sys.argv[1]
11新增: if not value or len(value) > 8192 or any(ord(c) < 32 for c in value):
12新增: return 1
13新增: parsed = urlsplit(value)
14新增: if parsed.scheme == 'claude':
15新增: os.execv('/usr/bin/claude-desktop', ['claude-desktop', '--user-data-dir=' + str(Path.home() / 'DesktopProfile'), value])
16新增: host = parsed.hostname or ''
17新增: if parsed.scheme != 'https' or parsed.username or parsed.password or parsed.port not in (443, None):
18新增: return 1
19新增: if not any(host == d or host.endswith('.' + d) for d in ('anthropic.com', 'claude.ai', 'claude.com')):
20新增: return 1
21新增: port = (Path(os.environ['XDG_RUNTIME_DIR']) / 'proxy').read_text()
22新增: os.execv('/usr/bin/chromium', ['chromium', '--user-data-dir=' + str(Path.home() / 'LoginProfile'),
23新增: '--class=CagePhoneLogin', '--no-first-run', '--no-default-browser-check', '--disable-extensions',
24新增: '--disable-quic', '--force-webrtc-ip-handling-policy=disable_non_proxied_udp',
25新增: '--proxy-server=socks5://127.0.0.1:' + str(int(port)), '--proxy-bypass-list=<-loopback>',
26新增: '--disable-dev-shm-usage', '--lang=' + os.environ.get('CAGE_LANGUAGE', 'en-US'), '--app=' + value])
27新增:
28新增:try:
29新增: sys.exit(launch())
30新增:except Exception:
31新增: sys.exit(1)
新增internal/cage/phone_desktop.go+40 −0看文件
@@ -0,0 +1,40 @@
1新增:package cage
2新增:
3新增:import (
4新增: "embed"
5新增: "fmt"
6新增: "strings"
7新增:)
8新增:
9新增://go:embed phone-desktop/control.py phone-desktop/session.sh phone-desktop/xdg-open phone-desktop/view.py
10新增://go:embed phone-desktop/handler.desktop phone-desktop/openbox.xml phone-desktop/network.mjs browser-phone-desktop.mjs
11新增:var phoneDesktopFiles embed.FS
12新增:
13新增:// PhoneDesktopProvisionScript installs capture and input for the shared
14新增:// desktop window. The desktop service owns the app and its login data.
15新增:func PhoneDesktopProvisionScript() string {
16新增: var s strings.Builder
17新增: s.WriteString(`
18新增:sudo install -d -m 0755 /usr/local/lib/cage-phone-desktop
19新增:if [ -x /usr/bin/claude-desktop ] && { ! command -v xsettingsd >/dev/null || ! /usr/bin/python3 -c 'from PIL import Image; from Xlib.ext import composite,xtest' 2>/dev/null; }; then
20新增: sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get install -y --no-install-recommends python3-pil python3-xlib xsettingsd ||
21新增: printf '%s\n' '手机 Desktop 组件暂未就绪,可在电脑上修复 Desktop 安装。' >&2
22新增:fi
23新增:`)
24新增: for _, name := range []string{"control.py", "session.sh", "xdg-open", "handler.desktop", "openbox.xml", "view.py", "network.mjs", "browser-phone-desktop.mjs"} {
25新增: source, target := "phone-desktop/"+name, "/usr/local/lib/cage-phone-desktop/"+name
26新增: if name == "browser-phone-desktop.mjs" {
27新增: source, target = name, "/usr/local/lib/"+name
28新增: }
29新增: b, err := phoneDesktopFiles.ReadFile(source)
30新增: if err != nil {
31新增: panic(err)
32新增: }
33新增: fmt.Fprintf(&s, "sudo tee %s >/dev/null <<'CAGE_PHONE_DESKTOP_FILE'\n%s\nCAGE_PHONE_DESKTOP_FILE\n", target, b)
34新增: }
35新增: s.WriteString(`sudo chmod 0755 /usr/local/lib/cage-phone-desktop/{control.py,session.sh,xdg-open}
36新增:printf '%s\n' 'cage-browser ALL=(root) NOPASSWD: /usr/local/lib/cage-phone-desktop/control.py ""' | sudo tee /etc/sudoers.d/cage-phone-desktop >/dev/null
37新增:sudo chmod 0440 /etc/sudoers.d/cage-phone-desktop
38新增:`)
39新增: return s.String()
40新增:}
新增internal/cage/resource_limits.go+55 −0看文件
@@ -0,0 +1,55 @@
1新增:package cage
2新增:
3新增:import (
4新增: "encoding/json"
5新增: "errors"
6新增: "fmt"
7新增: "os"
8新增: "path/filepath"
9新增:)
10新增:
11新增:// ResourceAllocation is separate from network configuration: changing a VM's
12新增:// capacity does not change its network authorization fingerprint.
13新增:type ResourceAllocation struct {
14新增: Automatic bool `json:"automatic"`
15新增: MemoryGiB int `json:"memory_gib"`
16新增: CPUs int `json:"cpus"`
17新增:}
18新增:
19新增:func ResourceAllocationPath(configPath string) string {
20新增: return filepath.Join(filepath.Dir(configPath), "resource-limits.json")
21新增:}
22新增:
23新增:func (a ResourceAllocation) Limits() (memory, cpus int, err error) {
24新增: memory, cpus = ResourceLimits()
25新增: if a.Automatic {
26新增: return memory, cpus, nil
27新增: }
28新增: if a.MemoryGiB < 2 || a.MemoryGiB > memory || a.CPUs < 1 || a.CPUs > cpus {
29新增: return 0, 0, fmt.Errorf("内存上限须为 2–%d GiB,CPU 须为 1–%d 个逻辑核心", memory, cpus)
30新增: }
31新增: return a.MemoryGiB, a.CPUs, nil
32新增:}
33新增:
34新增:func LoadResourceAllocation(configPath string) (ResourceAllocation, error) {
35新增: a := ResourceAllocation{Automatic: true}
36新增: b, err := os.ReadFile(ResourceAllocationPath(configPath))
37新增: if errors.Is(err, os.ErrNotExist) {
38新增: return a, nil
39新增: }
40新增: if err != nil {
41新增: return a, err
42新增: }
43新增: if err = json.Unmarshal(b, &a); err != nil {
44新增: return a, err
45新增: }
46新增: return a, nil
47新增:}
48新增:
49新增:func ConfiguredResourceLimits(configPath string) (int, int, error) {
50新增: a, err := LoadResourceAllocation(configPath)
51新增: if err != nil {
52新增: return 0, 0, err
53新增: }
54新增: return a.Limits()
55新增:}
修改internal/cage/resources.go+14 −6看文件
@@ -15,6 +15,7 @@ import (
1515
1616 "github.com/sylvinus/agent-vm/internal/diagnostics"
1717 "github.com/sylvinus/agent-vm/internal/host"
18新增: "github.com/sylvinus/agent-vm/internal/usererror"
1819)
1920
2021// ResourceLimits keeps the existing host-share policy while replacing the fixed
@@ -230,11 +231,17 @@ func StartResourceManager(parent context.Context, dir string, maximum uint64, cp
230231 }
231232 }
232233 now := time.Now()
234新增: detail := ""
233235 status.UpdatedAt, status.HostPressure = now, host.MemoryPressure()
234236 target := p.target
235237 if err != nil {
236238 p.idleSince = time.Time{}
237删除: status.Error = "资源采样暂时不可用,已暂停内存回收"
239新增: cause := usererror.Reason(err)
240新增: if cause == "" {
241新增: cause = "环境未能返回完整有效的内存与 CPU 数据"
242新增: }
243新增: status.Error = "读取资源用量失败:" + cause + "。自动回收内存已暂停;若持续出现,请在设置中导出诊断包。"
244新增: detail = fmt.Sprintf("%s: %v", status.Error, err)
238245 // A stalled guest may itself be out of memory. Restore its budget
239246 // without relying on a command that needs guest RAM to execute.
240247 if !status.HostPressure {
@@ -265,17 +272,18 @@ func StartResourceManager(parent context.Context, dir string, maximum uint64, cp
265272 e := set(changeCtx, target)
266273 finish()
267274 if e != nil {
268删除: status.Error = "内存目标未能应用,保持当前配置"
275新增: status.Error = "调整环境内存失败:虚拟机没有接受新的内存目标,当前分配保持不变。请在设置中导出诊断包。"
276新增: detail = fmt.Sprintf("%s: %v", status.Error, e)
269277 } else {
270278 p.target, status.Target = target, target
271279 diagnostics.Log("info", "resources", fmt.Sprintf("memory target=%d maximum=%d", target, maximum))
272280 }
273281 }
274删除: if status.Error != lastError {
275删除: if status.Error != "" {
276删除: diagnostics.Log("warn", "resources", status.Error)
282新增: if detail != lastError {
283新增: if detail != "" {
284新增: diagnostics.Log("warn", "resources", detail)
277285 }
278删除: lastError = status.Error
286新增: lastError = detail
279287 }
280288 if e := writeResourceStatus(dir, status); e != nil && lastError != "status write failed" {
281289 diagnostics.Log("warn", "resources", "resource status write failed")
修改internal/cage/resources_test.go+40 −0看文件
@@ -2,11 +2,15 @@ package cage
22
33import (
44 "context"
5新增: "errors"
56 "fmt"
7新增: "os"
8新增: "path/filepath"
69 "strings"
710 "testing"
811 "time"
912
13新增: "github.com/sylvinus/agent-vm/internal/diagnostics"
1014 "github.com/sylvinus/agent-vm/internal/host"
1115)
1216
@@ -24,6 +28,42 @@ func TestResourceLimitsUseExistingHostShare(t *testing.T) {
2428 }
2529}
2630
31新增:func TestResourceFailuresKeepDiagnosticCausePrivate(t *testing.T) {
32新增: profile := t.TempDir()
33新增: previous := diagnostics.Default()
34新增: diagnostics.SetDefault(diagnostics.New(profile))
35新增: t.Cleanup(func() { diagnostics.SetDefault(previous) })
36新增: dir := t.TempDir()
37新增: var attempts int
38新增: stop := StartResourceManager(context.Background(), dir, 4<<30, 2, func(context.Context, string) ([]byte, error) {
39新增: attempts++
40新增: if attempts <= 2 {
41新增: return nil, errors.New("resource probe execution failed: exit status 255; stderr=getsockname failed: Not a socket; token=private-probe-token")
42新增: }
43新增: return []byte("invalid metrics"), nil
44新增: }, func(context.Context, uint64) error { t.Error("failed sample changed memory target"); return nil })
45新增: defer stop()
46新增: deadline := time.Now().Add(9 * time.Second)
47新增: var log []byte
48新增: for time.Now().Before(deadline) {
49新增: log, _ = os.ReadFile(filepath.Join(profile, "logs", "events.jsonl"))
50新增: if strings.Contains(string(log), "incomplete guest resource observation") {
51新增: break
52新增: }
53新增: time.Sleep(25 * time.Millisecond)
54新增: }
55新增: if !strings.Contains(string(log), "Not a socket") || !strings.Contains(string(log), "incomplete guest resource observation") {
56新增: t.Fatalf("failure causes missing from diagnostics: %s", log)
57新增: }
58新增: if strings.Contains(string(log), "private-probe-token") || strings.Count(string(log), "Not a socket") != 1 {
59新增: t.Fatalf("secret leaked or repeated failure flooded log: %s", log)
60新增: }
61新增: status, err := ReadResourceStatus(dir)
62新增: if err != nil || !strings.Contains(status.Error, "自动回收内存已暂停") || strings.Contains(status.Error, "Not a socket") || strings.Contains(status.Error, "private-probe-token") {
63新增: t.Fatalf("technical detail escaped to resource status: %+v %v", status, err)
64新增: }
65新增:}
66新增:
2767func TestMemoryPolicyBurstIdleAndHostPressure(t *testing.T) {
2868 now := time.Now()
2969 gib := uint64(1 << 30)
修改internal/cage/safety.go+38 −7看文件
@@ -2,20 +2,25 @@ package cage
22
33import (
44 "errors"
5新增: "fmt"
6新增: "strings"
57 "time"
8新增:
9新增: "github.com/sylvinus/agent-vm/internal/diagnostics"
10新增: "github.com/sylvinus/agent-vm/internal/exitpolicy"
611)
712
813// SafetyPolicyVersion changes when the mandatory evidence contract changes.
914// Reports authorize one running VM with one applied configuration.
10删除:const SafetyPolicyVersion = "cage-safety/2"
15新增:const SafetyPolicyVersion = "cage-safety/3"
1116const SafetyReportLifetime = 24 * time.Hour
1217
13删除:type CheckState string
18新增:type CheckState = exitpolicy.State
1419
1520const (
16删除: CheckPassed CheckState = "passed"
17删除: CheckFailed CheckState = "failed"
18删除: CheckUnknown CheckState = "unknown"
21新增: CheckPassed = exitpolicy.Passed
22新增: CheckFailed = exitpolicy.Failed
23新增: CheckUnknown = exitpolicy.Unknown
1924)
2025
2126type SafetyCheck struct {
@@ -64,15 +69,41 @@ func (r SafetyReport) Authorizes(runID, configuration string, now time.Time) err
6469 }
6570 seen[check.ID] = check
6671 if check.Critical && check.State != CheckPassed {
67删除: return errors.New("关键检查尚未通过,外网保持关闭")
72新增: state := "未通过"
73新增: if check.State == CheckUnknown {
74新增: state = "未能确认"
75新增: }
76新增: title := safetyCheckTitle(check)
77新增: evidence := strings.TrimRight(diagnostics.Redact(check.Evidence), "。;;")
78新增: if evidence == "" {
79新增: evidence = "没有取得检测结果"
80新增: }
81新增: next := strings.TrimRight(diagnostics.Redact(check.Remedy), "。;;")
82新增: if next == "" {
83新增: next = "打开“检查清单”查看此项结果,重新检测;仍失败时在设置中导出诊断包"
84新增: }
85新增: return fmt.Errorf("联网检查未通过:%s%s。%s。%s。外网保持关闭。", title, state, evidence, next)
6886 }
6987 }
7088 for _, id := range requiredSafetyChecks {
7189 check, found := seen[id]
7290 if !found || !check.Critical || check.State != CheckPassed || check.Evidence == "" ||
7391 check.CheckedAt.Before(r.CreatedAt) || check.CheckedAt.After(now.Add(time.Minute)) {
74删除: return errors.New("关键检测证据不完整,外网保持关闭")
92新增: return fmt.Errorf("联网检查缺少有效证据:%s的记录缺失、过期或不完整。请重新检测;仍失败时在设置中导出诊断包。外网保持关闭。", safetyCheckTitle(SafetyCheck{ID: id}))
7593 }
7694 }
7795 return nil
7896}
97新增:
98新增:func safetyCheckTitle(check SafetyCheck) string {
99新增: if check.Title != "" && check.Title != check.ID {
100新增: return check.Title
101新增: }
102新增: titles := map[string]string{
103新增: "egress_policy": "环境外出站约束", "proxy_transport": "代理连接", "dns_transport": "DNS 解析", "guest_settings": "系统时区与语言", "browser_settings": "浏览器时区与语言", "filesystem_boundary": "项目目录共享", "management_boundary": "宿主管理接口隔离", "fail_closed": "代理故障断网", "udp_policy": "UDP 出站约束", "ipv6_policy": "IPv6 出站约束", "exit_consistency": "出口 IP 与地区",
104新增: }
105新增: if title := titles[check.ID]; title != "" {
106新增: return title
107新增: }
108新增: return "必需检测项目"
109新增:}
新增internal/cage/safety_message_test.go+30 −0看文件
@@ -0,0 +1,30 @@
1新增:package cage
2新增:
3新增:import (
4新增: "strings"
5新增: "testing"
6新增: "time"
7新增:)
8新增:
9新增:func TestSafetyRejectionExplainsFailedCheck(t *testing.T) {
10新增: report := SafetyReport{Policy: SafetyPolicyVersion, ID: "test", RunID: "run", CheckID: "check", Configuration: "config", CreatedAt: time.Now()}
11新增: for _, id := range requiredSafetyChecks {
12新增: report.Checks = append(report.Checks, SafetyCheck{ID: id, Critical: true, State: CheckPassed, Evidence: "verified", CheckedAt: report.CreatedAt})
13新增: }
14新增: report.Checks[4].State = CheckFailed
15新增: report.Checks[4].Title = "浏览器时区与语言"
16新增: report.Checks[4].Evidence = "浏览器语言与设置不一致"
17新增: report.Checks[4].Remedy = "更新环境组件,再重新检测"
18新增: err := report.Authorizes(report.RunID, report.Configuration, time.Now())
19新增: for _, part := range []string{"浏览器时区与语言", "浏览器语言与设置不一致", "更新环境组件", "外网保持关闭"} {
20新增: if err == nil || !strings.Contains(err.Error(), part) {
21新增: t.Fatalf("missing actionable failure %q: %v", part, err)
22新增: }
23新增: }
24新增: report.Checks[4].State = CheckUnknown
25新增: report.Checks[4].Evidence = "未能读取浏览器设置"
26新增: err = report.Authorizes(report.RunID, report.Configuration, time.Now())
27新增: if err == nil || !strings.Contains(err.Error(), "未能确认") {
28新增: t.Fatalf("unknown was presented as a confirmed mismatch: %v", err)
29新增: }
30新增:}
新增internal/cage/shared-clipboard.py+637 −0看文件
@@ -0,0 +1,637 @@
1新增:#!/usr/bin/python3
2新增:"""Share CLIPBOARD selections over a private stdin/stdout channel.
3新增:
4新增:No clipboard payload is logged. File bytes use a separate streaming archive.
5新增:"""
6新增:import base64
7新增:from contextlib import contextmanager
8新增:import fcntl
9新增:import json
10新增:import os
11新增:from pathlib import Path
12新增:import queue
13新增:import shutil
14新增:import stat
15新增:import sys
16新增:import tarfile
17新增:import tempfile
18新增:import threading
19新增:import time
20新增:import uuid
21新增:from urllib.parse import unquote, urlsplit
22新增:
23新增:TEXT_LIMIT = 2 * 1024 * 1024
24新增:IMAGE_LIMIT = 20 * 1024 * 1024
25新增:FILE_LIMIT = 2 * 1024 * 1024 * 1024
26新增:WIRE_LIMIT = 30 * 1024 * 1024
27新增:
28新增:
29新增:class CacheRegistry:
30新增: def __init__(self, directory=None):
31新增: self.directory = Path(directory or Path(tempfile.gettempdir()) / ('cage-clipboard-ownership-' + str(os.getuid())))
32新增:
33新增: def ensure_directory(self):
34新增: self.directory.mkdir(mode=0o700, parents=True, exist_ok=True)
35新增: info = self.directory.lstat()
36新增: if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.geteuid() or info.st_mode & 0o077:
37新增: raise ValueError('Clipboard ownership directory is not private')
38新增:
39新增: def records(self):
40新增: if not self.directory.exists():
41新增: return []
42新增: self.ensure_directory()
43新增: records = []
44新增: for path in self.directory.iterdir():
45新增: if path.suffix != '.json' or not path.is_file():
46新增: continue
47新增: record = json.loads(path.read_text())
48新增: identity = record.get('id') if isinstance(record, dict) else None
49新增: directory = record.get('directory') if isinstance(record, dict) else None
50新增: paths = record.get('paths') if isinstance(record, dict) else None
51新增: marker = record.get('marker') if isinstance(record, dict) else None
52新增: if (not isinstance(identity, str) or len(identity) != 32 or any(c not in '0123456789abcdef' for c in identity)
53新增: or identity + '.json' != path.name or not isinstance(directory, str)
54新增: or not Path(directory).is_absolute() or os.path.normpath(directory) != directory
55新增: or not isinstance(paths, list) or not 1 <= len(paths) <= 100
56新增: or any(not isinstance(item, str) or Path(item).parent != Path(directory) or os.path.normpath(item) != item for item in paths)
57新增: or not isinstance(marker, str) or marker in ('', '.', '..') or Path(marker).name != marker
58新增: or not isinstance(record.get('session'), str) or not isinstance(record.get('retired'), bool)):
59新增: raise ValueError('Invalid clipboard ownership record')
60新增: records.append(record)
61新增: return records
62新增:
63新增: def save(self, record):
64新增: self.ensure_directory()
65新增: fd, temporary = tempfile.mkstemp(dir=self.directory, prefix='.record-')
66新增: try:
67新增: with os.fdopen(fd, 'w') as output:
68新增: json.dump(record, output)
69新增: os.replace(temporary, self.directory / (record['id'] + '.json'))
70新增: finally:
71新增: Path(temporary).unlink(missing_ok=True)
72新增:
73新增: def register(self, paths, session):
74新增: root = Path(paths[0]).parent
75新增: identity = uuid.uuid4().hex
76新增: fd, marker = tempfile.mkstemp(dir=root, prefix='.cage-clipboard-owner-')
77新增: with os.fdopen(fd, 'w') as output:
78新增: output.write(identity)
79新增: self.ensure_directory()
80新增: lock = self.directory / (identity + '.lock')
81新增: lock.touch(mode=0o600, exist_ok=False)
82新增: try:
83新增: self.save({'id': identity, 'directory': str(root), 'marker': Path(marker).name,
84新增: 'paths': paths, 'session': session, 'retired': False})
85新增: except BaseException:
86新增: lock.unlink(missing_ok=True)
87新增: raise
88新增:
89新增: def retire(self, paths):
90新增: selected = set(paths)
91新增: for record in self.records():
92新增: if selected.intersection(record['paths']):
93新增: record['retired'] = True
94新增: self.save(record)
95新增:
96新增: def adopt(self, paths, session):
97新增: selected = set(paths)
98新增: for record in self.records():
99新增: if selected.intersection(record['paths']):
100新增: record['session'] = session
101新增: self.save(record)
102新增:
103新增: @contextmanager
104新增: def reading(self, paths):
105新增: leases = []
106新增: try:
107新增: for record in self.records():
108新增: root = Path(record['directory'])
109新增: if any(Path(path).is_relative_to(root) for path in paths):
110新增: lock = (self.directory / (record['id'] + '.lock')).open('rb')
111新增: fcntl.flock(lock, fcntl.LOCK_SH)
112新增: leases.append(lock)
113新增: yield
114新增: finally:
115新增: for lease in leases:
116新增: lease.close()
117新增:
118新增: def collect(self, selected, session):
119新增: for record in self.records():
120新增: root = Path(record['directory'])
121新增: if root.exists() and not record['retired'] and (not record['session'] or record['session'] == session):
122新增: continue
123新增: if any(Path(path).is_relative_to(root) or root.is_relative_to(Path(path)) for path in selected):
124新增: continue
125新增: lock_path = self.directory / (record['id'] + '.lock')
126新增: with lock_path.open('rb') as lease:
127新增: try:
128新增: fcntl.flock(lease, fcntl.LOCK_EX | fcntl.LOCK_NB)
129新增: except BlockingIOError:
130新增: continue
131新增: if root.exists():
132新增: marker = root / record['marker']
133新增: if root.is_symlink() or marker.is_symlink() or marker.read_text() != record['id']:
134新增: raise ValueError('Clipboard ownership changed')
135新增: for item in root.iterdir():
136新增: if item == marker:
137新增: continue
138新增: if item.is_dir() and not item.is_symlink():
139新增: shutil.rmtree(item)
140新增: else:
141新增: item.unlink()
142新增: marker.unlink()
143新增: try:
144新增: root.rmdir()
145新增: except OSError:
146新增: marker.write_text(record['id'])
147新增: marker.chmod(0o600)
148新增: raise
149新增: (self.directory / (record['id'] + '.json')).unlink()
150新增: lock_path.unlink(missing_ok=True)
151新增:
152新增:
153新增:def file_paths(uris):
154新增: paths = []
155新增: for uri in uris:
156新增: parsed = urlsplit(uri)
157新增: if parsed.scheme != 'file' or parsed.netloc not in ('', 'localhost'):
158新增: raise ValueError('Only local clipboard files can be shared')
159新增: path = Path(unquote(parsed.path))
160新增: if not path.is_absolute() or path.is_symlink() or not path.exists():
161新增: raise ValueError('Clipboard file unavailable')
162新增: paths.append(str(path))
163新增: if not 1 <= len(paths) <= 100:
164新增: raise ValueError('Clipboard supports 1 to 100 selected files or folders')
165新增: return paths
166新增:
167新增:
168新增:def export_files(paths, output):
169新增: paths = file_paths([Path(path).as_uri() for path in paths])
170新增: names = set()
171新增: with tarfile.open(fileobj=output, mode='w|') as archive:
172新增: def check(info):
173新增: if not (info.isfile() or info.isdir()) or info.size > FILE_LIMIT:
174新增: raise ValueError('Clipboard supports ordinary files up to 2 GB')
175新增: return info
176新增: for path in paths:
177新增: name = Path(path).name
178新增: if not name or name in names:
179新增: raise ValueError('Clipboard file names must be distinct')
180新增: names.add(name)
181新增: archive.add(path, arcname=name, filter=check)
182新增:
183新增:
184新增:def import_files(source, session=''):
185新增: root = Path(tempfile.mkdtemp(prefix='cage-clipboard-'))
186新增: try:
187新增: paths = extract_files(source, root)
188新增: CacheRegistry().register(paths, session)
189新增: return paths
190新增: except BaseException:
191新增: shutil.rmtree(root)
192新增: raise
193新增:
194新增:
195新增:def extract_files(source, root):
196新增: root.chmod(0o755)
197新增: names = []
198新增: with tarfile.open(fileobj=source, mode='r|') as archive:
199新增: for item in archive:
200新增: parts = item.name.split('/')
201新增: if (not parts or any(part in ('', '.', '..') or '\\' in part for part in parts)
202新增: or not (item.isfile() or item.isdir()) or item.size > FILE_LIMIT):
203新增: raise ValueError('Invalid clipboard archive')
204新增: if parts[0] not in names:
205新增: names.append(parts[0])
206新增: if len(names) > 100:
207新增: raise ValueError('Too many clipboard files')
208新增: destination = root.joinpath(*parts)
209新增: destination.parent.mkdir(parents=True, exist_ok=True, mode=0o755)
210新增: if item.isdir():
211新增: destination.mkdir(exist_ok=True, mode=0o755)
212新增: else:
213新增: with archive.extractfile(item) as source_file, destination.open('xb') as target:
214新增: while chunk := source_file.read(1024 * 1024):
215新增: target.write(chunk)
216新增: destination.chmod(0o644)
217新增: if not names:
218新增: raise ValueError('Empty clipboard archive')
219新增: return [str(root / name) for name in names]
220新增:
221新增:
222新增:def materialize_guest_files(paths, user, session=''):
223新增: # The two graphical sessions have separate UIDs. Read only with the
224新增: # copying application's permissions, then provide a shared temporary copy.
225新增: import multiprocessing
226新增: import pwd
227新增: account = pwd.getpwnam(user)
228新增: read_fd, write_fd = os.pipe()
229新增: def export():
230新增: os.close(read_fd)
231新增: os.initgroups(account.pw_name, account.pw_gid)
232新增: os.setgid(account.pw_gid)
233新增: os.setuid(account.pw_uid)
234新增: try:
235新增: with os.fdopen(write_fd, 'wb') as output:
236新增: export_files(paths, output)
237新增: except BaseException:
238新增: os._exit(1)
239新增: process = multiprocessing.get_context('fork').Process(target=export)
240新增: process.start()
241新增: os.close(write_fd)
242新增: copied = None
243新增: try:
244新增: with os.fdopen(read_fd, 'rb') as source:
245新增: copied = import_files(source, session)
246新增: process.join(timeout=3)
247新增: if process.exitcode != 0:
248新增: raise ValueError('Clipboard source files cannot be read')
249新增: return copied
250新增: except BaseException:
251新增: if copied:
252新增: shutil.rmtree(Path(copied[0]).parent)
253新增: raise
254新增: finally:
255新增: if process.is_alive():
256新增: process.terminate(); process.join(timeout=2)
257新增:
258新增:
259新增:def clipboard_worker(name, connection):
260新增: os.environ['NO_AT_BRIDGE'] = '1'
261新增: os.environ['DISPLAY'] = name
262新增: if name == ':78':
263新增: os.environ['XAUTHORITY'] = '/run/cage-desktop/Xauthority'
264新增: else:
265新增: os.environ.pop('XAUTHORITY', None)
266新增: import gi
267新增: gi.require_version('Gtk', '3.0')
268新增: gi.require_version('Gdk', '3.0')
269新增: from gi.repository import Gdk, GdkPixbuf, GLib, Gtk
270新增:
271新增: Gtk.init_check([])
272新增: display = Gdk.Display.get_default()
273新增: if not display:
274新增: return
275新增: clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
276新增: displays = {name: (display, clipboard)}
277新增: last = None
278新增: initialized = False
279新增: commands = queue.Queue()
280新增: changes = {}
281新增: # Bytes are owned by Gtk and retained until another application copies.
282新增: def write(clipboard, payload):
283新增: if 'text' in payload:
284新增: clipboard.set_text(payload['text'], -1)
285新增: elif 'png' in payload:
286新增: loader = GdkPixbuf.PixbufLoader.new_with_type('png')
287新增: loader.write(base64.b64decode(payload['png'], validate=True))
288新增: loader.close()
289新增: image = loader.get_pixbuf()
290新增: if image.get_width() * image.get_height() > 40_000_000:
291新增: raise ValueError('Clipboard image too large')
292新增: clipboard.set_image(image)
293新增: else:
294新增: uris = [Path(path).as_uri() for path in payload['files']]
295新增: # PyGObject does not expose gtk_clipboard_set_with_data. Supply the
296新增: # URI selection through its C API while keeping callbacks alive.
297新增: set_files(clipboard, uris)
298新增:
299新增: import ctypes as C
300新增: gtk = C.CDLL('libgtk-3.so.0')
301新增: gdk = C.CDLL('libgdk-3.so.0')
302新增: p = C.c_void_p
303新增: def bind(lib, name, result, *args):
304新增: function = getattr(lib, name)
305新增: function.restype, function.argtypes = result, list(args)
306新增: return function
307新增: atom = bind(gdk, 'gdk_atom_intern_static_string', p, C.c_char_p)
308新增: set_data = bind(gtk, 'gtk_selection_data_set', None, p, p, C.c_int, p, C.c_int)
309新增: get_clipboard = bind(gtk, 'gtk_clipboard_get_for_display', p, p, p)
310新增: class Target(C.Structure):
311新增: _fields_ = [('target', C.c_char_p), ('flags', C.c_uint), ('info', C.c_uint)]
312新增: provide_type = C.CFUNCTYPE(None, p, p, C.c_uint, p)
313新增: clear_type = C.CFUNCTYPE(None, p, p)
314新增: own = bind(gtk, 'gtk_clipboard_set_with_data', C.c_int, p, C.POINTER(Target), C.c_uint, provide_type, clear_type, p)
315新增: owners = {}
316新增: def set_files(clipboard, uris):
317新增: names = [b'text/uri-list', b'x-special/gnome-copied-files']
318新增: data = [('\r\n'.join(uris) + '\r\n').encode(), ('copy\n' + '\n'.join(uris)).encode()]
319新增: buffers = [C.create_string_buffer(value) for value in data]
320新增: @provide_type
321新增: def provide(_clipboard, selection, index, _user):
322新增: set_data(selection, atom(names[index]), 8, buffers[index], len(data[index]))
323新增: @clear_type
324新增: def clear(_clipboard, _user):
325新增: pass
326新增: display = clipboard.get_display()
327新增: native_clipboard = get_clipboard(hash(display), atom(b'CLIPBOARD'))
328新增: targets = (Target * 2)(*(Target(name, 0, index) for index, name in enumerate(names)))
329新增: # Keep old INCR transfers alive briefly when replacing the owner.
330新增: previous = owners.get(hash(display))
331新增: if previous:
332新增: GLib.timeout_add_seconds(10, lambda retained=previous: False)
333新增: owners[hash(display)] = (provide, clear, buffers, targets)
334新增: if not own(native_clipboard, targets, 2, provide, clear, None):
335新增: raise ValueError('Cannot own clipboard files')
336新增:
337新增: def publish(payload, source):
338新增: nonlocal last
339新增: if not initialized or payload == last:
340新增: return
341新增: last = payload
342新增: for name, (_, clipboard) in displays.items():
343新增: if name != source:
344新增: write(clipboard, payload)
345新增: message = dict(payload)
346新增: if 'files' in payload:
347新增: message['source'] = 'cage-browser' if source == ':77' else 'cage'
348新增: connection.send(message)
349新增:
350新增: def changed(clipboard, _event, name):
351新增: # Read the actual OS CLIPBOARD, never X11's drag-selection PRIMARY.
352新增: # Requests stay asynchronous: reading one X server must not block this
353新增: # process from answering selection requests on the other X server.
354新增: changes[name] = changes.get(name, 0) + 1
355新增: sequence = changes[name]
356新增: def valid():
357新增: return sequence == changes.get(name)
358新增: def failure():
359新增: connection.send({'error': '剪贴板内容无法共享,请检查文件是否仍存在及大小限制。'})
360新增: def text_ready(_clipboard, text, _data):
361新增: if not valid() or text is None:
362新增: return
363新增: if len(text.encode()) > TEXT_LIMIT:
364新增: failure()
365新增: else:
366新增: publish({'text': text}, name)
367新增: def image_ready(_clipboard, image, _data):
368新增: if not valid():
369新增: return
370新增: if not image:
371新增: clipboard.request_text(text_ready, None)
372新增: return
373新增: try:
374新增: if image.get_width() * image.get_height() > 40_000_000:
375新增: raise ValueError('Clipboard image too large')
376新增: ok, data = image.save_to_bufferv('png', [], [])
377新增: if not ok or len(data) > IMAGE_LIMIT:
378新增: raise ValueError('Clipboard image too large')
379新增: publish({'png': base64.b64encode(data).decode()}, name)
380新增: except (ValueError, OSError, GLib.Error):
381新增: failure()
382新增: def selected_files(uris):
383新增: if not valid():
384新增: return
385新增: if uris:
386新增: try:
387新增: paths = file_paths(uris)
388新增: connection.send({'clipboard_files': paths})
389新增: publish({'files': paths}, name)
390新增: except (ValueError, OSError):
391新增: failure()
392新增: else:
393新增: connection.send({'clipboard_files': []})
394新增: clipboard.request_image(image_ready, None)
395新增: def gnome_ready(_clipboard, selection, _data):
396新增: data = selection.get_data() or b''
397新增: if len(data) > TEXT_LIMIT:
398新增: failure()
399新增: return
400新增: try:
401新增: lines = data.decode('utf-8', errors='strict').splitlines()
402新增: except UnicodeError:
403新增: failure()
404新增: return
405新增: selected_files(lines[1:] if lines and lines[0] in ('copy', 'cut') else [])
406新增: def uris_ready(_clipboard, uris, _data):
407新增: if uris:
408新增: selected_files(uris)
409新增: else:
410新增: clipboard.request_contents(Gdk.Atom.intern('x-special/gnome-copied-files', False), gnome_ready, None)
411新增: clipboard.request_uris(uris_ready, None)
412新增:
413新增: def tick():
414新增: nonlocal last, initialized
415新增: while not commands.empty():
416新增: payload = commands.get()
417新增: if payload is None:
418新增: Gtk.main_quit()
419新增: return False
420新增: try:
421新增: serial = payload.pop('serial', 0)
422新增: if 'text' in payload and isinstance(payload['text'], str) and len(payload['text'].encode()) <= TEXT_LIMIT:
423新增: pass
424新增: elif 'png' in payload and len(base64.b64decode(payload['png'], validate=True)) <= IMAGE_LIMIT:
425新增: pass
426新增: elif 'files' in payload:
427新增: payload = {'files': file_paths([Path(path).as_uri() for path in payload['files']])}
428新增: else:
429新增: raise ValueError('Invalid clipboard payload')
430新增: last = payload
431新增: initialized = True
432新增: for _, clipboard in displays.values():
433新增: write(clipboard, payload)
434新增: connection.send({'ack': serial})
435新增: except (TypeError, ValueError, KeyError, OSError, GLib.Error):
436新增: connection.send({'error': '剪贴板内容无法共享。'})
437新增: return True
438新增:
439新增: def read():
440新增: try:
441新增: while True:
442新增: commands.put(connection.recv())
443新增: except EOFError:
444新增: pass
445新增: commands.put(None)
446新增: threading.Thread(target=read, daemon=True).start()
447新增: clipboard.connect('owner-change', changed, name)
448新增: changed(clipboard, None, name)
449新增: GLib.timeout_add(100, tick)
450新增: Gtk.main()
451新增:
452新增:
453新增:def bridge():
454新增: # GTK's providers use a default display. Keep one small worker per X11
455新增: # session, under that application's UID, and merge only clipboard events.
456新增: import multiprocessing
457新增: import pwd
458新增: import selectors
459新增: import uuid
460新增: workers = {}
461新增: commands = queue.Queue()
462新增: pending = {}
463新增: last = None
464新增: initialized = False
465新增: internal_serial = 0
466新增: session = str(uuid.uuid4())
467新增: announced = None
468新增: registry = CacheRegistry()
469新增: current_files = {}
470新增: next_cache_check = 0
471新增: cleanup_needed = True
472新增: def referenced_files():
473新增: selected = [path for paths in current_files.values() for path in paths]
474新增: if last:
475新增: selected.extend(last.get('files', []))
476新增: for value in pending.values():
477新增: selected.extend(value.get('files', []))
478新增: return selected
479新增: def run_worker(name, connection, uid, gid, home):
480新增: os.initgroups(pwd.getpwuid(uid).pw_name, gid)
481新增: os.setgid(gid)
482新增: os.setuid(uid)
483新增: os.environ['HOME'] = home
484新增: clipboard_worker(name, connection)
485新增: selector = selectors.DefaultSelector()
486新增: selector.register(sys.stdin.fileno(), selectors.EVENT_READ)
487新增: incoming = b''
488新增: context = multiprocessing.get_context('fork')
489新增: try:
490新增: running = True
491新增: while running:
492新增: if selector.select(timeout=.05):
493新增: chunk = os.read(sys.stdin.fileno(), 65536)
494新增: if not chunk:
495新增: break
496新增: incoming += chunk
497新增: if len(incoming) > WIRE_LIMIT:
498新增: break
499新增: while b'\n' in incoming:
500新增: line, incoming = incoming.split(b'\n', 1)
501新增: try:
502新增: commands.put(json.loads(line))
503新增: except ValueError:
504新增: running = False
505新增: break
506新增: for name, user in ((':77', 'cage-browser'), (':78', 'cage')):
507新增: previous = workers.get(name)
508新增: if previous and not previous[0].is_alive():
509新增: previous[0].join(); previous[1].close(); del workers[name]
510新增: current_files.pop(name, None)
511新增: if name not in workers and Path('/tmp/.X11-unix/X' + name[1:]).exists():
512新增: account = pwd.getpwnam(user)
513新增: parent, child = context.Pipe()
514新增: process = context.Process(target=run_worker, args=(name, child, account.pw_uid, account.pw_gid, account.pw_dir))
515新增: process.start(); child.close()
516新增: workers[name] = (process, parent)
517新增: if initialized:
518新增: parent.send(last)
519新增: available = bool(workers)
520新增: if available != announced:
521新增: print(json.dumps({'hello': {'version': 1, 'os': 'linux', 'session': session,
522新增: 'formats': ['text', 'png', 'files'], 'available': available, 'file_release': True}}), flush=True)
523新增: announced = available
524新增: while not commands.empty():
525新增: message = commands.get()
526新增: if message is None:
527新增: running = False
528新增: break
529新增: if 'release' in message:
530新增: registry.retire(message['release'])
531新增: cleanup_needed = True
532新增: continue
533新增: serial = message.get('serial', 0)
534新增: last = {key: value for key, value in message.items() if key in ('text', 'png', 'files')}
535新增: initialized = True
536新增: registry.adopt(last.get('files', []), session)
537新增: pending[serial] = {'targets': set(workers), 'message': None, 'files': last.get('files', [])}
538新增: for _, connection in workers.values():
539新增: connection.send({**last, 'serial': serial})
540新增: if not pending[serial]['targets']:
541新增: print(json.dumps({'ack': serial}), flush=True)
542新增: del pending[serial]
543新增: for name, (process, connection) in list(workers.items()):
544新增: while process.is_alive() and connection.poll():
545新增: try:
546新增: message = connection.recv()
547新增: except EOFError:
548新增: break
549新增: if 'clipboard_files' in message:
550新增: current_files[name] = message['clipboard_files']
551新增: cleanup_needed = True
552新增: continue
553新增: if 'ack' in message:
554新增: serial = message['ack']
555新增: if serial in pending:
556新增: pending[serial]['targets'].discard(name)
557新增: if not pending[serial]['targets']:
558新增: outgoing = pending[serial]['message']
559新增: if outgoing is None:
560新增: print(json.dumps({'ack': serial}), flush=True)
561新增: elif {key: value for key, value in outgoing.items() if key in ('text','png','files')} == last:
562新增: print(json.dumps(outgoing), flush=True)
563新增: else:
564新增: registry.retire(outgoing.get('files', []))
565新增: cleanup_needed = True
566新增: del pending[serial]
567新增: continue
568新增: if message.get('error'):
569新增: print(json.dumps(message), flush=True)
570新增: continue
571新增: payload = {key: value for key, value in message.items() if key in ('text', 'png', 'files')}
572新增: if not initialized or payload == last:
573新增: continue
574新增: if 'files' in payload:
575新增: try:
576新增: with registry.reading(payload['files']):
577新增: payload = {'files': materialize_guest_files(payload['files'], 'cage-browser' if name == ':77' else 'cage', session)}
578新增: message = {**payload, 'source': 'cage'}
579新增: except (ValueError, OSError, tarfile.TarError):
580新增: print('{"error":"剪贴板文件无法共享,请检查文件是否仍存在及读取权限。"}', flush=True)
581新增: continue
582新增: last = payload
583新增: internal_serial -= 1
584新增: targets = set(workers) if 'files' in payload else set(workers) - {name}
585新增: pending[internal_serial] = {'targets': targets, 'message': message, 'files': payload.get('files', [])}
586新增: for other, (_, sibling) in workers.items():
587新增: if other in targets:
588新增: sibling.send({**payload, 'serial': internal_serial})
589新增: if not targets:
590新增: print(json.dumps(message), flush=True)
591新增: del pending[internal_serial]
592新增: if workers and all(name in current_files for name in workers) and (cleanup_needed or time.monotonic() >= next_cache_check):
593新增: try:
594新增: registry.collect(referenced_files(), session)
595新增: except (ValueError, OSError):
596新增: print('Clipboard cache cleanup failed; creation records retained.', file=sys.stderr)
597新增: cleanup_needed = False
598新增: next_cache_check = time.monotonic() + 1
599新增: finally:
600新增: try:
601新增: for record in registry.records():
602新增: if record['session'] == session:
603新增: registry.retire(record['paths'])
604新增: if workers and all(name in current_files for name in workers):
605新增: registry.collect(referenced_files(), session)
606新增: except (ValueError, OSError):
607新增: print('Clipboard cache cleanup failed; creation records retained.', file=sys.stderr)
608新增: selector.close()
609新增: for process, connection in workers.values():
610新增: connection.close()
611新增: process.terminate(); process.join(timeout=2)
612新增: if process.is_alive():
613新增: process.kill(); process.join()
614新增:
615新增:
616新增:if __name__ == '__main__':
617新增: if sys.argv[1:] == ['--import'] or len(sys.argv) == 4 and sys.argv[1:3] == ['--import', '--session']:
618新增: print(json.dumps({'paths': import_files(sys.stdin.buffer, sys.argv[3] if len(sys.argv) == 4 else '')}))
619新增: elif len(sys.argv) == 4 and sys.argv[1] == '--export-user' and sys.argv[2] in ('cage', 'cage-browser') and sys.argv[3] == '--paths-stdin':
620新增: import pwd
621新增: selection = sys.stdin.buffer.read((1 << 20) + 1)
622新增: if len(selection) > 1 << 20:
623新增: raise ValueError('file selection exceeded its limit')
624新增: paths = json.loads(selection)
625新增: with CacheRegistry().reading(paths):
626新增: account = pwd.getpwnam(sys.argv[2])
627新增: os.initgroups(account.pw_name, account.pw_gid)
628新增: os.setgid(account.pw_gid)
629新增: os.setuid(account.pw_uid)
630新增: export_files(paths, sys.stdout.buffer)
631新增: elif len(sys.argv) == 3 and sys.argv[1] == '--export':
632新增: selection = sys.stdin.buffer.read((1 << 20) + 1) if sys.argv[2] == '--paths-stdin' else sys.argv[2]
633新增: if len(selection) > 1 << 20:
634新增: raise ValueError('file selection exceeded its limit')
635新增: export_files(json.loads(selection), sys.stdout.buffer)
636新增: else:
637新增: bridge()
新增internal/cage/shared-clipboard.test.py+123 −0看文件
@@ -0,0 +1,123 @@
1新增:import importlib.util
2新增:import io
3新增:import json
4新增:from pathlib import Path
5新增:import tarfile
6新增:import tempfile
7新增:import unittest
8新增:from unittest.mock import patch
9新增:
10新增:
11新增:spec = importlib.util.spec_from_file_location('shared_clipboard', Path(__file__).with_name('shared-clipboard.py'))
12新增:clipboard = importlib.util.module_from_spec(spec)
13新增:spec.loader.exec_module(clipboard)
14新增:
15新增:
16新增:class CacheOwnershipTests(unittest.TestCase):
17新增: def setUp(self):
18新增: self.temporary = tempfile.TemporaryDirectory()
19新增: self.addCleanup(self.temporary.cleanup)
20新增: self.root = Path(self.temporary.name)
21新增: self.registry = clipboard.CacheRegistry(self.root / 'receipts')
22新增: self.cache = self.root / 'created'
23新增: self.cache.mkdir()
24新增: self.file = self.cache / 'fixture.txt'
25新增: self.file.write_bytes(b'complete copied bytes')
26新增: self.paths = [str(self.file)]
27新增: self.registry.register(self.paths, 'current-session')
28新增:
29新增: def test_current_clipboard_and_reader_references_retain_retired_files(self):
30新增: self.registry.retire(self.paths)
31新增: self.registry.collect(self.paths, 'current-session')
32新增: self.assertTrue(self.file.exists())
33新增: with self.registry.reading(self.paths):
34新增: self.registry.collect([], 'current-session')
35新增: self.assertEqual(self.file.read_bytes(), b'complete copied bytes')
36新增: self.registry.collect([], 'current-session')
37新增: self.assertFalse(self.cache.exists())
38新增: self.assertEqual(self.registry.records(), [])
39新增:
40新增: def test_delayed_external_path_requires_recopy_but_open_reader_finishes(self):
41新增: self.registry.retire(self.paths)
42新增: with self.file.open('rb') as reader:
43新增: self.registry.collect([], 'current-session')
44新增: self.assertEqual(reader.read(), b'complete copied bytes')
45新增: self.assertFalse(self.file.exists())
46新增:
47新增: def test_only_created_cache_is_collected(self):
48新增: unrelated = self.root / 'cage-clipboard-qa-test-unrelated'
49新增: unrelated.mkdir()
50新增: (unrelated / 'keep.txt').write_text('user content')
51新增: self.registry.collect([], 'new-session')
52新增: self.assertFalse(self.cache.exists())
53新增: self.assertEqual((unrelated / 'keep.txt').read_text(), 'user content')
54新增:
55新增: def test_active_and_legacy_unpublished_selections_are_retained(self):
56新增: self.registry.collect([], 'current-session')
57新增: self.assertTrue(self.file.exists())
58新增: record = self.registry.records()[0]
59新增: record['session'] = ''
60新增: self.registry.save(record)
61新增: self.registry.collect([], 'new-session')
62新增: self.assertTrue(self.file.exists())
63新增: self.registry.retire(self.paths)
64新增: self.registry.collect([], 'new-session')
65新增: self.assertFalse(self.cache.exists())
66新增:
67新增: def test_changed_creation_marker_blocks_deletion(self):
68新增: record = self.registry.records()[0]
69新增: (self.cache / record['marker']).write_text('changed owner')
70新增: self.registry.retire(self.paths)
71新增: with self.assertRaises(ValueError):
72新增: self.registry.collect([], 'current-session')
73新增: self.assertEqual(self.file.read_bytes(), b'complete copied bytes')
74新增:
75新增: def test_directory_removal_failure_retains_proof_for_retry(self):
76新增: self.registry.retire(self.paths)
77新增: with patch.object(Path, 'rmdir', side_effect=PermissionError('simulated busy directory')):
78新增: with self.assertRaises(PermissionError):
79新增: self.registry.collect([], 'current-session')
80新增: self.registry.collect([], 'current-session')
81新增: self.assertFalse(self.cache.exists())
82新增:
83新增: def test_malformed_receipt_and_symlink_registry_fail_without_removing_files(self):
84新增: record = self.registry.records()[0]
85新增: path = self.registry.directory / (record['id'] + '.json')
86新增: path.write_text(json.dumps({'id': None}))
87新增: with self.assertRaises(ValueError):
88新增: self.registry.records()
89新增: self.assertTrue(self.file.exists())
90新增: alias = self.root / 'alias'
91新增: alias.symlink_to(self.registry.directory, target_is_directory=True)
92新增: with self.assertRaises(ValueError):
93新增: clipboard.CacheRegistry(alias).records()
94新增:
95新增: def test_import_registers_exact_owned_directory_and_keeps_original_bytes(self):
96新增: source = io.BytesIO()
97新增: clipboard.export_files(self.paths, source)
98新增: source.seek(0)
99新增: with patch.object(clipboard.tempfile, 'tempdir', str(self.root)):
100新增: paths = clipboard.import_files(source, 'import-session')
101新增: registry = clipboard.CacheRegistry()
102新增: self.assertEqual(registry.records()[0]['paths'], paths)
103新增: registry.retire(paths)
104新增: registry.collect([], 'import-session')
105新增: self.assertEqual(self.file.read_bytes(), b'complete copied bytes')
106新增: self.assertFalse(Path(paths[0]).parent.exists())
107新增:
108新增: def test_failed_archive_is_removed_before_it_can_be_published(self):
109新增: source = io.BytesIO()
110新增: with tarfile.open(fileobj=source, mode='w') as archive:
111新增: entry = tarfile.TarInfo('../outside')
112新增: entry.size = 1
113新增: archive.addfile(entry, io.BytesIO(b'x'))
114新增: source.seek(0)
115新增: before = set(self.root.iterdir())
116新增: with patch.object(clipboard.tempfile, 'tempdir', str(self.root)):
117新增: with self.assertRaises(ValueError):
118新增: clipboard.import_files(source, 'import-session')
119新增: self.assertEqual(set(self.root.iterdir()), before)
120新增:
121新增:
122新增:if __name__ == '__main__':
123新增: unittest.main()
新增internal/cage/shared_clipboard.go+10 −0看文件
@@ -0,0 +1,10 @@
1新增:package cage
2新增:
3新增:import _ "embed"
4新增:
5新增://go:embed shared-clipboard.py
6新增:var SharedClipboardHelper string
7新增:
8新增:func sharedClipboardScript() string {
9新增: return "sudo tee /usr/local/bin/cage-shared-clipboard >/dev/null <<'CAGE_SHARED_CLIPBOARD'\n" + SharedClipboardHelper + "\nCAGE_SHARED_CLIPBOARD\nsudo chmod 0755 /usr/local/bin/cage-shared-clipboard\n"
10新增:}
新增internal/cage/split-extension/browser-identity.js+5 −0看文件
@@ -0,0 +1,5 @@
1新增:// Cage's private control pipe serves a person using the browser.
2新增:Object.defineProperty(Navigator.prototype, "webdriver", {
3新增: get: () => false,
4新增: configurable: true,
5新增:});
修改internal/cage/split-extension/control.js+12 −0看文件
@@ -2,6 +2,18 @@
22// The debugger permission maps CDP target IDs to Chrome tab IDs. We never
33// attach a debugger through the extension or accept messages from webpages.
44const targetsByTab = new Map();
5新增:globalThis.manageCageExtensions = async function (input) {
6新增: const items = (await chrome.management.getAll()).filter(item => item.id !== chrome.runtime.id && item.type === 'extension');
7新增: if (input.mode === 'list') return { items: items.map(({ id, name, description, version, enabled, mayDisable, optionsUrl, permissions, hostPermissions, installType }) =>
8新增: ({ id, name, description, version, enabled, mayDisable, optionsUrl, permissions, hostPermissions, installType })) };
9新增: const entry = items.find(item => item.id === input.id);
10新增: if (!entry) throw new Error('扩展不存在');
11新增: if (input.mode === 'options') return { url: entry.optionsUrl || '' };
12新增: if (!entry.mayDisable) throw new Error('此扩展由浏览器管理');
13新增: if (!['enable', 'disable'].includes(input.mode)) throw new Error('扩展操作无效');
14新增: await chrome.management.setEnabled(input.id, input.mode === 'enable');
15新增: return { ok: true };
16新增:};
517let managedSplit;
618const faviconVersions = new Map();
719chrome.tabs.onUpdated.addListener((tabId, changes) => {
修改internal/cage/split-extension/manifest.json+9 −1看文件
@@ -2,5 +2,13 @@
22 "manifest_version": 3,
33 "name": "Cage browser panes",
44 "version": "1.0",
5删除: "permissions": ["debugger", "tabs", "favicon"]
5新增: "permissions": ["debugger", "tabs", "favicon", "management"],
6新增: "content_scripts": [{
7新增: "matches": ["<all_urls>"],
8新增: "js": ["browser-identity.js"],
9新增: "run_at": "document_start",
10新增: "all_frames": true,
11新增: "match_origin_as_fallback": true,
12新增: "world": "MAIN"
13新增: }]
614}
新增internal/cage/split-extension/settings.html+1 −0看文件
@@ -0,0 +1 @@
1新增:<!doctype html><meta charset="utf-8"><title>Cage 浏览器设置</title>
修改internal/cage/storage.go+92 −6看文件
@@ -12,6 +12,7 @@ import (
1212 "runtime"
1313 "strconv"
1414 "strings"
15新增: "time"
1516
1617 "github.com/sylvinus/agent-vm/internal/host"
1718 "github.com/sylvinus/agent-vm/internal/paths"
@@ -39,6 +40,8 @@ type storageMove struct {
3940 // Previous anchor is retained when the old storage is a directory.
4041 // If it was a link, only the link is discarded after commit.
4142 PreviousCustom bool
43新增: Runtime string `json:",omitempty"`
44新增: Transition StorageTransition `json:",omitempty"`
4245}
4346
4447func readStorageRecord(profile string) (storageRecord, error) {
@@ -228,6 +231,11 @@ func getStorageLocation(profile string) (StorageLocation, error) {
228231 break
229232 }
230233 }
234新增: if _, err := os.Stat(filepath.Join(profile, "windows-guest.json")); err == nil {
235新增: loc.HasEnvironment = true
236新增: } else if !errors.Is(err, os.ErrNotExist) {
237新增: return loc, err
238新增: }
231239 return loc, nil
232240}
233241
@@ -256,6 +264,10 @@ func AcquireStorageUse(profile string) (*os.File, StorageLocation, error) {
256264}
257265
258266func openStorageLock(profile string, exclusive bool) (*os.File, error) {
267新增: return openStorageLockWithRuntime(context.Background(), profile, exclusive, nil)
268新增:}
269新增:
270新增:func openStorageLockWithRuntime(ctx context.Context, profile string, exclusive bool, runtime StorageRuntime) (*os.File, error) {
259271 f, err := os.OpenFile(filepath.Join(profile, "environment-storage.lock"), os.O_CREATE|os.O_RDWR, 0600)
260272 if err != nil {
261273 return nil, err
@@ -279,14 +291,14 @@ func openStorageLock(profile string, exclusive bool) (*os.File, error) {
279291 f.Close()
280292 // Acquire exclusively before attempting recovery, then reacquire a
281293 // shared lease. Recheck the journal once more under the new lease.
282删除: w, err := openStorageLock(profile, true)
294新增: w, err := openStorageLockWithRuntime(ctx, profile, true, runtime)
283295 if err != nil {
284296 return nil, err
285297 }
286298 w.Close()
287删除: return openStorageLock(profile, false)
299新增: return openStorageLockWithRuntime(ctx, profile, false, runtime)
288300 }
289删除: if err = recoverStorage(profile); err != nil {
301新增: if err = recoverStorageWithRuntime(ctx, profile, runtime); err != nil {
290302 f.Close()
291303 return nil, err
292304 }
@@ -417,11 +429,20 @@ func stoppedStorage(source string) error {
417429}
418430
419431func MoveStorage(ctx context.Context, profile, directory string, expected StorageLocation, report func(copied, total int64)) (loc StorageLocation, err error) {
420删除: lock, err := openStorageLock(profile, true)
432新增: return MoveStorageWithRuntime(ctx, profile, directory, expected, nil, report)
433新增:}
434新增:
435新增:func MoveStorageWithRuntime(ctx context.Context, profile, directory string, expected StorageLocation, runtime StorageRuntime, report func(copied, total int64)) (loc StorageLocation, err error) {
436新增: lock, err := openStorageLockWithRuntime(ctx, profile, true, runtime)
421437 if err != nil {
422438 return loc, err
423439 }
424440 defer lock.Close()
441新增: if _, bindingErr := os.Stat(filepath.Join(profile, "windows-guest.json")); bindingErr == nil && runtime == nil {
442新增: return loc, errors.New("Windows 客机迁移需要同步更新系统管理助手的磁盘绑定")
443新增: } else if bindingErr != nil && !errors.Is(bindingErr, os.ErrNotExist) {
444新增: return loc, bindingErr
445新增: }
425446 loc, err = getStorageLocation(profile)
426447 if err != nil {
427448 return loc, err
@@ -465,6 +486,35 @@ func MoveStorage(ctx context.Context, profile, directory string, expected Storag
465486 next.Backups = append(next.Backups, backup)
466487 }
467488 move := storageMove{Next: next, PreviousCustom: loc.Custom}
489新增: var excluded []string
490新增: if runtime != nil {
491新增: snapshot, snapshotErr := runtime.Snapshot(ctx, src)
492新增: if snapshotErr != nil {
493新增: return loc, snapshotErr
494新增: }
495新增: backup := anchorBackup
496新增: if loc.Custom {
497新增: backup = src
498新增: }
499新增: move.Runtime = runtime.Name()
500新增: move.Transition = StorageTransition{ID: id, Source: src, Destination: filepath.Join(directory, "state"), Backup: backup, State: snapshot.State}
501新增: if move.Runtime == "" || !json.Valid(snapshot.State) {
502新增: return loc, errors.New("客机存储事务缺少有效的恢复信息")
503新增: }
504新增: for _, retained := range snapshot.Backups {
505新增: if !filepath.IsAbs(retained) || StoragePathsOverlap(retained, directory) {
506新增: return loc, errors.New("客机备份路径与迁移目标冲突")
507新增: }
508新增: move.Next.Backups = append(move.Next.Backups, retained)
509新增: }
510新增: next = move.Next
511新增: for _, path := range snapshot.Excluded {
512新增: if !filepath.IsAbs(path) || sameStoragePath(path, src) || !StorageContains(src, path) {
513新增: return loc, errors.New("客机管理文件超出当前存储目录")
514新增: }
515新增: }
516新增: excluded = snapshot.Excluded
517新增: }
468518 if err = host.EnsurePrivateDir(directory); err != nil {
469519 if errors.Is(err, os.ErrPermission) {
470520 return loc, fmt.Errorf("无法将目标目录设为仅当前用户可访问。请选择自己新建且可以修改权限的空文件夹:%w", err)
@@ -480,7 +530,10 @@ func MoveStorage(ctx context.Context, profile, directory string, expected Storag
480530 // Recovery only removes files under the newly claimed target with a
481531 // matching random identity. It never recursively removes an old copy.
482532 defer func() {
483删除: if recErr := recoverStorage(profile); recErr != nil {
533新增: // A cancelled copy still needs bounded time to restore its VM binding.
534新增: recovery, cancel := context.WithTimeout(context.WithoutCancel(ctx), 3*time.Minute)
535新增: defer cancel()
536新增: if recErr := recoverStorageWithRuntime(recovery, profile, runtime); recErr != nil {
484537 err = errors.Join(err, fmt.Errorf("恢复迁移:%w", recErr))
485538 }
486539 }()
@@ -497,8 +550,13 @@ func MoveStorage(ctx context.Context, profile, directory string, expected Storag
497550 _ = os.Remove(destState)
498551 return loc, err
499552 }
553新增: if runtime != nil {
554新增: if err = runtime.Begin(ctx, move.Transition); err != nil {
555新增: return loc, err
556新增: }
557新增: }
500558 if info != nil {
501删除: if err = copyStorage(ctx, src, destState, report); err != nil {
559新增: if err = copyStorageExcluding(ctx, src, destState, excluded, report); err != nil {
502560 return loc, err
503561 }
504562 }
@@ -512,6 +570,14 @@ func MoveStorage(ctx context.Context, profile, directory string, expected Storag
512570 if err = ctx.Err(); err != nil {
513571 return loc, err
514572 }
573新增: if runtime != nil {
574新增: if err = runtime.Switch(ctx, move.Transition); err != nil {
575新增: return loc, err
576新增: }
577新增: }
578新增: if err = ctx.Err(); err != nil {
579新增: return loc, err
580新增: }
515581 if info != nil {
516582 if err = renameStorage(anchor, anchorBackup); err != nil {
517583 return loc, err
@@ -539,6 +605,10 @@ func claimStorageTarget(dir, id string) error {
539605}
540606
541607func recoverStorage(profile string) error {
608新增: return recoverStorageWithRuntime(context.Background(), profile, nil)
609新增:}
610新增:
611新增:func recoverStorageWithRuntime(ctx context.Context, profile string, runtime StorageRuntime) error {
542612 journal := filepath.Join(profile, pendingFile)
543613 b, err := os.ReadFile(journal)
544614 if err != nil {
@@ -552,6 +622,12 @@ func recoverStorage(profile string) error {
552622 if !validStorageID(next.ID) || !filepath.IsAbs(next.Directory) {
553623 return errors.New("存储迁移记录损坏")
554624 }
625新增: if p.Runtime != "" && (runtime == nil || runtime.Name() != p.Runtime) {
626新增: return ErrStorageRuntimeRecovery
627新增: }
628新增: if p.Runtime != "" && (p.Transition.ID != next.ID || !sameStoragePath(p.Transition.Destination, filepath.Join(next.Directory, "state")) || !filepath.IsAbs(p.Transition.Source) || !filepath.IsAbs(p.Transition.Backup) || !json.Valid(p.Transition.State)) {
629新增: return errors.New("客机存储恢复记录损坏")
630新增: }
555631 r, err := readStorageRecord(profile)
556632 if err != nil {
557633 return err
@@ -561,6 +637,11 @@ func recoverStorage(profile string) error {
561637 anchor := storageAnchor(profile)
562638 dest := filepath.Join(next.Directory, "state")
563639 if r.ID == next.ID {
640新增: if p.Runtime != "" {
641新增: if err = runtime.Recover(ctx, p.Transition, true); err != nil {
642新增: return err
643新增: }
644新增: }
564645 if token, e := os.ReadFile(filepath.Join(dest, storageMarker)); e == nil && string(token) == next.ID {
565646 if err = os.Remove(filepath.Join(dest, storageMarker)); err != nil {
566647 return err
@@ -587,6 +668,11 @@ func recoverStorage(profile string) error {
587668 } else if !errors.Is(e, os.ErrNotExist) {
588669 return e
589670 }
671新增: if p.Runtime != "" {
672新增: if err = runtime.Recover(ctx, p.Transition, false); err != nil {
673新增: return err
674新增: }
675新增: }
590676 // Disconnected destination disks never prevent resuming the old copy.
591677 marker := filepath.Join(next.Directory, storageMarker)
592678 if token, e := os.ReadFile(marker); e == nil && string(token) == next.ID {
修改internal/cage/storage_copy.go+24 −0看文件
@@ -16,9 +16,27 @@ import (
1616// Copy cold VM disks without expanding their zero-filled regions. Hash the
1717// written copy independently before switching any path used by the runtime.
1818func copyStorage(ctx context.Context, source, target string, report func(int64, int64)) error {
19新增: return copyStorageExcluding(ctx, source, target, nil, report)
20新增:}
21新增:
22新增:func copyStorageExcluding(ctx context.Context, source, target string, excluded []string, report func(int64, int64)) error {
1923 var total, copied int64
2024 var last time.Time
25新增: skip := func(path string) bool {
26新增: for _, managed := range excluded {
27新增: if StorageContains(managed, path) {
28新增: return true
29新增: }
30新增: }
31新增: return false
32新增: }
2133 err := filepath.WalkDir(source, func(path string, d fs.DirEntry, err error) error {
34新增: if skip(path) {
35新增: if d != nil && d.IsDir() {
36新增: return filepath.SkipDir
37新增: }
38新增: return nil
39新增: }
2240 if err != nil {
2341 return err
2442 }
@@ -50,6 +68,12 @@ func copyStorage(ctx context.Context, source, target string, report func(int64,
5068 }
5169 }
5270 err = filepath.WalkDir(source, func(path string, d fs.DirEntry, err error) error {
71新增: if skip(path) {
72新增: if d != nil && d.IsDir() {
73新增: return filepath.SkipDir
74新增: }
75新增: return nil
76新增: }
5377 if err != nil {
5478 return err
5579 }
新增internal/cage/storage_runtime.go+75 −0看文件
@@ -0,0 +1,75 @@
1新增:package cage
2新增:
3新增:import (
4新增: "context"
5新增: "encoding/json"
6新增: "errors"
7新增: "os"
8新增: "path/filepath"
9新增:)
10新增:
11新增:// StorageTransition identifies one cold move. Runtime state is captured before
12新增:// the journal is published and survives process termination with that journal.
13新增:type StorageTransition struct {
14新增: ID string `json:"id"`
15新增: Source string `json:"source"`
16新增: Destination string `json:"destination"`
17新增: Backup string `json:"backup"`
18新增: State json.RawMessage `json:"state,omitempty"`
19新增:}
20新增:
21新增:type StorageRuntimeSnapshot struct {
22新增: State json.RawMessage
23新增: Backups []string
24新增: Excluded []string
25新增:}
26新增:
27新增:// StorageRuntime coordinates an independently registered VM with the shared
28新增:// filesystem transaction. Begin prevents VM starts until Recover completes.
29新增:// Switch runs after the verified copy and before the stable directory changes.
30新增:// Recovery restores the directory first, then resolves the runtime, and only
31新增:// then removes a failed copy. The original data is retained after commit.
32新增:type StorageRuntime interface {
33新增: Name() string
34新增: Snapshot(context.Context, string) (StorageRuntimeSnapshot, error)
35新增: Begin(context.Context, StorageTransition) error
36新增: Switch(context.Context, StorageTransition) error
37新增: Recover(context.Context, StorageTransition, bool) error
38新增:}
39新增:
40新增:var ErrStorageRuntimeRecovery = errors.New("环境迁移需要客机管理助手完成恢复,请重新打开原工作台")
41新增:
42新增:// RecoverStorage resolves the durable journal using its owning runtime. Plain
43新增:// filesystem callers leave a native VM transaction intact until this succeeds.
44新增:func RecoverStorage(ctx context.Context, profile string, runtime StorageRuntime) error {
45新增: if _, err := os.Stat(filepath.Join(profile, pendingFile)); errors.Is(err, os.ErrNotExist) {
46新增: return nil
47新增: } else if err != nil {
48新增: return err
49新增: }
50新增: lock, err := openStorageLockWithRuntime(ctx, profile, true, runtime)
51新增: if err != nil {
52新增: return err
53新增: }
54新增: return lock.Close()
55新增:}
56新增:
57新增:// CopyStorage copies an additional runtime-owned directory into a fresh private
58新增:// directory. It uses the same sparse-file and digest verification as the move.
59新增:func CopyStorage(ctx context.Context, source, target string, report func(int64, int64)) error {
60新增: if err := os.Mkdir(target, 0700); err != nil {
61新增: return err
62新增: }
63新增: return copyStorage(ctx, source, target, report)
64新增:}
65新增:
66新增:func CopyStorageFile(ctx context.Context, source, target string) error {
67新增: info, err := os.Lstat(source)
68新增: if err != nil {
69新增: return err
70新增: }
71新增: if !info.Mode().IsRegular() {
72新增: return errors.New("环境磁盘需要真实本地文件")
73新增: }
74新增: return copyStorageFile(ctx, source, target, info, make([]byte, 1<<20), make([]byte, 1<<20), func(int) {})
75新增:}
新增internal/cage/storage_runtime_test.go+182 −0看文件
@@ -0,0 +1,182 @@
1新增:package cage
2新增:
3新增:import (
4新增: "context"
5新增: "errors"
6新增: "os"
7新增: "path/filepath"
8新增: "reflect"
9新增: "testing"
10新增:)
11新增:
12新增:type storageRuntimeFixture struct {
13新增: events []string
14新增: begin func(StorageTransition) error
15新增: switchVM func(StorageTransition) error
16新增: finish func(StorageTransition, bool) error
17新增:}
18新增:
19新增:func (*storageRuntimeFixture) Name() string { return "test-native-vm" }
20新增:func (*storageRuntimeFixture) Snapshot(context.Context, string) (StorageRuntimeSnapshot, error) {
21新增: return StorageRuntimeSnapshot{State: []byte(`{"vm":"original"}`)}, nil
22新增:}
23新增:func (runtime *storageRuntimeFixture) Begin(_ context.Context, move StorageTransition) error {
24新增: runtime.events = append(runtime.events, "begin")
25新增: if runtime.begin != nil {
26新增: return runtime.begin(move)
27新增: }
28新增: return nil
29新增:}
30新增:func (runtime *storageRuntimeFixture) Switch(_ context.Context, move StorageTransition) error {
31新增: runtime.events = append(runtime.events, "switch")
32新增: if runtime.switchVM != nil {
33新增: return runtime.switchVM(move)
34新增: }
35新增: return nil
36新增:}
37新增:func (runtime *storageRuntimeFixture) Recover(_ context.Context, move StorageTransition, committed bool) error {
38新增: action := "rollback"
39新增: if committed {
40新增: action = "commit"
41新增: }
42新增: runtime.events = append(runtime.events, action)
43新增: if runtime.finish != nil {
44新增: return runtime.finish(move, committed)
45新增: }
46新增: return nil
47新增:}
48新增:
49新增:func TestStorageRuntimeUsesVerifiedCopyAndRetainsOriginal(t *testing.T) {
50新增: profile, root := newStorageFixture(t)
51新增: payload := []byte("original VM disk and account state")
52新增: file := filepath.Join("native-vm", "system.vhdx")
53新增: writeStorageFixture(t, filepath.Join(profile, "state", file), payload)
54新增: runtime := &storageRuntimeFixture{}
55新增: runtime.switchVM = func(move StorageTransition) error {
56新增: assertStorageFile(t, filepath.Join(move.Source, file), payload)
57新增: assertStorageFile(t, filepath.Join(move.Destination, file), payload)
58新增: if _, err := os.Readlink(storageAnchor(profile)); err == nil {
59新增: t.Fatal("stable path changed before the runtime accepted its new data")
60新增: }
61新增: return nil
62新增: }
63新增: runtime.finish = func(move StorageTransition, committed bool) error {
64新增: if !committed {
65新增: t.Fatal("successful move rolled back")
66新增: }
67新增: assertStorageFile(t, filepath.Join(move.Backup, file), payload)
68新增: actual, err := filepath.EvalSymlinks(storageAnchor(profile))
69新增: if err != nil || actual != move.Destination {
70新增: t.Fatalf("runtime committed before directory: %s %v", actual, err)
71新增: }
72新增: return nil
73新增: }
74新增: location, err := MoveStorageWithRuntime(context.Background(), profile, filepath.Join(root, "moved"), storageExpectation(t, profile), runtime, nil)
75新增: if err != nil {
76新增: t.Fatal(err)
77新增: }
78新增: if !reflect.DeepEqual(runtime.events, []string{"begin", "switch", "commit"}) {
79新增: t.Fatal(runtime.events)
80新增: }
81新增: assertStorageFile(t, filepath.Join(location.Backup, file), payload)
82新增:}
83新增:
84新增:func TestStorageRuntimeFailureRetainsBothCopiesUntilRecovery(t *testing.T) {
85新增: profile, root := newStorageFixture(t)
86新增: payload := []byte("original")
87新增: file := filepath.Join("native-vm", "system.vhdx")
88新增: writeStorageFixture(t, filepath.Join(profile, "state", file), payload)
89新增: runtime := &storageRuntimeFixture{switchVM: func(StorageTransition) error { return errors.New("runtime attach failed") }}
90新增: var transition StorageTransition
91新增: runtime.finish = func(move StorageTransition, committed bool) error {
92新增: transition = move
93新增: if committed {
94新增: t.Fatal("failed runtime attached as committed")
95新增: }
96新增: assertStorageFile(t, filepath.Join(storageAnchor(profile), file), payload)
97新增: assertStorageFile(t, filepath.Join(move.Destination, file), payload)
98新增: return errors.New("helper disconnected")
99新增: }
100新增: if _, err := MoveStorageWithRuntime(context.Background(), profile, filepath.Join(root, "moved"), storageExpectation(t, profile), runtime, nil); err == nil {
101新增: t.Fatal("failed migration succeeded")
102新增: }
103新增: if _, err := GetStorageLocation(profile); !errors.Is(err, ErrStorageRuntimeRecovery) {
104新增: t.Fatalf("plain caller resolved native transaction: %v", err)
105新增: }
106新增: if _, _, err := AcquireStorageUse(profile); !errors.Is(err, ErrStorageRuntimeRecovery) {
107新增: t.Fatalf("CLI started unresolved VM: %v", err)
108新增: }
109新增: assertStorageFile(t, filepath.Join(transition.Destination, file), payload)
110新增: runtime.finish = func(move StorageTransition, committed bool) error {
111新增: assertStorageFile(t, filepath.Join(storageAnchor(profile), file), payload)
112新增: assertStorageFile(t, filepath.Join(move.Destination, file), payload)
113新增: return nil
114新增: }
115新增: if err := RecoverStorage(context.Background(), profile, runtime); err != nil {
116新增: t.Fatal(err)
117新增: }
118新增: if _, err := os.Stat(transition.Destination); !errors.Is(err, os.ErrNotExist) {
119新增: t.Fatal("recovered failed copy retained", err)
120新增: }
121新增: assertStorageFile(t, filepath.Join(storageAnchor(profile), file), payload)
122新增:}
123新增:
124新增:func TestStorageRuntimeCrashRecoveryUsesDurableCommit(t *testing.T) {
125新增: for _, committed := range []bool{false, true} {
126新增: name := "before_commit"
127新增: if committed {
128新增: name = "after_commit"
129新增: }
130新增: t.Run(name, func(t *testing.T) {
131新增: profile, root := newStorageFixture(t)
132新增: id := "0123456789abcdef0123456789abcdef"
133新增: target := filepath.Join(root, "new")
134新增: payload := []byte("disk data")
135新增: writeStorageFixture(t, filepath.Join(storageAnchor(profile), "system.vhdx"), payload)
136新增: writeStorageFixture(t, filepath.Join(target, "state", "system.vhdx"), payload)
137新增: if err := claimStorageTarget(target, id); err != nil {
138新增: t.Fatal(err)
139新增: }
140新增: if err := claimStorageTarget(filepath.Join(target, "state"), id); err != nil {
141新增: t.Fatal(err)
142新增: }
143新增: backup := filepath.Join(profile, "state-backup-"+id)
144新增: move := storageMove{Next: storageRecord{Directory: target, ID: id, Backups: []string{backup}}, Runtime: "test-native-vm", Transition: StorageTransition{ID: id, Source: storageAnchor(profile), Destination: filepath.Join(target, "state"), Backup: backup, State: []byte(`{"vm":"original"}`)}}
145新增: if err := writeStorageJSON(filepath.Join(profile, pendingFile), move); err != nil {
146新增: t.Fatal(err)
147新增: }
148新增: if err := renameStorage(storageAnchor(profile), backup); err != nil {
149新增: t.Fatal(err)
150新增: }
151新增: if err := linkStorage(storageAnchor(profile), move.Transition.Destination); err != nil {
152新增: t.Fatal(err)
153新增: }
154新增: if committed {
155新增: if err := writeStorageJSON(filepath.Join(profile, locationFile), move.Next); err != nil {
156新增: t.Fatal(err)
157新增: }
158新增: }
159新增: runtime := &storageRuntimeFixture{finish: func(transition StorageTransition, actual bool) error {
160新增: if actual != committed {
161新增: t.Fatal("runtime used a different commit decision")
162新增: }
163新增: assertStorageFile(t, filepath.Join(storageAnchor(profile), "system.vhdx"), payload)
164新增: assertStorageFile(t, filepath.Join(transition.Destination, "system.vhdx"), payload)
165新增: _, linkErr := os.Readlink(storageAnchor(profile))
166新增: if committed != (linkErr == nil) {
167新增: t.Fatal("directory rollback happened after runtime recovery")
168新增: }
169新增: return nil
170新增: }}
171新增: if err := RecoverStorage(context.Background(), profile, runtime); err != nil {
172新增: t.Fatal(err)
173新增: }
174新增: if err := RecoverStorage(context.Background(), profile, runtime); err != nil {
175新增: t.Fatal("idempotent recovery failed", err)
176新增: }
177新增: if len(runtime.events) != 1 {
178新增: t.Fatal("completed recovery repeated a VM operation", runtime.events)
179新增: }
180新增: })
181新增: }
182新增:}
新增internal/cage/tailnet-client.mjs+49 −0看文件
@@ -0,0 +1,49 @@
1新增:// Private stdio control of the Cage-owned guest node. No browser page can
2新增:// select an executable, destination command, data directory or auth key.
3新增:import { spawn } from "node:child_process";
4新增:import { access } from "node:fs/promises";
5新增:import { fileURLToPath } from "node:url";
6新增:import { createInterface } from "node:readline";
7新增:
8新增:export function createTailnetClient({ executable, launch, start = spawn } = {}) {
9新增: executable ||= process.platform === "linux" ? "/usr/local/bin/cage-tailnet"
10新增: : fileURLToPath(new URL(process.platform === "win32" ? "./cage-tailnet.exe" : "./cage-tailnet", import.meta.url));
11新增: let child, lines, pending, queue = Promise.resolve();
12新增: async function open() {
13新增: if (child) return true;
14新增: try { await access(executable); } catch { return false; }
15新增: const command = launch || (process.platform === "linux" ? { file: "/usr/bin/sudo", args: ["-n", "-H", "-u", "cage", executable] } : { file: executable, args: [] });
16新增: const current = start(command.file, command.args, { stdio: ["pipe", "pipe", "ignore"], windowsHide: true });
17新增: child = current;
18新增: const reset = () => {
19新增: if (child !== current) return;
20新增: pending?.reject(new Error("Tailscale 组件连接中断,请重新打开面板")); pending = undefined;
21新增: lines?.close(); child = undefined;
22新增: };
23新增: lines = createInterface({ input: current.stdout });
24新增: lines.on("line", line => {
25新增: const active = pending; pending = undefined;
26新增: if (!active) return;
27新增: try { const value = JSON.parse(line); if (value.error) { value.tailnet_error = value.error; delete value.error; } active.resolve(value); }
28新增: catch (error) { active.reject(error); }
29新增: });
30新增: current.once("error", reset); current.once("exit", reset);
31新增: current.stdin.on("error", reset);
32新增: return true;
33新增: }
34新增: async function run(input) {
35新增: if (!input || !["status", "connect", "login", "disconnect", "logout", "add-key", "remove-key"].includes(input.action) || typeof input.key !== "undefined" && (typeof input.key !== "string" || input.key.length > 8192)) throw new Error("Tailscale 操作无效");
36新增: if (!await open()) return { installed: false, enabled: false, backend: "NotInstalled", ips: [], peers: [], keys: [] };
37新增: return new Promise((resolve, reject) => {
38新增: const current = child;
39新增: const timer = setTimeout(() => { current.kill(); reject(new Error("Tailscale 暂未响应,请稍后重试")); }, 12000);
40新增: pending = { resolve: value => { clearTimeout(timer); resolve(value); }, reject: error => { clearTimeout(timer); reject(error); } };
41新增: current.stdin.write(JSON.stringify({ action: input.action, ...(input.key === undefined ? {} : { key: input.key }) }) + "\n");
42新增: });
43新增: }
44新增: return {
45新增: request(input) { const result = queue.then(() => run(input)); queue = result.catch(() => {}); return result; },
46新增: close() { child?.stdin.end(); },
47新增: restore() { return this.request({ action: "status" }); },
48新增: };
49新增:}
新增internal/cage/tailnet-client.test.mjs+22 −0看文件
@@ -0,0 +1,22 @@
1新增:import test from "node:test";
2新增:import assert from "node:assert/strict";
3新增:import { spawn } from "node:child_process";
4新增:import { createTailnetClient } from "./tailnet-client.mjs";
5新增:
6新增:test("stdio requests are serialized, preserve component errors and reject wire commands", async () => {
7新增: const seen = [];
8新增: const fixture = `let text=''; process.stdin.on('data',chunk=>{text+=chunk;let end;while((end=text.indexOf('\\n'))>=0){const input=JSON.parse(text.slice(0,end));text=text.slice(end+1);setTimeout(()=>console.log(JSON.stringify(input.action==='add-key'?{error:'请粘贴有效 SSH 公钥'}:{installed:true,action:input.action})),10)}});`;
9新增: const client = createTailnetClient({ executable: process.execPath, start: (file,args,options) => { seen.push({file,args}); return spawn(process.execPath, ["-e", fixture], options); } });
10新增: try {
11新增: const values = await Promise.all([client.request({action:"status"}), client.request({action:"connect"}), client.request({action:"add-key",key:"invalid"})]);
12新增: assert.deepEqual(values.map(v=>v.action||v.tailnet_error), ["status","connect","请粘贴有效 SSH 公钥"]);
13新增: assert.equal(seen.length,1);
14新增: await assert.rejects(client.request({action:"shell",command:"whoami"}));
15新增: await assert.rejects(client.request({action:"add-key",key:"x".repeat(8193)}));
16新增: assert.equal((await client.request({action:"status"})).installed,true);
17新增: } finally {client.close();}
18新增:});
19新增:test("missing guest payload offers installation without spawning a host VPN", async()=>{
20新增: const client=createTailnetClient({executable:"/nonexistent-cage-tailnet",start:()=>{throw Error("must not spawn")}});
21新增: assert.equal((await client.request({action:"status"})).installed,false);
22新增:});
修改internal/cage/tool-versions.env+7 −0看文件
@@ -8,3 +8,10 @@ CAGE_MISE_AMD64_SHA256=199966edaad1b208eb4c72955f1722dafb8fa799f575db720dea05aaa
88CAGE_MISE_NPM_ARM64_SHA256=e60a51a1fd16a6fe2c6f821075000b9528f7281f42c33a9b9f812429d83a1824
99CAGE_MISE_NPM_AMD64_SHA256=70150a3b5f53f524273c34a8eeff9ec9b2f343a4f066889470b5d368f9f7c3a8
1010CAGE_CLAUDE_VERSION=2.1.314
11新增:
12新增:# Ubuntu portable browser and noVNC: official upstream archives, SHA-256 verified.
13新增:CAGE_UBUNTU_BROWSER_VERSION=157.0.8103.38
14新增:CAGE_UBUNTU_BROWSER_ARM64_SHA256=5517510e61657ff43ee9ab804ecd1a499b3d5bd3caf72f097516bd6565ba5a17
15新增:CAGE_UBUNTU_BROWSER_SHA256=8cdeb344e9b2cefe59f4aea8d1d93d5d93054c03cde217665c16fc1f62e72a66
16新增:CAGE_UBUNTU_NOVNC_VERSION=1.6.0
17新增:CAGE_UBUNTU_NOVNC_SHA256=5066103959ef4e9b10f37e5a148627360dd8414e4cf8a7db92bdbd022e728aaa
新增internal/cage/ubuntu-browser.sh+75 −0看文件
@@ -0,0 +1,75 @@
1新增:# shellcheck shell=bash
2新增:# Ubuntu's Chromium package is a Snap transition. Use the upstream portable
3新增:# build with extension loading and inherited CDP pipes, without snapd.
4新增:cage_is_ubuntu() (
5新增: . /etc/os-release
6新增: [ "$ID" = ubuntu ]
7新增:)
8新增:
9新增:cage_install_ubuntu_browser() (
10新增: set -euo pipefail
11新增: local version="$CAGE_UBUNTU_BROWSER_VERSION" checksum="$CAGE_UBUNTU_BROWSER_SHA256" platform=linux64
12新增: case "$(dpkg --print-architecture)" in
13新增: amd64) ;;
14新增: arm64) platform=linux-arm64; checksum="$CAGE_UBUNTU_BROWSER_ARM64_SHA256" ;;
15新增: *) echo 'Ubuntu guest browsers require amd64 or arm64.' >&2; exit 1 ;;
16新增: esac
17新增: local directory=chrome-$platform
18新增: local cache="$HOME/.cache/cage/downloads/$checksum" target="/opt/cage-browser/$version" stage
19新增: mkdir -p "$cache"
20新增: exec 8>"$cache/lock"
21新增: flock -w 60 8
22新增: # Package names differ after Ubuntu's time_t transition.
23新增: local asound=libasound2 atk=libatk1.0-0 bridge=libatk-bridge2.0-0 cups=libcups2
24新增: if . /etc/os-release; [ "$VERSION_ID" = 24.04 ]; then
25新增: asound=libasound2t64 atk=libatk1.0-0t64 bridge=libatk-bridge2.0-0t64 cups=libcups2t64
26新增: fi
27新增: sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get install -y --no-install-recommends \
28新增: "$asound" "$atk" "$bridge" "$cups" libnss3 libnspr4 libdrm2 libgbm1 libgtk-3-0 \
29新增: libx11-6 libxcb1 libxcomposite1 libxdamage1 libxext6 libxfixes3 libxrandr2 libxkbcommon0 \
30新增: fonts-liberation fonts-dejavu-core xvfb xauth unzip </dev/null
31新增: if [ ! -x "$target/chrome" ]; then
32新增: cage_download_tool "https://storage.googleapis.com/chrome-for-testing-public/$version/$platform/chrome-$platform.zip" "$checksum" "$cache/chrome.zip"
33新增: sudo install -d -m 0755 /opt/cage-browser
34新增: stage=$(sudo mktemp -d /opt/cage-browser/.install-XXXXXX)
35新增: trap 'sudo rm -rf "$stage"' EXIT
36新增: sudo unzip -q "$cache/chrome.zip" -d "$stage"
37新增: sudo chown -R root:root "$stage/$directory"
38新增: sudo chmod 4755 "$stage/$directory/chrome_sandbox"
39新增: sudo mv "$stage/$directory" "$target"
40新增: fi
41新增: sudo ln -sfn "$target/chrome" /usr/bin/chromium
42新增:)
43新增:
44新增:cage_install_chromium() {
45新增: if cage_is_ubuntu; then
46新增: cage_install_ubuntu_browser
47新增: else
48新增: cage_cache_chromium --no-install-recommends chromium chromium-l10n
49新增: sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get install -y --no-install-recommends chromium chromium-l10n </dev/null
50新增: fi
51新增:}
52新增:
53新增:# Jammy ships noVNC 1.0. The shared input/clipboard patch needs 1.6.
54新增:# Keep the system package untouched; websockify serves the Cage-owned copy.
55新增:cage_install_ubuntu_novnc() (
56新增: set -euo pipefail
57新增: local cache="$HOME/.cache/cage/downloads/$CAGE_UBUNTU_NOVNC_SHA256" stage
58新增: if [ -f /usr/local/share/cage-novnc/VERSION ] && [ "$(cat /usr/local/share/cage-novnc/VERSION)" = "$CAGE_UBUNTU_NOVNC_VERSION" ]; then
59新增: sudo chmod 0755 /usr/local/share/cage-novnc
60新增: return
61新增: fi
62新增: mkdir -p "$cache"
63新增: exec 8>"$cache/lock"
64新增: flock -w 60 8
65新增: cage_download_tool "https://github.com/novnc/noVNC/archive/refs/tags/v$CAGE_UBUNTU_NOVNC_VERSION.tar.gz" "$CAGE_UBUNTU_NOVNC_SHA256" "$cache/novnc.tar.gz"
66新增: sudo install -d -m 0755 /usr/local/share
67新增: stage=$(sudo mktemp -d /usr/local/share/.cage-novnc-XXXXXX)
68新增: trap 'sudo rm -rf "$stage"' EXIT
69新增: sudo tar -xzf "$cache/novnc.tar.gz" --strip-components=1 -C "$stage"
70新增: sudo chmod 0755 "$stage"
71新增: printf '%s\n' "$CAGE_UBUNTU_NOVNC_VERSION" | sudo tee "$stage/VERSION" >/dev/null
72新增: # Called only after cage-webvnc has stopped.
73新增: sudo rm -rf /usr/local/share/cage-novnc
74新增: sudo mv "$stage" /usr/local/share/cage-novnc
75新增:)
修改internal/cli/setup.go+16 −4看文件
@@ -15,6 +15,7 @@ import (
1515 "github.com/sylvinus/agent-vm/internal/diagnostics"
1616 "github.com/sylvinus/agent-vm/internal/env"
1717 "github.com/sylvinus/agent-vm/internal/host"
18新增: "github.com/sylvinus/agent-vm/internal/hostimage"
1819 "github.com/sylvinus/agent-vm/internal/state"
1920 "github.com/sylvinus/agent-vm/internal/ui"
2021 "github.com/sylvinus/agent-vm/internal/version"
@@ -452,6 +453,7 @@ func (e *app) buildBase(ctx context.Context, in install, disk, memory, cpus int)
452453 win.Close()
453454 if err != nil {
454455 fmt.Fprintf(log, "%v\n", err)
456新增: fmt.Fprintf(e.io.Stderr, "Error: %s\n", diagnostics.Redact(err.Error()))
455457 if f, ok := e.io.Stdout.(*os.File); ok && ui.IsTerminal(f) && os.Getenv(cage.ConfigEnv) == "" {
456458 fmt.Fprint(e.io.Stderr, ui.Tail(logPath, 20))
457459 }
@@ -464,14 +466,18 @@ func (e *app) buildBase(ctx context.Context, in install, disk, memory, cpus int)
464466 fmt.Fprintln(e.io.Stdout, "Creating base VM...")
465467 none := []vm.Mount{}
466468 if !resume && !windowed(func(w io.Writer) error {
467删除: return b.Create(ctx, building, "template:debian-13", vm.Settings{CPUs: cpus, MemoryGiB: memory, DiskGiB: disk, Mounts: &none, NoContainerd: true}, w)
469新增: template, err := hostimage.LinuxTemplate(string(e.state))
470新增: if err != nil {
471新增: return err
472新增: }
473新增: return b.Create(ctx, building, template, vm.Settings{CPUs: cpus, MemoryGiB: memory, DiskGiB: disk, Mounts: &none, NoContainerd: true}, w)
468474 }) {
469475 fmt.Fprintf(e.io.Stderr, "Error: Failed to create base VM. Full log: %s\n", logPath)
470476 return 1
471477 }
472478 (&start{app: e, ctx: ctx, name: building}).printResources()
473479
474删除: fmt.Fprintln(e.io.Stdout, "Starting base VM (the first run downloads a Debian image)...")
480新增: fmt.Fprintln(e.io.Stdout, "Starting the selected base system...")
475481 if !windowed(func(w io.Writer) error { return e.startVM(ctx, b, building, w) }) {
476482 ha := filepath.Join(LimaHome(e.state), building, "ha.stderr.log")
477483 fmt.Fprintf(e.io.Stderr, "Error: Failed to start base VM. Full log: %s\nLima's own log: %s\n", logPath, ha)
@@ -497,7 +503,13 @@ func (e *app) buildBase(ctx context.Context, in install, disk, memory, cpus int)
497503
498504 if user, ok := readRegular(e.state.Path("setup.sh")); ok {
499505 fmt.Fprintf(e.io.Stdout, "Running custom setup from %s...\n", e.state.Path("setup.sh"))
500删除: code, err := b.Shell(ctx, building, vm.ShellOpts{Args: []string{"zsh", "-l"},
506新增: shell := "zsh"
507新增: if os.Getenv(cage.ConfigEnv) != "" {
508新增: // Cage owns this script and its Bash functions. A guest's default
509新增: // login shell must not change their syntax or reserved variables.
510新增: shell = "bash"
511新增: }
512新增: code, err := b.Shell(ctx, building, vm.ShellOpts{Args: []string{shell, "-l"},
501513 Stdin: strings.NewReader(env.StripCR(user)), Stdout: e.io.Stdout, Stderr: e.io.Stderr})
502514 if err != nil || code != 0 {
503515 fmt.Fprintln(e.io.Stderr, "Error: Custom setup script failed.")
@@ -537,7 +549,7 @@ func cageInstallEnv() string {
537549 if os.Getenv("CAGE_SETUP_PROGRESS") == "1" {
538550 progress = "export CAGE_SETUP_PROGRESS=1\n"
539551 }
540删除: return "set -e\nexport CLAUDE_CAGE=1\n" + progress + cage.DebianMirrorsScript + "\n" + cage.ToolInstallPrelude()
552新增: return "set -e\nexport CLAUDE_CAGE=1\n" + progress + cage.DebianPrepareScript + "\n" + cage.ToolInstallPrelude()
541553 }
542554 return ""
543555}
修改internal/cli/setup_test.go+23 −0看文件
@@ -298,6 +298,29 @@ func TestSetupBase(t *testing.T) {
298298 }
299299}
300300
301新增:func TestCageCustomSetupUsesBashRegardlessOfGuestLoginShell(t *testing.T) {
302新增: te, code, _ := setupRun(t, "--preinstall=none")
303新增: if code != 0 {
304新增: t.Fatal(te.out())
305新增: }
306新增: t.Setenv("CLAUDE_CAGE_CONFIG", filepath.Join(t.TempDir(), "config.json"))
307新增: if err := os.WriteFile(te.state.Path("setup.sh"), []byte("set -euo pipefail\nlocal_marker=ready\n"), 0600); err != nil {
308新增: t.Fatal(err)
309新增: }
310新增: var commands []string
311新增: te.fake.ShellFunc = func(_ string, options vm.ShellOpts) int {
312新增: _, _ = io.Copy(io.Discard, options.Stdin)
313新增: commands = append(commands, strings.Join(options.Args, " "))
314新增: return 0
315新增: }
316新增: if result := te.setupBase([]string{"setup", "--preinstall=none"}); result != 0 {
317新增: t.Fatalf("%d: %s", result, te.out())
318新增: }
319新增: if len(commands) != 2 || commands[1] != "bash -l" {
320新增: t.Fatalf("Cage script ran in the guest login shell: %v", commands)
321新增: }
322新增:}
323新增:
301324func TestCageSetupResumesExistingBuild(t *testing.T) {
302325 t.Setenv("CLAUDE_CAGE_CONFIG", filepath.Join(t.TempDir(), "config.json"))
303326 te := newTestEnv(t, vmtest.New())
修改internal/host/prereqs.go+6 −2看文件
@@ -160,14 +160,18 @@ func WindowsPrereqs(out, w io.Writer) bool {
160160// WHPX.
161161const WHPXOn = "DISM /Online /Enable-Feature /FeatureName:HypervisorPlatform /All"
162162
163删除:// WindowsStartHint explains, after a failed start on Windows whose logs
164删除:// show QEMU could not use WHPX, how to turn it on.
163新增:// WindowsStartHint distinguishes an unavailable hypervisor from a QEMU
164新增:// initialization failure on a host where WHPX is already enabled.
165165func WindowsStartHint(w io.Writer, logs ...string) {
166166 if runtime.GOOS != "windows" {
167167 return
168168 }
169169 for _, l := range logs {
170170 if b, err := os.ReadFile(l); err == nil && strings.Contains(strings.ToLower(string(b)), "whpx") {
171新增: if windowsHypervisorReady() == nil {
172新增: fmt.Fprintln(w, "Windows Hypervisor Platform is enabled, but QEMU could not initialize WHPX. Check the original QEMU error and any custom QEMU arguments; Cage uses kernel-irqchip=off for WHPX compatibility.")
173新增: return
174新增: }
171175 fmt.Fprintf(w, `QEMU could not use the Windows hypervisor. It needs the "Windows Hypervisor
172176Platform" Windows feature, which an administrator turns on once, followed by
173177a reboot: in Windows Features, or from an administrator terminal:
修改internal/workbench/account.go+8 −0看文件
@@ -7,6 +7,14 @@ import (
77func (s *Server) accountStatus(w http.ResponseWriter, r *http.Request) {
88 v := s.account.viewFor(s.hasTrustedView(r))
99 v.BackgroundRunning = s.vmRunning()
10新增: if s.macosGuest != nil {
11新增: v.GuestSystem = "macos"
12新增: v.InitialMacSetup = s.macSetupPending()
13新增: v.MacOSGuestUser = s.macosGuest.User
14新增: }
15新增: if s.windowsGuest != nil {
16新增: v.GuestSystem = "windows-11"
17新增: }
1018 jsonReply(w, v)
1119}
1220
修改internal/workbench/account_store.go+3 −0看文件
@@ -49,6 +49,9 @@ type localAccount struct {
4949}
5050
5151type accountView struct {
52新增: MacOSGuestUser string `json:"macos_guest_user,omitempty"`
53新增: InitialMacSetup bool `json:"initial_mac_setup,omitempty"`
54新增: GuestSystem string `json:"guest_system,omitempty"`
5255 TrustedLocal bool `json:"trusted_local,omitempty"`
5356 TrustedLogin bool `json:"trusted_login,omitempty"`
5457 Exists bool `json:"exists"`
修改internal/workbench/audio.go+41 −0看文件
@@ -1,7 +1,10 @@
11package workbench
22
33import (
4新增: "bufio"
45 "context"
6新增: "encoding/json"
7新增: "errors"
58 "io"
69 "net/http"
710 "time"
@@ -17,6 +20,28 @@ var audioFormat = struct {
1720 Channels int `json:"channels"`
1821}{"s16le", 48000, 2}
1922
23新增:type bufferedAudio struct {
24新增: io.Reader
25新增: io.Closer
26新增:}
27新增:
28新增:func readAudioReady(reader *bufio.Reader) error {
29新增: line, err := reader.ReadSlice('\n')
30新增: if err != nil {
31新增: return err
32新增: }
33新增: var ready struct {
34新增: Ready bool `json:"ready"`
35新增: Format string `json:"format"`
36新增: SampleRate int `json:"sample_rate"`
37新增: Channels int `json:"channels"`
38新增: }
39新增: if json.Unmarshal(line, &ready) != nil || !ready.Ready || ready.Format != "s16le" || ready.SampleRate != 48000 || ready.Channels != 2 {
40新增: return errors.New("客机声音格式无效")
41新增: }
42新增: return nil
43新增:}
44新增:
2045// Audio is a local output stream. It does not grant guest Internet access and
2146// cannot select a microphone, arbitrary guest command, or host audio source.
2247func (s *Server) audio(w http.ResponseWriter, r *http.Request) {
@@ -28,6 +53,14 @@ func (s *Server) audio(w http.ResponseWriter, r *http.Request) {
2853 return
2954 }
3055 if !websocket.IsWebSocketUpgrade(r) {
56新增: if s.macosGuest != nil {
57新增: s.macOSAudioStatus(w, r)
58新增: return
59新增: }
60新增: if s.windowsGuest != nil {
61新增: s.windowsAudioStatus(w, r)
62新增: return
63新增: }
3164 jsonReply(w, audioFormat)
3265 return
3366 }
@@ -42,6 +75,14 @@ func (s *Server) audio(w http.ResponseWriter, r *http.Request) {
4275 defer func() { s.mu.Lock(); s.audioClients--; s.mu.Unlock() }()
4376 ctx, cancel := context.WithCancel(r.Context())
4477 defer cancel()
78新增: if s.macosGuest != nil {
79新增: s.macOSAudioCapture(w, r, ctx, cancel)
80新增: return
81新增: }
82新增: if s.windowsGuest != nil {
83新增: s.windowsAudioCapture(w, r, ctx, cancel)
84新增: return
85新增: }
4586 cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", audioCaptureCommand)
4687 pipe, err := cmd.StdoutPipe()
4788 if err != nil {
修改internal/workbench/browser_client.go+42 −6看文件
@@ -3,11 +3,16 @@ package workbench
33import (
44 "bytes"
55 "context"
6新增: "encoding/json"
67 "errors"
8新增: "fmt"
79 "io"
810 "net"
911 "net/http"
1012 "time"
13新增:
14新增: "github.com/sylvinus/agent-vm/internal/diagnostics"
15新增: "github.com/sylvinus/agent-vm/internal/usererror"
1116)
1217
1318const browserResponseLimit = 1 << 20
@@ -80,10 +85,12 @@ func (b *browserResponseBody) Close() error {
8085func (c *browserClient) request(ctx context.Context, token, method, path string, body []byte) ([]byte, error) {
8186 timeout := 5 * time.Second
8287 switch path {
83删除: case "/audit", "/paste-image":
88新增: case "/audit", "/paste-image", "/tailnet":
8489 timeout = 20 * time.Second
8590 case "/editor-restart":
8691 timeout = 30 * time.Second
92新增: case "/extensions":
93新增: timeout = 25 * time.Second
8794 }
8895 var reader io.Reader
8996 if body != nil {
@@ -91,18 +98,47 @@ func (c *browserClient) request(ctx context.Context, token, method, path string,
9198 }
9299 response, err := c.open(ctx, token, method, path, "application/json", reader, int64(len(body)), timeout)
93100 if err != nil {
94删除: return nil, errors.New("浏览器服务暂时无法连接")
101新增: diagnostics.Log("warn", "browser", fmt.Sprintf("operation=%s transport=%v", path, err))
102新增: return nil, usererror.Wrap(browserOperation(path), err, "请确认环境仍在运行,并重新连接浏览器;持续失败时在设置中导出诊断包。")
95103 }
96104 defer response.Body.Close()
97105 data, err := io.ReadAll(io.LimitReader(response.Body, browserResponseLimit+1))
98106 if err != nil {
99删除: return nil, errors.New("浏览器响应中断")
107新增: return nil, usererror.Wrap(browserOperation(path), err, "浏览器结果没有完整返回,请重新连接后核对本次操作是否已生效。")
100108 }
101109 if len(data) > browserResponseLimit {
102删除: return nil, errors.New("浏览器响应超出大小限制")
110新增: return nil, errors.New(browserOperation(path) + "失败:浏览器返回的数据超过 1 MiB,已停止读取。请关闭不再使用的标签页或扩展后再试;持续出现时导出诊断包。")
103111 }
104112 if response.StatusCode != http.StatusOK {
105删除: return nil, errors.New("浏览器操作失败,请刷新标签后重试")
113新增: diagnostics.Log("warn", "browser", fmt.Sprintf("operation=%s http=%d", path, response.StatusCode))
114新增: var result struct {
115新增: Error string `json:"error"`
116新增: }
117新增: _ = json.Unmarshal(data, &result)
118新增: known := map[string]string{
119新增: "Tab no longer exists": "标签页已关闭。请重新打开网页后再操作。",
120新增: "Browser is starting": "浏览器仍在启动。请等待启动完成后再操作。",
121新增: "Input target changed": "接收内容的页面已切换。请回到原页面并重新点击输入框。",
122新增: "Image target changed": "接收图片的页面已切换。请回到原页面并重新点击输入框。",
123新增: "Copy target changed": "要复制内容的页面已切换。请回到原页面重新复制。",
124新增: "Image too large": "图片超过允许大小。请缩小图片后重新粘贴。",
125新增: "Invalid PNG": "图片不是有效的 PNG 文件。请重新复制或导出图片。",
126新增: "Only HTTP(S) URLs without credentials are accepted": "网址中包含账号或密码。请使用不带登录凭据的 http 或 https 网址。",
127新增: "Only HTTP(S) URLs and supported browser pages are accepted": "不支持这个网址类型。请使用 http 或 https 网址。",
128新增: "Unknown browser action": "浏览器组件不支持这次操作。请更新环境组件后再试。",
129新增: "Split controller unavailable": "分屏组件没有就绪。请更新环境组件后重新打开分屏。",
130新增: "Editor authentication is unavailable": "编辑器的本地登录会话不可用。请从 Cage 重新打开编辑器。",
131新增: "文件接收网页已切换,请返回原网页重试": "文件接收网页已切换,请返回原网页重试。",
132新增: "浏览器组件未能恢复,请重启环境": "浏览器组件未能恢复,请保存工作后重启环境。",
133新增: "不同浏览会话不能分屏": "所选页面属于不同浏览会话,无法放在同一个分屏中。请在同一会话中打开两个网页。",
134新增: "无痕标签暂不支持双网页分屏": "无痕标签暂不支持双网页分屏。请使用普通标签页。",
135新增: "设置页请在单个浏览器窗格内使用": "设置页请在单个浏览器窗格内使用。请先退出分屏。",
136新增: "扩展 ZIP 不能超过 32 MB": "扩展 ZIP 不能超过 32 MB。请缩小扩展包后重新导入。",
137新增: }
138新增: if reason := known[result.Error]; reason != "" {
139新增: return nil, errors.New(browserOperation(path) + "失败:" + reason)
140新增: }
141新增: return nil, serviceHTTPFailure(browserOperation(path), response.StatusCode)
106142 }
107143 return data, nil
108144}
@@ -114,7 +150,7 @@ func (c *browserClient) events(ctx context.Context, token string) (io.ReadCloser
114150 }
115151 if response.StatusCode != http.StatusOK {
116152 response.Body.Close()
117删除: return nil, errors.New("Browser unavailable")
153新增: return nil, serviceHTTPFailure("接收浏览器状态", response.StatusCode)
118154 }
119155 return response.Body, nil
120156}
修改internal/workbench/browser_file_desktop.go+3 −26看文件
@@ -7,9 +7,7 @@ import (
77 "net/http"
88 "net/url"
99 "os"
10删除: "os/exec"
1110 "path/filepath"
12删除: "runtime"
1311 "sort"
1412 "time"
1513
@@ -123,6 +121,7 @@ func BrowserFileForConnection(configPath, connectionID, action, id, destination
123121 return result, err
124122 }
125123 defer client.close()
124新增: client.client.Timeout = 30 * time.Minute
126125 entry, _ := url.Parse(client.launch.URL)
127126 status, err := client.call("POST", "/api/session", map[string]string{"token": entry.Fragment}, nil)
128127 if err != nil || status != 200 {
@@ -192,30 +191,8 @@ func BrowserFileForConnection(configPath, connectionID, action, id, destination
192191 return result, errors.New("文件已移动、删除或无法访问")
193192 }
194193 file.Close()
195删除: var cmd *exec.Cmd
196删除: switch runtime.GOOS {
197删除: case "darwin":
198删除: args := []string{"--", result.Path}
199删除: if action == "reveal" {
200删除: args = []string{"-R", "--", result.Path}
201删除: }
202删除: cmd = exec.Command("/usr/bin/open", args...)
203删除: case "windows":
204删除: if action == "reveal" {
205删除: cmd = exec.Command("explorer.exe", "/select,"+result.Path)
206删除: } else {
207删除: cmd = exec.Command("rundll32.exe", "url.dll,FileProtocolHandler", result.Path)
208删除: }
209删除: default:
210删除: path := result.Path
211删除: if action == "reveal" {
212删除: path = filepath.Dir(path)
213删除: }
214删除: cmd = exec.Command("gio", "open", path)
215删除: }
216删除: hideCommand(cmd)
217删除: if err = cmd.Run(); err != nil {
218删除: return result, errors.New("无法打开文件,请通过显示的位置手动查看")
194新增: if err = openHostFile(result.Path, action); err != nil {
195新增: return result, err
219196 }
220197 }
221198 return result, nil
修改internal/workbench/browser_files.go+333 −21看文件
@@ -4,6 +4,7 @@ import (
44 "context"
55 "encoding/json"
66 "errors"
7新增: "fmt"
78 "io"
89 "mime"
910 "net/http"
@@ -12,6 +13,10 @@ import (
1213 "path/filepath"
1314 "regexp"
1415 "strings"
16新增: "time"
17新增:
18新增: "github.com/google/uuid"
19新增: "github.com/sylvinus/agent-vm/internal/usererror"
1520)
1621
1722const browserFileLimit int64 = 2 << 30
@@ -69,14 +74,18 @@ func (s *Server) browserUpload(w http.ResponseWriter, r *http.Request) {
6974}
7075
7176func (s *Server) proxyBrowserFile(w http.ResponseWriter, r *http.Request, token, method, path string, body io.Reader) {
77新增: if s.macosGuest != nil || s.windowsGuest != nil {
78新增: s.nativeBrowserFile(w, r, method, path, body)
79新增: return
80新增: }
7281 response, err := s.browserClient().file(r.Context(), token, method, path, body, r.ContentLength)
7382 if err != nil {
74删除: http.Error(w, "文件传递中断,请重试", 502)
83新增: http.Error(w, usererror.Wrap("传递浏览器文件", err, "请恢复环境连接后核对文件是否已收到,再重新选择文件。").Error(), 502)
7584 return
7685 }
7786 defer response.Body.Close()
7887 if response.StatusCode != 200 {
79删除: http.Error(w, "文件不可用或上传窗口已关闭,请重试", 502)
88新增: http.Error(w, serviceHTTPFailure("传递浏览器文件", response.StatusCode).Error(), 502)
8089 return
8190 }
8291 if method == "POST" {
@@ -92,11 +101,13 @@ func (s *Server) proxyBrowserFile(w http.ResponseWriter, r *http.Request, token,
92101}
93102
94103type browserDownloadInfo struct {
104新增: Target string `json:"target,omitempty"`
95105 ID string `json:"id"`
96106 Name string `json:"name"`
97107 State string `json:"state"`
98108 Path string `json:"path,omitempty"`
99109 Retryable bool `json:"retryable,omitempty"`
110新增: Error string `json:"error,omitempty"`
100111}
101112
102113func (s *Server) downloadInfo(ctx context.Context, id string) (browserDownloadInfo, error) {
@@ -112,36 +123,337 @@ func (s *Server) downloadInfo(ctx context.Context, id string) (browserDownloadIn
112123 if !ready {
113124 return browserDownloadInfo{}, errors.New("请先启动环境或从已保存的位置打开文件")
114125 }
115删除: data, err := s.guestAPI(ctx, token, "GET", "/tabs", nil)
126新增: item, err := s.guestDownloadInfo(ctx, token, id)
116127 if err != nil {
117128 return browserDownloadInfo{}, err
118129 }
119删除: var state struct {
120删除: Downloads []browserDownloadInfo `json:"downloads"`
130新增: if s.macosGuest != nil || s.windowsGuest != nil {
131新增: if item.State != "saved" && !(item.State == "failed" && item.Retryable) {
132新增: item.Path = ""
133新增: return item, nil
134新增: }
135新增: transfer, err := s.startNativeDownload(item)
136新增: if err != nil {
137新增: return browserDownloadInfo{}, err
138新增: }
139新增: select {
140新增: case <-ctx.Done():
141新增: return browserDownloadInfo{}, ctx.Err()
142新增: case <-transfer.done:
143新增: }
144新增: if transfer.err != nil {
145新增: return browserDownloadInfo{}, transfer.err
146新增: }
147新增: saved, err := readSavedDownload(s.profile, id)
148新增: return browserDownloadInfo{ID: id, Target: item.Target, Name: saved.Name, Path: saved.Path, State: "saved"}, err
121149 }
122删除: if json.Unmarshal(data, &state) != nil {
123删除: return browserDownloadInfo{}, errors.New("下载列表无效")
150新增: if item.State == "saved" {
151新增: root := s.environmentDir()
152新增: expected := strings.TrimRight(guestPath(root), "/") + "/Downloads/" + item.Name
153新增: if item.Path != expected {
154新增: return browserDownloadInfo{}, errors.New("下载保存位置无效")
155新增: }
156新增: item.Path = filepath.Join(root, "Downloads", item.Name)
157新增: if err = rememberDownload(s.profile, SavedDownload{ID: id, Name: item.Name, Path: item.Path}, true); err != nil {
158新增: return browserDownloadInfo{}, err
159新增: }
160新增: } else {
161新增: item.Path = ""
124162 }
125删除: for _, item := range state.Downloads {
126删除: if item.ID != id || !browserDownloadName(item.Name) {
163新增: return item, nil
164新增:}
165新增:
166新增:// The native bridge carries only a download ID. Resolve it from the producing
167新增:// service even after a controller restart or before the first UI poll.
168新增:func (s *Server) guestDownloadInfo(ctx context.Context, token, id string) (browserDownloadInfo, error) {
169新增: var failures []error
170新增: for _, target := range []string{"browser", "desktop"} {
171新增: var data []byte
172新增: var err error
173新增: if target == "browser" {
174新增: data, err = s.guestAPI(ctx, token, "GET", "/tabs", nil)
175新增: } else {
176新增: var result map[string]any
177新增: result, err = s.guestFiles(ctx, "desktop", "GET", "/requests", nil, "")
178新增: if err == nil {
179新增: data, err = json.Marshal(result)
180新增: }
181新增: }
182新增: if err != nil {
183新增: failures = append(failures, err)
184新增: continue
185新增: }
186新增: var state struct {
187新增: Downloads []browserDownloadInfo `json:"downloads"`
188新增: }
189新增: if json.Unmarshal(data, &state) != nil {
190新增: failures = append(failures, errors.New("下载列表无效"))
127191 continue
128192 }
129删除: if item.State == "saved" {
130删除: root := s.environmentDir()
131删除: expected := strings.TrimRight(guestPath(root), "/") + "/Downloads/" + item.Name
132删除: if item.Path != expected {
133删除: return browserDownloadInfo{}, errors.New("下载保存位置无效")
193新增: for _, item := range state.Downloads {
194新增: if item.ID == id {
195新增: if !browserDownloadName(item.Name) {
196新增: return browserDownloadInfo{}, errors.New("下载文件记录无效")
197新增: }
198新增: item.Target = target
199新增: return item, nil
134200 }
135删除: item.Path = filepath.Join(root, "Downloads", item.Name)
136删除: if err = rememberDownload(s.profile, SavedDownload{ID: id, Name: item.Name, Path: item.Path}, true); err != nil {
137删除: return browserDownloadInfo{}, err
201新增: }
202新增: }
203新增: if len(failures) != 0 {
204新增: return browserDownloadInfo{}, errors.Join(failures...)
205新增: }
206新增: return browserDownloadInfo{}, errors.New("下载记录已不存在,请从原应用重新下载")
207新增:}
208新增:
209新增:// The native guest owns the source file. Only a completed, recorded host copy
210新增:// may appear as saved in the common workbench or be opened by a native shell.
211新增:type nativeDownload struct {
212新增: item browserDownloadInfo
213新增: done chan struct{}
214新增: err error
215新增:}
216新增:
217新增:func (s *Server) startNativeDownload(item browserDownloadInfo) (*nativeDownload, error) {
218新增: if !browserFileID.MatchString(item.ID) || !browserDownloadName(item.Name) {
219新增: return nil, errors.New("下载文件记录无效")
220新增: }
221新增: s.mu.Lock()
222新增: current := s.nativeDownloads[item.ID]
223新增: s.mu.Unlock()
224新增: if current != nil {
225新增: return current, nil
226新增: }
227新增: s.op.Lock()
228新增: defer s.op.Unlock()
229新增: s.mu.Lock()
230新增: ready := s.ready && !s.closing
231新增: s.mu.Unlock()
232新增: if !ready {
233新增: return nil, errBrowserNotReady
234新增: }
235新增: var client *windowsBrowserClient
236新增: if item.Target != "desktop" {
237新增: client = s.nativeBrowserClient()
238新增: }
239新增: epoch, unlocked := s.account.access()
240新增: if !unlocked {
241新增: return nil, errors.New("Cage 已锁定,请先解锁再保存下载")
242新增: }
243新增: ctx, finish, err := s.beginActivity(epoch)
244新增: if err != nil {
245新增: return nil, err
246新增: }
247新增: s.mu.Lock()
248新增: if current = s.nativeDownloads[item.ID]; current != nil {
249新增: s.mu.Unlock()
250新增: finish()
251新增: return current, nil
252新增: }
253新增: if s.nativeDownloads == nil {
254新增: s.nativeDownloads = make(map[string]*nativeDownload)
255新增: s.nativeDownloadSlots = make(chan struct{}, 2)
256新增: }
257新增: current = &nativeDownload{item: item, done: make(chan struct{})}
258新增: s.nativeDownloads[item.ID] = current
259新增: s.nativeDownloadRevision++
260新增: slots := s.nativeDownloadSlots
261新增: s.mu.Unlock()
262新增: go func() {
263新增: defer finish()
264新增: defer func() {
265新增: close(current.done)
266新增: s.mu.Lock()
267新增: s.nativeDownloadRevision++
268新增: if current.err == nil && s.nativeDownloads[item.ID] == current {
269新增: delete(s.nativeDownloads, item.ID)
138270 }
139删除: } else {
140删除: item.Path = ""
271新增: s.mu.Unlock()
272新增: }()
273新增: ctx, cancel := context.WithTimeout(ctx, 30*time.Minute)
274新增: defer cancel()
275新增: select {
276新增: case <-ctx.Done():
277新增: current.err = ctx.Err()
278新增: return
279新增: case slots <- struct{}{}:
280新增: }
281新增: defer func() { <-slots }()
282新增: current.err = s.saveNativeDownload(ctx, item, client)
283新增: }()
284新增: return current, nil
285新增:}
286新增:
287新增:func (s *Server) retryNativeDownload(id string) (bool, error) {
288新增: s.mu.Lock()
289新增: transfer := s.nativeDownloads[id]
290新增: if transfer == nil {
291新增: s.mu.Unlock()
292新增: return false, nil
293新增: }
294新增: select {
295新增: case <-transfer.done:
296新增: delete(s.nativeDownloads, id)
297新增: default:
298新增: s.mu.Unlock()
299新增: return true, nil
300新增: }
301新增: s.mu.Unlock()
302新增: _, err := s.startNativeDownload(transfer.item)
303新增: return true, err
304新增:}
305新增:
306新增:func (s *Server) discardMissingNativeDownloads(target string, visible map[string]bool) {
307新增: s.mu.Lock()
308新增: defer s.mu.Unlock()
309新增: for id, transfer := range s.nativeDownloads {
310新增: if (transfer.item.Target == "desktop") != (target == "desktop") || visible[id] {
311新增: continue
312新增: }
313新增: select {
314新增: case <-transfer.done:
315新增: delete(s.nativeDownloads, id)
316新增: default:
317新增: }
318新增: }
319新增:}
320新增:
321新增:func (s *Server) nativeDownloadForHost(item browserDownloadInfo) browserDownloadInfo {
322新增: item.Path = ""
323新增: if saved, err := readSavedDownload(s.profile, item.ID); err == nil {
324新增: item.Name, item.Path, item.State, item.Retryable = saved.Name, saved.Path, "saved", false
325新增: item.Error = ""
326新增: return item
327新增: }
328新增: if item.State != "saved" && !(item.State == "failed" && item.Retryable) {
329新增: return item
330新增: }
331新增: transfer, err := s.startNativeDownload(item)
332新增: if err == nil {
333新增: select {
334新增: case <-transfer.done:
335新增: err = transfer.err
336新增: if err == nil {
337新增: saved, readErr := readSavedDownload(s.profile, item.ID)
338新增: if readErr == nil {
339新增: item.Name, item.Path, item.State, item.Retryable = saved.Name, saved.Path, "saved", false
340新增: item.Error = ""
341新增: return item
342新增: }
343新增: err = readErr
344新增: }
345新增: default:
346新增: item.State, item.Retryable = "saving", false
347新增: item.Error = ""
348新增: return item
349新增: }
350新增: }
351新增: item.State, item.Retryable = "failed", true
352新增: item.Error = usererror.Display("保存下载到本机", err, "请恢复环境连接或检查默认工作区空间,再点击重试。").Error()
353新增: return item
354新增:}
355新增:
356新增:func (s *Server) saveNativeDownload(ctx context.Context, item browserDownloadInfo, client *windowsBrowserClient) error {
357新增: if _, err := readSavedDownload(s.profile, item.ID); err == nil {
358新增: return nil
359新增: }
360新增: var source io.ReadCloser
361新增: var size int64
362新增: var name string
363新增: var err error
364新增: if item.Target == "desktop" {
365新增: source, size, name, err = s.openNativeDesktopDownload(ctx, item.ID)
366新增: } else {
367新增: source, size, name, err = client.download(ctx, item.ID)
368新增: }
369新增: if err != nil {
370新增: return err
371新增: }
372新增: defer source.Close()
373新增: if name != item.Name {
374新增: return errors.New("下载文件记录已变化,请刷新下载列表")
375新增: }
376新增: workspace, err := validateWorkspace(s.environmentDir(), s.profile)
377新增: if err != nil {
378新增: return err
379新增: }
380新增: root, err := os.OpenRoot(workspace)
381新增: if err != nil {
382新增: return err
383新增: }
384新增: defer root.Close()
385新增: if err := root.Mkdir("Downloads", 0700); err != nil && !os.IsExist(err) {
386新增: return err
387新增: }
388新增: directory, err := root.Lstat("Downloads")
389新增: if err != nil || !directory.IsDir() {
390新增: return errors.New("默认下载目录无效,请选择默认工作区中的普通文件夹")
391新增: }
392新增: downloads, err := root.OpenRoot("Downloads")
393新增: if err != nil {
394新增: return err
395新增: }
396新增: defer downloads.Close()
397新增: temporary := ".cage-download-" + uuid.NewString() + ".part"
398新增: file, err := downloads.OpenFile(temporary, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
399新增: if err != nil {
400新增: return err
401新增: }
402新增: defer downloads.Remove(temporary)
403新增: count, err := io.Copy(file, source)
404新增: if err == nil && count != size {
405新增: err = io.ErrUnexpectedEOF
406新增: }
407新增: if err == nil {
408新增: err = ctx.Err()
409新增: }
410新增: if err == nil {
411新增: err = file.Sync()
412新增: }
413新增: written, statErr := file.Stat()
414新增: err = errors.Join(err, statErr)
415新增: err = errors.Join(err, file.Close())
416新增: if err != nil {
417新增: return err
418新增: }
419新增: for attempt := 0; attempt < 1000; attempt++ {
420新增: candidate := name
421新增: if attempt != 0 {
422新增: extension := filepath.Ext(name)
423新增: candidate = fmt.Sprintf("%s (%d)%s", strings.TrimSuffix(name, extension), attempt, extension)
424新增: }
425新增: // Match the Linux save-download helper's exclusive publication. A
426新增: // simultaneous download or an existing filename wins without replacement.
427新增: if err = downloads.Link(temporary, candidate); os.IsExist(err) {
428新增: continue
429新增: }
430新增: if err != nil {
431新增: return err
432新增: }
433新增: saved := SavedDownload{ID: item.ID, Name: candidate, Path: filepath.Join(workspace, "Downloads", candidate)}
434新增: removePublished := func() {
435新增: if current, err := downloads.Lstat(candidate); err == nil && os.SameFile(written, current) {
436新增: _ = downloads.Remove(candidate)
437新增: }
438新增: }
439新增: published, openErr := openDownloadedFile(saved.Path)
440新增: if openErr != nil {
441新增: removePublished()
442新增: return openErr
443新增: }
444新增: current, statErr := published.Stat()
445新增: published.Close()
446新增: if statErr != nil || !os.SameFile(written, current) {
447新增: removePublished()
448新增: return errors.New("下载保存位置已变化,请重新保存")
449新增: }
450新增: if err = rememberDownload(s.profile, saved, true); err != nil {
451新增: removePublished()
452新增: return err
141453 }
142删除: return item, nil
454新增: return nil
143455 }
144删除: return browserDownloadInfo{}, errors.New("下载记录已不存在,请从原网页重新下载")
456新增: return errors.New("默认下载目录中的同名文件过多,请整理后重试")
145457}
146458
147459func (s *Server) browserDownload(w http.ResponseWriter, r *http.Request) {
修改internal/workbench/browser_files_test.go+9 −0看文件
@@ -168,6 +168,15 @@ func TestCompletedDownloadsRemainAvailableAfterVMStops(t *testing.T) {
168168
169169func TestNativeSaveUsesAuthenticatedControllerAndPersistsChosenPath(t *testing.T) {
170170 s := testServer(t)
171新增: lock, err := openControllerLock(s.profile, os.O_CREATE|os.O_RDWR)
172新增: if err != nil {
173新增: t.Fatal(err)
174新增: }
175新增: defer lock.Close()
176新增: if err := lockController(lock); err != nil {
177新增: t.Fatal(err)
178新增: }
179新增: defer unlockController(lock)
171180 server := httptest.NewServer(s.handler())
172181 defer server.Close()
173182 endpoint, _ := url.Parse(server.URL)
修改internal/workbench/browser_http.go+21 −1看文件
@@ -1,6 +1,8 @@
11package workbench
22
33import (
4新增: "context"
5新增: "encoding/json"
46 "errors"
57 "net/http"
68 "time"
@@ -12,7 +14,7 @@ func (s *Server) browser(w http.ResponseWriter, r *http.Request) {
1214 action = "tabs"
1315 }
1416 switch action {
15删除: case "tabs", "split", "new", "activate", "close", "navigate", "back", "forward", "reload", "editor", "editor-restart", "download-retry", "upload-finish", "upload-cancel", "resize", "insert-text", "copy-context":
17新增: case "tabs", "split", "new", "activate", "close", "navigate", "back", "forward", "reload", "editor", "editor-restart", "download-retry", "upload-finish", "upload-cancel", "resize", "insert-text", "copy-context", "cookies", "settings", "extensions", "internal-page", "info":
1618 default:
1719 http.NotFound(w, r)
1820 return
@@ -50,6 +52,24 @@ func (s *Server) remoteInput(w http.ResponseWriter, r *http.Request) {
5052 if !readJSON(w, r, &input) {
5153 return
5254 }
55新增: if s.windowsGuest != nil && input.Target == "desktop" {
56新增: if input.ID != "desktop" || len(input.Text) > 8192 {
57新增: http.Error(w, "输入目标或文字无效", 400)
58新增: return
59新增: }
60新增: body, _ := json.Marshal(input)
61新增: var value map[string]any
62新增: _ = json.Unmarshal(body, &value)
63新增: var output map[string]any
64新增: ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
65新增: defer cancel()
66新增: if err := s.windowsDesktopRequest(ctx, "ime", value, &output); err != nil {
67新增: http.Error(w, err.Error(), 502)
68新增: return
69新增: }
70新增: jsonReply(w, output)
71新增: return
72新增: }
5373 data, err := s.browserAction(r.Context(), "ime", &input)
5474 if err != nil {
5575 status := http.StatusBadGateway
新增internal/workbench/browser_import.go+367 −0看文件
@@ -0,0 +1,367 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "archive/zip"
5新增: "bytes"
6新增: "crypto/sha256"
7新增: "encoding/base64"
8新增: "encoding/hex"
9新增: "encoding/json"
10新增: "errors"
11新增: "fmt"
12新增: "io"
13新增: "net/http"
14新增: "os"
15新增: "path/filepath"
16新增: "runtime"
17新增: "sort"
18新增: "strings"
19新增:)
20新增:
21新增:type localBrowserRoot struct{ Name, Path string }
22新增:type localBrowserExtension struct {
23新增: ID string `json:"id"`
24新增: Name string `json:"name"`
25新增: Version string `json:"version"`
26新增: Enabled bool `json:"enabled"`
27新增: StateKnown bool `json:"state_known"`
28新增: Compatible bool `json:"compatible"`
29新增: IdentityPreserved bool `json:"identity_preserved"`
30新增: Permissions []string `json:"permissions"`
31新增: HostPermissions []string `json:"hostPermissions"`
32新增: directory string
33新增: key string
34新增:}
35新增:type localBrowserProfile struct {
36新增: ID string `json:"id"`
37新增: Browser string `json:"browser"`
38新增: Name string `json:"name"`
39新增: Extensions []localBrowserExtension `json:"extensions"`
40新增:}
41新增:
42新增:func localBrowserRoots() []localBrowserRoot {
43新增: home, _ := os.UserHomeDir()
44新增: var base string
45新增: var locations []string
46新增: switch runtime.GOOS {
47新增: case "darwin":
48新增: base = filepath.Join(home, "Library", "Application Support")
49新增: locations = []string{"Microsoft Edge", "Google/Chrome", "BraveSoftware/Brave-Browser", "Chromium"}
50新增: case "windows":
51新增: base = os.Getenv("LOCALAPPDATA")
52新增: locations = []string{"Microsoft/Edge/User Data", "Google/Chrome/User Data", "BraveSoftware/Brave-Browser/User Data", "Chromium/User Data"}
53新增: default:
54新增: base, _ = os.UserConfigDir()
55新增: locations = []string{"microsoft-edge", "google-chrome", "BraveSoftware/Brave-Browser", "chromium"}
56新增: }
57新增: if base == "" {
58新增: return nil
59新增: }
60新增: var roots []localBrowserRoot
61新增: for i, name := range []string{"Microsoft Edge", "Google Chrome", "Brave", "Chromium"} {
62新增: roots = append(roots, localBrowserRoot{name, filepath.Join(base, filepath.FromSlash(locations[i]))})
63新增: }
64新增: return roots
65新增:}
66新增:func readBrowserJSON(path string, value any) bool {
67新增: info, err := os.Lstat(path)
68新增: if err != nil || !info.Mode().IsRegular() || info.Size() > 16<<20 {
69新增: return false
70新增: }
71新增: file, err := os.Open(path)
72新增: if err != nil {
73新增: return false
74新增: }
75新增: defer file.Close()
76新增: return json.NewDecoder(io.LimitReader(file, 16<<20)).Decode(value) == nil
77新增:}
78新增:func browserDirectory(path string) bool {
79新增: info, err := os.Lstat(path)
80新增: return err == nil && info.IsDir() && info.Mode()&os.ModeSymlink == 0
81新增:}
82新增:
83新增:func scanLocalBrowserProfiles(roots []localBrowserRoot) []localBrowserProfile {
84新增: result := []localBrowserProfile{}
85新增: for _, root := range roots {
86新增: if !browserDirectory(root.Path) {
87新增: continue
88新增: }
89新增: entries, err := os.ReadDir(root.Path)
90新增: if err != nil {
91新增: continue
92新增: }
93新增: var local struct {
94新增: Profile struct {
95新增: Info map[string]struct {
96新增: Name string `json:"name"`
97新增: } `json:"info_cache"`
98新增: } `json:"profile"`
99新增: }
100新增: readBrowserJSON(filepath.Join(root.Path, "Local State"), &local)
101新增: for _, entry := range entries {
102新增: name := entry.Name()
103新增: if name != "Default" && !strings.HasPrefix(name, "Profile ") {
104新增: continue
105新增: }
106新增: profilePath := filepath.Join(root.Path, name)
107新增: if !browserDirectory(profilePath) {
108新增: continue
109新增: }
110新增: digest := sha256.Sum256([]byte(root.Path + "\x00" + name))
111新增: profile := localBrowserProfile{ID: hex.EncodeToString(digest[:16]), Browser: root.Name, Name: local.Profile.Info[name].Name, Extensions: []localBrowserExtension{}}
112新增: if profile.Name == "" {
113新增: profile.Name = name
114新增: }
115新增: var prefs struct {
116新增: Extensions struct {
117新增: Settings map[string]struct {
118新增: State *int `json:"state"`
119新增: DisableReasons json.RawMessage `json:"disable_reasons"`
120新增: Path string `json:"path"`
121新增: Manifest struct {
122新增: Key string `json:"key"`
123新增: } `json:"manifest"`
124新增: } `json:"settings"`
125新增: } `json:"extensions"`
126新增: }
127新增: readBrowserJSON(filepath.Join(profilePath, "Preferences"), &prefs)
128新增: // Secure Preferences owns protected extension state on desktop Chromium.
129新增: var secure = prefs
130新增: if readBrowserJSON(filepath.Join(profilePath, "Secure Preferences"), &secure) {
131新增: for id, value := range secure.Extensions.Settings {
132新增: if prefs.Extensions.Settings == nil {
133新增: prefs.Extensions.Settings = secure.Extensions.Settings
134新增: break
135新增: }
136新增: prefs.Extensions.Settings[id] = value
137新增: }
138新增: }
139新增: extRoot := filepath.Join(profilePath, "Extensions")
140新增: if !browserDirectory(extRoot) {
141新增: continue
142新增: }
143新增: extensionDirs, _ := os.ReadDir(extRoot)
144新增: for _, extensionDir := range extensionDirs {
145新增: id := extensionDir.Name()
146新增: if len(id) != 32 || strings.Trim(id, "abcdefghijklmnop") != "" {
147新增: continue
148新增: }
149新增: directory := filepath.Join(extRoot, id)
150新增: if !browserDirectory(directory) {
151新增: continue
152新增: }
153新增: versions, _ := os.ReadDir(directory)
154新增: sort.Slice(versions, func(i, j int) bool {
155新增: a, _ := versions[i].Info()
156新增: b, _ := versions[j].Info()
157新增: return a != nil && (b == nil || a.ModTime().After(b.ModTime()))
158新增: })
159新增: state := prefs.Extensions.Settings[id]
160新增: if _, registered := prefs.Extensions.Settings[id]; prefs.Extensions.Settings != nil && !registered {
161新增: continue
162新增: }
163新增: if state.State != nil && *state.State == 2 {
164新增: continue
165新增: }
166新增: if state.Path != "" {
167新增: desired := filepath.Base(filepath.Clean(state.Path))
168新增: sort.SliceStable(versions, func(i, j int) bool { return versions[i].Name() == desired && versions[j].Name() != desired })
169新增: }
170新增: for _, version := range versions {
171新增: packagePath := filepath.Join(directory, version.Name())
172新增: if !browserDirectory(packagePath) {
173新增: continue
174新增: }
175新增: var manifest struct {
176新增: Name string `json:"name"`
177新增: Version string `json:"version"`
178新增: ManifestVersion int `json:"manifest_version"`
179新增: Key string `json:"key"`
180新增: Permissions []string `json:"permissions"`
181新增: Hosts []string `json:"host_permissions"`
182新增: Content []struct {
183新增: Matches []string `json:"matches"`
184新增: } `json:"content_scripts"`
185新增: Locale string `json:"default_locale"`
186新增: }
187新增: if !readBrowserJSON(filepath.Join(packagePath, "manifest.json"), &manifest) || manifest.Name == "" || manifest.Version == "" {
188新增: continue
189新增: }
190新增: display := manifest.Name
191新增: if strings.HasPrefix(display, "__MSG_") && strings.HasSuffix(display, "__") && filepath.Base(manifest.Locale) == manifest.Locale {
192新增: var messages map[string]struct {
193新增: Message string `json:"message"`
194新增: }
195新增: if readBrowserJSON(filepath.Join(packagePath, "_locales", manifest.Locale, "messages.json"), &messages) {
196新增: if text := messages[strings.TrimSuffix(strings.TrimPrefix(display, "__MSG_"), "__")].Message; text != "" {
197新增: display = text
198新增: }
199新增: }
200新增: }
201新增: publicKey := manifest.Key
202新增: if publicKey == "" {
203新增: publicKey = state.Manifest.Key
204新增: }
205新增: if publicKey != "" {
206新增: data, decodeErr := base64.StdEncoding.DecodeString(publicKey)
207新增: digest := sha256.Sum256(data)
208新增: actual := ""
209新增: for _, char := range hex.EncodeToString(digest[:16]) {
210新增: var value int
211新增: if char >= 'a' {
212新增: value = int(char-'a') + 10
213新增: } else {
214新增: value = int(char - '0')
215新增: }
216新增: actual += string(rune('a' + value))
217新增: }
218新增: if decodeErr != nil || actual != id {
219新增: publicKey = ""
220新增: }
221新增: }
222新增: enabled, known := importedExtensionState(state.State, state.DisableReasons)
223新增: hosts := append([]string{}, manifest.Hosts...)
224新增: for _, content := range manifest.Content {
225新增: hosts = append(hosts, content.Matches...)
226新增: }
227新增: profile.Extensions = append(profile.Extensions, localBrowserExtension{ID: id, Name: display, Version: manifest.Version, Enabled: enabled, StateKnown: known, Compatible: manifest.ManifestVersion == 3, IdentityPreserved: publicKey != "", Permissions: manifest.Permissions, HostPermissions: hosts, directory: packagePath, key: publicKey})
228新增: break
229新增: }
230新增: }
231新增: sort.Slice(profile.Extensions, func(i, j int) bool { return profile.Extensions[i].Name < profile.Extensions[j].Name })
232新增: result = append(result, profile)
233新增: }
234新增: }
235新增: return result
236新增:}
237新增:
238新增:// Current Chromium records disable_reasons; older profiles also have state.
239新增:func importedExtensionState(state *int, reasons json.RawMessage) (bool, bool) {
240新增: if len(reasons) > 0 && string(reasons) != "null" {
241新增: var list []json.RawMessage
242新增: if json.Unmarshal(reasons, &list) == nil {
243新增: return len(list) == 0 && (state == nil || *state == 1), true
244新增: }
245新增: var mask int
246新增: if json.Unmarshal(reasons, &mask) == nil {
247新增: return mask == 0 && (state == nil || *state == 1), true
248新增: }
249新增: }
250新增: if state != nil {
251新增: return *state == 1, true
252新增: }
253新增: return false, false
254新增:}
255新增:
256新增:func packageLocalExtension(extension localBrowserExtension) ([]byte, error) {
257新增: if !extension.Compatible || !browserDirectory(extension.directory) {
258新增: return nil, errors.New("此扩展不支持导入")
259新增: }
260新增: var output bytes.Buffer
261新增: archive := zip.NewWriter(&output)
262新增: count := 0
263新增: var total int64
264新增: err := filepath.WalkDir(extension.directory, func(path string, entry os.DirEntry, walkErr error) error {
265新增: if walkErr != nil {
266新增: return walkErr
267新增: }
268新增: relative, e := filepath.Rel(extension.directory, path)
269新增: if e != nil {
270新增: return e
271新增: }
272新增: if relative == "." {
273新增: return nil
274新增: }
275新增: if entry.IsDir() {
276新增: if entry.Name() == "_metadata" || entry.Name() == ".git" {
277新增: return filepath.SkipDir
278新增: }
279新增: return nil
280新增: }
281新增: info, e := entry.Info()
282新增: if e != nil {
283新增: return e
284新增: }
285新增: if !info.Mode().IsRegular() || entry.Type()&os.ModeSymlink != 0 {
286新增: return errors.New("扩展包含无法导入的特殊文件")
287新增: }
288新增: count++
289新增: total += info.Size()
290新增: if count > 3000 || total > 128<<20 || info.Size() > 32<<20 {
291新增: return errors.New("扩展文件超出导入限制")
292新增: }
293新增: target, e := archive.Create(filepath.ToSlash(relative))
294新增: if e != nil {
295新增: return e
296新增: }
297新增: source, e := os.Open(path)
298新增: if e != nil {
299新增: return e
300新增: }
301新增: defer source.Close()
302新增: if relative == "manifest.json" && extension.key != "" {
303新增: var manifest map[string]any
304新增: if json.NewDecoder(io.LimitReader(source, 1<<20)).Decode(&manifest) != nil {
305新增: return errors.New("扩展配置已变化,请刷新清单")
306新增: }
307新增: manifest["key"] = extension.key
308新增: return json.NewEncoder(target).Encode(manifest)
309新增: }
310新增: _, e = io.CopyN(target, source, info.Size())
311新增: if output.Len() > 32<<20 {
312新增: return errors.New("扩展压缩包不能超过 32 MB")
313新增: }
314新增: return e
315新增: })
316新增: closeErr := archive.Close()
317新增: if err != nil {
318新增: return nil, err
319新增: }
320新增: if closeErr != nil {
321新增: return nil, closeErr
322新增: }
323新增: if output.Len() > 32<<20 {
324新增: return nil, errors.New("扩展压缩包不能超过 32 MB")
325新增: }
326新增: return output.Bytes(), nil
327新增:}
328新增:
329新增:func (s *Server) localBrowserExtensions(w http.ResponseWriter, r *http.Request) {
330新增: profiles := scanLocalBrowserProfiles(localBrowserRoots())
331新增: if r.Method == http.MethodGet {
332新增: jsonReply(w, map[string]any{"profiles": profiles})
333新增: return
334新增: }
335新增: var input struct {
336新增: Profile string `json:"profile"`
337新增: ID string `json:"id"`
338新增: Version string `json:"version"`
339新增: }
340新增: if !readJSON(w, r, &input) {
341新增: return
342新增: }
343新增: for _, profile := range profiles {
344新增: if profile.ID != input.Profile {
345新增: continue
346新增: }
347新增: for _, extension := range profile.Extensions {
348新增: if extension.ID != input.ID {
349新增: continue
350新增: }
351新增: if extension.Version != input.Version {
352新增: requestError(w, errors.New("本机扩展已更新,请刷新清单"))
353新增: return
354新增: }
355新增: data, err := packageLocalExtension(extension)
356新增: if err != nil {
357新增: requestError(w, err)
358新增: return
359新增: }
360新增: w.Header().Set("Content-Type", "application/zip")
361新增: w.Header().Set("Content-Length", fmt.Sprint(len(data)))
362新增: _, _ = w.Write(data)
363新增: return
364新增: }
365新增: }
366新增: http.Error(w, "所选本机扩展已不可用,请刷新清单", http.StatusNotFound)
367新增:}
新增internal/workbench/browser_language_test.go+70 −0看文件
@@ -0,0 +1,70 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "strings"
5新增: "testing"
6新增:
7新增: "github.com/sylvinus/agent-vm/internal/cage"
8新增:)
9新增:
10新增:func TestBrowserSettingsJapaneseChromiumLocale(t *testing.T) {
11新增: cfg := cage.DefaultConfig()
12新增: cfg.Timezone, cfg.BrowserLanguage = "Asia/Tokyo", "ja-JP"
13新增: for _, language := range []string{"ja", "JA", "ja-JP", "ja-US", "en-US", ""} {
14新增: v := browserObservation{Timezone: cfg.Timezone, ExpectedTimezone: cfg.Timezone, Language: language, Platform: "Linux x86_64"}
15新增: want := language == "ja" || language == "JA" || language == "ja-JP"
16新增: if got := browserSettingsMatch(v, cfg); got != want {
17新增: t.Errorf("Japanese browser language %q: got %t, want %t", language, got, want)
18新增: }
19新增: }
20新增: cfg.BrowserLanguage = "zh-TW"
21新增: v := browserObservation{Timezone: cfg.Timezone, ExpectedTimezone: cfg.Timezone, Language: "zh", Platform: "Linux x86_64"}
22新增: if browserSettingsMatch(v, cfg) {
23新增: t.Fatal("regional distinction in Chinese was discarded")
24新增: }
25新增:}
26新增:
27新增:func TestBrowserSettingsReportsOnlyMismatchedFields(t *testing.T) {
28新增: cfg := cage.DefaultConfig()
29新增: cfg.Timezone, cfg.BrowserLanguage = "Asia/Taipei", "zh-TW"
30新增: valid := browserObservation{Timezone: "Asia/Taipei", ExpectedTimezone: "Asia/Taipei", Language: "zh-TW", Platform: "Linux x86_64"}
31新增: for _, field := range []string{"none", "language", "timezone", "platform", "all", "timezone-alias", "language-case"} {
32新增: t.Run(field, func(t *testing.T) {
33新增: v := valid
34新增: var want []string
35新增: switch field {
36新增: case "language":
37新增: v.Language = "en-US"
38新增: want = []string{"语言不一致", `"zh-TW"`, `"en-US"`}
39新增: case "timezone":
40新增: v.Timezone = "UTC"
41新增: want = []string{"时区不一致", `"Asia/Taipei"`, `"UTC"`}
42新增: case "platform":
43新增: v.Platform = "MacIntel"
44新增: want = []string{"系统标识不一致", "Linux", `"MacIntel"`}
45新增: case "all":
46新增: v = browserObservation{}
47新增: want = []string{"时区不一致", "语言不一致", "系统标识不一致"}
48新增: case "timezone-alias":
49新增: v.Timezone, v.ExpectedTimezone = "Asia/Calcutta", "Asia/Calcutta"
50新增: case "language-case":
51新增: v.Language = "zh-tw"
52新增: }
53新增: mismatch := browserSettingsMismatch(v, cfg)
54新增: if browserSettingsMatch(v, cfg) != (len(want) == 0) {
55新增: t.Fatalf("unexpected match: %s", mismatch)
56新增: }
57新增: for _, text := range want {
58新增: if !strings.Contains(mismatch, text) {
59新增: t.Fatalf("missing %q in %q", text, mismatch)
60新增: }
61新增: }
62新增: if len(want) == 0 && mismatch != "" {
63新增: t.Fatal(mismatch)
64新增: }
65新增: if field == "language" && (strings.Contains(mismatch, "时区") || strings.Contains(mismatch, "系统标识")) {
66新增: t.Fatalf("language failure blamed unrelated fields: %s", mismatch)
67新增: }
68新增: })
69新增: }
70新增:}
新增internal/workbench/browser_privacy_test.go+76 −0看文件
@@ -0,0 +1,76 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "encoding/json"
5新增: "io"
6新增: "net/http"
7新增: "strings"
8新增: "testing"
9新增:)
10新增:
11新增:func TestBrowserPrivacyHTTPContract(t *testing.T) {
12新增: s := testServer(t)
13新增: s.ready = true
14新增: calls := 0
15新增: s.browserControl = browserClientForTest(t, s, browserTransport(func(r *http.Request) (*http.Response, error) {
16新增: calls++
17新增: if r.Header.Get("Authorization") != "Bearer "+s.credentials.Token {
18新增: t.Fatal("guest authentication missing")
19新增: }
20新增: var input browserInput
21新增: if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
22新增: t.Fatal(err)
23新增: }
24新增: switch r.URL.Path {
25新增: case "/new":
26新增: if !input.Incognito || input.URL != "https://example.test/" {
27新增: t.Fatalf("private flag lost: %+v", input)
28新增: }
29新增: case "/cookies":
30新增: if input.ID != "private-tab" || input.Mode != "delete" || input.Scope != "site" || input.Query != "session" || input.Page != 2 || input.CookieKey != strings.Repeat("a", 64) || input.URL != "https://example.test/" {
31新增: t.Fatalf("cookie input lost: %+v", input)
32新增: }
33新增: default:
34新增: t.Fatalf("unexpected action: %s", r.URL.Path)
35新增: }
36新增: return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"ok":true}`)), Header: make(http.Header)}, nil
37新增: }))
38新增: for _, body := range []struct{ path, input string }{
39新增: {"new", `{"url":"https://example.test/","incognito":true}`},
40新增: {"cookies", `{"id":"private-tab","url":"https://example.test/","mode":"delete","scope":"site","query":"session","page":2,"cookieKey":"` + strings.Repeat("a", 64) + `"}`},
41新增: } {
42新增: response := request(s, "POST", "/api/browser/"+body.path, s.origin, body.input, true)
43新增: if response.Code != 200 {
44新增: t.Fatalf("%s: %d %s", body.path, response.Code, response.Body.String())
45新增: }
46新增: }
47新增: if calls != 2 {
48新增: t.Fatalf("calls = %d", calls)
49新增: }
50新增: for _, input := range []string{
51新增: `{"mode":"clear","scope":"all"}`,
52新增: `{"id":"tab","mode":"clear","scope":"arbitrary-context"}`,
53新增: `{"id":"tab","mode":"delete","scope":"all","cookieKey":"bad"}`,
54新增: `{"id":"tab","mode":"list","scope":"site","page":-1}`,
55新增: } {
56新增: response := request(s, "POST", "/api/browser/cookies", s.origin, input, true)
57新增: if response.Code != http.StatusBadRequest {
58新增: t.Fatalf("invalid input accepted: %s: %d", input, response.Code)
59新增: }
60新增: }
61新增: if calls != 2 {
62新增: t.Fatal("invalid request reached guest")
63新增: }
64新增: response := request(s, "POST", "/api/browser/cookies", s.origin, `{"id":"tab","mode":"list","scope":"all"}`, false)
65新增: if response.Code != http.StatusUnauthorized {
66新增: t.Fatalf("unauthenticated request: %d", response.Code)
67新增: }
68新增: s.account.lock()
69新增: response = request(s, "POST", "/api/browser/cookies", s.origin, `{"id":"tab","mode":"list","scope":"all"}`, true)
70新增: if response.Code != http.StatusLocked {
71新增: t.Fatalf("locked request: %d", response.Code)
72新增: }
73新增: if calls != 2 {
74新增: t.Fatal("unauthorized request reached guest")
75新增: }
76新增:}
修改internal/workbench/browser_service.go+46 −1看文件
@@ -7,6 +7,7 @@ import (
77 "io"
88 "net"
99 "net/http"
10新增: "path/filepath"
1011 "time"
1112
1213 "github.com/sylvinus/agent-vm/internal/containerenv"
@@ -20,6 +21,12 @@ var (
2021type browserInputError struct{ error }
2122
2223type browserInput struct {
24新增: Incognito bool `json:"incognito,omitempty"`
25新增: Enabled *bool `json:"enabled,omitempty"`
26新增: CookieKey string `json:"cookieKey,omitempty"`
27新增: Scope string `json:"scope,omitempty"`
28新增: Query string `json:"query,omitempty"`
29新增: Page int `json:"page,omitempty"`
2330 Left string `json:"left,omitempty"`
2431 Right string `json:"right,omitempty"`
2532 ID string `json:"id"`
@@ -27,6 +34,8 @@ type browserInput struct {
2734 Width int `json:"width,omitempty"`
2835 Height int `json:"height,omitempty"`
2936 Workspace string `json:"workspace,omitempty"`
37新增: ProjectID string `json:"project_id,omitempty"`
38新增: ProjectGrant string `json:"grant,omitempty"`
3039 Text string `json:"text,omitempty"`
3140 Mode string `json:"mode,omitempty"`
3241 Target string `json:"target,omitempty"`
@@ -42,8 +51,9 @@ func (s *Server) browserClient() *browserClient {
4251 defer s.mu.Unlock()
4352 if s.browserControl == nil {
4453 s.browserControl = newBrowserClient(s.lifetimeContextLocked())
54新增: transport := s.browserControl.http.Transport.(*http.Transport)
55新增: lifetime := s.browserControl.ctx
4556 if containerenv.Configured(s.profile) {
46删除: transport := s.browserControl.http.Transport.(*http.Transport)
4757 transport.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) {
4858 environment, err := containerenv.Load(s.profile)
4959 if err != nil {
@@ -58,12 +68,19 @@ func (s *Server) browserClient() *browserClient {
5868 }
5969 return (&net.Dialer{Timeout: 3 * time.Second}).DialContext(ctx, network, state.BrowserAddress)
6070 }
71新增: } else {
72新增: transport.DialContext = func(ctx context.Context, _, _ string) (net.Conn, error) {
73新增: return s.dialGuestBrowser(ctx, lifetime)
74新增: }
6175 }
6276 }
6377 return s.browserControl
6478}
6579
6680func (s *Server) guestAPI(ctx context.Context, token, method, path string, body []byte) ([]byte, error) {
81新增: if s.macosGuest != nil || s.windowsGuest != nil {
82新增: return s.nativeBrowserAPI(ctx, method, path, body)
83新增: }
6784 return s.browserClient().request(ctx, token, method, path, body)
6885}
6986
@@ -84,6 +101,17 @@ func (s *Server) browserAction(ctx context.Context, action string, input *browse
84101 var body []byte
85102 if input != nil {
86103 method = http.MethodPost
104新增: if action == "download-retry" && (s.macosGuest != nil || s.windowsGuest != nil) {
105新增: if handled, err := s.retryNativeDownload(input.ID); handled {
106新增: return []byte(`{"ok":true}`), err
107新增: }
108新增: }
109新增: if action == "cookies" && (input.ID == "" ||
110新增: (input.Mode != "list" && input.Mode != "details" && input.Mode != "delete" && input.Mode != "clear") ||
111新增: (input.Scope != "site" && input.Scope != "all") || len(input.Query) > 800 || input.Page < 0 ||
112新增: ((input.Mode == "delete" || input.Mode == "details") && len(input.CookieKey) != 64)) {
113新增: return nil, browserInputError{errors.New("Cookie 操作或目标标签无效")}
114新增: }
87115 if action == "copy-context" && (input.ID == "" || !validInputToken(input.Context)) {
88116 return nil, browserInputError{errors.New("复制操作或目标标签无效")}
89117 }
@@ -126,6 +154,20 @@ func (s *Server) browserAction(ctx context.Context, action string, input *browse
126154 return nil, browserInputError{err}
127155 }
128156 input.Workspace = guestPath(workspace)
157新增: if s.macosGuest != nil {
158新增: if isClientMountPath(workspace) {
159新增: return nil, browserInputError{errors.New("请先打开并授权本机项目")}
160新增: }
161新增: input.Workspace = filepath.Base(macOSProjectPath(s.macosGuest.User, workspace))
162新增: } else if s.windowsGuest != nil {
163新增: project, err := s.windowsProjectForHost(workspace)
164新增: if err != nil {
165新增: return nil, browserInputError{err}
166新增: }
167新增: input.Workspace = project.Path
168新增: input.ProjectID = project.ID
169新增: input.ProjectGrant = project.Grant
170新增: }
129171 }
130172 body, _ = json.Marshal(input)
131173 }
@@ -161,5 +203,8 @@ func (s *Server) subscribeBrowser(ctx context.Context) (io.ReadCloser, error) {
161203 if !ready {
162204 return nil, errBrowserNotReady
163205 }
206新增: if s.macosGuest != nil || s.windowsGuest != nil {
207新增: return s.subscribeNativeBrowser(ctx), nil
208新增: }
164209 return s.browserClient().events(ctx, token)
165210}
新增internal/workbench/browser_settings.go+114 −0看文件
@@ -0,0 +1,114 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "encoding/json"
5新增: "errors"
6新增: "io"
7新增: "net/http"
8新增: "net/url"
9新增: "path/filepath"
10新增: "strings"
11新增:)
12新增:
13新增:func (s *Server) browserPreferences(w http.ResponseWriter, r *http.Request) {
14新增: if r.Method == http.MethodGet {
15新增: s.mu.Lock()
16新增: home := browserHomeURL(s.preferences)
17新增: s.mu.Unlock()
18新增: jsonReply(w, map[string]string{"browser_home_url": home})
19新增: return
20新增: }
21新增: var input struct {
22新增: Home string `json:"browser_home_url"`
23新增: }
24新增: if !readJSON(w, r, &input) {
25新增: return
26新增: }
27新增: home := strings.TrimSpace(input.Home)
28新增: parsed, err := url.Parse(home)
29新增: if err != nil || len(home) > 8192 || parsed == nil || (parsed.Scheme != "https" && parsed.Scheme != "http") || parsed.Hostname() == "" || parsed.User != nil {
30新增: requestError(w, errors.New("新标签页地址必须是完整的 HTTP 或 HTTPS 网址,且不能包含用户名或密码"))
31新增: return
32新增: }
33新增: if !s.op.TryLock() {
34新增: http.Error(w, "环境正在执行其他操作,请稍后保存", http.StatusConflict)
35新增: return
36新增: }
37新增: defer s.op.Unlock()
38新增: s.mu.Lock()
39新增: previous, ready, token, closing := s.preferences, s.ready, s.credentials.Token, s.closing
40新增: s.mu.Unlock()
41新增: if closing {
42新增: http.Error(w, "服务正在关闭", http.StatusServiceUnavailable)
43新增: return
44新增: }
45新增: if ready {
46新增: if err = s.setBrowserHome(r.Context(), token, home); err != nil {
47新增: requestError(w, err)
48新增: return
49新增: }
50新增: }
51新增: next := previous
52新增: next.BrowserHomeURL = home
53新增: if err = writePrivate(filepath.Join(s.profile, "workbench.json"), next); err != nil {
54新增: if ready {
55新增: _ = s.setBrowserHome(r.Context(), token, browserHomeURL(previous))
56新增: }
57新增: requestError(w, errors.New("保存浏览器设置失败,请重试"))
58新增: return
59新增: }
60新增: s.mu.Lock()
61新增: s.preferences = next
62新增: s.mu.Unlock()
63新增: jsonReply(w, map[string]string{"browser_home_url": home})
64新增:}
65新增:
66新增:func (s *Server) browserExtensionUpload(w http.ResponseWriter, r *http.Request) {
67新增: const limit = 32 << 20
68新增: if r.ContentLength > limit {
69新增: http.Error(w, "扩展 ZIP 不能超过 32 MB", 413)
70新增: return
71新增: }
72新增: s.mu.Lock()
73新增: ready, token := s.ready, s.credentials.Token
74新增: s.mu.Unlock()
75新增: if !ready {
76新增: http.Error(w, "环境尚未就绪", 409)
77新增: return
78新增: }
79新增: r.Body = http.MaxBytesReader(w, r.Body, limit)
80新增: if s.macosGuest != nil || s.windowsGuest != nil {
81新增: data, err := s.nativeBrowserClient().uploadExtension(r.Context(), r.Body, r.ContentLength)
82新增: if err != nil {
83新增: requestError(w, err)
84新增: return
85新增: }
86新增: w.Header().Set("Content-Type", "application/json")
87新增: _, _ = w.Write(data)
88新增: return
89新增: }
90新增: response, err := s.browserClient().file(r.Context(), token, http.MethodPost, "/extensions-upload", r.Body, r.ContentLength)
91新增: if err != nil {
92新增: http.Error(w, "扩展上传中断,请重试", http.StatusBadGateway)
93新增: return
94新增: }
95新增: defer response.Body.Close()
96新增: data, err := io.ReadAll(io.LimitReader(response.Body, browserResponseLimit+1))
97新增: if err != nil || len(data) > browserResponseLimit {
98新增: http.Error(w, "扩展包响应无效,请重试", http.StatusBadGateway)
99新增: return
100新增: }
101新增: if response.StatusCode != http.StatusOK {
102新增: var failure struct {
103新增: Error string `json:"error"`
104新增: }
105新增: _ = json.Unmarshal(data, &failure)
106新增: if failure.Error == "" {
107新增: failure.Error = "扩展包读取失败,请选择有效的扩展 ZIP"
108新增: }
109新增: http.Error(w, failure.Error, http.StatusBadRequest)
110新增: return
111新增: }
112新增: w.Header().Set("Content-Type", "application/json")
113新增: _, _ = w.Write(data)
114新增:}
新增internal/workbench/browser_settings_test.go+135 −0看文件
@@ -0,0 +1,135 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "archive/zip"
5新增: "bytes"
6新增: "encoding/json"
7新增: "io"
8新增: "net/http"
9新增: "os"
10新增: "path/filepath"
11新增: "strings"
12新增: "testing"
13新增:)
14新增:
15新增:func TestBrowserPreferencesPatchAndFailure(t *testing.T) {
16新增: s := testServer(t)
17新增: s.ready = true
18新增: s.preferences.ClaudeTerminalCommand = "claude --continue"
19新增: s.preferences.Workspace = t.TempDir()
20新增: var homes []string
21新增: s.browserControl = browserClientForTest(t, s, browserTransport(func(r *http.Request) (*http.Response, error) {
22新增: var input browserInput
23新增: if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
24新增: t.Fatal(err)
25新增: }
26新增: if r.URL.Path != "/homepage" {
27新增: t.Fatalf("unexpected lifecycle operation %s", r.URL.Path)
28新增: }
29新增: homes = append(homes, input.URL)
30新增: return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"ok":true}`)), Header: http.Header{}}, nil
31新增: }))
32新增: response := request(s, "POST", "/api/browser/preferences", s.origin, `{"browser_home_url":"https://example.test/new"}`, true)
33新增: if response.Code != 200 {
34新增: t.Fatal(response.Code, response.Body.String())
35新增: }
36新增: if s.preferences.BrowserHomeURL != "https://example.test/new" || s.preferences.ClaudeTerminalCommand != "claude --continue" {
37新增: t.Fatal("unrelated preferences changed")
38新增: }
39新增: if !s.ready {
40新增: t.Fatal("browser preference stopped environment")
41新增: }
42新增: before := s.preferences
43新增: for _, body := range []string{`{"browser_home_url":"file:///etc/passwd"}`, `{"browser_home_url":"https://user:[email protected]"}`, `{"browser_home_url":"javascript:alert(1)"}`} {
44新增: if w := request(s, "POST", "/api/browser/preferences", s.origin, body, true); w.Code != 400 {
45新增: t.Fatal("invalid URL accepted", w.Code)
46新增: }
47新增: }
48新增: if len(homes) != 1 {
49新增: t.Fatal("invalid URL reached guest")
50新增: }
51新增: if err := os.Remove(filepath.Join(s.profile, "workbench.json")); err != nil {
52新增: t.Fatal(err)
53新增: }
54新增: if err := os.Mkdir(filepath.Join(s.profile, "workbench.json"), 0700); err != nil {
55新增: t.Fatal(err)
56新增: }
57新增: response = request(s, "POST", "/api/browser/preferences", s.origin, `{"browser_home_url":"https://example.test/rejected"}`, true)
58新增: if response.Code == 200 || s.preferences != before {
59新增: t.Fatal("failed write committed preferences")
60新增: }
61新增: if strings.Join(homes, ",") != "https://example.test/new,https://example.test/rejected,https://example.test/new" {
62新增: t.Fatal("guest homepage was not rolled back", homes)
63新增: }
64新增: s.account.lock()
65新增: if w := request(s, "GET", "/api/browser/preferences", "", "", true); w.Code != 423 {
66新增: t.Fatal("locked preferences accessible")
67新增: }
68新增:}
69新增:
70新增:func TestLocalExtensionImportCopiesProgramOnly(t *testing.T) {
71新增: root := t.TempDir()
72新增: profile := filepath.Join(root, "Default")
73新增: id := strings.Repeat("a", 32)
74新增: directory := filepath.Join(profile, "Extensions", id, "1.0_0")
75新增: if err := os.MkdirAll(directory, 0700); err != nil {
76新增: t.Fatal(err)
77新增: }
78新增: write := func(path, body string) {
79新增: t.Helper()
80新增: if err := os.WriteFile(path, []byte(body), 0600); err != nil {
81新增: t.Fatal(err)
82新增: }
83新增: }
84新增: write(filepath.Join(root, "Local State"), `{"profile":{"info_cache":{"Default":{"name":"工作配置"}}}}`)
85新增: write(filepath.Join(profile, "Secure Preferences"), `{"extensions":{"settings":{"`+id+`":{"state":1,"path":"`+id+`/1.0_0"}}}}`)
86新增: write(filepath.Join(directory, "manifest.json"), `{"manifest_version":3,"name":"Test extension","version":"1.0","permissions":["storage"],"content_scripts":[{"matches":["https://example.test/*"],"js":["main.js"]}]}`)
87新增: write(filepath.Join(directory, "main.js"), `globalThis.testExtension=true`)
88新增: write(filepath.Join(profile, "Cookies"), "PRIVATE_COOKIE_FIXTURE")
89新增: write(filepath.Join(profile, "Preferences"), `{"unrelated_secret":"PRIVATE_PROFILE_FIXTURE"}`)
90新增: profiles := scanLocalBrowserProfiles([]localBrowserRoot{{"Edge", root}})
91新增: if len(profiles) != 1 || profiles[0].Name != "工作配置" || len(profiles[0].Extensions) != 1 {
92新增: t.Fatalf("scan: %+v", profiles)
93新增: }
94新增: extension := profiles[0].Extensions[0]
95新增: if !extension.Enabled || !extension.StateKnown || !extension.Compatible || len(extension.HostPermissions) != 1 {
96新增: t.Fatal("import metadata", extension)
97新增: }
98新增: encoded, _ := json.Marshal(profiles)
99新增: if bytes.Contains(encoded, []byte(root)) || bytes.Contains(encoded, []byte("PRIVATE_")) {
100新增: t.Fatal("inventory exposed filesystem path or profile data")
101新增: }
102新增: data, err := packageLocalExtension(extension)
103新增: if err != nil {
104新增: t.Fatal(err)
105新增: }
106新增: archive, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
107新增: if err != nil {
108新增: t.Fatal(err)
109新增: }
110新增: if len(archive.File) != 2 {
111新增: t.Fatalf("unexpected packaged files: %d", len(archive.File))
112新增: }
113新增: for _, file := range archive.File {
114新增: if file.Name != "manifest.json" && file.Name != "main.js" {
115新增: t.Fatal("unexpected file", file.Name)
116新增: }
117新增: }
118新增:}
119新增:
120新增:func TestImportedExtensionStates(t *testing.T) {
121新增: enabled, disabled := 1, 0
122新增: for _, tc := range []struct {
123新增: state *int
124新增: reasons string
125新增: enabled, known bool
126新增: }{
127新增: {nil, `[]`, true, true}, {nil, `["1"]`, false, true}, {nil, `0`, true, true}, {nil, `8`, false, true},
128新增: {&enabled, ``, true, true}, {&disabled, ``, false, true}, {nil, ``, false, false}, {&disabled, `[]`, false, true},
129新增: } {
130新增: actual, known := importedExtensionState(tc.state, json.RawMessage(tc.reasons))
131新增: if actual != tc.enabled || known != tc.known {
132新增: t.Fatalf("state %v reasons %q = %v,%v", tc.state, tc.reasons, actual, known)
133新增: }
134新增: }
135新增:}
新增internal/workbench/browser_ssh.go+69 −0看文件
@@ -0,0 +1,69 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "context"
5新增: "io"
6新增: "net"
7新增: "sync"
8新增:)
9新增:
10新增:// Browser control goes through this instance's authenticated SSH connection.
11新增:// It never relies on a host port that another application or VM can occupy.
12新增:func (s *Server) dialGuestBrowser(ctx context.Context, lifetime context.Context) (net.Conn, error) {
13新增: if err := ctx.Err(); err != nil {
14新增: return nil, err
15新增: }
16新增: processContext, cancel := context.WithCancel(lifetime)
17新增: cmd := s.sshCommand(processContext, "-T", "-W", "127.0.0.1:18500", s.sshTarget())
18新增: input, err := cmd.StdinPipe()
19新增: if err != nil {
20新增: cancel()
21新增: return nil, err
22新增: }
23新增: output, err := cmd.StdoutPipe()
24新增: if err != nil {
25新增: input.Close()
26新增: cancel()
27新增: return nil, err
28新增: }
29新增: local, remote := net.Pipe()
30新增: conn := &browserSSHConnection{Conn: local, cancel: cancel}
31新增: stop := context.AfterFunc(ctx, func() { _ = conn.Close() })
32新增: defer stop()
33新增: if err := cmd.Start(); err != nil {
34新增: conn.Close()
35新增: remote.Close()
36新增: input.Close()
37新增: output.Close()
38新增: return nil, err
39新增: }
40新增: written := make(chan struct{})
41新增: go func() {
42新增: defer close(written)
43新增: _, _ = io.Copy(input, remote)
44新增: _ = input.Close()
45新增: }()
46新增: go func() {
47新增: _, _ = io.Copy(remote, output)
48新增: _ = remote.Close()
49新增: cancel()
50新增: <-written
51新增: _ = cmd.Wait()
52新增: }()
53新增: if err := ctx.Err(); err != nil {
54新增: conn.Close()
55新增: return nil, err
56新增: }
57新增: return conn, nil
58新增:}
59新增:
60新增:type browserSSHConnection struct {
61新增: net.Conn
62新增: cancel context.CancelFunc
63新增: once sync.Once
64新增:}
65新增:
66新增:func (c *browserSSHConnection) Close() error {
67新增: c.once.Do(c.cancel)
68新增: return c.Conn.Close()
69新增:}
新增internal/workbench/browser_ssh_test.go+130 −0看文件
@@ -0,0 +1,130 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "context"
5新增: "crypto/ed25519"
6新增: "crypto/rand"
7新增: "fmt"
8新增: "io"
9新增: "net"
10新增: "net/http"
11新增: "net/http/httptest"
12新增: "os"
13新增: "path/filepath"
14新增: "sync/atomic"
15新增: "testing"
16新增: "time"
17新增:
18新增: "golang.org/x/crypto/ssh"
19新增:)
20新增:
21新增:func TestBrowserUsesInstanceSSHWithHostPortOccupied(t *testing.T) {
22新增: var leaked atomic.Bool
23新增: unrelated := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
24新增: leaked.Store(true)
25新增: http.Error(w, "unrelated application", http.StatusForbidden)
26新增: }))
27新增: defer unrelated.Close()
28新增: streamClosed := make(chan struct{})
29新增: guest := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
30新增: if r.Header.Get("Authorization") != "Bearer isolated-test-token" {
31新增: t.Error("guest request lost authentication")
32新增: }
33新增: if r.URL.Path == "/events" {
34新增: w.(http.Flusher).Flush()
35新增: <-r.Context().Done()
36新增: close(streamClosed)
37新增: return
38新增: }
39新增: _, _ = io.WriteString(w, `{"ok":true}`)
40新增: }))
41新增: defer guest.Close()
42新增: listener, err := net.Listen("tcp", "127.0.0.1:0")
43新增: if err != nil {
44新增: t.Fatal(err)
45新增: }
46新增: defer listener.Close()
47新增: _, key, _ := ed25519.GenerateKey(rand.Reader)
48新增: signer, _ := ssh.NewSignerFromKey(key)
49新增: config := &ssh.ServerConfig{NoClientAuth: true}
50新增: config.AddHostKey(signer)
51新增: var connections atomic.Int32
52新增: go func() {
53新增: for {
54新增: conn, err := listener.Accept()
55新增: if err != nil {
56新增: return
57新增: }
58新增: go func() {
59新增: server, channels, requests, err := ssh.NewServerConn(conn, config)
60新增: if err != nil {
61新增: conn.Close()
62新增: return
63新增: }
64新增: defer server.Close()
65新增: connections.Add(1)
66新增: go ssh.DiscardRequests(requests)
67新增: for incoming := range channels {
68新增: var target struct {
69新增: Host string
70新增: Port uint32
71新增: Origin string
72新增: OriginPort uint32
73新增: }
74新增: if incoming.ChannelType() != "direct-tcpip" || ssh.Unmarshal(incoming.ExtraData(), &target) != nil || target.Host != "127.0.0.1" || target.Port != 18500 {
75新增: _ = incoming.Reject(ssh.Prohibited, "unexpected destination")
76新增: continue
77新增: }
78新增: channel, requests, err := incoming.Accept()
79新增: if err != nil {
80新增: return
81新增: }
82新增: go ssh.DiscardRequests(requests)
83新增: remote, err := net.Dial("tcp", guest.Listener.Addr().String())
84新增: if err != nil {
85新增: channel.Close()
86新增: return
87新增: }
88新增: go func() { _, _ = io.Copy(remote, channel); remote.Close(); channel.Close() }()
89新增: go func() { _, _ = io.Copy(channel, remote); remote.Close(); channel.Close() }()
90新增: }
91新增: }()
92新增: }
93新增: }()
94新增: s := testServer(t)
95新增: dir := s.instanceDir()
96新增: if err := os.MkdirAll(dir, 0700); err != nil {
97新增: t.Fatal(err)
98新增: }
99新增: sshConfig := fmt.Sprintf("Host *\n HostName 127.0.0.1\n Port %d\n User cage\n StrictHostKeyChecking no\n UserKnownHostsFile %s\n", listener.Addr().(*net.TCPAddr).Port, os.DevNull)
100新增: if err := os.WriteFile(filepath.Join(dir, "ssh.config"), []byte(sshConfig), 0600); err != nil {
101新增: t.Fatal(err)
102新增: }
103新增: client := s.browserClient()
104新增: defer client.close()
105新增: // Model an occupied host port at the socket boundary without binding or
106新增: // contacting an existing host service. The production SSH dialer ignores
107新增: // this host address; the old TCP dialer reaches the unrelated application.
108新增: transport := client.http.Transport.(*http.Transport)
109新增: dial := transport.DialContext
110新增: transport.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) {
111新增: return dial(ctx, network, unrelated.Listener.Addr().String())
112新增: }
113新增: ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
114新增: defer cancel()
115新增: data, err := client.request(ctx, "isolated-test-token", http.MethodGet, "/tabs", nil)
116新增: if err != nil || string(data) != `{"ok":true}` || connections.Load() == 0 || leaked.Load() {
117新增: t.Fatalf("browser did not use instance SSH: data=%q err=%v SSH=%d host-port-contacted=%t", data, err, connections.Load(), leaked.Load())
118新增: }
119新增: body, err := client.events(ctx, "isolated-test-token")
120新增: if err != nil {
121新增: t.Fatal(err)
122新增: }
123新增: client.close()
124新增: body.Close()
125新增: select {
126新增: case <-streamClosed:
127新增: case <-time.After(3 * time.Second):
128新增: t.Fatal("SSH browser subscription survived client closure")
129新增: }
130新增:}
修改internal/workbench/browser_workspaces.go+46 −4看文件
@@ -34,6 +34,20 @@ func (s *Server) browserStateForHost(body []byte) ([]byte, error) {
3434 if json.Unmarshal(encoded, &item) != nil {
3535 continue
3636 }
37新增: if s.macosGuest != nil || s.windowsGuest != nil {
38新增: item.Target = "browser"
39新增: mapped := s.nativeDownloadForHost(item)
40新增: record["name"], _ = json.Marshal(mapped.Name)
41新增: record["path"], _ = json.Marshal(mapped.Path)
42新增: record["state"], _ = json.Marshal(mapped.State)
43新增: record["retryable"], _ = json.Marshal(mapped.Retryable)
44新增: delete(record, "error")
45新增: if mapped.Error != "" {
46新增: record["error"], _ = json.Marshal(mapped.Error)
47新增: }
48新增: downloadsChanged = true
49新增: continue
50新增: }
3751 if item.State != "saved" || !browserFileID.MatchString(item.ID) || !browserDownloadName(item.Name) || item.Path != guestPath(filepath.Join(root, "Downloads", item.Name)) {
3852 continue
3953 }
@@ -46,8 +60,18 @@ func (s *Server) browserStateForHost(body []byte) ([]byte, error) {
4660 downloadsChanged = true
4761 }
4862 }
63新增: if s.macosGuest != nil || s.windowsGuest != nil {
64新增: visible := make(map[string]bool, len(downloads))
65新增: for _, record := range downloads {
66新增: var id string
67新增: if json.Unmarshal(record["id"], &id) == nil {
68新增: visible[id] = true
69新增: }
70新增: }
71新增: s.discardMissingNativeDownloads("browser", visible)
72新增: }
4973 }
50删除: if !paths.Windows() {
74新增: if !paths.Windows() && s.windowsGuest == nil && s.macosGuest == nil {
5175 return body, nil
5276 }
5377 var tabs []map[string]json.RawMessage
@@ -60,7 +84,24 @@ func (s *Server) browserStateForHost(body []byte) ([]byte, error) {
6084 }
6185 byGuest := make(map[string]string, len(authorized))
6286 for _, hostPath := range authorized {
63删除: byGuest[guestPath(hostPath)] = hostPath
87新增: if s.macosGuest != nil {
88新增: byGuest[macOSProjectPath(s.macosGuest.User, hostPath)] = hostPath
89新增: } else {
90新增: byGuest[guestPath(hostPath)] = hostPath
91新增: }
92新增: }
93新增: if s.windowsGuest != nil {
94新增: allowed := map[string]bool{}
95新增: for _, hostPath := range authorized {
96新增: allowed[hostPath] = true
97新增: }
98新增: s.mu.Lock()
99新增: for guestPath, hostPath := range s.windowsProjectHistory {
100新增: if allowed[hostPath] {
101新增: byGuest[guestPath] = hostPath
102新增: }
103新增: }
104新增: s.mu.Unlock()
64105 }
65106 changed := downloadsChanged
66107 for _, tab := range tabs {
@@ -102,8 +143,9 @@ func (s *Server) writeBrowserEvents(ctx context.Context, w http.ResponseWriter,
102143 if bytes.HasPrefix(line, []byte("event: ")) {
103144 eventName = string(line[len("event: "):])
104145 }
105删除: // Clipboard notifications are one-shot payloads, not tab snapshots.
106删除: if bytes.HasPrefix(line, []byte("data: ")) && eventName != "clipboard" {
146新增: // Named notifications retain their own payload and sequence. Only
147新增: // ordinary message events contain a browser state snapshot.
148新增: if bytes.HasPrefix(line, []byte("data: ")) && eventName == "" {
107149 mapped, err := s.browserStateForHost(line[len("data: "):])
108150 if err != nil {
109151 return err
新增internal/workbench/claude_account_resume.md+10 −0看文件
@@ -0,0 +1,10 @@
1新增:Continue the unfinished part of the user's latest task from this saved history.
2新增:
3新增:The user authorized continuation with another account. Keep completed work and
4新增:recorded tool results. Check the existing files and results before deciding what
5新增:remains. Do not repeat completed commands or external actions. If an earlier
6新增:tool's outcome is uncertain, verify its outcome before attempting it again.
7新增:
8新增:Pending tool permissions do not transfer. Obtain any required permission through
9新增:this execution's normal approval flow. If the latest task is complete, report its
10新增:result without starting new work.
修改internal/workbench/claude_accounts.go+51 −5看文件
@@ -30,6 +30,7 @@ type claudeAccount struct {
3030 Email string `json:"email,omitempty"`
3131 Organization string `json:"organization,omitempty"`
3232 Plan string `json:"plan,omitempty"`
33新增: HandoffGroup string `json:"handoff_group,omitempty"`
3334 Quota *claudeQuota `json:"quota,omitempty"`
3435 CheckedAt int64 `json:"checked_at,omitempty"`
3536 UsageStatus string `json:"usage_status,omitempty"`
@@ -60,8 +61,28 @@ type claudeGuestSnapshot struct {
6061}
6162
6263type claudeAccountList struct {
63删除: Accounts []claudeAccount `json:"accounts"`
64删除: PendingLogin string `json:"pending_login,omitempty"`
64新增: Accounts []claudeAccount `json:"accounts"`
65新增: PendingLogin string `json:"pending_login,omitempty"`
66新增: Scheduling claudeScheduling `json:"scheduling"`
67新增:}
68新增:
69新增:type claudeScheduling struct {
70新增: Mode string `json:"mode"`
71新增: SwitchPolicy string `json:"switch_policy"`
72新增:}
73新增:
74新增:func (p claudeScheduling) defaults() claudeScheduling {
75新增: if p.Mode == "" {
76新增: p.Mode = "balanced"
77新增: }
78新增: if p.SwitchPolicy == "" {
79新增: p.SwitchPolicy = "ask"
80新增: }
81新增: return p
82新增:}
83新增:
84新增:func (p claudeScheduling) valid() bool {
85新增: return (p.Mode == "balanced" || p.Mode == "sequential") && (p.SwitchPolicy == "ask" || p.SwitchPolicy == "allow" || p.SwitchPolicy == "wait")
6586}
6687
6788type claudeAccountManager struct {
@@ -96,7 +117,7 @@ func validClaudeID(id string) bool {
96117}
97118
98119func (s *Server) loadClaudeAccounts() (claudeAccountList, error) {
99删除: list := claudeAccountList{Accounts: []claudeAccount{}}
120新增: list := claudeAccountList{Accounts: []claudeAccount{}, Scheduling: (claudeScheduling{}).defaults()}
100121 data, err := os.ReadFile(filepath.Join(s.profile, "claude-accounts.json"))
101122 if os.IsNotExist(err) {
102123 return list, nil
@@ -104,6 +125,10 @@ func (s *Server) loadClaudeAccounts() (claudeAccountList, error) {
104125 if err != nil || json.Unmarshal(data, &list) != nil || list.Accounts == nil {
105126 return list, errors.New("Claude 账号文件无法读取,请检查配置目录或恢复备份")
106127 }
128新增: list.Scheduling = list.Scheduling.defaults()
129新增: if !list.Scheduling.valid() {
130新增: return list, errors.New("Claude 调度设置无效,请检查配置文件")
131新增: }
107132 ids := make(map[string]bool)
108133 profiles := make(map[string]bool)
109134 for i := range list.Accounts {
@@ -111,7 +136,7 @@ func (s *Server) loadClaudeAccounts() (claudeAccountList, error) {
111136 if a.Source == "" {
112137 a.Source = "managed"
113138 }
114删除: if !validClaudeID(a.ID) || ids[a.ID] || a.Source != "managed" && a.Source != "default" || a.Source == "default" && (a.Email == "" || a.ProfileID != "") || a.ProfileID != "" && !validClaudeID(a.ProfileID) {
139新增: if !validClaudeID(a.ID) || ids[a.ID] || a.Source != "managed" && a.Source != "default" || a.Source == "default" && (a.Email == "" || a.ProfileID != "") || a.ProfileID != "" && !validClaudeID(a.ProfileID) || len(a.HandoffGroup) > 64 {
115140 return list, errors.New("Claude 账号文件含无效或重复的记录,请从备份恢复")
116141 }
117142 ids[a.ID] = true
@@ -176,6 +201,13 @@ func (list *claudeAccountList) change(input claudeAccountInput) error {
176201 if input.Enabled != nil {
177202 a.Enabled = *input.Enabled
178203 }
204新增: if input.HandoffGroup != nil {
205新增: group := strings.TrimSpace(*input.HandoffGroup)
206新增: if len(group) > 64 || strings.IndexFunc(group, unicode.IsControl) >= 0 {
207新增: return errors.New("接续分组最多 64 字节,不能含控制字符")
208新增: }
209新增: a.HandoffGroup = group
210新增: }
179211 return nil
180212}
181213
@@ -360,6 +392,12 @@ func (s *Server) readClaudeGuestQuotas(ctx context.Context, ids []string) (map[s
360392 // server-controlled deadline; keep completed chunks when a later one fails.
361393 readings := make(map[string]claudeGuestQuota)
362394 for chunk := range slices.Chunk(ids, 96) {
395新增: if s.windowsGuest != nil {
396新增: if err := s.windowsCLIRequest(ctx, map[string]any{"action": "account", "mode": "quotas", "ids": chunk}, &readings); err != nil {
397新增: return readings, err
398新增: }
399新增: continue
400新增: }
363401 data, err := s.guest(ctx, "exec /usr/local/bin/cage-claude-account quotas "+strings.Join(chunk, " "))
364402 if err != nil {
365403 return readings, err
@@ -427,7 +465,7 @@ func (s *Server) allocateClaudeAccount(previous claudeAccountList, workspace str
427465 return empty, err
428466 }
429467 }
430删除: active := make(map[string]int)
468新增: active := s.mobileCLI.activeAccounts()
431469 logins := make(map[string]bool)
432470 for _, session := range s.terminals.snapshot() {
433471 if session["closed"] == true {
@@ -463,6 +501,14 @@ func (s *Server) allocateClaudeAccount(previous claudeAccountList, workspace str
463501// Start at the account following the last allocation. Among eligible accounts,
464502// prefer fewer live sessions, then the largest known remaining minimum window.
465503func pickClaudeAccount(list claudeAccountList, active map[string]int, logins map[string]bool, last, preferred string, now time.Time) string {
504新增: if list.Scheduling.Mode == "sequential" {
505新增: for _, a := range list.Accounts {
506新增: if _, eligible := a.headroom(now); a.Enabled && a.Status == "ready" && !logins[a.ID] && eligible {
507新增: return a.ID
508新增: }
509新增: }
510新增: return ""
511新增: }
466512 start := slices.IndexFunc(list.Accounts, func(a claudeAccount) bool { return a.ID == last }) + 1
467513 best := ""
468514 var bestActive int
修改internal/workbench/claude_accounts_discovery.go+9 −7看文件
@@ -22,13 +22,14 @@ type claudeDetected struct {
2222}
2323
2424type claudePanel struct {
25删除: UsagePanelRunning bool `json:"usage_panel_running"`
26删除: UsageUnavailableReason string `json:"usage_unavailable_reason,omitempty"`
27删除: Accounts []claudeAccount `json:"accounts"`
28删除: Detected *claudeDetected `json:"detected,omitempty"`
29删除: DetectionStatus string `json:"detection_status"`
30删除: DetectionError string `json:"detection_error,omitempty"`
31删除: LoginNotice string `json:"login_notice,omitempty"`
25新增: Scheduling claudeScheduling `json:"scheduling"`
26新增: UsagePanelRunning bool `json:"usage_panel_running"`
27新增: UsageUnavailableReason string `json:"usage_unavailable_reason,omitempty"`
28新增: Accounts []claudeAccount `json:"accounts"`
29新增: Detected *claudeDetected `json:"detected,omitempty"`
30新增: DetectionStatus string `json:"detection_status"`
31新增: DetectionError string `json:"detection_error,omitempty"`
32新增: LoginNotice string `json:"login_notice,omitempty"`
3233}
3334
3435func (s *Server) probeClaude(ctx context.Context, guestID string) (claudeGuestSnapshot, error) {
@@ -221,6 +222,7 @@ func (s *Server) claudePanelView(ctx context.Context) (claudePanel, claudeAccoun
221222 return view, list, err
222223 }
223224 view.Accounts, view.LoginNotice = list.Accounts, m.loginNotice
225新增: view.Scheduling = list.Scheduling
224226 view.UsagePanelRunning = m.panelRunning
225227 if subject := reading.subject(); view.DetectionStatus == "ready" && list.bySubject(subject) == nil {
226228 view.Detected = &claudeDetected{Identity: subject, Email: reading.email(), Organization: strings.TrimSpace(reading.Organization), Plan: reading.Plan, Quota: reading.Quota, CheckedAt: checked.Unix()}
修改internal/workbench/claude_accounts_http.go+38 −7看文件
@@ -11,11 +11,14 @@ import (
1111var errClaudeAccessLost = errors.New("Cage 已锁定,请先解锁")
1212
1313type claudeAccountInput struct {
14删除: Action string `json:"action"`
15删除: Identity string `json:"identity"`
16删除: ID string `json:"id"`
17删除: Label string `json:"label"`
18删除: Enabled *bool `json:"enabled"`
14新增: Action string `json:"action"`
15新增: Identity string `json:"identity"`
16新增: ID string `json:"id"`
17新增: Label string `json:"label"`
18新增: Enabled *bool `json:"enabled"`
19新增: HandoffGroup *string `json:"handoff_group"`
20新增: Scheduling *claudeScheduling `json:"scheduling"`
21新增: Order []string `json:"order"`
1922}
2023
2124func (s *Server) listClaudeAccounts(w http.ResponseWriter, r *http.Request) {
@@ -62,12 +65,40 @@ func (s *Server) mutateClaudeAccounts(w http.ResponseWriter, r *http.Request) {
6265 return
6366 case "refresh", "refresh_default":
6467 err = s.refreshClaudeUsage(r.Context(), input)
65删除: case "update":
68新增: case "update", "scheduling":
69新增: s.op.Lock()
70新增: defer s.op.Unlock()
6671 m := &s.claudeAccounts
6772 m.mu.Lock()
6873 list, loadErr := s.loadClaudeAccounts()
6974 err = loadErr
70删除: if err == nil {
75新增: if err == nil && input.Action == "scheduling" {
76新增: if input.Scheduling == nil || !input.Scheduling.valid() {
77新增: err = errors.New("请选择有效的调度模式和切换授权")
78新增: } else {
79新增: list.Scheduling = *input.Scheduling
80新增: }
81新增: if err == nil && input.Order != nil {
82新增: if len(input.Order) != len(list.Accounts) {
83新增: err = errors.New("账号列表已变化,请刷新后排序")
84新增: } else {
85新增: ordered := make([]claudeAccount, 0, len(input.Order))
86新增: seen := map[string]bool{}
87新增: for _, id := range input.Order {
88新增: a := list.find(id)
89新增: if a == nil || seen[id] {
90新增: err = errors.New("账号顺序无效")
91新增: break
92新增: }
93新增: seen[id] = true
94新增: ordered = append(ordered, *a)
95新增: }
96新增: if err == nil {
97新增: list.Accounts = ordered
98新增: }
99新增: }
100新增: }
101新增: } else if err == nil {
71102 err = list.change(input)
72103 }
73104 if err == nil {
修改internal/workbench/claude_desktop.go+90 −34看文件
@@ -11,15 +11,19 @@ import (
1111 "time"
1212
1313 "github.com/sylvinus/agent-vm/internal/cage"
14新增: "github.com/sylvinus/agent-vm/internal/diagnostics"
15新增: "github.com/sylvinus/agent-vm/internal/usererror"
1416)
1517
1618type claudeDesktopState struct {
17删除: Installed bool `json:"installed"`
18删除: Version string `json:"version"`
19删除: Running bool `json:"running"`
20删除: Failed bool `json:"failed"`
21删除: Managed bool `json:"managed"`
22删除: FailureReason string `json:"failure_reason,omitempty"`
19新增: Installed bool `json:"installed"`
20新增: Version string `json:"version"`
21新增: Running bool `json:"running"`
22新增: Failed bool `json:"failed"`
23新增: Managed bool `json:"managed"`
24新增: NativeUserSession bool `json:"native_user_session,omitempty"`
25新增: DisplayScale float64 `json:"display_scale,omitempty"`
26新增: FailureReason string `json:"failure_reason,omitempty"`
2327}
2428
2529const claudeDesktopSnapshot = `python3 - <<'CAGE_DESKTOP_STATE'
@@ -41,10 +45,23 @@ func (s *Server) claudeDesktopStatus(w http.ResponseWriter, r *http.Request) {
4145 }
4246 ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
4347 defer cancel()
44删除: b, err := s.guest(ctx, claudeDesktopSnapshot)
48新增: var b []byte
49新增: var err error
50新增: if s.windowsGuest != nil {
51新增: var result claudeDesktopState
52新增: err = s.windowsDesktopRequest(ctx, "status", nil, &result)
53新增: b, _ = json.Marshal(result)
54新增: } else {
55新增: b, err = s.guest(ctx, claudeDesktopSnapshot)
56新增: }
4557 var state claudeDesktopState
46删除: if err != nil || json.Unmarshal(b, &state) != nil {
47删除: http.Error(w, "无法读取 Claude Desktop 状态,请重试", 502)
58新增: if err != nil {
59新增: _ = diagnostics.New(s.profile).Record("warn", "claude-desktop", fmt.Sprintf("read state: %v", err))
60新增: http.Error(w, usererror.Wrap("读取 Claude Desktop 状态", err, "请确认环境仍在运行;重新连接后再打开应用。持续失败时导出诊断包。").Error(), 502)
61新增: return
62新增: }
63新增: if json.Unmarshal(b, &state) != nil {
64新增: http.Error(w, "读取 Claude Desktop 状态失败:环境返回的应用状态格式无效。请更新环境组件;仍失败时导出诊断包。", 502)
4865 return
4966 }
5067 jsonReply(w, state)
@@ -65,6 +82,12 @@ func (s *Server) claudeDesktopAction(w http.ResponseWriter, r *http.Request) {
6582 return
6683 }
6784 s.launch(w, "claude-desktop-"+action, func() error {
85新增: if s.windowsGuest != nil {
86新增: if action == "install" {
87新增: return errors.New("Windows 客机的自动安装尚未接通,请保留已有官方应用")
88新增: }
89新增: return s.windowsDesktopRequest(s.operationContext(), action, nil, nil)
90新增: }
6891 switch action {
6992 case "install":
7093 s.mu.Lock()
@@ -100,26 +123,7 @@ func (s *Server) claudeDesktopAction(w http.ResponseWriter, r *http.Request) {
100123 s.setMessage("正在下载并安装 Claude Desktop,可在操作详情查看进度…")
101124 return RunMaintenanceScript(s.operationContext(), s.configPath, cage.ClaudeDesktopInstallScript(), s.jobs.execution(), s.jobs.execution())
102125 case "start":
103删除: s.setMessage("正在打开 Claude Desktop…")
104删除: key, err := s.account.desktopKey()
105删除: if err != nil {
106删除: return err
107删除: }
108删除: defer clear(key)
109删除: script := `test "$(dpkg-query -W -f='${Status}' claude-desktop 2>/dev/null)" = 'install ok installed' || { echo '请先安装 Claude Desktop。'; exit 1; }
110删除:` + cage.ClaudeDesktopProvisionScript()
111删除: if err = s.runDesktopScript(script, 20*time.Second); err != nil {
112删除: return err
113删除: }
114删除: ctx, cancel := context.WithTimeout(s.operationContext(), 55*time.Second)
115删除: defer cancel()
116删除: cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", "/usr/local/bin/cage-claude-start")
117删除: cmd.Stdin = bytes.NewReader(key)
118删除: cmd.Stdout, cmd.Stderr = s.jobs.execution(), s.jobs.execution()
119删除: if err = cmd.Run(); err != nil {
120删除: return errors.New("Claude Desktop 未能启动,请查看操作详情;已有登录数据保持不变")
121删除: }
122删除: return nil
126新增: return s.startClaudeDesktop()
123127 default:
124128 s.setMessage("正在关闭 Claude Desktop…")
125129 return s.runDesktopScript("sudo systemctl stop cage-claude-desktop.service", 30*time.Second)
@@ -127,6 +131,29 @@ func (s *Server) claudeDesktopAction(w http.ResponseWriter, r *http.Request) {
127131 })
128132}
129133
134新增:func (s *Server) startClaudeDesktop() error {
135新增: s.setMessage("正在打开 Claude Desktop…")
136新增: key, err := s.account.desktopKey()
137新增: if err != nil {
138新增: return err
139新增: }
140新增: defer clear(key)
141新增: script := `test "$(dpkg-query -W -f='${Status}' claude-desktop 2>/dev/null)" = 'install ok installed' || { echo '请先安装 Claude Desktop。'; exit 1; }
142新增:` + cage.ClaudeDesktopProvisionScript()
143新增: if err = s.runDesktopScript(script, 20*time.Second); err != nil {
144新增: return err
145新增: }
146新增: ctx, cancel := context.WithTimeout(s.operationContext(), 55*time.Second)
147新增: defer cancel()
148新增: cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", "/usr/local/bin/cage-claude-start")
149新增: cmd.Stdin = bytes.NewReader(key)
150新增: cmd.Stdout, cmd.Stderr = s.jobs.execution(), s.jobs.execution()
151新增: if err = cmd.Run(); err != nil {
152新增: return executionFailure("打开 Claude Desktop", errors.Join(ctx.Err(), err), s.jobs.snapshot().Log)
153新增: }
154新增: return nil
155新增:}
156新增:
130157func (s *Server) runDesktopScript(script string, timeout time.Duration) error {
131158 ctx, cancel := context.WithTimeout(s.operationContext(), timeout)
132159 defer cancel()
@@ -143,21 +170,34 @@ func (s *Server) runDesktopScript(script string, timeout time.Duration) error {
143170 _, _ = s.guest(cleanup, "sudo systemctl stop cage-desktop-operation.service")
144171 return ctx.Err()
145172 }
146删除: return errors.New("Claude Desktop 操作未完成,请查看操作详情;安装失败可重试,已有浏览器和终端不受影响")
173新增: return executionFailure("准备或关闭 Claude Desktop", err, s.jobs.snapshot().Log)
147174 }
148175 return nil
149176}
150177
151178func (s *Server) claudeDesktopCredentials(w http.ResponseWriter, r *http.Request) {
179新增: if s.windowsGuest != nil {
180新增: s.windowsDesktopCredentials(w, r)
181新增: return
182新增: }
152183 ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
153184 defer cancel()
154删除: b, err := s.guest(ctx, "systemctl is-active --quiet cage-claude-desktop.service && cat /home/cage/.config/claude-cage/desktop-password")
155删除: password := strings.TrimSpace(string(b))
185新增: b, err := s.guest(ctx, `set -eu
186新增:systemctl is-active --quiet cage-claude-desktop.service
187新增:password=$(cat /home/cage/.config/claude-cage/desktop-password)
188新增:printf '%s\n' "$password"
189新增:if test -f /run/cage-desktop/base-display-scale; then cat /run/cage-desktop/base-display-scale
190新增:elif test -f /run/cage-desktop/display-scale; then cat /run/cage-desktop/display-scale; fi`)
191新增: password, scale, _ := strings.Cut(strings.TrimSpace(string(b)), "\n")
156192 if err != nil || len(password) != 8 {
157193 http.Error(w, "Claude Desktop 尚未启动", 409)
158194 return
159195 }
160删除: jsonReply(w, map[string]string{"password": password})
196新增: density := 2.0
197新增: if scale == "1.5" {
198新增: density = 1.5
199新增: }
200新增: jsonReply(w, map[string]any{"password": password, "display_scale": density})
161201}
162202
163203func (s *Server) claudeDesktopResize(w http.ResponseWriter, r *http.Request) {
@@ -172,12 +212,24 @@ func (s *Server) claudeDesktopResize(w http.ResponseWriter, r *http.Request) {
172212 http.Error(w, "画面尺寸无效", 400)
173213 return
174214 }
215新增: if s.windowsGuest != nil {
216新增: ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
217新增: defer cancel()
218新增: if err := s.windowsDesktopRequest(ctx, "resize", map[string]any{"width": input.Width, "height": input.Height}, nil); err != nil {
219新增: http.Error(w, err.Error(), 502)
220新增: return
221新增: }
222新增: jsonReply(w, map[string]bool{"ok": true})
223新增: return
224新增: }
175225 // Fixed commands and validated integers only; no host shell executes input.
176226 wid, hei := input.Width, input.Height
177227 script := fmt.Sprintf(`set -eu
178228export DISPLAY=:78 XAUTHORITY=/run/cage-desktop/Xauthority
179229exec 9>/run/cage-desktop/resize.lock
180230flock 9
231新增:printf '%%s %%s\n' %d %d > /run/cage-desktop/desktop-size
232新增:if test -f /run/cage-phone-desktop/layout.json; then exit 0; fi
181233name=cage-%dx%d
182234if ! xrandr --query | grep -q " $name "; then
183235 xrandr --newmode "$name" %.3f %d %d %d %d %d %d %d %d +HSync -VSync
@@ -186,7 +238,7 @@ fi
186238xrandr --output VNC-0 --mode "$name"
187239for old in $(xrandr --query | awk '/^ +cage-/ {print $1}'); do
188240 if [ "$old" != "$name" ]; then xrandr --delmode VNC-0 "$old"; xrandr --rmmode "$old"; fi
189删除:done`, wid, hei, float64((wid+32)*(hei+8)*60)/1000000, wid, wid+8, wid+16, wid+32, hei, hei+1, hei+2, hei+8)
241新增:done`, wid, hei, wid, hei, float64((wid+32)*(hei+8)*60)/1000000, wid, wid+8, wid+16, wid+32, hei, hei+1, hei+2, hei+8)
190242 ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
191243 defer cancel()
192244 if _, err := s.guest(ctx, script); err != nil {
@@ -197,6 +249,10 @@ done`, wid, hei, float64((wid+32)*(hei+8)*60)/1000000, wid, wid+8, wid+16, wid+3
197249}
198250
199251func (s *Server) claudeDesktopVNC(w http.ResponseWriter, r *http.Request) {
252新增: if s.windowsGuest != nil {
253新增: s.windowsDesktopVNC(w, r)
254新增: return
255新增: }
200256 if !s.vmRunning() {
201257 http.Error(w, "环境尚未启动", 409)
202258 return
新增internal/workbench/claude_handoff_cli_test.go+134 −0看文件
@@ -0,0 +1,134 @@
1新增://go:build !windows
2新增:
3新增:package workbench
4新增:
5新增:import (
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.
26新增:func 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新增:}
新增internal/workbench/claude_scheduling_test.go+102 −0看文件
@@ -0,0 +1,102 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "context"
5新增: "encoding/json"
6新增: "strings"
7新增: "testing"
8新增: "time"
9新增:)
10新增:
11新增:func TestClaudeAutomaticSwitchRequiresQuotaAndConsent(t *testing.T) {
12新增: s, id, _ := metadataFixture(t)
13新增: s.ready = true
14新增: a, b := strings.Repeat("a", 24), strings.Repeat("b", 24)
15新增: list := claudeAccountList{Accounts: []claudeAccount{{ID: a, Label: "A", Email: "[email protected]", Enabled: true, Status: "ready", HandoffGroup: "personal"}, {ID: b, Label: "B", Email: "[email protected]", Enabled: true, Status: "ready", HandoffGroup: "personal"}}}
16新增: if err := s.saveClaudeAccounts(list); err != nil {
17新增: t.Fatal(err)
18新增: }
19新增: record, _ := s.mobileCLI.record(s.profile, id)
20新增: record.Launcher = "claude"
21新增: record.Account = claudeSelection{a, a, claudeIdentityHash("[email protected]", "")}
22新增: epoch, _ := s.account.access()
23新增: ctx := context.WithValue(context.Background(), mobileEpochKey{}, epoch)
24新增: for _, scenario := range []struct{ policy, failure, reason string }{{"ask", "rate_limit", "手动确认"}, {"allow", "overloaded", "手动确认"}, {"allow", "rate_limit", "尚未确认"}} {
25新增: record.SwitchPolicy, record.AccountFailure = scenario.policy, scenario.failure
26新增: if err := writePrivate(mobileRecordPath(s.profile, id), record); err != nil {
27新增: t.Fatal(err)
28新增: }
29新增: err := s.switchClaudeAccount(ctx, id, claudeSwitchInput{SourceID: record.CLIID, Target: b}, true)
30新增: if err == nil || !strings.Contains(err.Error(), scenario.reason) {
31新增: t.Fatal(scenario, err)
32新增: }
33新增: stored, _ := s.mobileCLI.record(s.profile, id)
34新增: if stored.Switch != nil || stored.Account.ID != a {
35新增: t.Fatal("preflight changed ownership")
36新增: }
37新增: }
38新增:}
39新增:
40新增:func TestClaudeSchedulingModesAndPersistence(t *testing.T) {
41新增: s := testServer(t)
42新增: a, b := strings.Repeat("a", 24), strings.Repeat("b", 24)
43新增: list := claudeAccountList{Accounts: []claudeAccount{{ID: a, Label: "A", Enabled: true, Status: "ready", Email: "[email protected]"}, {ID: b, Label: "B", Enabled: true, Status: "ready", Email: "[email protected]"}}}
44新增: if err := s.saveClaudeAccounts(list); err != nil {
45新增: t.Fatal(err)
46新增: }
47新增: loaded, err := s.loadClaudeAccounts()
48新增: if err != nil || loaded.Scheduling.Mode != "balanced" || loaded.Scheduling.SwitchPolicy != "ask" {
49新增: t.Fatal("legacy defaults", loaded, err)
50新增: }
51新增: if id := pickClaudeAccount(loaded, map[string]int{a: 2}, nil, "", "", time.Now()); id != b {
52新增: t.Fatal("balance ignored occupancy", id)
53新增: }
54新增: response := request(s, "POST", "/api/claude-accounts", s.origin, `{"action":"scheduling","scheduling":{"mode":"sequential","switch_policy":"allow"},"order":["`+b+`","`+a+`"]}`, true)
55新增: if response.Code != 200 {
56新增: t.Fatal(response.Code, response.Body.String())
57新增: }
58新增: loaded, err = s.loadClaudeAccounts()
59新增: if err != nil || loaded.Scheduling.Mode != "sequential" || loaded.Accounts[0].ID != b {
60新增: t.Fatal(loaded, err)
61新增: }
62新增: if id := pickClaudeAccount(loaded, map[string]int{b: 3}, nil, "", "", time.Now()); id != b {
63新增: t.Fatal("sequential did not keep priority", id)
64新增: }
65新增: loaded.Accounts[0].Quota = &claudeQuota{FiveHour: &claudeWindow{UsedPercentage: 100, ResetsAt: time.Now().Add(time.Hour).Unix(), ObservedAt: time.Now().Unix()}}
66新增: if id := pickClaudeAccount(loaded, nil, nil, "", "", time.Now()); id != a {
67新增: t.Fatal("exhausted account selected", id)
68新增: }
69新增: response = request(s, "POST", "/api/claude-accounts", s.origin, `{"action":"scheduling","scheduling":{"mode":"sequential","switch_policy":"allow"},"order":["`+b+`","`+b+`"]}`, true)
70新增: if response.Code == 200 {
71新增: t.Fatal("duplicate order accepted")
72新增: }
73新增:}
74新增:
75新增:func TestClaudeSwitchGroupAndDurableBinding(t *testing.T) {
76新增: a, b := strings.Repeat("a", 24), strings.Repeat("b", 24)
77新增: list := claudeAccountList{Accounts: []claudeAccount{{ID: a, Label: "A", Email: "[email protected]", Enabled: true, Status: "ready"}, {ID: b, Label: "B", Email: "[email protected]", Enabled: true, Status: "ready"}}}
78新增: record := &mobileRecord{Account: claudeSelection{ID: a, GuestID: a, Subject: claudeIdentityHash("[email protected]", "")}}
79新增: if len(switchCandidates(list, record)) != 0 {
80新增: t.Fatal("ungrouped history escaped")
81新增: }
82新增: for i := range list.Accounts {
83新增: list.Accounts[i].HandoffGroup = "personal"
84新增: }
85新增: if got := switchCandidates(list, record); len(got) != 1 || got[0].ID != b {
86新增: t.Fatal(got)
87新增: }
88新增: list.Accounts[1].HandoffGroup = "company"
89新增: if len(switchCandidates(list, record)) != 0 {
90新增: t.Fatal("organization boundary escaped")
91新增: }
92新增: list.Accounts[1].HandoffGroup = "personal"
93新增: record.Account.Subject = "changed"
94新增: if len(switchCandidates(list, record)) != 0 {
95新增: t.Fatal("stale source identity accepted")
96新增: }
97新增: record.Switch = &claudeAccountSwitch{ID: "receipt", Phase: "starting", Source: claudeExecution{Config: "private-config"}, Target: claudeSelection{Subject: "private-subject"}}
98新增: raw, _ := json.Marshal(record.snapshot())
99新增: if strings.Contains(string(raw), "private-") {
100新增: t.Fatal("internal authentication binding exposed", string(raw))
101新增: }
102新增:}
新增internal/workbench/claude_switch.go+471 −0看文件
@@ -0,0 +1,471 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "context"
5新增: "errors"
6新增: "net/http"
7新增: "strings"
8新增: "time"
9新增:
10新增: "github.com/google/uuid"
11新增:)
12新增:
13新增:type claudeSwitchInput struct {
14新增: Action string `json:"action"`
15新增: Policy string `json:"policy"`
16新增: Target string `json:"target"`
17新增: RequestID string `json:"request_id"`
18新增: SourceID string `json:"source_id"`
19新增: Confirm bool `json:"confirm"`
20新增: Continue bool `json:"continue"`
21新增:}
22新增:
23新增:type claudeSwitchOption struct {
24新增: ID string `json:"id"`
25新增: Label string `json:"label"`
26新增:}
27新增:
28新增:func validSwitchPolicy(policy string) bool {
29新增: return policy == "ask" || policy == "allow" || policy == "wait"
30新增:}
31新增:
32新增:// Explicit groups prevent a work transcript from silently moving to a personal
33新增:// identity. Empty groups never authorize a cross-account transfer.
34新增:func switchCandidates(list claudeAccountList, record *mobileRecord) []claudeSwitchOption {
35新增: options := []claudeSwitchOption{}
36新增: source := list.find(record.Account.ID)
37新增: if source == nil || source.HandoffGroup == "" || source.guestID() != record.Account.GuestID || claudeIdentityHash(source.Email, source.Organization) != record.Account.Subject {
38新增: return options
39新增: }
40新增: for _, a := range list.Accounts {
41新增: _, available := a.headroom(time.Now())
42新增: if a.ID != source.ID && a.Enabled && a.Status == "ready" && a.HandoffGroup == source.HandoffGroup && available {
43新增: options = append(options, claudeSwitchOption{a.ID, a.Label})
44新增: }
45新增: }
46新增: return options
47新增:}
48新增:
49新增:func (s *Server) mobileSessionAccount(w http.ResponseWriter, r *http.Request) {
50新增: view, terminal, ok := s.authorizedMobileSessionRecord(w, r)
51新增: if !ok {
52新增: return
53新增: }
54新增: var input claudeSwitchInput
55新增: if !readJSON(w, r, &input) {
56新增: return
57新增: }
58新增: if input.Action == "switch" {
59新增: if !input.Confirm || !mobileID(input.RequestID) || !validCLIUUID(input.SourceID) {
60新增: http.Error(w, "请确认本次账号接续并提供当前会话标识", 400)
61新增: return
62新增: }
63新增: if err := s.switchClaudeAccount(r.Context(), view.ID, input, false); err != nil {
64新增: http.Error(w, err.Error(), 409)
65新增: return
66新增: }
67新增: } else if input.Action == "cancel" {
68新增: if err := s.cancelClaudeSwitch(r.Context(), view.ID, input.RequestID); err != nil {
69新增: http.Error(w, err.Error(), 409)
70新增: return
71新增: }
72新增: } else if input.Action == "policy" {
73新增: if !validSwitchPolicy(input.Policy) {
74新增: http.Error(w, "切换授权无效", 400)
75新增: return
76新增: }
77新增: if !s.op.TryLock() {
78新增: http.Error(w, errTerminalBusy.Error(), 409)
79新增: return
80新增: }
81新增: defer s.op.Unlock()
82新增: s.account.mu.Lock()
83新增: if !s.mobileAuthorized(r.Context()) {
84新增: s.account.mu.Unlock()
85新增: http.Error(w, errMobileLocked.Error(), 423)
86新增: return
87新增: }
88新增: s.mobileCLI.mu.Lock()
89新增: record, err := s.mobileCLI.record(s.profile, view.ID)
90新增: if err == nil {
91新增: if record.Switch != nil && record.Switch.Phase != "completed" {
92新增: err = errors.New("账号交接中,请等待完成后修改授权")
93新增: } else {
94新增: record.SwitchPolicy = input.Policy
95新增: record.changed()
96新增: err = writePrivate(mobileRecordPath(s.profile, view.ID), record)
97新增: }
98新增: }
99新增: s.mobileCLI.mu.Unlock()
100新增: s.account.mu.Unlock()
101新增: if err != nil {
102新增: requestError(w, err)
103新增: return
104新增: }
105新增: } else if input.Action != "inspect" {
106新增: http.Error(w, "未知账号操作", 400)
107新增: return
108新增: }
109新增: if terminal {
110新增: if _, err := s.terminalConversationView(r.Context(), view.ID); err != nil && input.Action != "inspect" {
111新增: http.Error(w, err.Error(), 503)
112新增: return
113新增: }
114新增: }
115新增: s.claudeAccounts.mu.Lock()
116新增: list, err := s.loadClaudeAccounts()
117新增: s.claudeAccounts.mu.Unlock()
118新增: if err != nil {
119新增: requestError(w, err)
120新增: return
121新增: }
122新增: s.mobileCLI.mu.Lock()
123新增: record, err := s.mobileCLI.record(s.profile, view.ID)
124新增: if err != nil {
125新增: s.mobileCLI.mu.Unlock()
126新增: requestError(w, err)
127新增: return
128新增: }
129新增: if a := list.find(record.Account.ID); a != nil {
130新增: record.AccountLabel = a.Label
131新增: }
132新增: snapshot := record.snapshot()
133新增: policy := record.SwitchPolicy
134新增: if policy == "" {
135新增: policy = list.Scheduling.SwitchPolicy
136新增: }
137新增: sourceID := record.CLIID
138新增: options := switchCandidates(list, record)
139新增: supported := record.Terminal && record.Launcher == "claude" && record.Account.ID != ""
140新增: s.mobileCLI.mu.Unlock()
141新增: jsonReply(w, map[string]any{"session": snapshot, "source_id": sourceID, "switch_policy": policy, "candidates": options, "supported": supported})
142新增:}
143新增:
144新增:func (s *Server) switchClaudeAccount(ctx context.Context, id string, input claudeSwitchInput, automatic bool) error {
145新增: if !s.op.TryLock() {
146新增: return errTerminalBusy
147新增: }
148新增: defer s.op.Unlock()
149新增: s.conversationMu.Lock()
150新增: defer s.conversationMu.Unlock()
151新增: s.account.mu.Lock()
152新增: allowed := s.mobileAuthorized(ctx)
153新增: s.account.mu.Unlock()
154新增: if !allowed {
155新增: return errMobileLocked
156新增: }
157新增: s.mu.Lock()
158新增: ready := s.ready && !s.closing && !s.guestUpdateRequired && claudeTerminalCommand(s.preferences) == "claude"
159新增: s.mu.Unlock()
160新增: if !ready {
161新增: return errTerminalNotReady
162新增: }
163新增: s.claudeAccounts.mu.Lock()
164新增: list, err := s.loadClaudeAccounts()
165新增: s.claudeAccounts.mu.Unlock()
166新增: if err != nil {
167新增: return err
168新增: }
169新增: m := &s.mobileCLI
170新增: m.mu.Lock()
171新增: record, err := m.record(s.profile, id)
172新增: m.mu.Unlock()
173新增: if err != nil {
174新增: return err
175新增: }
176新增: if record.Archived || record.Deleted || !record.Terminal || record.Launcher != "claude" {
177新增: return errors.New("此会话不能进行账号接续")
178新增: }
179新增: if sw := record.Switch; sw != nil && sw.ID == input.RequestID && sw.Phase == "completed" {
180新增: return nil
181新增: }
182新增: if record.Switch != nil && record.Switch.Phase != "completed" && record.Switch.ID != input.RequestID {
183新增: return errors.New("已有账号交接待恢复,请重试原操作")
184新增: }
185新增: if input.SourceID != record.CLIID && (record.Switch == nil || record.Switch.ID != input.RequestID || record.Switch.Source.CLIID != input.SourceID) {
186新增: return errors.New("会话账号已变化,请刷新后确认")
187新增: }
188新增: if record.Switch == nil || record.Switch.ID != input.RequestID {
189新增: if automatic {
190新增: policy := record.SwitchPolicy
191新增: if policy == "" {
192新增: policy = list.Scheduling.SwitchPolicy
193新增: }
194新增: a := list.find(record.Account.ID)
195新增: if policy != "allow" || record.AccountFailure != "rate_limit" || a == nil {
196新增: return errors.New("当前会话需要手动确认切换")
197新增: }
198新增: if _, available := a.headroom(time.Now()); available {
199新增: return errors.New("尚未确认订阅额度耗尽,保留原账号")
200新增: }
201新增: }
202新增: found := false
203新增: for _, option := range switchCandidates(list, record) {
204新增: if option.ID == input.Target {
205新增: found = true
206新增: }
207新增: }
208新增: if !found {
209新增: return errors.New("目标账号不可用,请将允许接续的账号设置为同一分组并检查额度")
210新增: }
211新增: a := list.find(input.Target)
212新增: selection := claudeSelection{ID: a.ID, GuestID: a.guestID(), Subject: claudeIdentityHash(a.Email, a.Organization)}
213新增: // Check the official CLI identity before stopping any existing work.
214新增: status, probeErr := s.probeClaude(ctx, selection.GuestID)
215新增: if probeErr != nil || status.subject() != selection.Subject {
216新增: return errors.New("无法确认目标账号登录,请先检查账号状态")
217新增: }
218新增: sourceStatus, sourceErr := s.probeClaude(ctx, record.Account.GuestID)
219新增: if sourceErr != nil || sourceStatus.subject() != record.Account.Subject {
220新增: return errors.New("原账号身份已改变,请先检查原会话登录")
221新增: }
222新增: record.Switch = &claudeAccountSwitch{ID: input.RequestID, Phase: "preparing", Source: claudeExecution{record.CLIID, record.Account, record.GuestConfig}, Target: selection, TargetLabel: a.Label, TargetID: uuid.NewString(), Connection: record.Connection, Continue: input.Continue}
223新增: if err := s.saveClaudeSwitch(record); err != nil {
224新增: return err
225新增: }
226新增: }
227新增: sw := record.Switch
228新增: fail := func(err error) error { sw.Error = err.Error(); _ = s.saveClaudeSwitch(record); return err }
229新增: if sw.Phase == "preparing" {
230新增: // Authorization can be revoked or the target identity can change while
231新增: // an interrupted preparation is waiting for a retry.
232新增: target := list.find(sw.Target.ID)
233新增: eligible := false
234新增: for _, option := range switchCandidates(list, record) {
235新增: eligible = eligible || option.ID == sw.Target.ID
236新增: }
237新增: if !eligible || target == nil || target.guestID() != sw.Target.GuestID || claudeIdentityHash(target.Email, target.Organization) != sw.Target.Subject {
238新增: return fail(errors.New("目标账号或接续分组已变化,请取消本次交接后重新选择"))
239新增: }
240新增: status, err := s.probeClaude(ctx, sw.Target.GuestID)
241新增: if err != nil || status.subject() != sw.Target.Subject {
242新增: return fail(errors.New("目标账号登录已变化,请取消交接后检查账号"))
243新增: }
244新增: var result struct {
245新增: Transcript string `json:"transcript"`
246新增: Error string `json:"error"`
247新增: }
248新增: if sw.Source.Config == "" || sw.Connection == "" {
249新增: return fail(errors.New("原会话连接尚未就绪,请先打开原会话"))
250新增: }
251新增: query := map[string]any{"cli_id": sw.Source.CLIID, "config": sw.Source.Config, "connection": sw.Connection, "workspace": record.GuestWorkspace, "target_cli_id": sw.TargetID, "switch_id": sw.ID}
252新增: if err := s.windowsConversationInput(record, query); err != nil {
253新增: return fail(err)
254新增: }
255新增: err = s.runCLIChannel(ctx, "account-switch", query, &result)
256新增: if err != nil {
257新增: return fail(err)
258新增: }
259新增: if result.Error != "" {
260新增: return fail(errors.New(result.Error))
261新增: }
262新增: if !strings.HasPrefix(result.Transcript, "/") && !(s.windowsGuest != nil && windowsCLIAbsolutePath(result.Transcript)) {
263新增: return fail(errors.New("原会话历史未确认,未启动目标账号"))
264新增: }
265新增: if old := s.terminals.get(record.TerminalID); old != nil {
266新增: s.terminals.remove(old.id)
267新增: }
268新增: record.Executions = append(record.Executions, sw.Source)
269新增: record.CLIID, record.Account, record.AccountLabel = sw.TargetID, sw.Target, sw.TargetLabel
270新增: record.GuestConfig, record.Connection, record.TerminalID = "", "", ""
271新增: record.Resume, record.TerminalRunning, record.Active = false, false, false
272新增: record.ResumeTranscript = result.Transcript
273新增: record.AccountFailure = ""
274新增: sw.Phase, sw.Error = "prepared", ""
275新增: if err := s.saveClaudeSwitch(record); err != nil {
276新增: return err
277新增: }
278新增: }
279新增: if sw.Phase == "prepared" {
280新增: // Treat a previous launch with unknown HTTP outcome as owned until its
281新增: // PTY or the guest registry proves otherwise. The connection UUID is
282新增: // deterministic for this switch, and guest launch also rejects duplicates.
283新增: var state struct {
284新增: Running bool `json:"running"`
285新增: }
286新增: query := map[string]any{"cli_id": record.CLIID, "config": record.GuestConfig, "account": record.Account.GuestID}
287新增: if err := s.windowsConversationInput(record, query); err != nil {
288新增: return fail(err)
289新增: }
290新增: if err := s.runCLIChannel(ctx, "active", query, &state); err != nil {
291新增: return fail(err)
292新增: }
293新增: if state.Running {
294新增: sw.Phase = "starting"
295新增: return s.saveClaudeSwitch(record)
296新增: }
297新增: status, err := s.probeClaude(ctx, record.Account.GuestID)
298新增: if err != nil || status.subject() != record.Account.Subject {
299新增: return fail(errors.New("目标账号身份无法确认,保留待恢复历史"))
300新增: }
301新增: _, err = s.createTerminalLocked(terminalRequest{Workspace: record.Workspace, Kind: "claude", sharedID: id, requestContext: ctx})
302新增: if err != nil {
303新增: return fail(err)
304新增: }
305新增: // A launched process may outlive the HTTP request. Never launch it again
306新增: // while its published PTY or guest registry can still own this execution.
307新增: m.mu.Lock()
308新增: latest, loadErr := m.record(s.profile, id)
309新增: m.mu.Unlock()
310新增: if loadErr != nil {
311新增: return loadErr
312新增: }
313新增: record = latest
314新增: record.Switch.Phase = "starting"
315新增: if err := s.saveClaudeSwitch(record); err != nil {
316新增: return err
317新增: }
318新增: }
319新增: return nil
320新增:}
321新增:
322新增:func (s *Server) cancelClaudeSwitch(ctx context.Context, id, requestID string) error {
323新增: if !s.op.TryLock() {
324新增: return errTerminalBusy
325新增: }
326新增: defer s.op.Unlock()
327新增: s.conversationMu.Lock()
328新增: defer s.conversationMu.Unlock()
329新增: s.account.mu.Lock()
330新增: allowed := s.mobileAuthorized(ctx)
331新增: s.account.mu.Unlock()
332新增: if !allowed {
333新增: return errMobileLocked
334新增: }
335新增: s.mobileCLI.mu.Lock()
336新增: record, err := s.mobileCLI.record(s.profile, id)
337新增: s.mobileCLI.mu.Unlock()
338新增: if err != nil {
339新增: return err
340新增: }
341新增: if record.Switch == nil {
342新增: return nil
343新增: }
344新增: sw := record.Switch
345新增: if sw.ID != requestID || sw.Phase != "preparing" {
346新增: return errors.New("目标账号已接管历史,请在当前会话继续")
347新增: }
348新增: var response struct {
349新增: OK bool `json:"ok"`
350新增: Error string `json:"error"`
351新增: }
352新增: query := map[string]any{"cli_id": sw.Source.CLIID, "connection": sw.Connection, "switch_id": sw.ID}
353新增: if err := s.windowsConversationInput(record, query); err != nil {
354新增: return err
355新增: }
356新增: if err := s.runCLIChannel(ctx, "account-switch-cancel", query, &response); err != nil {
357新增: return err
358新增: }
359新增: if !response.OK {
360新增: return errors.New(response.Error)
361新增: }
362新增: record.Switch = nil
363新增: return s.saveClaudeSwitch(record)
364新增:}
365新增:
366新增:// Preserve metadata written concurrently while committing execution ownership.
367新增:func (s *Server) saveClaudeSwitch(record *mobileRecord) error {
368新增: m := &s.mobileCLI
369新增: m.mu.Lock()
370新增: defer m.mu.Unlock()
371新增: current, err := m.record(s.profile, record.ID)
372新增: if err != nil {
373新增: return err
374新增: }
375新增: record.CustomTitle, record.Pinned, record.Archived, record.Deleted = current.CustomTitle, current.Pinned, current.Archived, current.Deleted
376新增: record.SwitchPolicy = current.SwitchPolicy
377新增: record.Revision = current.Revision
378新增: record.changed()
379新增: return writePrivate(mobileRecordPath(s.profile, record.ID), record)
380新增:}
381新增:
382新增:func (s *Server) monitorClaudeAccount(terminal *terminalSession, id string) {
383新增: ctx, cancel := context.WithCancel(s.lifetimeContext())
384新增: s.activities.Add(1)
385新增: go func() {
386新增: defer s.activities.Done()
387新增: defer cancel()
388新增: var lastUsageCheck time.Time
389新增: ticker := time.NewTicker(10 * time.Second)
390新增: defer ticker.Stop()
391新增: for {
392新增: select {
393新增: case <-ctx.Done():
394新增: return
395新增: case <-terminal.done:
396新增: return
397新增: case <-ticker.C:
398新增: }
399新增: epoch, ok := s.account.access()
400新增: if !ok {
401新增: continue
402新增: }
403新增: // Locking pauses observation; unlocking resumes it for the same
404新增: // terminal. Cancel an in-flight attempt if its access epoch ends.
405新增: attempt, finish := context.WithCancel(context.WithValue(ctx, mobileEpochKey{}, epoch))
406新增: stop := context.AfterFunc(epoch, finish)
407新增: s.maybeSwitchClaudeAccount(attempt, id, &lastUsageCheck)
408新增: stop()
409新增: finish()
410新增: }
411新增: }()
412新增:}
413新增:
414新增:func (s *Server) maybeSwitchClaudeAccount(ctx context.Context, id string, lastUsageCheck *time.Time) {
415新增: view, err := s.terminalConversationView(ctx, id)
416新增: if err != nil || view.AccountFailure != "rate_limit" || view.SwitchPolicy != "allow" || view.AccountSwitch != nil && view.AccountSwitch.Phase != "completed" {
417新增: return
418新增: }
419新增: s.claudeAccounts.mu.Lock()
420新增: list, err := s.loadClaudeAccounts()
421新增: s.claudeAccounts.mu.Unlock()
422新增: if err != nil {
423新增: return
424新增: }
425新增: s.mobileCLI.mu.Lock()
426新增: record, err := s.mobileCLI.record(s.profile, id)
427新增: s.mobileCLI.mu.Unlock()
428新增: if err != nil {
429新增: return
430新增: }
431新增: options := switchCandidates(list, record)
432新增: if len(options) == 0 {
433新增: return
434新增: }
435新增: // One bounded quota refresh on the failure path. The CLI owns this
436新增: // query and its tokens; no model prompt is generated for probing.
437新增: if time.Since(*lastUsageCheck) >= claudeUsageInterval {
438新增: *lastUsageCheck = time.Now()
439新增: _ = s.refreshClaudeUsage(ctx, claudeAccountInput{Action: "refresh", ID: record.Account.ID})
440新增: }
441新增: // Apply the same scheduling mode to eligible handoff targets.
442新增: candidates := claudeAccountList{Scheduling: list.Scheduling}
443新增: for _, a := range list.Accounts {
444新增: for _, option := range options {
445新增: if option.ID == a.ID {
446新增: candidates.Accounts = append(candidates.Accounts, a)
447新增: }
448新增: }
449新增: }
450新增: active := s.mobileCLI.activeAccounts()
451新增: logins := make(map[string]bool)
452新增: for _, terminal := range s.terminals.snapshot() {
453新增: if terminal["closed"] == true {
454新增: continue
455新增: }
456新增: account, _ := terminal["claude_account_id"].(string)
457新增: if terminal["kind"] == "claude-login" {
458新增: logins[account] = true
459新增: } else {
460新增: active[account]++
461新增: }
462新增: }
463新增: s.claudeAccounts.mu.Lock()
464新增: last := s.claudeAccounts.lastPick
465新增: s.claudeAccounts.mu.Unlock()
466新增: target := pickClaudeAccount(candidates, active, logins, last, "", time.Now())
467新增: if target == "" {
468新增: return
469新增: }
470新增: _ = s.switchClaudeAccount(ctx, id, claudeSwitchInput{RequestID: uuid.NewString(), SourceID: record.CLIID, Target: target, Continue: true}, true)
471新增:}
新增internal/workbench/claude_switch_e2e_test.go+275 −0看文件
@@ -0,0 +1,275 @@
1新增://go:build !windows
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新增: // Rewrite the helper path in decoded launch payloads at the test boundary.
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新增: // The real channel's StopFailure observation and a known exhausted
212新增: // quota are both required before the same production handoff can run.
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新增: // Shutdown can wait for a last hook. Reuse the same durable operation;
250新增: // the retry must never create a second source or target execution.
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新增: // Replay an acknowledged pre-switch request through the new account channel.
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新增:}
新增internal/workbench/cli_channel.go+581 −0看文件
@@ -0,0 +1,581 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "bytes"
5新增: "compress/gzip"
6新增: "context"
7新增: "crypto/sha256"
8新增: _ "embed"
9新增: "encoding/json"
10新增: "errors"
11新增: "fmt"
12新增: "os"
13新增: "strings"
14新增: "time"
15新增:
16新增: "al.essio.dev/pkg/shellescape"
17新增: "github.com/google/uuid"
18新增: "github.com/sylvinus/agent-vm/internal/diagnostics"
19新增:)
20新增:
21新增://go:embed cli_channel.py
22新增:var cliChannelHelper string
23新增:
24新增://go:embed cli_channel.resume.md
25新增:var cliResumePrompt string
26新增:
27新增://go:embed claude_account_resume.md
28新增:var claudeAccountResumePrompt string
29新增:
30新增:var cliChannelEncoded = func() string {
31新增: var helper strings.Builder
32新增: for _, line := range strings.Split(cliChannelHelper, "\n") {
33新增: if strings.TrimSpace(line) != "" && !strings.HasPrefix(strings.TrimSpace(line), "#") {
34新增: helper.WriteString(line + "\n")
35新增: }
36新增: }
37新增: bundle := []byte(strings.Join([]string{helper.String(), cliResumePrompt, claudeAccountResumePrompt}, "\x00"))
38新增: var compressed bytes.Buffer
39新增: writer, _ := gzip.NewWriterLevel(&compressed, gzip.BestCompression)
40新增: _, _ = writer.Write(bundle)
41新增: _ = writer.Close()
42新增: return cliTransport85(compressed.Bytes())
43新增:}()
44新增:
45新增:// Python's RFC 1924 base85 alphabet has no single quote. It fits the compressed
46新增:// helper within Windows' command limit without expanding shell quoting.
47新增:func cliTransport85(data []byte) string {
48新增: const alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~"
49新增: var out strings.Builder
50新增: for len(data) > 0 {
51新增: n := min(4, len(data))
52新增: var value uint64
53新增: for i := 0; i < 4; i++ {
54新增: value <<= 8
55新增: if i < n {
56新增: value |= uint64(data[i])
57新增: }
58新增: }
59新增: var block [5]byte
60新增: for i := 4; i >= 0; i-- {
61新增: block[i] = alphabet[value%85]
62新增: value /= 85
63新增: }
64新增: out.Write(block[:n+1])
65新增: data = data[n:]
66新增: }
67新增: return out.String()
68新增:}
69新增:
70新增:type terminalConversation struct {
71新增: NativeCCSUnverified bool `json:"native_ccs_unverified"`
72新增: AccountFailure string `json:"account_failure"`
73新增: ResumePending bool `json:"resume_pending"`
74新增: NativeHistory bool `json:"native_history"`
75新增: CLIID string `json:"cli_id"`
76新增: Config string `json:"config"`
77新增: Connection string `json:"connection"`
78新增: Workspace string `json:"workspace"`
79新增: Title string `json:"title"`
80新增: UpdatedAt float64 `json:"updated_at"`
81新增: Turns []mobileTurn `json:"turns"`
82新增: CanSend bool `json:"can_send"`
83新增: ChannelReady bool `json:"channel_ready"`
84新增: HasHistory bool `json:"has_history"`
85新增: Running bool `json:"running"`
86新增: Active bool `json:"active"`
87新增: ConnectionNotice string `json:"connection_notice"`
88新增: HistoryTruncated bool `json:"history_truncated"`
89新增:}
90新增:
91新增:func cliChannelCommand(mode, argument string) string {
92新增: // Versioned helpers let an open terminal keep its original protocol while a
93新增: // rebuilt host begins new sessions. No account configuration is overwritten.
94新增: bootstrap := fmt.Sprintf(`import base64, gzip, os, pathlib, sys, tempfile
95新增:folder = pathlib.Path.home() / ".local/share/cage/cli-channel-code"
96新增:folder.mkdir(parents=True, exist_ok=True, mode=0o700)
97新增:name = "%x"
98新增:files = gzip.decompress(base64.b85decode("%s")).decode("utf-8").split("\0")
99新增:for suffix, content in zip((".py", ".resume.md", ".account-resume.md"), files):
100新增: path = folder / (name + suffix)
101新增: if not path.exists():
102新增: with tempfile.NamedTemporaryFile(dir=folder, delete=False) as stream:
103新增: stream.write(content.encode("utf-8"))
104新增: temporary = stream.name
105新增: os.replace(temporary, path)
106新增:path = folder / (name + ".py")
107新增:os.execv(sys.executable, [sys.executable, "-I", str(path), *sys.argv[1:]])
108新增:`, sha256.Sum256([]byte(cliChannelHelper+cliResumePrompt+claudeAccountResumePrompt)), cliChannelEncoded)
109新增: return shellescape.QuoteCommand([]string{"python3", "-I", "-c", bootstrap, mode, argument})
110新增:}
111新增:
112新增:func (s *Server) runCLIChannel(ctx context.Context, mode string, input any, output any) error {
113新增: started := time.Now()
114新增: epoch, ok := s.account.access()
115新增: if !ok {
116新增: return errMobileLocked
117新增: }
118新增: ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
119新增: stop := context.AfterFunc(epoch, cancel)
120新增: defer func() { stop(); cancel() }()
121新增: if s.windowsGuest != nil {
122新增: return s.windowsCLIRequest(ctx, map[string]any{"action": "channel", "mode": mode, "input": input}, output)
123新增: }
124新增: data, err := json.Marshal(input)
125新增: if err != nil {
126新增: return err
127新增: }
128新增: command := "exec /bin/bash -c " + shellescape.Quote("exec 3>&1 1>&2; exec /bin/bash -lc "+shellescape.Quote("exec 1>&3 3>&-; exec "+s.cliHelperCommand(mode, "-")))
129新增: cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", command)
130新增: cmd.Stdin = strings.NewReader(string(data))
131新增: var stderr fileControlStderr
132新增: cmd.Stderr = &stderr
133新增: cmd.WaitDelay = 2 * time.Second
134新增: result, err := cmd.Output()
135新增: if err != nil || len(result) > 4<<20 || json.Unmarshal(result, output) != nil {
136新增: failure := "guest_response"
137新增: message := "电脑未能读取会话状态,聊天记录已保留。"
138新增: if errors.Is(ctx.Err(), context.DeadlineExceeded) {
139新增: failure, message = "timeout", "电脑读取运行环境超时,暂时无法获取会话状态。"
140新增: } else if err != nil {
141新增: failure = "guest_command"
142新增: if cmd.ProcessState != nil && cmd.ProcessState.ExitCode() == 255 {
143新增: failure, message = "ssh_connection", "电脑暂时无法连接运行环境,聊天记录已保留。"
144新增: }
145新增: }
146新增: exit := -1
147新增: if cmd.ProcessState != nil {
148新增: exit = cmd.ProcessState.ExitCode()
149新增: }
150新增: // Record transport and protocol evidence without terminal output,
151新增: // prompts, account paths or raw SSH/Python error messages.
152新增: _ = diagnostics.New(s.profile).Record("warn", "cli-channel", fmt.Sprintf("operation=%s failure=%s exit=%d elapsed_ms=%d context=%v output_bytes=%d stderr_bytes=%d", mode, failure, exit, time.Since(started).Milliseconds(), ctx.Err(), len(result), len(stderr.data)))
153新增: return errors.New(message)
154新增: }
155新增: return nil
156新增:}
157新增:
158新增:func (s *Server) discoverTerminalConversations(ctx context.Context, paths []string) error {
159新增: s.conversationMu.Lock()
160新增: defer s.conversationMu.Unlock()
161新增: s.mu.Lock()
162新增: ready := s.ready && !s.closing
163新增: s.mu.Unlock()
164新增: if !ready {
165新增: return nil
166新增: }
167新增: accounts := []string{"default"}
168新增: s.claudeAccounts.mu.Lock()
169新增: list, err := s.loadClaudeAccounts()
170新增: s.claudeAccounts.mu.Unlock()
171新增: if err != nil {
172新增: return err
173新增: }
174新增: for _, account := range list.Accounts {
175新增: if account.guestID() != "default" {
176新增: accounts = append(accounts, account.guestID())
177新增: }
178新增: }
179新增: workspaces := make(map[string]string, len(paths))
180新增: for _, path := range paths {
181新增: if s.windowsGuest != nil {
182新增: binding, err := s.windowsProjectForHost(path)
183新增: if err == nil {
184新增: workspaces[binding.Path] = path
185新增: }
186新增: } else {
187新增: workspaces[s.cliWorkspace(path)] = path
188新增: }
189新增: }
190新增: var found []terminalConversation
191新增: if err := s.runCLIChannel(ctx, "discover", map[string]any{"accounts": accounts, "workspaces": workspaces}, &found); err != nil {
192新增: return err
193新增: }
194新增: m := &s.mobileCLI
195新增: m.mu.Lock()
196新增: defer m.mu.Unlock()
197新增: known := map[string]*mobileRecord{}
198新增: for id := range m.catalog {
199新增: record, err := m.record(s.profile, id)
200新增: if err != nil {
201新增: return err
202新增: }
203新增: known[record.CLIID] = record
204新增: for _, execution := range record.Executions {
205新增: known[execution.CLIID] = record
206新增: }
207新增: }
208新增: for _, item := range found {
209新增: var workspace, matched string
210新增: for guest, path := range workspaces {
211新增: if cliWorkspaceWithin(item.Workspace, guest, s.windowsGuest != nil) && len(guest) > len(matched) {
212新增: workspace, matched = path, guest
213新增: }
214新增: }
215新增: if workspace == "" || !validCLIUUID(item.CLIID) {
216新增: continue
217新增: }
218新增: record := known[item.CLIID]
219新增: if record != nil && record.CLIID != item.CLIID {
220新增: continue
221新增: }
222新增: if record != nil && (record.Deleted || record.Archived) {
223新增: continue
224新增: }
225新增: if record != nil && !record.Terminal {
226新增: continue
227新增: }
228新增: if record == nil {
229新增: record = &mobileRecord{mobileSession: mobileSession{mobileSummary: mobileSummary{ID: uuid.NewString(), Workspace: workspace}, Turns: []mobileTurn{}}, CLIID: item.CLIID, Terminal: true, Resume: true}
230新增: record.Generation = m.epochLocked()
231新增: record.Account.GuestID = "default"
232新增: for _, account := range list.Accounts {
233新增: config := strings.ReplaceAll(item.Config, "\\", "/")
234新增: if strings.Contains(config, "/claude-accounts/"+account.guestID()+"/") || s.windowsGuest != nil && strings.HasSuffix(strings.ToLower(config), "/accounts/"+account.guestID()+"/config") {
235新增: record.Account = claudeSelection{ID: account.ID, GuestID: account.guestID(), Subject: claudeIdentityHash(account.Email, account.Organization)}
236新增: }
237新增: }
238新增: }
239新增: record.Workspace = workspace
240新增: record.Active = item.Active
241新增: record.Title, record.GuestConfig, record.Connection = item.Title, item.Config, item.Connection
242新增: record.GuestWorkspace = item.Workspace
243新增: if item.Connection != "" {
244新增: if terminal := s.terminals.forConversation(item.Connection); terminal != nil {
245新增: record.TerminalID = terminal.id
246新增: terminal.mu.Lock()
247新增: terminal.sharedID = record.ID
248新增: terminal.mu.Unlock()
249新增: }
250新增: }
251新增: record.UpdatedAt = time.UnixMilli(int64(item.UpdatedAt * 1000)).UTC()
252新增: if err := writePrivate(mobileRecordPath(s.profile, record.ID), record); err != nil {
253新增: return err
254新增: }
255新增: m.catalog[record.ID] = record.summary()
256新增: known[record.CLIID] = record
257新增: }
258新增: return nil
259新增:}
260新增:
261新增:func (s *Server) terminalConversationView(ctx context.Context, id string) (mobileSession, error) {
262新增: s.conversationMu.Lock()
263新增: defer s.conversationMu.Unlock()
264新增: m := &s.mobileCLI
265新增: m.mu.Lock()
266新增: record, err := m.record(s.profile, id)
267新增: m.mu.Unlock()
268新增: if err != nil {
269新增: return mobileSession{}, err
270新增: }
271新增: var current terminalConversation
272新增: input := map[string]any{"cli_id": record.CLIID, "config": record.GuestConfig, "connection": record.Connection, "account": record.Account.GuestID}
273新增: if err := s.windowsConversationInput(record, input); err != nil {
274新增: return mobileSession{}, err
275新增: }
276新增: if err := s.runCLIChannel(ctx, "view", input, &current); err != nil {
277新增: return mobileSession{}, err
278新增: }
279新增: root := s.cliWorkspace(record.Workspace)
280新增: if legacy := s.macOSLegacyWorkspace(record); legacy != "" {
281新增: root = legacy
282新增: }
283新增: if s.windowsGuest != nil {
284新增: root = record.GuestWorkspace
285新增: }
286新增: if current.Workspace == "" && !current.HasHistory && record.TerminalID != "" {
287新增: if record.Switch != nil && record.Switch.Phase == "starting" && !current.Running {
288新增: if owner := s.terminals.get(record.TerminalID); owner == nil || !owner.ownsConversation() {
289新增: m.mu.Lock()
290新增: record.Switch.Phase, record.Switch.Error = "prepared", "目标账号未建立会话,请重试交接"
291新增: record.changed()
292新增: err = writePrivate(mobileRecordPath(s.profile, id), record)
293新增: m.mu.Unlock()
294新增: if err != nil {
295新增: return mobileSession{}, err
296新增: }
297新增: }
298新增: }
299新增: return record.snapshot(), nil
300新增: }
301新增: if !cliWorkspaceWithin(current.Workspace, root, s.windowsGuest != nil) {
302新增: return mobileSession{}, errors.New("终端的项目已变化,请重新读取会话列表")
303新增: }
304新增: if terminal := s.terminals.get(record.TerminalID); terminal != nil && current.Connection != "" && current.Workspace != "" {
305新增: terminal.mu.Lock()
306新增: if terminal.connectionID == current.Connection {
307新增: terminal.conversationEnded = !current.Running
308新增: }
309新增: terminal.mu.Unlock()
310新增: }
311新增: m.mu.Lock()
312新增: defer m.mu.Unlock()
313新增: // Reload after SSH so another request's identity and terminal attachment are
314新增: // retained. The guest owns transcript content, the host owns the public ID.
315新增: record, err = m.record(s.profile, id)
316新增: if err != nil {
317新增: return mobileSession{}, err
318新增: }
319新增: if record.Deleted {
320新增: return mobileSession{}, os.ErrNotExist
321新增: }
322新增: before, _ := json.Marshal(record)
323新增: record.Turns = adoptedMobileTurns(record.LegacyTurns, current.Turns)
324新增: if record.Turns == nil {
325新增: record.Turns = []mobileTurn{}
326新增: }
327新增: record.Title, record.ConnectionNotice = current.Title, current.ConnectionNotice
328新增: if s.macOSLegacyWorkspace(record) != "" {
329新增: record.ConnectionNotice = strings.TrimSpace(record.ConnectionNotice + "\n" + macOSLegacyWorkspaceNotice)
330新增: }
331新增: record.CanSend, record.HistoryTruncated = &current.CanSend, current.HistoryTruncated
332新增: record.GuestConfig, record.Connection = current.Config, current.Connection
333新增: record.GuestWorkspace = current.Workspace
334新增: record.Resume = record.Resume || current.HasHistory
335新增: record.TerminalRunning = current.Running
336新增: record.Active = current.Active
337新增: record.AccountFailure = current.AccountFailure
338新增: if current.NativeHistory {
339新增: record.ResumeTranscript = ""
340新增: }
341新增: if record.Switch != nil && record.Switch.Phase == "starting" && current.CLIID == record.Switch.TargetID {
342新增: if current.ChannelReady && !current.ResumePending || current.HasHistory && !current.Running {
343新增: record.Switch.Phase, record.Switch.Error = "completed", ""
344新增: if current.NativeHistory {
345新增: record.ResumeTranscript = ""
346新增: }
347新增: } else if !current.Running {
348新增: if owner := s.terminals.get(record.TerminalID); owner == nil || !owner.ownsConversation() {
349新增: record.Switch.Phase, record.Switch.Error = "prepared", "目标账号未建立会话,请重试交接"
350新增: }
351新增: }
352新增: }
353新增: after, _ := json.Marshal(record)
354新增: if string(before) != string(after) {
355新增: record.Revision++
356新增: record.UpdatedAt = time.UnixMilli(int64(current.UpdatedAt * 1000)).UTC()
357新增: if err := writePrivate(mobileRecordPath(s.profile, id), record); err != nil {
358新增: return mobileSession{}, err
359新增: }
360新增: if m.catalog != nil {
361新增: m.catalog[id] = record.summary()
362新增: }
363新增: }
364新增: return record.snapshot(), nil
365新增:}
366新增:
367新增:func (s *Server) terminalConversationAction(ctx context.Context, id string, input map[string]any) (mobileSession, error) {
368新增: if !s.op.TryLock() {
369新增: return mobileSession{}, errTerminalBusy
370新增: }
371新增: defer s.op.Unlock()
372新增: s.account.mu.Lock()
373新增: authorized := s.mobileAuthorized(ctx)
374新增: s.account.mu.Unlock()
375新增: if !authorized {
376新增: return mobileSession{}, errMobileLocked
377新增: }
378新增: m := &s.mobileCLI
379新增: m.mu.Lock()
380新增: record, err := m.record(s.profile, id)
381新增: m.mu.Unlock()
382新增: if err != nil {
383新增: return mobileSession{}, err
384新增: }
385新增: if record.Deleted {
386新增: return mobileSession{}, os.ErrNotExist
387新增: }
388新增: if input["action"] == "send" {
389新增: for _, previous := range record.LegacyTurns {
390新增: if previous.ID == input["request_id"] {
391新增: if previous.Prompt != input["text"] {
392新增: return mobileSession{}, errors.New("同一发送编号已用于另一条消息")
393新增: }
394新增: view := record.snapshot()
395新增: view.AcknowledgedRequestID = previous.ID
396新增: return view, nil
397新增: }
398新增: }
399新增: }
400新增: if record.Connection == "" {
401新增: return mobileSession{}, errors.New("会话连接尚未就绪,请稍后重试")
402新增: }
403新增: if record.Archived {
404新增: return mobileSession{}, errors.New("此会话已归档,请先撤销归档")
405新增: }
406新增: input["cli_id"], input["connection"] = record.CLIID, record.Connection
407新增: if err := s.windowsConversationInput(record, input); err != nil {
408新增: return mobileSession{}, err
409新增: }
410新增: var response struct {
411新增: OK bool `json:"ok"`
412新增: Error string `json:"error"`
413新增: }
414新增: if err := s.runCLIChannel(ctx, "rpc", input, &response); err != nil {
415新增: return mobileSession{}, err
416新增: }
417新增: if !response.OK {
418新增: return mobileSession{}, errors.New(response.Error)
419新增: }
420新增: if input["action"] == "send" {
421新增: // The guest already committed this message. Return its receipt now;
422新增: // fetching the transcript is a separate read, not part of admission.
423新增: s.account.mu.Lock()
424新增: defer s.account.mu.Unlock()
425新增: if !s.mobileAuthorized(ctx) {
426新增: return mobileSession{}, errMobileLocked
427新增: }
428新增: m.mu.Lock()
429新增: defer m.mu.Unlock()
430新增: record, err = m.record(s.profile, id)
431新增: if err != nil {
432新增: return mobileSession{}, err
433新增: }
434新增: view := record.snapshot()
435新增: requestID, _ := input["request_id"].(string)
436新增: if findMobileTurn(record, requestID) == nil {
437新增: text, _ := input["text"].(string)
438新增: view.Turns = append(view.Turns, mobileTurn{ID: requestID, Prompt: text, Status: "queued"})
439新增: }
440新增: view.AcknowledgedRequestID = requestID
441新增: return view, nil
442新增: }
443新增: return s.terminalConversationView(ctx, id)
444新增:}
445新增:
446新增:func (s *Server) prepareTerminalConversation(workspace string, selection claudeSelection, existing string) (string, *mobileRecord, error) {
447新增: s.mu.Lock()
448新增: launcher := claudeTerminalCommand(s.preferences)
449新增: s.mu.Unlock()
450新增: s.claudeAccounts.mu.Lock()
451新增: list, loadErr := s.loadClaudeAccounts()
452新增: s.claudeAccounts.mu.Unlock()
453新增: if loadErr != nil {
454新增: return "", nil, loadErr
455新增: }
456新增: m := &s.mobileCLI
457新增: id := existing
458新增: if id == "" {
459新增: id = uuid.NewString()
460新增: }
461新增: if _, err := m.create(s.profile, workspace, id); err != nil {
462新增: return "", nil, err
463新增: }
464新增: m.mu.Lock()
465新增: defer m.mu.Unlock()
466新增: record, err := m.record(s.profile, id)
467新增: if err != nil {
468新增: return "", nil, err
469新增: }
470新增: legacyWorkspace := ""
471新增: if existing != "" {
472新增: legacyWorkspace = s.macOSLegacyWorkspace(record)
473新增: }
474新增: if selection.ID == "" && selection.Subject == "" {
475新增: selection.GuestID = ""
476新增: }
477新增: prefix, err := mobileLaunchArgs(launcher, selection)
478新增: if err != nil {
479新增: return "", nil, err
480新增: }
481新增: record.Terminal, record.Account, record.Launcher = true, selection, launcher
482新增: if record.SwitchPolicy == "" {
483新增: record.SwitchPolicy = list.Scheduling.SwitchPolicy
484新增: if a := list.find(selection.ID); a != nil {
485新增: record.AccountLabel = a.Label
486新增: }
487新增: }
488新增: record.TerminalID, record.TerminalRunning = "", true
489新增: record.Connection = uuid.NewString()
490新增: if record.ResumeTranscript != "" && record.Switch != nil {
491新增: record.Connection = record.Switch.ID
492新增: }
493新增: payload := map[string]any{"id": record.Connection, "session_id": record.CLIID, "prefix": prefix, "config": record.GuestConfig}
494新增: if record.Resume {
495新增: payload["resume"] = record.CLIID
496新增: }
497新增: if record.ResumeTranscript != "" {
498新增: payload["resume_transcript"] = record.ResumeTranscript
499新增: payload["resume"] = ""
500新增: payload["switch_id"] = record.Switch.ID
501新增: payload["continue_after_switch"] = record.Switch.Continue
502新增: }
503新增: if s.macosGuest != nil && record.GuestWorkspace != "" {
504新增: root := s.cliWorkspace(workspace)
505新增: if legacyWorkspace != "" {
506新增: root = legacyWorkspace
507新增: }
508新增: if !cliWorkspaceWithin(record.GuestWorkspace, root, false) {
509新增: return "", nil, errors.New("会话目录不在已授权的 macOS 项目内")
510新增: }
511新增: payload["project_subdir"] = strings.TrimPrefix(strings.TrimPrefix(record.GuestWorkspace, root), "/")
512新增: }
513新增: data, _ := json.Marshal(payload)
514新增: record.CanSend = new(bool)
515新增: record.ConnectionNotice = ""
516新增: if legacyWorkspace != "" {
517新增: record.ConnectionNotice = macOSLegacyWorkspaceNotice
518新增: }
519新增: if s.windowsGuest != nil {
520新增: binding, err := s.windowsProjectForHost(workspace)
521新增: if err != nil {
522新增: return "", nil, err
523新增: }
524新增: record.GuestWorkspace = binding.Path
525新增: if err := writePrivate(mobileRecordPath(s.profile, id), record); err != nil {
526新增: return "", nil, err
527新增: }
528新增: return string(data), record, nil
529新增: }
530新增: body := s.cliHelperCommand("launch", string(data)) + "; exec bash -i"
531新增: directory := record.GuestWorkspace
532新增: if directory == "" {
533新增: directory = s.cliWorkspace(workspace)
534新增: }
535新增: record.GuestWorkspace = directory
536新增: if err := writePrivate(mobileRecordPath(s.profile, id), record); err != nil {
537新增: return "", nil, err
538新增: }
539新增: if s.macosGuest != nil {
540新增: if legacyWorkspace != "" {
541新增: return "cd -- " + shellescape.Quote(legacyWorkspace) + " && exec " + s.cliHelperCommand("macos-launch", string(data)), record, nil
542新增: }
543新增: return s.macOSClaudeLaunch(workspace, string(data)), record, nil
544新增: }
545新增: script := "cd " + shellescape.Quote(directory) + " && exec env TERM=xterm-256color COLORTERM=truecolor CAGE_WORKBENCH=1 bash -lic " + shellescape.Quote(body)
546新增: return script, record, nil
547新增:}
548新增:
549新增:func (s *Server) isTerminalConversation(id string) bool {
550新增: s.mobileCLI.mu.Lock()
551新增: defer s.mobileCLI.mu.Unlock()
552新增: record, err := s.mobileCLI.record(s.profile, id)
553新增: return err == nil && record.Terminal
554新增:}
555新增:
556新增:func (s *Server) stopTerminalConversation(ctx context.Context, view mobileSession, turnID string) (mobileSession, error) {
557新增: if len(view.Turns) == 0 || view.Turns[len(view.Turns)-1].ID != turnID || view.Turns[len(view.Turns)-1].Status != "running" {
558新增: return view, errors.New("本轮运行状态已变化,请重新读取")
559新增: }
560新增: s.mobileCLI.mu.Lock()
561新增: record, err := s.mobileCLI.record(s.profile, view.ID)
562新增: s.mobileCLI.mu.Unlock()
563新增: if err != nil {
564新增: return view, err
565新增: }
566新增: terminal := s.terminals.get(record.TerminalID)
567新增: if terminal == nil {
568新增: return view, errors.New("请在电脑终端停止这次运行")
569新增: }
570新增: s.account.mu.Lock()
571新增: if !s.mobileAuthorized(ctx) {
572新增: s.account.mu.Unlock()
573新增: return view, errMobileLocked
574新增: }
575新增: err = terminal.enqueueInput(ctx, "\x1b")
576新增: s.account.mu.Unlock()
577新增: if err != nil {
578新增: return view, err
579新增: }
580新增: return s.terminalConversationAction(ctx, view.ID, map[string]any{"action": "stop"})
581新增:}
新增internal/workbench/cli_channel.py+911 −0看文件
@@ -0,0 +1,911 @@
1新增:"""Guest-side Claude terminal discovery and authenticated local channel bridge."""
2新增:import contextlib
3新增:import hashlib
4新增:import json
5新增:import os
6新增:from pathlib import Path
7新增:import re
8新增:import runpy
9新增:import shlex
10新增:import shutil
11新增:import signal
12新增:import socket
13新增:import socketserver
14新增:import subprocess
15新增:import sys
16新增:import tempfile
17新增:import threading
18新增:import time
19新增:import uuid
20新增:
21新增:
22新增:if os.name == "nt":
23新增: _platform = runpy.run_path(Path(__file__).with_name("windows_cli_platform.py"))
24新增: fcntl = _platform["FileLock"]
25新增:else:
26新增: import fcntl
27新增:
28新增:def process_fingerprint(pid):
29新增: if os.name == "nt":
30新增: return _platform["process_fingerprint"](pid)
31新增: return subprocess.run(["ps", "-o", "lstart=,comm=", "-p", str(pid)], capture_output=True, text=True, timeout=2).stdout
32新增:
33新增:def terminate_cli(pid, force=False):
34新增: if os.name == "nt":
35新增: return _platform["terminate_cli"](pid, force)
36新增: return os.kill(int(pid), signal.SIGKILL if force else signal.SIGTERM)
37新增:
38新增:ROOT = Path(os.environ["CAGE_CLI_STATE_ROOT"]) if os.name == "nt" else Path.home() / ".local/share/cage/cli-channels"
39新增:PROMPT_LIMIT = 32 << 10
40新增:REPLY_LIMIT = 128 << 10
41新增:HISTORY_LIMIT = 448 << 10
42新增:
43新增:
44新增:def identifier(value):
45新增: return str(uuid.UUID(value))
46新增:
47新增:
48新增:def read_json(path, default=None):
49新增: try:
50新增: return json.loads(path.read_text())
51新增: except FileNotFoundError:
52新增: return default
53新增:
54新增:
55新增:def save(path, value):
56新增: path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
57新增: with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, delete=False) as stream:
58新增: json.dump(value, stream, ensure_ascii=False)
59新增: temporary = stream.name
60新增: os.replace(temporary, path)
61新增:
62新增:
63新增:@contextlib.contextmanager
64新增:def state_file(connection):
65新增: folder = ROOT / identifier(connection)
66新增: folder.mkdir(parents=True, exist_ok=True, mode=0o700)
67新增: with (folder / "lock").open("a") as lock:
68新增: fcntl.flock(lock, fcntl.LOCK_EX)
69新增: path = folder / "state.json"
70新增: state = read_json(path, {})
71新增: yield state
72新增: save(path, state)
73新增:
74新增:
75新增:def live(pid):
76新增: if os.name == "nt":
77新增: return _platform["process_live"](pid)
78新增: try:
79新增: os.kill(int(pid), 0)
80新增: return True
81新增: except (OSError, ValueError, TypeError):
82新增: return False
83新增:
84新增:
85新增:def config_directory(account):
86新增: if account == "default":
87新增: return Path(os.environ.get("CLAUDE_CONFIG_DIR") or Path.home() / ".claude").resolve()
88新增: if not re.fullmatch(r"[0-9a-f]{24}", account):
89新增: raise ValueError("invalid account")
90新增: root = Path(os.environ["CAGE_CLI_ACCOUNT_ROOT"]) if os.name == "nt" else Path.home() / ".local/share/cage/claude-accounts"
91新增: return root / account / "config"
92新增:
93新增:
94新增:def workspace_within(path, root):
95新增: if os.name == "nt":
96新增: path, root = path.replace("\\", "/").lower(), root.replace("\\", "/").lower()
97新增: return path == root or path.startswith(root.rstrip("/") + "/")
98新增:
99新增:
100新增:def text_content(message):
101新增: content = message.get("content", [])
102新增: if isinstance(content, str):
103新增: return content
104新增: return "\n".join(item.get("text", "") for item in content if isinstance(item, dict) and item.get("type") == "text")
105新增:
106新增:
107新增:def clip_text(text, limit):
108新增: return text.encode("utf-8")[:limit].decode("utf-8", errors="ignore")
109新增:
110新增:
111新增:def channel_message(text):
112新增: match = re.match(r'^<channel\s+[^>]*cage_request="([0-9a-f-]{36})"[^>]*>\n?', text)
113新增: if not match or not text.endswith("</channel>"):
114新增: return None
115新增: # Only remove the framing newline. The user's text can itself contain XML
116新增: # tags, including </channel>, and must remain an opaque message body.
117新增: body = text[match.end():-len("</channel>")]
118新增: return match.group(1), body.removesuffix("\n")
119新增:
120新增:
121新增:def update_tools(turn, role, content):
122新增: if not isinstance(content, list):
123新增: return
124新增: tools = turn.get("tools", [])
125新增: by_id = {tool["id"]: tool for tool in tools}
126新增: for block in content:
127新增: if not isinstance(block, dict):
128新增: continue
129新增: kind = block.get("type")
130新增: if role == "user" and kind == "tool_result":
131新增: result_id = block.get("tool_use_id")
132新增: tool = by_id.get(result_id) if isinstance(result_id, str) else None
133新增: if tool:
134新增: tool["status"] = "failed" if block.get("is_error") else "completed"
135新增: if role != "assistant" or kind not in ("tool_use", "server_tool_use"):
136新增: continue
137新增: key, name = block.get("id"), block.get("name")
138新增: if not isinstance(key, str) or not 0 < len(key.encode()) <= 128 or key in by_id or len(tools) >= 64:
139新增: continue
140新增: if not isinstance(name, str) or not re.fullmatch(r"[a-zA-Z0-9_.:-]{1,128}", name):
141新增: continue
142新增: tool = {"id": key, "name": name, "status": "called"}
143新增: args = block.get("input")
144新增: if isinstance(args, dict):
145新增: for field in ("description", "subject", "file_path", "pattern", "query", "skill", "subagent_type"):
146新增: value = args.get(field)
147新增: if isinstance(value, str) and value.strip():
148新增: tool["detail"] = value.strip()[:160]
149新增: break
150新增: by_id[key] = tool
151新增: tools.append(tool)
152新增: if tools:
153新增: turn["tools"] = tools
154新增:
155新增:
156新增:def transcript(path):
157新增: turns, seen, workspace, title = [], set(), "", ""
158新增: if not path or not path.is_file() or path.is_symlink():
159新增: return turns, workspace, title, seen
160新增: with path.open() as stream:
161新增: for line in stream:
162新增: if len(line) > 4 * 1024 * 1024:
163新增: continue
164新增: try:
165新增: row = json.loads(line)
166新增: except ValueError:
167新增: continue
168新增: if row.get("isSidechain"):
169新增: continue
170新增: workspace = row.get("cwd") or workspace
171新增: if row.get("type") == "custom-title":
172新增: title = row.get("customTitle") or title
173新增: key = row.get("uuid")
174新增: if not key or key in seen:
175新增: continue
176新增: seen.add(key)
177新增: message = row.get("message") or {}
178新增: if turns:
179新增: update_tools(turns[-1], row.get("type"), message.get("content"))
180新增: text = text_content(message)
181新增: if not text:
182新增: continue
183新增: if row.get("type") == "assistant" and message.get("model") == "<synthetic>" and text == "No response requested.":
184新增: continue
185新增: if row.get("type") == "user":
186新增: channel = channel_message(text) if row.get("isMeta") else None
187新增: if channel:
188新增: key, text = channel
189新增: seen.add(key)
190新增: elif row.get("isCompactSummary") or (row.get("isMeta") and not text.lstrip().startswith("<task-notification>")):
191新增: continue
192新增: turns.append({"id": key, "prompt": clip_text(text, PROMPT_LIMIT), "prompt_truncated": len(text.encode()) > PROMPT_LIMIT, "text": "", "status": "completed"})
193新增: turns = turns[-256:]
194新增: elif row.get("type") == "assistant" and turns:
195新增: turn = turns[-1]
196新增: value = turn["text"] + ("\n\n" if turn["text"] else "") + text
197新增: turn["text"], turn["truncated"] = clip_text(value, REPLY_LIMIT), len(value.encode()) > REPLY_LIMIT
198新增: return turns, workspace, title, seen
199新增:
200新增:
201新增:def connection_for(session_id, config):
202新增: matches = []
203新增: for path in ROOT.glob("*/state.json"):
204新增: state = read_json(path, {})
205新增: if state.get("cli_id") == session_id and state.get("config") == str(config):
206新增: matches.append((path.parent.name, state))
207新增: return max(matches, key=lambda item: (live(item[1].get("pid")) and not item[1].get("closed"), live(item[1].get("channel_pid")), item[1].get("updated_at", 0)), default=("", {}))
208新增:
209新增:
210新增:def view(config, session_id, path=None):
211新增: connection, state = connection_for(session_id, config)
212新增: path = path or next((config / "projects").glob("*/" + session_id + ".jsonl"), None)
213新增: native_history = path is not None
214新增: if path is None and state.get("resume_transcript"):
215新增: frozen = Path(state["resume_transcript"])
216新增: if frozen.parent.parent == ROOT.parent / "cli-account-switches" and frozen.name == "history.jsonl":
217新增: path = frozen
218新增: turns, workspace, title, received = transcript(path)
219新增: has_history = bool(turns)
220新增: if connection and any(sent["id"] in received for sent in state.get("sent", [])):
221新增: with state_file(connection) as latest:
222新增: latest["sent"] = [sent for sent in latest.get("sent", []) if sent["id"] not in received]
223新增: state = dict(latest)
224新增: running = live(state.get("pid")) and not state.get("closed")
225新增: channel = running and live(state.get("channel_pid")) and not state.get("blocked") and not state.get("policy_unavailable") and not state.get("native_ccs_unverified")
226新增: known = {turn["id"] for turn in turns}
227新增: for sent in state.get("sent", []):
228新增: if sent["id"] not in known:
229新增: turns.append({"id": sent["id"], "prompt": sent["text"], "text": "", "status": "interrupted" if sent.get("interrupted") else "queued"})
230新增: display = state.get("display")
231新增: if turns and display and state.get("busy") and display.get("text"):
232新增: text = display["text"]
233新增: if not turns[-1]["text"].endswith(text):
234新增: turns[-1]["text"] = clip_text((turns[-1]["text"] + "\n\n" + text).strip(), REPLY_LIMIT)
235新增: if turns:
236新增: if state.get("account_failure"):
237新增: turns[-1]["status"] = "failed"
238新增: elif state.get("stopped"):
239新增: turns[-1]["status"] = "stopped"
240新增: elif running and state.get("busy"):
241新增: turns[-1]["status"] = "running"
242新增: elif not running and turns[-1]["status"] == "queued":
243新增: turns[-1]["status"] = "interrupted"
244新增: approvals = state.get("approvals", [])
245新增: if running and approvals:
246新增: turns[-1]["status"] = "running"
247新增: turns[-1]["approval"] = {key: value for key, value in approvals[0].items() if key != "relay_id"}
248新增: shortened = any(turn.get("prompt_truncated") for turn in turns)
249新增: while len(turns) > 1 and len(json.dumps(turns, ensure_ascii=False).encode()) > HISTORY_LIMIT:
250新增: turns.pop(0)
251新增: shortened = True
252新增: modified = max(path.stat().st_mtime if path else 0, float(state.get("updated_at", 0)))
253新增: notice = state.get("native_ccs_notice", "")
254新增: if state.get("blocked"):
255新增: notice = "这台主机的 Claude Code 管理策略关闭了 Channels,请由主机管理员处理。"
256新增: elif state.get("policy_unavailable"):
257新增: notice = "Cage 默认环境的通道配置未能更新,请在电脑更新环境组件。"
258新增: return {"cli_id": session_id, "config": str(config), "connection": connection, "native_ccs_unverified": bool(state.get("native_ccs_unverified")),
259新增: "workspace": workspace or state.get("workspace", ""), "title": title or (turns[0]["prompt"][:40] if turns else "Claude Code"),
260新增: "updated_at": modified, "turns": turns, "running": bool(running), "active": bool(running and (state.get("busy") or state.get("approvals"))), "channel_ready": bool(channel), "can_send": bool(channel and not state.get("resume_task")), "has_history": has_history, "history_truncated": shortened,
261新增: "connection_notice": "" if channel else notice, "account_failure": state.get("account_failure", ""),
262新增: "resume_pending": bool(state.get("resume_task")), "native_history": native_history}
263新增:
264新增:
265新增:def history_summary(path):
266新增: workspace, title = "", ""
267新增: with path.open() as stream:
268新增: for _ in range(64):
269新增: line = stream.readline(4 << 20)
270新增: if not line:
271新增: break
272新增: try:
273新增: row = json.loads(line)
274新增: except ValueError:
275新增: continue
276新增: workspace = row.get("cwd") or workspace
277新增: if row.get("type") == "user":
278新增: text = text_content(row.get("message") or {})
279新增: channel = channel_message(text) if row.get("isMeta") else None
280新增: if channel:
281新增: title = channel[1][:40]
282新增: elif not row.get("isMeta"):
283新增: title = text[:40]
284新增: if workspace and title:
285新增: break
286新增: # Names and directory changes are appended to the transcript. Read a
287新增: # bounded tail for the list, and load full message history only on opening.
288新增: with path.open("rb") as stream:
289新增: stream.seek(max(0, path.stat().st_size - (64 << 10)))
290新增: lines = stream.read().splitlines()
291新增: for line in lines:
292新增: try:
293新增: row = json.loads(line)
294新增: except (ValueError, UnicodeDecodeError):
295新增: continue
296新增: workspace = row.get("cwd") or workspace
297新增: if row.get("type") == "custom-title":
298新增: title = row.get("customTitle") or title
299新增: return workspace, title
300新增:
301新增:
302新增:def discover(request):
303新增: allowed = request["workspaces"]
304新增: sessions = []
305新增: configs = {str(config_directory(account)) for account in request["accounts"]}
306新增: for state_path in ROOT.glob("*/state.json"):
307新增: state = read_json(state_path, {})
308新增: if state.get("config"):
309新增: configs.add(state["config"])
310新增: for config_name in configs:
311新增: config = Path(config_name)
312新增: paths = sorted((config / "projects").glob("*/*.jsonl"), key=lambda p: p.stat().st_mtime, reverse=True)
313新增: found = set()
314新增: for path in paths:
315新增: if path.is_symlink():
316新增: continue
317新增: try:
318新增: session_id = identifier(path.stem)
319新增: except ValueError:
320新增: continue
321新增: workspace, title = history_summary(path)
322新增: if not any(workspace_within(workspace, root) for root in allowed):
323新增: continue
324新增: connection, state = connection_for(session_id, config)
325新增: item = {"cli_id": session_id, "config": config_name, "connection": connection,
326新增: "workspace": workspace, "title": title or "Claude Code", "updated_at": path.stat().st_mtime,
327新增: "active": bool(live(state.get("pid")) and not state.get("closed") and (state.get("busy") or state.get("approvals")))}
328新增: found.add(session_id)
329新增: sessions.append(item)
330新增: for state_path in ROOT.glob("*/state.json"):
331新增: state = read_json(state_path, {})
332新增: session_id = state.get("cli_id")
333新增: workspace = state.get("workspace", "")
334新增: if state.get("config") != config_name or not session_id or session_id in found or not any(workspace_within(workspace, root) for root in allowed):
335新增: continue
336新增: item = view(config, session_id)
337新增: item.pop("turns")
338新增: sessions.append(item)
339新增: return sessions
340新增:
341新增:
342新增:def hook(connection):
343新增: payload = json.load(sys.stdin)
344新增: event = payload.get("hook_event_name")
345新增: with state_file(connection) as state:
346新增: if state.get("account_switch"):
347新增: if event == "UserPromptSubmit":
348新增: return {"decision": "block", "reason": "Cage 正在切换账号,请在目标会话中继续。"}
349新增: if event == "PreToolUse":
350新增: return {"hookSpecificOutput": {"hookEventName": event, "permissionDecision": "deny", "permissionDecisionReason": "Cage 正在切换账号。"}}
351新增: state["updated_at"] = time.time()
352新增: state["cli_id"] = identifier(payload["session_id"])
353新增: state["workspace"] = payload.get("cwd", state.get("workspace", ""))
354新增: state["config"] = str(config_directory("default"))
355新增: if event == "SessionStart":
356新增: state["closed"] = False
357新增: if event in ("UserPromptSubmit", "PreToolUse"):
358新增: state["busy"] = True
359新增: if event == "UserPromptSubmit":
360新增: state.pop("account_failure", None)
361新增: state.pop("stopped", None)
362新增: state.pop("pending_send", None)
363新增: if event in ("UserPromptSubmit", "PreToolUse", "PostToolUse", "PostToolUseFailure", "Stop", "SessionEnd"):
364新增: state["approvals"] = []
365新增: if event in ("Stop", "StopFailure", "SessionEnd"):
366新增: state["busy"] = False
367新增: state.pop("display", None)
368新增: if event == "StopFailure":
369新增: state["account_failure"] = payload.get("error", "unknown")
370新增: if event == "SessionEnd":
371新增: state["closed"] = True
372新增: if event == "MessageDisplay":
373新增: current = state.get("display") or {}
374新增: if current.get("id") != payload.get("message_id"):
375新增: current = {"id": payload.get("message_id"), "text": "", "index": -1}
376新增: if payload.get("index", 0) > current["index"]:
377新增: current["text"] = clip_text(current["text"] + payload.get("delta", ""), REPLY_LIMIT)
378新增: current["index"] = payload.get("index", 0)
379新增: state["display"] = current
380新增: return {}
381新增:
382新增:
383新增:def migrate_cage_policy():
384新增: if os.name == "nt":
385新增: # Organizational Windows policy is never rewritten by a GUI user.
386新增: return None
387新增: path = Path("/etc/claude-code/managed-settings.json")
388新增: original = {"permissions": {"defaultMode": "bypassPermissions"}, "tui": "fullscreen"}
389新增: if sys.platform != "linux":
390新增: return
391新增: try:
392新增: if read_json(path) != original:
393新增: return
394新增: except (OSError, ValueError):
395新增: return False
396新增: # Upgrade only the exact policy shipped by Cage. An administrator's
397新增: # explicit settings, including channelsEnabled=false, take precedence.
398新增: migration = '''import json, pathlib, tempfile, os
399新增:p = pathlib.Path('/etc/claude-code/managed-settings.json')
400新增:old = p.read_bytes()
401新增:value = json.loads(old)
402新增:if value == {"permissions": {"defaultMode": "bypassPermissions"}, "tui": "fullscreen"}:
403新增: backup = p.with_name('managed-settings.json.cage-before-channels')
404新增: if not backup.exists():
405新增: backup.write_bytes(old)
406新增: backup.chmod(0o600)
407新增: value['channelsEnabled'] = True
408新增: with tempfile.NamedTemporaryFile(dir=p.parent, mode='w', delete=False) as f:
409新增: json.dump(value, f)
410新增: name = f.name
411新增: os.chmod(name, 0o644)
412新增: os.replace(name, p)
413新增:'''
414新增: try:
415新增: subprocess.run(["/usr/bin/sudo", "-n", "python3", "-I", "-c", migration], timeout=10,
416新增: stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
417新增: except (OSError, subprocess.SubprocessError):
418新增: return False
419新增: return True
420新增:
421新增:
422新增:def active_session(session_id, config=""):
423新增: return bool(active_sessions(session_id, config))
424新增:
425新增:
426新增:def active_sessions(session_id, config=""):
427新增: env = dict(os.environ)
428新增: if config:
429新增: env["CLAUDE_CONFIG_DIR"] = config
430新增: listing = subprocess.run(["claude", "agents", "--json"], env=env, capture_output=True, text=True, timeout=10)
431新增: if listing.returncode != 0:
432新增: raise ValueError("无法检查原会话是否仍在运行")
433新增: return [row for row in json.loads(listing.stdout) if row.get("sessionId") == session_id and live(row.get("pid"))]
434新增:
435新增:
436新增:def handoff_session(request):
437新增: session_id = identifier(request["cli_id"])
438新增: config = request["config"]
439新增: workspace = request["workspace"]
440新增: rows = active_sessions(session_id, config)
441新增: # A live shared channel is reusable even after the host service restarts.
442新增: _, state = connection_for(session_id, Path(config))
443新增: if live(state.get("pid")) and live(state.get("channel_pid")) and not state.get("closed"):
444新增: return {"running": True, "channel_ready": True}
445新增: for row in rows:
446新增: if row.get("cwd") != workspace:
447新增: raise ValueError("原会话的项目已变化,请重新读取会话列表")
448新增: # A waiting CLI has no executing tool. Resume its task on the shared
449新增: # channel so any permission decision is requested again on the phone.
450新增: if row.get("status") not in ("idle", "waiting") or row.get("kind") != "interactive":
451新增: return {"running": True}
452新增: for row in rows:
453新增: # Refresh the supported CLI registry immediately before signalling so
454新增: # stale discovery data cannot select a different process or workspace.
455新增: current = active_sessions(session_id, config)
456新增: matched = next((item for item in current if item.get("pid") == row["pid"] and item.get("cwd") == workspace and item.get("kind") == "interactive" and item.get("status") in ("idle", "waiting")), None)
457新增: if matched is None:
458新增: return {"running": bool(current)}
459新增: if matched["status"] == "waiting":
460新增: save(handoff_receipt(config, session_id), {"resume_task": True, "permission_mode": "manual" if matched.get("waitingFor") != "input needed" else ""})
461新增: try:
462新增: terminate_cli(row["pid"])
463新增: except ProcessLookupError:
464新增: pass
465新增: deadline = time.monotonic() + 5
466新增: while rows and time.monotonic() < deadline:
467新增: if not any(live(row["pid"]) for row in rows):
468新增: return {"running": False}
469新增: time.sleep(0.05)
470新增: return {"running": bool(rows)}
471新增:
472新增:
473新增:def handoff_receipt(config, session_id):
474新增: key = hashlib.sha256((str(config) + "\n" + session_id).encode()).hexdigest()
475新增: return ROOT.parent / "cli-handoffs" / (key + ".json")
476新增:
477新增:
478新增:def prepare_account_switch(request):
479新增: # Freeze only an idle source. Never resubmit prompts or tools here.
480新增: sid = identifier(request["cli_id"])
481新增: switch_id = identifier(request["switch_id"])
482新增: config = Path(request["config"]).resolve()
483新增: connection = identifier(request["connection"])
484新增: workspace = request["workspace"]
485新增: folder = ROOT.parent / "cli-account-switches" / switch_id
486新增: receipt = folder / "receipt.json"
487新增: binding = {key: request[key] for key in ("cli_id", "config", "connection", "workspace", "target_cli_id")}
488新增: if receipt.exists():
489新增: saved = read_json(receipt)
490新增: if saved["binding"] != binding:
491新增: raise ValueError("账号交接编号已用于另一项操作")
492新增: return {"transcript": str(folder / "history.jsonl")}
493新增: with state_file(connection) as state:
494新增: if state.get("cli_id") != sid or state.get("config") != str(config) or state.get("workspace") != workspace:
495新增: raise ValueError("原会话身份或项目已变化,请刷新后重试")
496新增: if state.get("busy") or state.get("approvals") or state.get("pending_send") or state.get("sent"):
497新增: raise ValueError("原会话仍有任务、待发消息或审批,请结束后再切换账号")
498新增: existing = state.get("account_switch")
499新增: if existing and existing != switch_id:
500新增: raise ValueError("此会话已有账号交接尚未完成")
501新增: state["account_switch"] = switch_id
502新增: save(ROOT / connection / "state.json", state)
503新增: rows = active_sessions(sid, str(config))
504新增: # Any other live worker in this account can represent a background
505新增: # child of the source. The registry does not expose a complete ancestry.
506新增: listing = subprocess.run(["claude", "agents", "--json"], env={**os.environ, "CLAUDE_CONFIG_DIR": str(config)}, capture_output=True, text=True, timeout=10)
507新增: if listing.returncode != 0:
508新增: raise ValueError("无法确认后台任务,未切换账号")
509新增: if any(row.get("sessionId") != sid and live(row.get("pid")) for row in json.loads(listing.stdout)):
510新增: raise ValueError("原账号仍有其他执行任务,请结束后台任务后再交接")
511新增: for row in rows:
512新增: if row.get("cwd") != workspace or row.get("status") != "idle" or row.get("kind") != "interactive":
513新增: raise ValueError("原 Claude Code 尚未安全停止,请先结束本轮任务")
514新增: pid = state.get("pid")
515新增: fingerprint = process_fingerprint(pid) if live(pid) else ""
516新增: def executing():
517新增: if not live(pid):
518新增: return False
519新增: if os.name == "nt":
520新增: return True
521新增: status = subprocess.run(["ps", "-o", "stat=", "-p", str(pid)], capture_output=True, text=True, timeout=2)
522新增: return bool(status.stdout.strip()) and not status.stdout.lstrip().startswith("Z")
523新增: if executing() and not any(row.get("pid") == pid for row in rows):
524新增: raise ValueError("无法核对原进程状态,请先退出原 Claude Code 后重试")
525新增: for row in rows:
526新增: terminate_cli(row["pid"])
527新增: deadline = time.monotonic() + 5
528新增: while executing() and time.monotonic() < deadline:
529新增: time.sleep(.05)
530新增: if executing():
531新增: latest = read_json(ROOT / connection / "state.json", {})
532新增: current = process_fingerprint(pid)
533新增: # The CLI can finish its SessionEnd hook but hang while shutting down
534新增: # its MCP child. Terminate only that same, already idle and fenced CLI.
535新增: if latest.get("closed") and latest.get("account_switch") == switch_id and fingerprint and current == fingerprint and not active_sessions(sid, str(config)):
536新增: terminate_cli(pid, True)
537新增: deadline = time.monotonic() + 1
538新增: while executing() and time.monotonic() < deadline:
539新增: time.sleep(.05)
540新增: if executing():
541新增: raise ValueError("原进程尚未退出,未启动目标账号")
542新增: path = next((config / "projects").glob("*/" + sid + ".jsonl"), None)
543新增: if path is None or path.is_symlink():
544新增: raise ValueError("原会话历史不可用,未切换账号")
545新增: pending = set()
546新增: for line in path.read_text().splitlines():
547新增: row = json.loads(line)
548新增: if row.get("isSidechain"):
549新增: continue
550新增: if row.get("cwd") and row["cwd"] != workspace:
551新增: raise ValueError("历史项目与当前项目不一致")
552新增: blocks = (row.get("message") or {}).get("content", [])
553新增: if not isinstance(blocks, list):
554新增: continue
555新增: for block in blocks:
556新增: if block.get("type") == "tool_use":
557新增: pending.add(block["id"])
558新增: elif block.get("type") == "tool_result":
559新增: pending.discard(block.get("tool_use_id"))
560新增: if pending:
561新增: raise ValueError("历史仍有结果未确认的工具,不能自动接续")
562新增: folder.mkdir(mode=0o700, parents=True, exist_ok=True)
563新增: target = folder / "history.jsonl"
564新增: with tempfile.NamedTemporaryFile(dir=folder, delete=False) as stream:
565新增: stream.write(path.read_bytes())
566新增: temporary = stream.name
567新增: os.replace(temporary, target)
568新增: save(receipt, {"binding": binding, "requests": state.get("requests", {})})
569新增: with state_file(connection) as state:
570新增: state["closed"] = True
571新增: return {"transcript": str(target)}
572新增:
573新增:
574新增:def cancel_account_switch(request):
575新增: connection = identifier(request["connection"])
576新增: switch_id = identifier(request["switch_id"])
577新增: with state_file(connection) as state:
578新增: if state.get("cli_id") != identifier(request["cli_id"]) or state.get("account_switch") not in (None, switch_id):
579新增: raise ValueError("原会话交接已变化")
580新增: state.pop("account_switch", None)
581新增: # The source may already be stopped, but it remains resumable. Remove only
582新增: # this operation's frozen copy so a later retry cannot use stale history.
583新增: folder = ROOT.parent / "cli-account-switches" / switch_id
584新增: if folder.exists():
585新增: shutil.rmtree(folder)
586新增: return {"ok": True}
587新增:
588新增:
589新增:def purge_session(request):
590新增: session_id = identifier(request["cli_id"])
591新增: config = Path(request["config"]) if request.get("config") else config_directory(request.get("account") or "default")
592新增: config = config.resolve()
593新增: workspace = request["workspace"].rstrip("/")
594新增: if active_session(session_id, str(config)):
595新增: raise ValueError("Claude Code 仍在运行这段会话,请先结束原终端中的 Claude Code")
596新增: projects = config / "projects"
597新增: if projects.is_symlink():
598新增: raise ValueError("会话目录是符号链接,请检查主机配置")
599新增: paths = list(projects.glob("*/" + session_id + ".jsonl"))
600新增: for path in paths:
601新增: if path.is_symlink() or path.parent.is_symlink():
602新增: raise ValueError("会话历史路径已变化,请检查主机配置")
603新增: directory, _ = history_summary(path)
604新增: if not workspace_within(directory, workspace):
605新增: raise ValueError("会话历史与已授权项目不一致")
606新增: key = hashlib.sha256((str(config) + "\n" + session_id).encode()).hexdigest()
607新增: receipt = ROOT.parent / "cli-deleted" / (key + ".json")
608新增: if not paths and request.get("expect_history") and not receipt.exists():
609新增: raise ValueError("当前账号配置中未找到原始会话,请核对主机配置后重试")
610新增: # The SDK's delete_session removes the transcript and its sibling session
611新增: # directory. Keep a content-free receipt so a lost response can be retried.
612新增: save(receipt, {"cli_id": session_id, "config": str(config), "complete": False})
613新增: for path in paths:
614新增: related = path.parent / session_id
615新增: if related.is_symlink():
616新增: related.unlink()
617新增: elif related.exists():
618新增: shutil.rmtree(related)
619新增: path.unlink(missing_ok=True)
620新增: for path in ROOT.glob("*/state.json"):
621新增: state = read_json(path, {})
622新增: if state.get("cli_id") == session_id and state.get("config") == str(config):
623新增: if live(state.get("pid")) and not state.get("closed"):
624新增: raise ValueError("会话通道尚未退出,请稍后重试")
625新增: shutil.rmtree(path.parent)
626新增: identity = ROOT.parent / "mobile-cli-identities" / session_id
627新增: identity.unlink(missing_ok=True)
628新增: handoff_receipt(config, session_id).unlink(missing_ok=True)
629新增: save(receipt, {"cli_id": session_id, "config": str(config), "complete": True})
630新增: for saved in (ROOT.parent / "cli-account-switches").glob("*/receipt.json"):
631新增: binding = read_json(saved, {}).get("binding", {})
632新增: if binding.get("cli_id") == session_id or binding.get("target_cli_id") == session_id:
633新增: shutil.rmtree(saved.parent)
634新增: return {"ok": True}
635新增:
636新增:
637新增:def launch(request):
638新增: if os.name == "nt" and request.get("ccs_profile"):
639新增: return _platform["launch_ccs_parent"](request, globals())
640新增: policy_available = migrate_cage_policy()
641新增: connection = identifier(request["id"])
642新增: folder = ROOT / connection
643新增: folder.mkdir(parents=True, exist_ok=True, mode=0o700)
644新增: prefix = request["prefix"]
645新增: if os.name == "nt":
646新增: account_id = request.get("account") or "default"
647新增: os.environ["CLAUDE_CONFIG_DIR"] = str(config_directory(account_id))
648新增: if request.get("subject"):
649新增: os.environ["CAGE_CLAUDE_SUBJECT"] = request["subject"]
650新增: prefix = [os.environ["CAGE_CLI_BINARY"]]
651新增: request["prefix"] = prefix
652新增: elif len(prefix) == 5 and Path(prefix[2]).name == "cage-claude-account" and prefix[3] == "run":
653新增: os.environ["CLAUDE_CONFIG_DIR"] = str(config_directory(prefix[4]))
654新增: elif request.get("config"):
655新增: os.environ["CLAUDE_CONFIG_DIR"] = request["config"]
656新增: session_id = identifier(request.get("resume") or request.get("session_id") or connection)
657新增: _, previous = connection_for(session_id, config_directory("default"))
658新增: if request.get("resume"):
659新增: if active_session(request["resume"]):
660新增: raise ValueError("原会话仍在电脑终端运行,请先结束该终端中的 Claude Code 再接续")
661新增: command = shlex.join([sys.executable, *(["-X", "utf8"] if os.name == "nt" else []), "-I", str(Path(__file__).resolve()), "hook", connection])
662新增: events = ("SessionStart", "UserPromptSubmit", "MessageDisplay", "PreToolUse", "PostToolUse", "PostToolUseFailure", "Stop", "StopFailure", "SessionEnd")
663新增: handler = {"type": "command", "command": command, "timeout": 5}
664新增: if os.name == "nt":
665新增: handler = {"type": "command", "command": sys.executable,
666新增: "args": ["-X", "utf8", "-I", str(Path(__file__).resolve()), "hook", connection], "timeout": 5}
667新增: settings = {"hooks": {event: [{"hooks": [handler.copy()]}] for event in events}}
668新增: prefix = request["prefix"]
669新增: if os.name == "nt":
670新增: account = runpy.run_path(os.environ["CAGE_CLI_ACCOUNT_HELPER"])
671新增: if not account["has_status_line"](account["profile"](account_id)):
672新增: status_command = shlex.join([sys.executable, "-X", "utf8", "-I", os.environ["CAGE_CLI_ACCOUNT_HELPER"], "statusline", account_id])
673新增: settings["statusLine"] = {"type": "command", "command": status_command}
674新增: elif len(prefix) == 5 and Path(prefix[2]).name == "cage-claude-account" and prefix[3] == "run":
675新增: account = runpy.run_path(prefix[2])
676新增: if not account["has_status_line"](account["profile"](prefix[4])):
677新增: settings["statusLine"] = {"type": "command", "command": prefix[2] + " statusline " + prefix[4]}
678新增: save(folder / "settings.json", settings)
679新增: config = {"mcpServers": {"cage": {"command": sys.executable, "args": [*(["-X", "utf8"] if os.name == "nt" else []), "-I", str(Path(__file__).resolve()), "serve", connection]}}}
680新增: save(folder / "mcp.json", config)
681新增: with state_file(connection) as state:
682新增: if live(state.get("pid")) and not state.get("closed"):
683新增: raise ValueError("目标会话已有进程,未重复启动")
684新增: state.update(cli_id=session_id, config=str(config_directory("default")),
685新增: workspace=str(Path.cwd()), pid=os.getpid(), closed=False, updated_at=time.time(), approvals=[], busy=False,
686新增: channel_pid=None, pending_send=None, display=None, stopped=False,
687新增: requests=previous.get("requests", {}), sent=previous.get("sent", []))
688新增: receipt = handoff_receipt(config_directory("default"), session_id)
689新增: transfer = read_json(receipt, {})
690新增: state["resume_task"] = previous.get("resume_task", False) or transfer.get("resume_task", False)
691新增: state["account_resume"] = previous.get("account_resume", False)
692新增: if request.get("resume_transcript"):
693新增: state["resume_transcript"] = request["resume_transcript"]
694新增: state["resume_task"] = bool(request.get("continue_after_switch"))
695新增: state["account_resume"] = True
696新增: transfer = read_json(ROOT.parent / "cli-account-switches" / identifier(request["switch_id"]) / "receipt.json", {})
697新增: state["requests"] = {**transfer.get("requests", {}), **state["requests"]}
698新增: state["handoff_permission_mode"] = transfer.get("permission_mode") or previous.get("handoff_permission_mode", "")
699新增: receipt.unlink(missing_ok=True)
700新增: for sent in state.get("sent", []):
701新增: sent["interrupted"] = True
702新增: try:
703新增: policy = Path(os.environ.get("ProgramFiles", "C:/Program Files")) / "ClaudeCode/managed-settings.json" if os.name == "nt" else Path("/Library/Application Support/ClaudeCode/managed-settings.json") if sys.platform == "darwin" else Path("/etc/claude-code/managed-settings.json")
704新增: managed = read_json(policy, {})
705新增: state["blocked"] = isinstance(managed, dict) and managed.get("channelsEnabled") is False
706新增: except (OSError, ValueError):
707新增: state["blocked"] = False
708新增: state["policy_unavailable"] = policy_available is False
709新增: args = [*request["prefix"], "--settings", str(folder / "settings.json"), "--mcp-config", str(folder / "mcp.json"),
710新增: "--dangerously-load-development-channels", "server:cage"]
711新增: if request.get("resume_transcript"):
712新增: expected = ROOT.parent / "cli-account-switches" / identifier(request["switch_id"]) / "history.jsonl"
713新增: if Path(request["resume_transcript"]) != expected or not expected.is_file():
714新增: raise ValueError("账号交接历史无效")
715新增: args += ["--resume", str(expected), "--fork-session", "--session-id", session_id]
716新增: else:
717新增: args += ["--resume", session_id] if request.get("resume") else ["--session-id", session_id]
718新增: if state.get("handoff_permission_mode") == "manual":
719新增: args += ["--permission-mode", "manual"]
720新增: if os.name == "nt":
721新增: return _platform["launch_cli"](args, request, connection, state_file)
722新增: os.execvpe(args[0], args, os.environ)
723新增:
724新增:
725新增:def rpc(request):
726新增: connection = identifier(request["connection"])
727新增: os.chdir(ROOT / connection)
728新增: with socket.socket(socket.AF_UNIX) as client:
729新增: client.settimeout(5)
730新增: client.connect("rpc")
731新增: client.sendall(json.dumps(request).encode() + b"\n")
732新增: with client.makefile("rb") as stream:
733新增: return json.loads(stream.readline(1 << 20))
734新增:
735新增:
736新增:def serve(connection):
737新增: connection = identifier(connection)
738新增: output_lock = threading.Lock()
739新增:
740新增: def emit(message):
741新增: with output_lock:
742新增: sys.stdout.write(json.dumps({"jsonrpc": "2.0", **message}) + "\n")
743新增: sys.stdout.flush()
744新增:
745新增: class Handler(socketserver.StreamRequestHandler):
746新增: def handle(self):
747新增: self.connection.settimeout(5)
748新增: try:
749新增: request = json.loads(self.rfile.readline(72 << 10))
750新增: with state_file(connection) as state:
751新增: if request["cli_id"] != state.get("cli_id") or state.get("closed"):
752新增: raise ValueError("终端已切换会话,请重新读取列表")
753新增: action = request["action"]
754新增: if state.get("account_switch"):
755新增: raise ValueError("此会话正在切换账号,请等待交接完成")
756新增: if action == "send":
757新增: request_id = identifier(request["request_id"])
758新增: text = request["text"]
759新增: if not text.strip() or len(text.encode()) > PROMPT_LIMIT:
760新增: raise ValueError("消息为空或过长")
761新增: digest = hashlib.sha256(text.encode()).hexdigest()
762新增: requests = state.setdefault("requests", {})
763新增: previous = requests.get(request_id)
764新增: if previous is not None:
765新增: if previous != digest:
766新增: raise ValueError("同一发送编号已用于另一条消息")
767新增: else:
768新增: if state.get("busy") or state.get("pending_send"):
769新增: raise ValueError("这段会话已有消息正在处理,请等待后重试")
770新增: state.pop("stopped", None)
771新增: state["pending_send"] = request_id
772新增: requests[request_id] = digest
773新增: state.setdefault("sent", []).append({"id": request_id, "text": text})
774新增: # Persist admission before writing to the CLI. A lost
775新增: # acknowledgement must never replay a channel event.
776新增: save(ROOT / connection / "state.json", state)
777新增: emit({"method": "notifications/claude/channel", "params": {"content": text, "meta": {"cage_request": request_id}}})
778新增: elif action == "approve":
779新增: pending = state.get("approvals", [])
780新增: if not pending or pending[0]["id"] != request["approval_id"] or type(request["allow"]) is not bool:
781新增: raise ValueError("审批已结束,请重新读取会话")
782新增: approval = pending.pop(0)
783新增: emit({"method": "notifications/claude/channel/permission", "params": {
784新增: "request_id": approval["relay_id"], "behavior": "allow" if request["allow"] else "deny"}})
785新增: elif action == "stop":
786新增: state["stopped"] = True
787新增: state["busy"] = False
788新增: state["approvals"] = []
789新增: elif action == "resume":
790新增: if state.get("resume_task"):
791新增: state["resume_task"] = False
792新增: state["busy"] = True
793新增: # Commit before notification; reconnecting must not
794新增: # inject the same continuation twice.
795新增: save(ROOT / connection / "state.json", state)
796新增: emit({"method": "notifications/claude/channel", "params": {
797新增: "content": Path(__file__).with_suffix(".account-resume.md" if state.get("account_resume") else ".resume.md").read_text(encoding="utf-8"),
798新增: "meta": {"cage_resume": "true"}}})
799新增: else:
800新增: raise ValueError("unsupported operation")
801新增: state["updated_at"] = time.time()
802新增: response = {"ok": True}
803新增: except (OSError, ValueError, KeyError, TypeError) as error:
804新增: response = {"error": str(error)}
805新增: self.wfile.write(json.dumps(response).encode() + b"\n")
806新增:
807新增: os.chdir(ROOT / connection)
808新增: address = "rpc"
809新增: # A connection UUID is created once by the host. A second live server must
810新增: # fail to bind instead of stealing the first server's socket.
811新增: if Path(address).is_socket():
812新增: with socket.socket(socket.AF_UNIX) as probe:
813新增: try:
814新增: probe.connect(address)
815新增: except ConnectionRefusedError:
816新增: Path(address).unlink()
817新增: else:
818新增: raise ValueError("会话通道已在运行")
819新增: with socketserver.ThreadingUnixStreamServer(address, Handler) as server:
820新增: server.daemon_threads = True
821新增: os.chmod(address, 0o600)
822新增: threading.Thread(target=server.serve_forever, daemon=True).start()
823新增: try:
824新增: for line in sys.stdin:
825新增: message = json.loads(line)
826新增: method = message.get("method")
827新增: if method == "initialize":
828新增: emit({"id": message["id"], "result": {"protocolVersion": "2024-11-05", "serverInfo": {"name": "cage", "version": "1"},
829新增: "capabilities": {"experimental": {"claude/channel": {}, "claude/channel/permission": {}}},
830新增: "instructions": "The user is viewing this same Claude Code conversation from Cage on a phone. Respond normally in the conversation. Cage synchronizes the transcript."}})
831新增: elif method == "notifications/initialized":
832新增: with state_file(connection) as state:
833新增: state["channel_pid"] = os.getpid()
834新增: state["updated_at"] = time.time()
835新增: elif method == "notifications/claude/channel/permission_request":
836新增: params = message["params"]
837新增: preview = params.get("input_preview", "")
838新增: try:
839新增: arguments = json.loads(preview)
840新增: except ValueError:
841新增: arguments = {"preview": preview}
842新增: with state_file(connection) as state:
843新增: state.setdefault("approvals", []).append({"id": str(uuid.uuid4()), "relay_id": params["request_id"],
844新增: "tool": params["tool_name"], "input": arguments, "preview": True})
845新增: state["updated_at"] = time.time()
846新增: elif "id" in message:
847新增: if method == "ping":
848新增: emit({"id": message["id"], "result": {}})
849新增: else:
850新增: emit({"id": message["id"], "error": {"code": -32601, "message": "Method not supported"}})
851新增: finally:
852新增: server.shutdown()
853新增: Path(address).unlink(missing_ok=True)
854新增: with state_file(connection) as state:
855新增: state["channel_pid"] = None
856新增: state["approvals"] = []
857新增:
858新增:
859新增:def main():
860新增: os.umask(0o077)
861新增: mode, argument = sys.argv[1:3]
862新增: if mode == "ccs-live" and os.name == "nt":
863新增: return _platform["launch_ccs_live"](argument, globals())
864新增: if mode == "serve":
865新增: return serve(argument)
866新增: if mode == "hook":
867新增: result = hook(argument)
868新增: else:
869新增: request = json.load(sys.stdin) if argument == "-" else json.loads(argument)
870新增: if mode == "launch":
871新增: return launch(request)
872新增: if mode == "discover":
873新增: result = discover(request)
874新增: elif mode == "view":
875新增: config = Path(request["config"]) if request.get("config") else config_directory(request.get("account") or "default")
876新增: state = read_json(ROOT / identifier(request.get("connection") or request["cli_id"]) / "state.json", {})
877新增: if state.get("cli_id") == request["cli_id"] and state.get("config"):
878新增: config = Path(state["config"])
879新增: result = view(config, identifier(request["cli_id"]))
880新增: elif mode == "rpc":
881新增: result = rpc(request)
882新增: elif mode == "active":
883新增: config = request.get("config") or str(config_directory(request.get("account") or "default"))
884新增: result = {"running": active_session(identifier(request["cli_id"]), config)}
885新增: elif mode == "handoff":
886新增: try:
887新增: result = handoff_session(request)
888新增: except (OSError, ValueError, subprocess.SubprocessError) as error:
889新增: result = {"error": str(error)}
890新增: elif mode == "purge":
891新增: try:
892新增: result = purge_session(request)
893新增: except (OSError, ValueError, subprocess.SubprocessError) as error:
894新增: result = {"error": str(error)}
895新增: elif mode == "account-switch":
896新增: try:
897新增: result = prepare_account_switch(request)
898新增: except (OSError, ValueError, KeyError, subprocess.SubprocessError) as error:
899新增: result = {"error": str(error)}
900新增: elif mode == "account-switch-cancel":
901新增: try:
902新增: result = cancel_account_switch(request)
903新增: except (OSError, ValueError, KeyError) as error:
904新增: result = {"error": str(error)}
905新增: else:
906新增: raise ValueError("unsupported operation")
907新增: print(json.dumps(result, ensure_ascii=False))
908新增:
909新增:
910新增:if __name__ == "__main__":
911新增: sys.exit(main() or 0)
新增internal/workbench/cli_channel.resume.md+11 −0看文件
@@ -0,0 +1,11 @@
1新增:The user has reopened this same conversation from their phone. Continue their unfinished task using the saved conversation.
2新增:
3新增:You receive:
4新增:- The original user requests, assistant messages, and recorded tool results.
5新增:- This reconnect notice. It does not approve any tool or grant additional access.
6新增:
7新增:1. Resume only the unfinished part of the latest user request. Preserve completed work and do not repeat successful actions.
8新增:2. The previous process ended while waiting for the user. A pending tool approval did not transfer. Request a fresh permission decision through the current session before running that tool. Follow the current permission mode.
9新增:3. If you were waiting for an answer, repeat the question and wait for the user.
10新增:
11新增:Respond normally in this conversation. Do not describe the reconnect procedure or request connection confirmation.
新增internal/workbench/cli_channel_test.go+927 −0看文件
@@ -0,0 +1,927 @@
1新增://go:build !windows
2新增:
3新增:package workbench
4新增:
5新增:import (
6新增: "context"
7新增: "crypto/sha256"
8新增: "encoding/json"
9新增: "fmt"
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新增: "unicode/utf16"
23新增:
24新增: "al.essio.dev/pkg/shellescape"
25新增: "github.com/google/uuid"
26新增: "github.com/sylvinus/agent-vm/internal/mobilelink"
27新增: "github.com/sylvinus/agent-vm/internal/relay"
28新增: "github.com/sylvinus/agent-vm/internal/remotelink"
29新增:)
30新增:
31新增:func TestCLIChannelProtocol(t *testing.T) {
32新增: python, err := exec.LookPath("python3")
33新增: if err != nil {
34新增: t.Skip("python3 unavailable")
35新增: }
36新增: cmd := exec.Command(python, "-I", "cli_channel_test.py")
37新增: if output, err := cmd.CombinedOutput(); err != nil {
38新增: t.Fatalf("channel protocol: %v\n%s", err, output)
39新增: }
40新增:}
41新增:
42新增:func TestCLIChannelCommandFitsWindows(t *testing.T) {
43新增: // Leave room in CreateProcessW's 32767 UTF-16 limit for SSH paths and the
44新增: // login-shell quoting around this command.
45新增: command := cliChannelCommand("launch", `{"id":"`+uuid.NewString()+`","prefix":["claude"]}`)
46新增: t.Logf("embedded command: %d UTF-16 units", len(utf16.Encode([]rune(command))))
47新增: if size := len(utf16.Encode([]rune(command))); size > 16000 {
48新增: t.Fatalf("channel command uses %d UTF-16 units", size)
49新增: }
50新增:}
51新增:
52新增:func TestSharedSendReceiptSurvivesReadFailure(t *testing.T) {
53新增: s, id, project := metadataFixture(t)
54新增: home := t.TempDir()
55新增: mobileTestSSH(t, s, home, []string{"HOME=" + home, "PATH=/usr/bin:/bin:/usr/local/bin"})
56新增: record, err := s.mobileCLI.record(s.profile, id)
57新增: if err != nil {
58新增: t.Fatal(err)
59新增: }
60新增: record.Terminal = true
61新增: record.Connection = uuid.NewString()
62新增: record.GuestWorkspace = guestPath(project)
63新增: if err = writePrivate(mobileRecordPath(s.profile, id), record); err != nil {
64新增: t.Fatal(err)
65新增: }
66新增: // Keep the real host SSH/bootstrap/RPC path; replace only the guest
67新增: // operation boundary to lose the read immediately after an admitted send.
68新增: helper := filepath.Join(home, ".local/share/cage/cli-channel-code", fmt.Sprintf("%x.py", sha256.Sum256([]byte(cliChannelHelper+cliResumePrompt+claudeAccountResumePrompt))))
69新增: if err = os.MkdirAll(filepath.Dir(helper), 0700); err != nil {
70新增: t.Fatal(err)
71新增: }
72新增: code := "import json,sys\nrequest=json.load(sys.stdin)\nif sys.argv[1]=='rpc': print(json.dumps({'ok':True}))\nelse: sys.exit(3)\n"
73新增: if err = os.WriteFile(helper, []byte(code), 0600); err != nil {
74新增: t.Fatal(err)
75新增: }
76新增: epoch, ok := s.account.access()
77新增: if !ok {
78新增: t.Fatal("missing unlock epoch")
79新增: }
80新增: ctx := context.WithValue(context.Background(), mobileEpochKey{}, epoch)
81新增: requestID := uuid.NewString()
82新增: view, err := s.terminalConversationAction(ctx, id, map[string]any{"action": "send", "request_id": requestID, "text": "accepted message"})
83新增: if err != nil || view.AcknowledgedRequestID != requestID {
84新增: t.Fatalf("admitted send lost its receipt: %#v %v", view, err)
85新增: }
86新增: if len(view.Turns) != len(record.Turns)+1 || view.Turns[len(view.Turns)-1].Text != "" || view.Turns[len(view.Turns)-1].Status != "queued" {
87新增: t.Fatal("receipt did not preserve the accepted message without inventing a reply")
88新增: }
89新增:}
90新增:
91新增:func TestSessionCatalogActivity(t *testing.T) {
92新增: s, id, project := metadataFixture(t)
93新增: record, err := s.mobileCLI.record(s.profile, id)
94新增: if err != nil {
95新增: t.Fatal(err)
96新增: }
97新增: record.Terminal = true
98新增: record.Active = true
99新增: if err := writePrivate(mobileRecordPath(s.profile, id), record); err != nil {
100新增: t.Fatal(err)
101新增: }
102新增: s.mobileCLI.catalog = nil
103新增: list, err := s.mobileCLI.summaries(s.profile, map[string]bool{project: true}, false)
104新增: if err != nil || len(list) != 1 || !list[0].Active {
105新增: t.Fatal("catalog lost task activity", list, err)
106新增: }
107新增: record.Terminal = false
108新增: record.Active = false
109新增: record.Turns = []mobileTurn{{Status: "running"}}
110新增: s.mobileCLI.active = map[string]*mobileRun{id: {record: record}}
111新增: list, err = s.mobileCLI.summaries(s.profile, map[string]bool{project: true}, false)
112新增: if err != nil || !list[0].Active {
113新增: t.Fatal("mobile turn activity missing", list, err)
114新增: }
115新增: record.Turns[0].Status = "completed"
116新增: list, err = s.mobileCLI.summaries(s.profile, map[string]bool{project: true}, false)
117新增: if err != nil || list[0].Active {
118新增: t.Fatal("completed turn stayed active", list, err)
119新增: }
120新增:}
121新增:
122新增:func TestImportedCLIUUIDIsIndependentOfPublicSessionID(t *testing.T) {
123新增: profile, id := t.TempDir(), uuid.NewString()
124新增: record := &mobileRecord{mobileSession: mobileSession{mobileSummary: mobileSummary{ID: id, Workspace: "/project"}, Turns: []mobileTurn{}}, CLIID: "c4cbf880-92e8-11f1-8596-0242ac120002", Terminal: true}
125新增: if err := writePrivate(mobileRecordPath(profile, id), record); err != nil {
126新增: t.Fatal(err)
127新增: }
128新增: var store mobileCLIStore
129新增: if _, err := store.record(profile, id); err != nil {
130新增: t.Fatal(err)
131新增: }
132新增: if mobileID(record.CLIID) {
133新增: t.Fatal("CLI identity widened the client creation contract")
134新增: }
135新增:}
136新增:
137新增:func TestArchivedCLIHistoryIsNotRediscovered(t *testing.T) {
138新增: s, id, project := metadataFixture(t)
139新增: home, _ := filepath.EvalSymlinks(t.TempDir())
140新增: mobileTestSSH(t, s, home, []string{"HOME=" + home, "PATH=/usr/bin:/bin:/usr/local/bin", "CLAUDE_CONFIG_DIR=" + filepath.Join(home, ".claude")})
141新增: record, err := s.mobileCLI.record(s.profile, id)
142新增: if err != nil {
143新增: t.Fatal(err)
144新增: }
145新增: history := filepath.Join(home, ".claude", "projects", "fixture", record.CLIID+".jsonl")
146新增: if err := os.MkdirAll(filepath.Dir(history), 0700); err != nil {
147新增: t.Fatal(err)
148新增: }
149新增: row, _ := json.Marshal(map[string]any{"cwd": guestPath(project), "type": "user", "uuid": uuid.NewString(), "message": map[string]string{"content": "guest title"}})
150新增: if err := os.WriteFile(history, append(row, '\n'), 0600); err != nil {
151新增: t.Fatal(err)
152新增: }
153新增: if _, err := s.mobileCLI.summaries(s.profile, map[string]bool{project: true}, false); err != nil {
154新增: t.Fatal(err)
155新增: }
156新增: s.ready = true
157新增: if err := s.discoverTerminalConversations(context.Background(), []string{project}); err != nil {
158新增: t.Fatal(err)
159新增: }
160新增: if w := request(s, "POST", "/api/mobile/cli/sessions/"+id+"/metadata", s.origin, `{"title":"保留用户命名","pinned":true}`, true); w.Code != 200 {
161新增: t.Fatal(w.Code, w.Body.String())
162新增: }
163新增: if err := s.discoverTerminalConversations(context.Background(), []string{project}); err != nil {
164新增: t.Fatal(err)
165新增: }
166新增: list, _ := s.mobileCLI.summaries(s.profile, map[string]bool{project: true}, false)
167新增: if len(list) != 1 || list[0].Title != "保留用户命名" || !list[0].Pinned {
168新增: t.Fatal("discovery overwrote metadata", list)
169新增: }
170新增: if err := s.setSessionArchived(id, true, nil); err != nil {
171新增: t.Fatal(err)
172新增: }
173新增: s.mobileCLI = mobileCLIStore{}
174新增: if _, err := s.mobileCLI.summaries(s.profile, map[string]bool{project: true}, false); err != nil {
175新增: t.Fatal(err)
176新增: }
177新增: if err := s.discoverTerminalConversations(context.Background(), []string{project}); err != nil {
178新增: t.Fatal(err)
179新增: }
180新增: list, _ = s.mobileCLI.summaries(s.profile, map[string]bool{project: true}, false)
181新增: if len(list) != 0 {
182新增: t.Fatal("guest history resurrected deleted entry", list)
183新增: }
184新增: if _, err := os.Stat(history); err != nil {
185新增: t.Fatal("CLI history was removed", err)
186新增: }
187新增:}
188新增:
189新增:func sharedCLIWorkbench(t *testing.T) (*Server, string, *atomic.Bool) {
190新增: t.Helper()
191新增: binary, flags := os.Getenv("CAGE_TEST_CLAUDE_CLI"), os.Getenv("CAGE_TEST_CHANNEL_FEATURES")
192新增: if runtime.GOOS != "darwin" || !filepath.IsAbs(binary) || !filepath.IsAbs(flags) {
193新增: t.Skip("set CAGE_TEST_CLAUDE_CLI and CAGE_TEST_CHANNEL_FEATURES on macOS for the isolated interactive CLI test")
194新增: }
195新增: features, err := os.ReadFile(flags)
196新增: if err != nil {
197新增: t.Fatal(err)
198新增: }
199新增: var booleans map[string]bool
200新增: if err := json.Unmarshal(features, &booleans); err != nil {
201新增: t.Fatal(err)
202新增: }
203新增: s := testServer(t)
204新增: home, _ := filepath.EvalSymlinks(t.TempDir())
205新增: project, _ := filepath.EvalSymlinks(t.TempDir())
206新增: s.ready = true
207新增: s.preferences.Workspace = project
208新增: if err := writePrivate(filepath.Join(s.profile, "environment.json"), map[string]string{"directory": project}); err != nil {
209新增: t.Fatal(err)
210新增: }
211新增: bin := filepath.Join(home, "bin")
212新增: if err := os.Mkdir(bin, 0700); err != nil {
213新增: t.Fatal(err)
214新增: }
215新增: actual, _ := filepath.EvalSymlinks(binary)
216新增: personal, _ := os.UserHomeDir()
217新增: quote := func(value string) string { b, _ := json.Marshal(value); return string(b) }
218新增: policy := "(version 1)(allow default)(deny mach-lookup)(deny file-read-data (subpath " + quote(personal) + ") (subpath \"/Library/Keychains\"))(allow file-read* (literal " + quote(actual) + "))(deny network-outbound)(allow network-outbound (remote ip \"localhost:*\"))"
219新增: debug := filepath.Join(home, "cli-debug.log")
220新增: t.Cleanup(func() {
221新增: if t.Failed() {
222新增: if data, err := os.ReadFile(debug); err == nil {
223新增: if len(data) > 16000 {
224新增: data = data[len(data)-16000:]
225新增: }
226新增: t.Log(string(data))
227新增: }
228新增: }
229新增: })
230新增: shim := "#!/bin/sh\nexec /usr/bin/sandbox-exec -p " + shellescape.Quote(policy) + " " + shellescape.Quote(actual) + " --debug-file " + shellescape.Quote(debug) + " --model sonnet --permission-mode manual \"$@\"\n"
231新增: if err := os.WriteFile(filepath.Join(bin, "claude"), []byte(shim), 0700); err != nil {
232新增: t.Fatal(err)
233新增: }
234新增: if strings.Contains(t.Name(), "CCS") {
235新增: // Exercise the profile dispatch boundary with a deterministic dispatcher;
236新增: // the interactive process and Channels remain the genuine CLI.
237新增: if err := os.WriteFile(filepath.Join(bin, "ccs"), []byte("#!/bin/sh\n[ \"$1\" = cage-fixture ] || exit 1\nshift\nexec claude \"$@\"\n"), 0700); err != nil {
238新增: t.Fatal(err)
239新增: }
240新增: s.preferences.ClaudeTerminalCommand = "ccs cage-fixture"
241新增: }
242新增: if err := os.WriteFile(filepath.Join(home, ".bash_profile"), []byte("export PATH="+shellescape.Quote(bin)+":/usr/bin:/bin\n"), 0600); err != nil {
243新增: t.Fatal(err)
244新增: }
245新增: key := "sk-ant-local-channel-test"
246新增: config := map[string]any{"hasCompletedOnboarding": true, "theme": "dark", "cachedGrowthBookFeatures": booleans,
247新增: "cachedGrowthBookFeaturesAt": time.Now().UnixMilli(), "customApiKeyResponses": map[string]any{"approved": []string{key[len(key)-20:]}, "rejected": []string{}},
248新增: "projects": map[string]any{project: map[string]bool{"hasTrustDialogAccepted": true}}}
249新增: if t.Name() == "TestSharedTerminalUntrustedProject" {
250新增: delete(config, "projects")
251新增: }
252新增: for _, path := range []string{filepath.Join(home, ".claude.json"), filepath.Join(home, ".claude", ".claude.json")} {
253新增: if err := writePrivate(path, config); err != nil {
254新增: t.Fatal(err)
255新增: }
256新增: }
257新增: var resumed atomic.Bool
258新增: model := mobileTestModel(t, &resumed)
259新增: t.Cleanup(model.Close)
260新增: mobileTestSSH(t, s, home, []string{"HOME=" + home, "PATH=" + bin + ":/usr/bin:/bin", "CLAUDE_CONFIG_DIR=" + filepath.Join(home, ".claude"),
261新增: "ANTHROPIC_API_KEY=" + key, "ANTHROPIC_BASE_URL=" + model.URL, "DISABLE_AUTOUPDATER=1", "TERM=xterm-256color",
262新增: "HTTPS_PROXY=http://127.0.0.1:1", "HTTP_PROXY=http://127.0.0.1:1", "NO_PROXY=127.0.0.1,localhost"})
263新增: // The local SSH stand-in must reap its CLI and hook children before the
264新增: // isolated home is removed. Closing the host PTY only waits for local SSH.
265新增: t.Cleanup(func() {
266新增: deadline := time.Now().Add(3 * time.Second)
267新增: for time.Now().Before(deadline) {
268新增: output, _ := exec.Command("pgrep", "-f", regexp.QuoteMeta(home)).Output()
269新增: if len(strings.TrimSpace(string(output))) == 0 {
270新增: return
271新增: }
272新增: for _, value := range strings.Fields(string(output)) {
273新增: pid, err := strconv.Atoi(value)
274新增: if err == nil && pid > 0 {
275新增: child, _ := os.FindProcess(pid)
276新增: _ = child.Kill()
277新增: _ = child.Release()
278新增: }
279新增: }
280新增: time.Sleep(30 * time.Millisecond)
281新增: }
282新增: t.Error("isolated CLI children did not exit")
283新增: })
284新增: t.Cleanup(s.terminals.closeAll)
285新增: return s, project, &resumed
286新增:}
287新增:
288新增:func TestSharedTerminalConversation(t *testing.T) {
289新增: testSharedTerminalConversation(t)
290新增:}
291新增:
292新增:func TestSharedCCSTerminalConversation(t *testing.T) {
293新增: testSharedTerminalConversation(t)
294新增:}
295新增:
296新增:func testSharedTerminalConversation(t *testing.T) {
297新增: s, project, resumed := sharedCLIWorkbench(t)
298新增: originalLauncher := claudeTerminalCommand(s.preferences)
299新增: if os.Getenv("CAGE_TEST_CHANNEL_BROWSER") != "" {
300新增: runSharedConversationBrowser(t, s, project)
301新增: return
302新增: }
303新增: api := func(method, path string, body any) mobileSession {
304新增: t.Helper()
305新增: data, _ := json.Marshal(body)
306新增: if body == nil {
307新增: data = nil
308新增: }
309新增: response := request(s, method, "/api/mobile/cli/"+path, s.origin, string(data), true)
310新增: if response.Code != http.StatusOK {
311新增: t.Fatalf("%s %s: %d %s", method, path, response.Code, response.Body.String())
312新增: }
313新增: var result mobileSession
314新增: if err := json.Unmarshal(response.Body.Bytes(), &result); err != nil {
315新增: t.Fatal(err)
316新增: }
317新增: return result
318新增: }
319新增: id := uuid.NewString()
320新增: // A phone built before shared-session negotiation omits the flag.
321新增: api("POST", "sessions", map[string]any{"id": id, "workspace": project})
322新增: // A view polled before the guest starts can mark the cached running flag
323新增: // false. The already published host PTY must remain its sole owner.
324新增: s.mobileCLI.mu.Lock()
325新增: starting, err := s.mobileCLI.record(s.profile, id)
326新增: if err == nil {
327新增: starting.TerminalRunning = false
328新增: err = writePrivate(mobileRecordPath(s.profile, id), starting)
329新增: }
330新增: s.mobileCLI.mu.Unlock()
331新增: if err != nil {
332新增: t.Fatal(err)
333新增: }
334新增: if view := api("POST", "sessions", map[string]any{"id": id, "workspace": project, "shared": false}); !view.TerminalAvailable {
335新增: t.Fatal("a client flag created a phone-only session")
336新增: }
337新增: terminals := s.terminals.snapshot()
338新增: if len(terminals) != 1 || terminals[0]["cli_session_id"] != id {
339新增: t.Fatalf("mobile creation did not expose its desktop terminal: %#v", terminals)
340新增: }
341新增: terminal := s.terminals.get(terminals[0]["id"].(string))
342新增: deadline := time.Now().Add(30 * time.Second)
343新增: var current mobileSession
344新增: wait := func(predicate func(mobileSession) bool) {
345新增: t.Helper()
346新增: for time.Now().Before(deadline) {
347新增: current = api("GET", "sessions/"+id, nil)
348新增: if predicate(current) {
349新增: return
350新增: }
351新增: time.Sleep(100 * time.Millisecond)
352新增: }
353新增: terminal.mu.Lock()
354新增: defer terminal.mu.Unlock()
355新增: t.Fatalf("shared conversation did not reach state: %#v\n%s", current, terminal.history)
356新增: }
357新增: wait(func(view mobileSession) bool { return view.CanSend != nil && *view.CanSend })
358新增: turn := uuid.NewString()
359新增: message := map[string]any{"request_id": turn, "text": "initial mobile prompt"}
360新增: api("POST", "sessions/"+id+"/messages", message)
361新增: api("POST", "sessions/"+id+"/messages", message)
362新增: wait(func(view mobileSession) bool { return len(view.Turns) == 1 && view.Turns[0].Approval != nil })
363新增: if _, err := os.Stat(filepath.Join(project, "mobile-approved.txt")); !os.IsNotExist(err) {
364新增: t.Fatal("tool ran before permission")
365新增: }
366新增: approval := map[string]any{"request_id": turn, "approval_id": current.Turns[0].Approval.ID, "allow": true}
367新增: api("POST", "sessions/"+id+"/approval", approval)
368新增: wait(func(view mobileSession) bool {
369新增: return len(view.Turns) == 1 && view.Turns[0].Text == "isolated tool completed" && view.Turns[0].Status == "completed"
370新增: })
371新增: if err := terminal.enqueueInput(context.Background(), "follow-up\r"); err != nil {
372新增: t.Fatal(err)
373新增: }
374新增: wait(func(view mobileSession) bool {
375新增: return len(view.Turns) == 2 && view.Turns[1].Prompt == "follow-up" && view.Turns[1].Text == "isolated continuation"
376新增: })
377新增: if !resumed.Load() || current.Turns[0].ID != turn {
378新增: t.Fatal("desktop and mobile diverged or duplicated a request")
379新增: }
380新增: listing := request(s, "GET", "/api/mobile/cli/sessions", s.origin, "", true)
381新增: var catalog struct {
382新增: Sessions []mobileSummary `json:"sessions"`
383新增: }
384新增: if err := json.Unmarshal(listing.Body.Bytes(), &catalog); err != nil || len(catalog.Sessions) != 1 || catalog.Sessions[0].ID != id {
385新增: t.Fatalf("catalog duplicated the terminal: %s", listing.Body.String())
386新增: }
387新增: mutate := func(path string, body string) {
388新增: t.Helper()
389新增: response := request(s, "POST", path, s.origin, body, true)
390新增: if response.Code != 200 {
391新增: t.Fatalf("%s: %d %s", path, response.Code, response.Body.String())
392新增: }
393新增: }
394新增: s.mobileCLI.mu.Lock()
395新增: record, err := s.mobileCLI.record(s.profile, id)
396新增: s.mobileCLI.mu.Unlock()
397新增: if err != nil {
398新增: t.Fatal(err)
399新增: }
400新增: cliID, config := record.CLIID, record.GuestConfig
401新增: mutate("/api/cli/sessions/"+id+"/archive", `{}`)
402新增: if len(s.terminals.snapshot()) != 0 {
403新增: t.Fatal("archive kept its terminal open")
404新增: }
405新增: mutate("/api/mobile/cli/sessions/"+id+"/restore", `{}`)
406新增: s.mu.Lock()
407新增: s.preferences.ClaudeTerminalCommand = "ccs changed"
408新增: s.mu.Unlock()
409新增: if response := request(s, "POST", "/api/mobile/cli/sessions/"+id+"/open", s.origin, `{"automatic":true}`, true); response.Code != 422 || len(s.terminals.snapshot()) != 0 {
410新增: t.Fatal("changed launcher created a terminal during automatic resume", response.Code)
411新增: }
412新增: s.mu.Lock()
413新增: s.preferences.ClaudeTerminalCommand = originalLauncher
414新增: s.mu.Unlock()
415新增: mutate("/api/cli/sessions/"+id+"/open", `{}`)
416新增: terminals = s.terminals.snapshot()
417新增: if len(terminals) != 1 {
418新增: t.Fatal("restore did not open a single terminal")
419新增: }
420新增: terminal = s.terminals.get(terminals[0]["id"].(string))
421新增: deadline = time.Now().Add(30 * time.Second)
422新增: wait(func(view mobileSession) bool { return view.CanSend != nil && *view.CanSend && len(view.Turns) == 2 })
423新增: // An acknowledgement lost before archival must not replay a turn after
424新增: // the same CLI history resumes through its new channel connection.
425新增: api("POST", "sessions/"+id+"/messages", message)
426新增: if current = api("GET", "sessions/"+id, nil); len(current.Turns) != 2 {
427新增: t.Fatal("resume lost message idempotency")
428新增: }
429新增: mutate("/api/mobile/cli/sessions/"+id+"/archive", `{}`)
430新增: purged := false
431新增: for attempt := 0; attempt < 20; attempt++ {
432新增: response := request(s, "POST", "/api/cli/sessions/"+id+"/purge", s.origin, `{"confirm":true}`, true)
433新增: if response.Code == 200 {
434新增: purged = true
435新增: break
436新增: }
437新增: if attempt == 19 {
438新增: t.Fatal(response.Code, response.Body.String())
439新增: }
440新增: time.Sleep(100 * time.Millisecond)
441新增: }
442新增: if !purged {
443新增: t.Fatal("purge did not complete")
444新增: }
445新增: mutate("/api/cli/sessions/"+id+"/purge", `{"confirm":true}`)
446新增: var removed terminalConversation
447新增: if err := s.runCLIChannel(context.Background(), "view", map[string]string{"cli_id": cliID, "config": config}, &removed); err != nil || removed.HasHistory || len(removed.Turns) != 0 {
448新增: t.Fatal("purge retained the CLI transcript", err)
449新增: }
450新增: probe := s.sshCommand(context.Background(), "-T", s.sshTarget(), "--", "claude --resume "+cliID+" --print")
451新增: output, err := probe.CombinedOutput()
452新增: if err == nil || !strings.Contains(strings.ToLower(string(output)), "no conversation found") {
453新增: t.Fatalf("Claude still resumed the deleted transcript: %v %s", err, output)
454新增: }
455新增: if response := request(s, "POST", "/api/cli/sessions/"+id+"/restore", s.origin, `{}`, true); response.Code != 404 {
456新增: t.Fatal("purged history was restored", response.Code)
457新增: }
458新增: s.account.lock()
459新增: if response := request(s, "GET", "/api/mobile/cli/sessions/"+id, s.origin, "", true); response.Code != 423 {
460新增: t.Fatal("lock did not revoke mobile access", response.Code)
461新增: }
462新增:}
463新增:
464新增:func TestLegacyMobileSessionOpensOnDesktop(t *testing.T) {
465新增: s, project, _ := sharedCLIWorkbench(t)
466新增: id, requestID := uuid.NewString(), uuid.NewString()
467新增: if _, err := s.mobileCLI.create(s.profile, project, id); err != nil {
468新增: t.Fatal(err)
469新增: }
470新增: path := "/api/mobile/cli/sessions/" + id
471新增: body, _ := json.Marshal(map[string]string{"request_id": requestID, "text": "follow-up"})
472新增: if w := request(s, "POST", path+"/messages", s.origin, string(body), true); w.Code != 200 {
473新增: t.Fatal(w.Code, w.Body.String())
474新增: }
475新增: deadline := time.Now().Add(30 * time.Second)
476新增: read := func() mobileSession {
477新增: t.Helper()
478新增: w := request(s, "GET", path, s.origin, "", true)
479新增: if w.Code != 200 {
480新增: t.Fatal(w.Code, w.Body.String())
481新增: }
482新增: var view mobileSession
483新增: if err := json.Unmarshal(w.Body.Bytes(), &view); err != nil {
484新增: t.Fatal(err)
485新增: }
486新增: return view
487新增: }
488新增: for {
489新增: view := read()
490新增: if len(view.Turns) == 1 && view.Turns[0].Status == "completed" {
491新增: break
492新增: }
493新增: if time.Now().After(deadline) {
494新增: t.Fatalf("legacy turn did not finish: %#v", view)
495新增: }
496新增: time.Sleep(100 * time.Millisecond)
497新增: }
498新增: w := request(s, "POST", "/api/cli/sessions/"+id+"/open", s.origin, "{}", true)
499新增: if w.Code != 200 {
500新增: t.Fatal("desktop open", w.Code, w.Body.String())
501新增: }
502新增: var opened mobileSession
503新增: if err := json.Unmarshal(w.Body.Bytes(), &opened); err != nil {
504新增: t.Fatal(err)
505新增: }
506新增: terminal := s.terminals.get(opened.DesktopTerminalID)
507新增: if terminal == nil || terminal.sharedID != id {
508新增: t.Fatal("desktop did not attach the original session")
509新增: }
510新增: for {
511新增: view := read()
512新增: if view.CanSend != nil && *view.CanSend {
513新增: if len(view.Turns) != 1 || view.Turns[0].ID != requestID {
514新增: t.Fatalf("history changed: %#v", view)
515新增: }
516新增: break
517新增: }
518新增: if time.Now().After(deadline) {
519新增: t.Fatalf("adopted terminal not ready: %#v", view)
520新增: }
521新增: time.Sleep(100 * time.Millisecond)
522新增: }
523新增: // Retrying a pre-upgrade request acknowledges it without sending it again.
524新增: if w := request(s, "POST", path+"/messages", s.origin, string(body), true); w.Code != 200 || !strings.Contains(w.Body.String(), requestID) {
525新增: t.Fatal(w.Code, w.Body.String())
526新增: }
527新增: if view := read(); len(view.Turns) != 1 {
528新增: t.Fatal("old request was replayed", view)
529新增: }
530新增: newBody, _ := json.Marshal(map[string]string{"request_id": uuid.NewString(), "text": "follow-up"})
531新增: if w := request(s, "POST", path+"/messages", s.origin, string(newBody), true); w.Code != 200 {
532新增: t.Fatal(w.Code, w.Body.String())
533新增: }
534新增: for {
535新增: view := read()
536新增: if len(view.Turns) == 2 && view.Turns[1].Status == "completed" {
537新增: break
538新增: }
539新增: if time.Now().After(deadline) {
540新增: t.Fatalf("shared continuation failed: %#v", view)
541新增: }
542新增: time.Sleep(100 * time.Millisecond)
543新增: }
544新增:}
545新增:
546新增:func TestFailedLegacyMobileSessionOpensOnDesktop(t *testing.T) {
547新增: s, project, _ := sharedCLIWorkbench(t)
548新增: id := uuid.NewString()
549新增: if _, err := s.mobileCLI.create(s.profile, project, id); err != nil {
550新增: t.Fatal(err)
551新增: }
552新增: record, err := s.mobileCLI.record(s.profile, id)
553新增: if err != nil {
554新增: t.Fatal(err)
555新增: }
556新增: record.Launcher = "claude"
557新增: record.Turns = []mobileTurn{{ID: uuid.NewString(), Prompt: "original failed message", Status: "failed", Error: "preflight failed"}}
558新增: if err := writePrivate(mobileRecordPath(s.profile, id), record); err != nil {
559新增: t.Fatal(err)
560新增: }
561新增: w := request(s, "POST", "/api/cli/sessions/"+id+"/open", s.origin, "{}", true)
562新增: if w.Code != 200 {
563新增: t.Fatal(w.Code, w.Body.String())
564新增: }
565新增: deadline := time.Now().Add(25 * time.Second)
566新增: for {
567新增: w = request(s, "GET", "/api/mobile/cli/sessions/"+id, s.origin, "", true)
568新增: if w.Code != 200 {
569新增: t.Fatal(w.Code, w.Body.String())
570新增: }
571新增: var view mobileSession
572新增: if err := json.Unmarshal(w.Body.Bytes(), &view); err != nil {
573新增: t.Fatal(err)
574新增: }
575新增: if view.CanSend != nil && *view.CanSend {
576新增: if len(view.Turns) != 1 || view.Turns[0].Error != "preflight failed" {
577新增: t.Fatalf("cached failure lost: %#v", view)
578新增: }
579新增: return
580新增: }
581新增: if time.Now().After(deadline) {
582新增: t.Fatalf("failed legacy session never became usable: %#v", view)
583新增: }
584新增: time.Sleep(100 * time.Millisecond)
585新增: }
586新增:}
587新增:
588新增:func TestImportAndResumeDesktopConversation(t *testing.T) {
589新增: s, project, resumed := sharedCLIWorkbench(t)
590新增: cmd := s.sshCommand(s.lifetimeContext(), "-tt", s.sshTarget(), "--", terminalScript(guestPath(project), "claude", "claude"))
591新增: original, err := s.terminals.startSession(cmd, project, "claude", claudeSelection{}, nil)
592新增: if err != nil {
593新增: t.Fatal(err)
594新增: }
595新增: deadline := time.Now().Add(60 * time.Second)
596新增: strip := regexp.MustCompile(`\x1b\[[0-?]*[ -/]*[@-~]|\s+`)
597新增: waitScreen := func(terminal *terminalSession, phrase string) {
598新增: t.Helper()
599新增: var text string
600新增: for time.Now().Before(deadline) {
601新增: terminal.mu.Lock()
602新增: text = strip.ReplaceAllString(string(terminal.history), "")
603新增: terminal.mu.Unlock()
604新增: if strings.Contains(text, phrase) {
605新增: return
606新增: }
607新增: time.Sleep(50 * time.Millisecond)
608新增: }
609新增: if len(text) > 6000 {
610新增: text = text[len(text)-6000:]
611新增: }
612新增: t.Fatalf("terminal did not show %q: %s", phrase, text)
613新增: }
614新增: waitScreen(original, "manualmodeon")
615新增: _ = original.enqueueInput(context.Background(), "initial mobile prompt\r")
616新增: waitScreen(original, "Doyouwanttoproceed?")
617新增: waitScreen(original, "Tabtoamend")
618新增: // The interactive permission dialog ignores keys during its opening guard.
619新增: time.Sleep(700 * time.Millisecond)
620新增: _ = original.enqueueInput(context.Background(), "1\r")
621新增: waitScreen(original, "isolatedtoolcompleted")
622新增: var catalog struct {
623新增: Sessions []mobileSummary `json:"sessions"`
624新增: }
625新增: for time.Now().Before(deadline) {
626新增: response := request(s, "GET", "/api/mobile/cli/sessions", s.origin, "", true)
627新增: if response.Code != 200 {
628新增: t.Fatal(response.Code, response.Body.String())
629新增: }
630新增: if err := json.Unmarshal(response.Body.Bytes(), &catalog); err != nil {
631新增: t.Fatal(err)
632新增: }
633新增: if len(catalog.Sessions) == 1 {
634新增: break
635新增: }
636新增: time.Sleep(100 * time.Millisecond)
637新增: }
638新增: if len(catalog.Sessions) != 1 {
639新增: t.Fatal("desktop history was not discovered")
640新增: }
641新增: id := catalog.Sessions[0].ID
642新增: path := "/api/mobile/cli/sessions/" + id
643新增: before := request(s, "GET", path, s.origin, "", true)
644新增: var view mobileSession
645新增: if before.Code != 200 || json.Unmarshal(before.Body.Bytes(), &view) != nil || len(view.Turns) != 1 || view.CanSend == nil || *view.CanSend {
646新增: t.Fatalf("unexpected imported history: %s", before.Body.String())
647新增: }
648新增: if response := request(s, "POST", path+"/open", s.origin, "{}", true); response.Code != 409 {
649新增: t.Fatal("opened a second live process for the same CLI history", response.Code)
650新增: }
651新增: var opened bool
652新增: for time.Now().Before(deadline) {
653新增: response := request(s, "POST", path+"/open", s.origin, `{"automatic":true}`, true)
654新增: if response.Code == 200 {
655新增: opened = true
656新增: break
657新增: }
658新增: if response.Code != 409 {
659新增: t.Fatal(response.Code, response.Body.String())
660新增: }
661新增: time.Sleep(100 * time.Millisecond)
662新增: }
663新增: if !opened {
664新增: original.mu.Lock()
665新增: output := strip.ReplaceAllString(string(original.history), "")
666新增: original.mu.Unlock()
667新增: t.Fatalf("original CLI did not exit: %s", output)
668新增: }
669新增: s.mobileCLI.mu.Lock()
670新增: record, err := s.mobileCLI.record(s.profile, id)
671新增: s.mobileCLI.mu.Unlock()
672新增: if err != nil {
673新增: t.Fatal(err)
674新增: }
675新增: terminal := s.terminals.get(record.TerminalID)
676新增: if terminal == nil || terminal == original {
677新增: t.Fatal("history did not open in a shared terminal")
678新增: }
679新增: for time.Now().Before(deadline) {
680新增: response := request(s, "GET", path, s.origin, "", true)
681新增: if response.Code == 200 && json.Unmarshal(response.Body.Bytes(), &view) == nil && view.CanSend != nil && *view.CanSend {
682新增: break
683新增: }
684新增: time.Sleep(100 * time.Millisecond)
685新增: }
686新增: message, _ := json.Marshal(map[string]string{"request_id": uuid.NewString(), "text": "follow-up"})
687新增: if response := request(s, "POST", path+"/messages", s.origin, string(message), true); response.Code != 200 {
688新增: t.Fatal(response.Code, response.Body.String())
689新增: }
690新增: for time.Now().Before(deadline) {
691新增: response := request(s, "GET", path, s.origin, "", true)
692新增: if response.Code == 200 && json.Unmarshal(response.Body.Bytes(), &view) == nil && len(view.Turns) == 2 && view.Turns[1].Text == "isolated continuation" {
693新增: if !resumed.Load() {
694新增: t.Fatal("resumed CLI lost the desktop context")
695新增: }
696新增: return
697新增: }
698新增: time.Sleep(100 * time.Millisecond)
699新增: }
700新增: t.Fatalf("resumed history did not finish: %#v", view)
701新增:}
702新增:
703新增:func TestSharedTerminalUntrustedProject(t *testing.T) {
704新增: s, project, _ := sharedCLIWorkbench(t)
705新增: // Start without a CLI trust entry; Cage's project grant is sufficient for
706新增: // its own startup, without granting any tools or external MCP servers.
707新增: id := uuid.NewString()
708新增: body, _ := json.Marshal(map[string]any{"id": id, "workspace": project, "shared": true})
709新增: response := request(s, "POST", "/api/mobile/cli/sessions", s.origin, string(body), true)
710新增: if response.Code != 200 {
711新增: t.Fatal(response.Code, response.Body.String())
712新增: }
713新增: deadline := time.Now().Add(35 * time.Second)
714新增: for time.Now().Before(deadline) {
715新增: response = request(s, "GET", "/api/mobile/cli/sessions/"+id, s.origin, "", true)
716新增: var view mobileSession
717新增: if response.Code == 200 && json.Unmarshal(response.Body.Bytes(), &view) == nil && view.CanSend != nil && *view.CanSend {
718新增: return
719新增: }
720新增: time.Sleep(100 * time.Millisecond)
721新增: }
722新增: for _, summary := range s.terminals.snapshot() {
723新增: terminal := s.terminals.get(summary["id"].(string))
724新增: terminal.mu.Lock()
725新增: t.Log(cliStartupText(terminal.history))
726新增: terminal.mu.Unlock()
727新增: }
728新增: t.Fatal("untrusted project startup required desktop input")
729新增:}
730新增:
731新增:func TestSharedTerminalStartupBrowser(t *testing.T) {
732新增: if os.Getenv("CAGE_TEST_CHANNEL_BROWSER") == "" {
733新增: t.Skip("set browser and isolated CLI fixture inputs")
734新增: }
735新增: s, project, _ := sharedCLIWorkbench(t)
736新增: server := httptest.NewServer(s.handler())
737新增: defer server.Close()
738新增: s.origin = server.URL
739新增: ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
740新增: defer cancel()
741新增: input, _ := json.Marshal(map[string]string{"origin": s.origin, "cookie": s.cookieName(), "session": s.session, "project": project})
742新增: driver := exec.CommandContext(ctx, "node", "../../ui/scripts/terminal-startup-live-smoke.mjs")
743新增: driver.Stdin = strings.NewReader(string(input))
744新增: if output, err := driver.CombinedOutput(); err != nil {
745新增: t.Fatalf("startup browser: %v\n%s", err, output)
746新增: } else {
747新增: t.Log(string(output))
748新增: }
749新增:}
750新增:
751新增:func TestWaitingDesktopApprovalMovesToPhone(t *testing.T) {
752新增: s, project, _ := sharedCLIWorkbench(t)
753新增: cmd := s.sshCommand(s.lifetimeContext(), "-tt", s.sshTarget(), "--", terminalScript(guestPath(project), "claude", "claude"))
754新增: original, err := s.terminals.startSession(cmd, project, "claude", claudeSelection{}, nil)
755新增: if err != nil {
756新增: t.Fatal(err)
757新增: }
758新增: deadline := time.Now().Add(45 * time.Second)
759新增: waitScreen := func(phrase string) {
760新增: t.Helper()
761新增: for time.Now().Before(deadline) {
762新增: original.mu.Lock()
763新增: text := cliStartupText(original.history)
764新增: original.mu.Unlock()
765新增: if strings.Contains(text, phrase) {
766新增: return
767新增: }
768新增: time.Sleep(50 * time.Millisecond)
769新增: }
770新增: t.Fatal("legacy CLI did not show ", phrase)
771新增: }
772新增: waitScreen("manualmodeon")
773新增: if err := original.enqueueInput(context.Background(), "initial mobile prompt\r"); err != nil {
774新增: t.Fatal(err)
775新增: }
776新增: waitScreen("Tabtoamend")
777新增: // Give the CLI's supported agent registry time to publish the dialog state.
778新增: for time.Now().Before(deadline) {
779新增: probe := s.sshCommand(context.Background(), "-T", s.sshTarget(), "--", "claude agents --json")
780新增: data, err := probe.Output()
781新增: if err != nil {
782新增: t.Fatal(err)
783新增: }
784新增: var rows []struct {
785新增: Status string `json:"status"`
786新增: }
787新增: if json.Unmarshal(data, &rows) == nil && len(rows) == 1 && rows[0].Status == "waiting" {
788新增: break
789新增: }
790新增: time.Sleep(100 * time.Millisecond)
791新增: }
792新增: listing := request(s, "GET", "/api/mobile/cli/sessions", s.origin, "", true)
793新增: var catalog struct {
794新增: Sessions []mobileSummary `json:"sessions"`
795新增: }
796新增: if listing.Code != 200 || json.Unmarshal(listing.Body.Bytes(), &catalog) != nil || len(catalog.Sessions) != 1 {
797新增: t.Fatal("missing legacy history", listing.Body.String())
798新增: }
799新增: path := "/api/mobile/cli/sessions/" + catalog.Sessions[0].ID
800新增: opened := request(s, "POST", path+"/open", s.origin, `{"automatic":true}`, true)
801新增: if opened.Code != 200 {
802新增: t.Fatal(opened.Code, opened.Body.String())
803新增: }
804新增: var view mobileSession
805新增: for time.Now().Before(deadline) {
806新增: response := request(s, "GET", path, s.origin, "", true)
807新增: if response.Code == 200 && json.Unmarshal(response.Body.Bytes(), &view) == nil && len(view.Turns) == 1 && view.Turns[0].Approval != nil {
808新增: break
809新增: }
810新增: time.Sleep(100 * time.Millisecond)
811新增: }
812新增: if len(view.Turns) != 1 || view.Turns[0].Approval == nil {
813新增: t.Fatalf("phone did not receive fresh approval: %#v", view)
814新增: }
815新增: if view.Turns[0].Prompt != "initial mobile prompt" {
816新增: t.Fatal("internal reconnect notice leaked into the conversation")
817新增: }
818新增: if strings.Contains(view.Turns[0].Text, "No response requested.") {
819新增: t.Fatal("synthetic restart message leaked into the conversation")
820新增: }
821新增: if _, err := os.Stat(filepath.Join(project, "mobile-approved.txt")); !os.IsNotExist(err) {
822新增: t.Fatal("handoff approved the tool")
823新增: }
824新增: body, _ := json.Marshal(map[string]any{"request_id": view.Turns[0].ID, "approval_id": view.Turns[0].Approval.ID, "allow": true})
825新增: response := request(s, "POST", path+"/approval", s.origin, string(body), true)
826新增: if response.Code != 200 {
827新增: t.Fatal(response.Code, response.Body.String())
828新增: }
829新增: for time.Now().Before(deadline) {
830新增: response = request(s, "GET", path, s.origin, "", true)
831新增: if response.Code == 200 && json.Unmarshal(response.Body.Bytes(), &view) == nil && len(view.Turns) == 1 && view.Turns[0].Status == "completed" {
832新增: if data, err := os.ReadFile(filepath.Join(project, "mobile-approved.txt")); err != nil || string(data) != "approved" {
833新增: t.Fatal("approved task did not complete", err)
834新增: }
835新增: return
836新增: }
837新增: time.Sleep(100 * time.Millisecond)
838新增: }
839新增: t.Fatal("resumed task did not complete")
840新增:}
841新增:
842新增:func runSharedConversationBrowser(t *testing.T, s *Server, project string) {
843新增: t.Helper()
844新增: ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
845新增: defer cancel()
846新增: server := httptest.NewServer(s.handler())
847新增: defer server.Close()
848新增: s.origin = server.URL
849新增: workbench, err := mobilelink.OpenWorkbench(ctx, s.origin, s.issueTicket())
850新增: if err != nil {
851新增: t.Fatal(err)
852新增: }
853新增: defer workbench.Close()
854新增: admin := strings.Repeat("c", 48)
855新增: service, err := relay.New(relay.Config{AdminToken: admin})
856新增: if err != nil {
857新增: t.Fatal(err)
858新增: }
859新增: defer service.Close()
860新增: relayServer := httptest.NewServer(service)
861新增: defer relayServer.Close()
862新增: hostIdentity, _ := remotelink.NewIdentity()
863新增: phoneIdentity, _ := remotelink.NewIdentity()
864新增: room, err := mobilelink.CreateRoom(ctx, relayServer.URL, admin)
865新增: if err != nil {
866新增: t.Fatal(err)
867新增: }
868新增: go func() {
869新增: _ = mobilelink.ServeHost(ctx, relayServer.URL, room.ID, room.HostToken, hostIdentity, phoneIdentity.Pin, workbench)
870新增: }()
871新增: client, err := mobilelink.ConnectClient(ctx, relayServer.URL, room.ID, room.ClientToken, phoneIdentity, hostIdentity.Pin)
872新增: if err != nil {
873新增: t.Fatal(err)
874新增: }
875新增: defer client.Close()
876新增: web := httptest.NewUnstartedServer(nil)
877新增: assets, _ := filepath.Abs("web")
878新增: handler, entry, err := mobilelink.NewBrowser("http://"+web.Listener.Addr().String(), assets, client)
879新增: if err != nil {
880新增: t.Fatal(err)
881新增: }
882新增: defer handler.Close()
883新增: web.Config.Handler = handler
884新增: web.Start()
885新增: defer web.Close()
886新增: // The browser must complete startup itself. This goroutine only verifies
887新增: // that a later desktop keyboard message still reaches the phone.
888新增: desktopCtx, stopDesktop := context.WithCancel(ctx)
889新增: done := make(chan struct{})
890新增: go func() {
891新增: defer close(done)
892新增: replied := false
893新增: strip := regexp.MustCompile(`\x1b\[[0-?]*[ -/]*[@-~]|\s+`)
894新增: ticker := time.NewTicker(100 * time.Millisecond)
895新增: defer ticker.Stop()
896新增: for {
897新增: select {
898新增: case <-desktopCtx.Done():
899新增: return
900新增: case <-ticker.C:
901新增: for _, row := range s.terminals.snapshot() {
902新增: terminal := s.terminals.get(row["id"].(string))
903新增: terminal.mu.Lock()
904新增: output := strip.ReplaceAllString(string(terminal.history), "")
905新增: terminal.mu.Unlock()
906新增: if !replied && strings.Contains(output, "isolatedtoolcompleted") {
907新增: _ = terminal.enqueueInput(desktopCtx, "follow-up\r")
908新增: replied = true
909新增: }
910新增: }
911新增: }
912新增: }
913新增: }()
914新增: defer func() { stopDesktop(); <-done }()
915新增: driver := exec.CommandContext(ctx, "node", "../../ui/scripts/shared-cli-live-smoke.mjs")
916新增: driver.Stdin = strings.NewReader(entry)
917新增: driver.Env = append(os.Environ(), "CAGE_TEST_MOBILE_MARKER="+filepath.Join(project, "mobile-approved.txt"))
918新增: if output, err := driver.CombinedOutput(); err != nil {
919新增: for _, row := range s.terminals.snapshot() {
920新增: terminal := s.terminals.get(row["id"].(string))
921新增: terminal.mu.Lock()
922新增: t.Log(cliStartupText(terminal.history))
923新增: terminal.mu.Unlock()
924新增: }
925新增: t.Fatalf("shared browser: %v\n%s", err, output)
926新增: }
927新增:}
新增internal/workbench/cli_channel_test.py+315 −0看文件
@@ -0,0 +1,315 @@
1新增:import concurrent.futures
2新增:import importlib.util
3新增:import io
4新增:import json
5新增:import os
6新增:from pathlib import Path
7新增:import select
8新增:import subprocess
9新增:import sys
10新增:import tempfile
11新增:import time
12新增:import unittest
13新增:import uuid
14新增:from unittest.mock import patch
15新增:
16新增:sys.dont_write_bytecode = True
17新增:source = Path(__file__).with_name("cli_channel.py").resolve()
18新增:spec = importlib.util.spec_from_file_location("channel", source)
19新增:channel = importlib.util.module_from_spec(spec)
20新增:spec.loader.exec_module(channel)
21新增:
22新增:
23新增:class ChannelTests(unittest.TestCase):
24新增: def setUp(self):
25新增: temporary = tempfile.TemporaryDirectory()
26新增: self.addCleanup(temporary.cleanup)
27新增: # macOS /var and /private/var identify one directory. Match the
28新增: # production config resolver so catalog order cannot duplicate it.
29新增: self.home = Path(temporary.name).resolve()
30新增: self.env = {**os.environ, "HOME": str(self.home), "CLAUDE_CONFIG_DIR": str(self.home / ".claude")}
31新增: environment = patch.dict(os.environ, self.env)
32新增: environment.start()
33新增: self.addCleanup(environment.stop)
34新增: self.root = self.home / ".local/share/cage/cli-channels"
35新增: root_patch = patch.object(channel, "ROOT", self.root)
36新增: root_patch.start()
37新增: self.addCleanup(root_patch.stop)
38新增: self.session = str(uuid.uuid4())
39新增: self.project = str(self.home / "project")
40新增:
41新增: def history(self, session, workspace, messages):
42新增: path = self.home / ".claude/projects/project" / (session + ".jsonl")
43新增: path.parent.mkdir(parents=True, exist_ok=True)
44新增: rows = [{"cwd": workspace, "uuid": str(uuid.uuid4()), **message} for message in messages]
45新增: path.write_text("\n".join(json.dumps(row) for row in rows) + "\n")
46新增: return path
47新增:
48新增: def test_channel_body_preserves_markup(self):
49新增: request = str(uuid.uuid4())
50新增: body = "show </channel> literally\n<channel cage_request=\"other\">example</channel>"
51新增: self.assertEqual(channel.channel_message('<channel source="cage" cage_request="' + request + '">\n' + body + '\n</channel>'), (request, body))
52新增: self.assertEqual(channel.clip_text("你好abc", 4), "你")
53新增:
54新增: def test_account_switch_preserves_tools_and_receipt(self):
55新增: tool = {"type":"tool_use","id":"tool-completed","name":"Bash","input":{"command":"already completed"}}
56新增: path = self.history(self.session,self.project,[
57新增: {"type":"user","message":{"content":"perform task"}},
58新增: {"type":"assistant","message":{"content":[tool]}},
59新增: {"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"tool-completed","content":"done"}]}},
60新增: ])
61新增: connection,switch_id,target = [str(uuid.uuid4()) for _ in range(3)]
62新增: request = {"cli_id":self.session,"config":str(self.home / ".claude"),"connection":connection,"workspace":self.project,"target_cli_id":target,"switch_id":switch_id}
63新增: channel.save(self.root/connection/"state.json",{"cli_id":self.session,"config":request["config"],"workspace":self.project,"busy":False,"requests":{"accepted":"digest"}})
64新增: completed = type("Result",(),{"returncode":0,"stdout":"[]"})()
65新增: original = path.read_bytes()
66新增: with patch.object(channel,"active_sessions",return_value=[]),patch.object(channel.subprocess,"run",return_value=completed):
67新增: result=channel.prepare_account_switch(request)
68新增: self.assertEqual(Path(result["transcript"]).read_bytes(),original)
69新增: self.assertEqual(channel.prepare_account_switch(request),result)
70新增: receipt=channel.read_json(Path(result["transcript"]).with_name("receipt.json"))
71新增: self.assertEqual(receipt["requests"],{"accepted":"digest"})
72新增: self.assertEqual(path.read_bytes(),original)
73新增: payload={"hook_event_name":"PreToolUse","session_id":self.session}
74新增: with patch.object(channel.sys,"stdin",io.StringIO(json.dumps(payload))):
75新增: denied=channel.hook(connection)
76新增: self.assertEqual(denied["hookSpecificOutput"]["permissionDecision"],"deny")
77新增: self.assertTrue(channel.cancel_account_switch(request)["ok"])
78新增: self.assertFalse(Path(result["transcript"]).exists())
79新增: self.assertTrue(path.exists())
80新增:
81新增: def test_account_switch_refuses_busy_and_unresolved_tools(self):
82新增: path=self.history(self.session,self.project,[{"type":"assistant","message":{"content":[{"type":"tool_use","id":"uncertain","name":"Bash","input":{}}]}}])
83新增: connection,switch_id,target=[str(uuid.uuid4()) for _ in range(3)]
84新增: request={"cli_id":self.session,"config":str(self.home/".claude"),"connection":connection,"workspace":self.project,"target_cli_id":target,"switch_id":switch_id}
85新增: state={"cli_id":self.session,"config":request["config"],"workspace":self.project,"busy":True}
86新增: channel.save(self.root/connection/"state.json",state)
87新增: with patch.object(channel.os,"kill") as kill:
88新增: with self.assertRaises(ValueError): channel.prepare_account_switch(request)
89新增: kill.assert_not_called()
90新增: state["busy"]=False
91新增: channel.save(self.root/connection/"state.json",state)
92新增: completed=type("Result",(),{"returncode":0,"stdout":"[]"})()
93新增: with patch.object(channel,"active_sessions",return_value=[]),patch.object(channel.subprocess,"run",return_value=completed):
94新增: with self.assertRaisesRegex(ValueError,"工具"): channel.prepare_account_switch(request)
95新增: self.assertTrue(path.exists())
96新增: self.assertFalse((self.root.parent/"cli-account-switches"/switch_id/"history.jsonl").exists())
97新增:
98新增: def test_failure_hook_reports_kind_and_new_turn_clears_it(self):
99新增: payload={"hook_event_name":"StopFailure","session_id":self.session,"error":"rate_limit","error_details":"private upstream diagnostic"}
100新增: with patch.object(channel.sys,"stdin",io.StringIO(json.dumps(payload))):channel.hook(self.session)
101新增: state=channel.read_json(self.root/self.session/"state.json")
102新增: self.assertEqual(state["account_failure"],"rate_limit")
103新增: self.assertNotIn("private upstream",json.dumps(state))
104新增: with patch.object(channel.sys,"stdin",io.StringIO(json.dumps({**payload,"hook_event_name":"UserPromptSubmit"}))):channel.hook(self.session)
105新增: self.assertNotIn("account_failure",channel.read_json(self.root/self.session/"state.json"))
106新增:
107新增: def test_first_display_delta_after_launch(self):
108新增: with channel.state_file(self.session) as state:
109新增: state["display"] = None
110新增: payload = {"hook_event_name":"MessageDisplay","session_id":self.session,"message_id":"reply","index":0,"delta":"hello"}
111新增: with patch.object(channel.sys,"stdin",io.StringIO(json.dumps(payload))):
112新增: channel.hook(self.session)
113新增: self.assertEqual(channel.read_json(self.root / self.session / "state.json")["display"]["text"],"hello")
114新增:
115新增: def test_ready_channel_wins_over_a_newer_unready_duplicate(self):
116新增: config = str(channel.config_directory("default"))
117新增: ready, starting = str(uuid.uuid4()), str(uuid.uuid4())
118新增: channel.save(self.root / ready / "state.json", {"cli_id":self.session,"config":config,"pid":os.getpid(),"channel_pid":os.getpid(),"updated_at":1})
119新增: channel.save(self.root / starting / "state.json", {"cli_id":self.session,"config":config,"pid":os.getpid(),"channel_pid":None,"updated_at":2})
120新增: self.assertEqual(channel.connection_for(self.session,Path(config))[0],ready)
121新增:
122新增: def test_launch_retains_pending_permission_mode(self):
123新增: config = str(channel.config_directory("default"))
124新增: channel.save(channel.handoff_receipt(config,self.session),{"resume_task":True,"permission_mode":"manual"})
125新增: connection = str(uuid.uuid4())
126新增: with patch.object(channel,"migrate_cage_policy"), patch.object(channel,"active_session",return_value=False), patch.object(channel.os,"execvpe") as execute:
127新增: channel.launch({"id":connection,"resume":self.session,"prefix":["claude"],"config":config})
128新增: self.assertEqual(execute.call_args.args[1][-2:],["--permission-mode","manual"])
129新增: self.assertTrue(channel.read_json(self.root / connection / "state.json")["resume_task"])
130新增:
131新增: def test_handoff_preserves_executing_tools(self):
132新增: request = {"cli_id":self.session, "config":str(self.home / ".claude"), "workspace":self.project}
133新增: for status in ("busy", None):
134新增: rows = [{"sessionId":self.session, "pid":1234, "cwd":self.project, "status":status, "kind":"interactive"}]
135新增: with patch.object(channel, "active_sessions", return_value=rows), patch.object(channel.os, "kill") as kill:
136新增: self.assertTrue(channel.handoff_session(request)["running"])
137新增: kill.assert_not_called()
138新增:
139新增: def test_handoff_rechecks_idle_identity_and_waits_for_exit(self):
140新增: request = {"cli_id":self.session, "config":str(self.home / ".claude"), "workspace":self.project}
141新增: row = {"sessionId":self.session, "pid":1234, "cwd":self.project, "status":"idle", "kind":"interactive"}
142新增: with patch.object(channel, "active_sessions", return_value=[row]), patch.object(channel, "live", return_value=False), patch.object(channel.os, "kill") as kill:
143新增: self.assertFalse(channel.handoff_session(request)["running"])
144新增: kill.assert_called_once_with(1234, channel.signal.SIGTERM)
145新增: with patch.object(channel, "active_sessions", side_effect=[[row], [{**row, "status":"busy"}]]), patch.object(channel.os, "kill") as kill:
146新增: self.assertTrue(channel.handoff_session(request)["running"])
147新增: kill.assert_not_called()
148新增:
149新增: def test_handoff_waiting_task_requires_fresh_approval(self):
150新增: request = {"cli_id":self.session, "config":str(self.home / ".claude"), "workspace":self.project}
151新增: row = {"sessionId":self.session, "pid":1234, "cwd":self.project, "status":"waiting", "kind":"interactive"}
152新增: with patch.object(channel, "active_sessions", return_value=[row]), patch.object(channel, "live", return_value=False), patch.object(channel.os, "kill") as kill:
153新增: self.assertFalse(channel.handoff_session(request)["running"])
154新增: kill.assert_called_once_with(1234, channel.signal.SIGTERM)
155新增: self.assertTrue(channel.read_json(channel.handoff_receipt(request["config"], self.session))["resume_task"])
156新增: with patch.object(channel, "active_sessions", return_value=[{**row, "cwd":self.project + "-other"}]), patch.object(channel.os, "kill") as kill:
157新增: with self.assertRaises(ValueError): channel.handoff_session(request)
158新增: kill.assert_not_called()
159新增:
160新增: def test_catalog_activity_requires_live_busy_process(self):
161新增: self.history(self.session, self.project, [{"type":"user", "message":{"content":"hello"}}])
162新增: connection = str(uuid.uuid4())
163新增: with channel.state_file(connection) as state:
164新增: state.update(cli_id=self.session, config=str(self.home / ".claude"), workspace=self.project,
165新增: pid=os.getpid(), busy=True)
166新增: request = {"accounts":["default"], "workspaces":{self.project:self.project}}
167新增: self.assertTrue(channel.discover(request)[0]["active"])
168新增: self.assertTrue(channel.view(self.home / ".claude", self.session)["active"])
169新增: with channel.state_file(connection) as state:
170新增: state["busy"] = False
171新增: self.assertFalse(channel.discover(request)[0]["active"], "idle CLI was shown as active")
172新增: with channel.state_file(connection) as state:
173新增: state.update(busy=True, closed=True)
174新增: self.assertFalse(channel.discover(request)[0]["active"], "closed CLI retained activity")
175新增:
176新增: def test_purge_removes_only_target_transcripts_and_retries(self):
177新增: target = self.history(self.session, self.project, [{"type":"user", "message":{"content":"delete this"}}])
178新增: other = self.history(str(uuid.uuid4()), self.project, [{"type":"user", "message":{"content":"keep this"}}])
179新增: child = target.parent / self.session / "subagents" / "agent-fixture.jsonl"
180新增: child.parent.mkdir(parents=True)
181新增: child.write_text("child history")
182新增: project_file = self.home / "project" / "main.py"
183新增: project_file.parent.mkdir()
184新增: project_file.write_text("project content")
185新增: request = {"cli_id":self.session, "account":"default", "workspace":self.project, "expect_history":True}
186新增: with patch.object(channel, "active_session", return_value=True):
187新增: with self.assertRaises(ValueError): channel.purge_session(request)
188新增: self.assertTrue(target.exists())
189新增: with patch.object(channel, "active_session", return_value=False):
190新增: with self.assertRaises(ValueError): channel.purge_session({**request, "workspace":self.project + "-other"})
191新增: self.assertTrue(channel.purge_session(request)["ok"])
192新增: self.assertTrue(channel.purge_session(request)["ok"])
193新增: self.assertFalse(target.exists())
194新增: self.assertFalse(child.parent.parent.exists())
195新增: self.assertTrue(other.exists())
196新增: self.assertEqual(project_file.read_text(), "project content")
197新增:
198新增: def test_only_cage_default_policy_is_migrated(self):
199新增: policy = self.home / "managed-settings.json"
200新增: original = {"permissions": {"defaultMode": "bypassPermissions"}, "tui": "fullscreen"}
201新增: policy.write_text(json.dumps(original))
202新增: def path(value):
203新增: return policy if str(value) == "/etc/claude-code/managed-settings.json" else Path(value)
204新增: def migrate(args, **kwargs):
205新增: code = args[-1].replace("/etc/claude-code/managed-settings.json", str(policy))
206新增: exec(code, {"__name__": "migration_test"})
207新增: with patch.object(channel, "Path", path), patch.object(channel.sys, "platform", "linux"), patch.object(channel.subprocess, "run", side_effect=migrate) as run:
208新增: self.assertTrue(channel.migrate_cage_policy())
209新增: self.assertTrue(json.loads(policy.read_text())["channelsEnabled"])
210新增: backup = policy.with_name("managed-settings.json.cage-before-channels")
211新增: self.assertEqual(json.loads(backup.read_text()), original)
212新增: blocked = {**original, "channelsEnabled": False}
213新增: policy.write_text(json.dumps(blocked))
214新增: channel.migrate_cage_policy()
215新增: self.assertEqual(json.loads(policy.read_text()), blocked)
216新增: self.assertEqual(run.call_count, 1)
217新增:
218新增: def test_history_projects_and_channel_identity(self):
219新增: request = str(uuid.uuid4())
220新增: self.history(self.session, self.project + "/nested", [
221新增: {"type": "user", "message": {"content": "desktop question"}},
222新增: {"type": "assistant", "message": {"content": [{"type": "text", "text": "desktop answer"}]}},
223新增: {"type": "assistant", "message": {"model":"<synthetic>", "content": [{"type": "text", "text": "No response requested."}]}},
224新增: {"type": "user", "isMeta": True, "message": {"content": "system metadata"}},
225新增: {"type": "user", "isMeta": True, "message": {"content": '<channel source="cage" cage_request="' + request + '">\nphone question\n</channel>'}},
226新增: {"type": "user", "message": {"content": [{"type": "tool_result", "content": "private tool output"}]}},
227新增: {"type": "assistant", "message": {"content": [{"type": "text", "text": "phone answer"}]}},
228新增: ])
229新增: self.history(str(uuid.uuid4()), self.project + "-other", [{"type": "user", "message": {"content": "outside project"}}])
230新增: found = channel.discover({"accounts": ["default"], "workspaces": [self.project]})
231新增: self.assertEqual([item["cli_id"] for item in found], [self.session])
232新增: view = channel.view(channel.config_directory("default"), self.session)
233新增: self.assertFalse(view["can_send"])
234新增: self.assertEqual(len(view["turns"]), 2)
235新增: self.assertEqual(view["turns"][1]["id"], request)
236新增: self.assertEqual(view["turns"][1]["prompt"], "phone question")
237新增: self.assertEqual(view["turns"][1]["text"], "phone answer")
238新增: self.assertNotIn("private tool output", json.dumps(view))
239新增:
240新增: def test_history_pairs_tool_only_rows_and_keeps_task_notice(self):
241新增: self.history(self.session, self.project, [
242新增: {"type": "user", "message": {"content": "run"}},
243新增: {"type": "assistant", "message": {"content": [
244新增: {"type": "tool_use", "id": "tool-1", "name": "Bash", "input": {"description": "检查结果", "command": "private-command"}},
245新增: {"type": "tool_use", "id": "tool-2", "name": "Read", "input": {"file_path": "result.md"}},
246新增: ]}},
247新增: {"type": "user", "message": {"content": [
248新增: {"type": "tool_result", "tool_use_id": "tool-2", "content": "private-output"},
249新增: {"type": "tool_result", "tool_use_id": "tool-1", "is_error": True},
250新增: ]}},
251新增: {"type": "user", "isMeta": True, "message": {"content": "<task-notification><summary>完成</summary></task-notification>"}},
252新增: ])
253新增: view = channel.view(channel.config_directory("default"), self.session)
254新增: self.assertEqual(len(view["turns"]), 2)
255新增: tools = view["turns"][0]["tools"]
256新增: self.assertEqual([(t["name"], t["status"], t["detail"]) for t in tools],
257新增: [("Bash", "failed", "检查结果"), ("Read", "completed", "result.md")])
258新增: self.assertTrue(view["turns"][1]["prompt"].startswith("<task-notification>"))
259新增: self.assertNotIn("private-", json.dumps(view))
260新增:
261新增: def test_concurrent_send_and_stale_approval(self):
262新增: with channel.state_file(self.session) as state:
263新增: state.update(cli_id=self.session, config=str(channel.config_directory("default")), workspace=self.project, pid=os.getpid())
264新增: process = subprocess.Popen([sys.executable, "-I", str(source), "serve", self.session],
265新增: env=self.env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
266新增: def stop():
267新增: process.stdin.close()
268新增: try:
269新增: process.wait(timeout=5)
270新增: except subprocess.TimeoutExpired:
271新增: process.kill()
272新增: process.wait()
273新增: process.stdout.close()
274新增: process.stderr.close()
275新增: self.addCleanup(stop)
276新增: def event(message):
277新增: process.stdin.write(json.dumps({"jsonrpc": "2.0", **message}) + "\n")
278新增: process.stdin.flush()
279新增: event({"id": 1, "method": "initialize", "params": {"protocolVersion": "2024-11-05"}})
280新增: self.assertIn("claude/channel/permission", json.loads(process.stdout.readline())["result"]["capabilities"]["experimental"])
281新增: event({"method": "notifications/initialized"})
282新增: def rpc(**fields):
283新增: result = subprocess.run([sys.executable, "-I", str(source), "rpc", "-"], env=self.env, text=True,
284新增: input=json.dumps({"cli_id": self.session, "connection": self.session, **fields}), capture_output=True, check=True)
285新增: return json.loads(result.stdout)
286新增: request = str(uuid.uuid4())
287新增: with concurrent.futures.ThreadPoolExecutor(2) as workers:
288新增: replies = list(workers.map(lambda _: rpc(action="send", request_id=request, text="once"), range(2)))
289新增: self.assertEqual(replies, [{"ok": True}, {"ok": True}])
290新增: sent = json.loads(process.stdout.readline())
291新增: self.assertEqual(sent["params"]["meta"]["cage_request"], request)
292新增: self.assertFalse(select.select([process.stdout], [], [], 0.1)[0])
293新增: self.assertIn("error", rpc(action="send", request_id=request, text="changed"))
294新增: event({"method": "notifications/claude/channel/permission_request", "params": {
295新增: "request_id": "abcde", "tool_name": "Bash", "input_preview": '{"command":"echo test"}'}})
296新增: path = self.root / self.session / "state.json"
297新增: deadline = time.monotonic() + 3
298新增: while time.monotonic() < deadline and not channel.read_json(path).get("approvals"):
299新增: time.sleep(0.01)
300新增: approval = channel.read_json(path)["approvals"][0]
301新增: self.assertIn("error", rpc(action="approve", approval_id=str(uuid.uuid4()), allow=True))
302新增: self.assertEqual(rpc(action="approve", approval_id=approval["id"], allow=False), {"ok": True})
303新增: self.assertEqual(json.loads(process.stdout.readline())["params"], {"request_id": "abcde", "behavior": "deny"})
304新增: self.assertIn("error", rpc(action="approve", approval_id=approval["id"], allow=True))
305新增: with channel.state_file(self.session) as state:
306新增: state["resume_task"] = True
307新增: self.assertEqual(rpc(action="resume"), {"ok":True})
308新增: self.assertEqual(rpc(action="resume"), {"ok":True})
309新增: resumed = json.loads(process.stdout.readline())
310新增: self.assertEqual(resumed["params"]["meta"], {"cage_resume":"true"})
311新增: self.assertFalse(select.select([process.stdout], [], [], 0.1)[0], "resume was injected twice")
312新增:
313新增:
314新增:if __name__ == "__main__":
315新增: unittest.main()
新增internal/workbench/cli_connect.go+114 −0看文件
@@ -0,0 +1,114 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "context"
5新增: "regexp"
6新增: "strings"
7新增: "time"
8新增: "unicode"
9新增:)
10新增:
11新增:var cliStartupEscape = regexp.MustCompile(`\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)`)
12新增:var cliOwnedChannel = regexp.MustCompile(`Channels:server:cage(?:[❯›>]?1\.|Iamusingthisforlocaldevelopment)`)
13新增:
14新增:func cliStartupText(data []byte) string {
15新增: return strings.Map(func(r rune) rune {
16新增: if unicode.IsSpace(r) {
17新增: return -1
18新增: }
19新增: return r
20新增: }, cliStartupEscape.ReplaceAllString(string(data), ""))
21新增:}
22新增:
23新增:// Cage already owns this locally generated channel and the user has granted
24新增:// access to this project. Only their two startup dialogs can be completed here.
25新增:// Tool approvals, external MCP servers and login dialogs remain untouched.
26新增:func cliStartupDialog(text, workspace string) string {
27新增: if strings.Contains(text, "WARNING:Loadingdevelopmentchannels") &&
28新增: cliOwnedChannel.MatchString(text) &&
29新增: strings.Contains(text, "Iamusingthisforlocaldevelopment") {
30新增: return "channel"
31新增: }
32新增: if workspace != "" && strings.Contains(strings.ToLower(text), "quicksafetycheck:isthisaprojectyoucreatedoroneyoutrust?") &&
33新增: strings.Contains(text, cliStartupText([]byte(workspace))) &&
34新增: strings.Contains(text, "Yes,Itrustthisfolder") {
35新增: return "project"
36新增: }
37新增: return ""
38新增:}
39新增:
40新增:func (s *Server) prepareCLIConnection(terminal *terminalSession, id string) {
41新增: terminal.mu.Lock()
42新增: terminal.cliStartupDone = make(chan struct{})
43新增: terminal.mu.Unlock()
44新增: s.activities.Add(1)
45新增: go func() {
46新增: defer s.activities.Done()
47新增: defer terminal.finishCLIStartup()
48新增: ctx, cancel := context.WithTimeout(s.lifetimeContext(), 45*time.Second)
49新增: defer cancel()
50新增: s.mobileCLI.mu.Lock()
51新增: record, err := s.mobileCLI.record(s.profile, id)
52新增: s.mobileCLI.mu.Unlock()
53新增: if err != nil {
54新增: return
55新增: }
56新增: ticker := time.NewTicker(200 * time.Millisecond)
57新增: defer ticker.Stop()
58新增: seen := map[string]time.Time{}
59新增: completed := map[string]bool{}
60新增: nextCheck := time.Now()
61新增: for {
62新增: select {
63新增: case <-ctx.Done():
64新增: return
65新增: case <-terminal.done:
66新增: return
67新增: case <-ticker.C:
68新增: }
69新增: if time.Now().After(nextCheck) {
70新增: var current terminalConversation
71新增: if err := s.runCLIChannel(ctx, "view", map[string]string{"cli_id": record.CLIID, "config": record.GuestConfig, "connection": record.Connection}, &current); err != nil {
72新增: nextCheck = time.Now().Add(time.Second)
73新增: continue
74新增: }
75新增: if current.ChannelReady || current.CanSend {
76新增: var response struct {
77新增: OK bool `json:"ok"`
78新增: }
79新增: if err := s.runCLIChannel(ctx, "rpc", map[string]string{"cli_id": record.CLIID, "connection": record.Connection, "action": "resume"}, &response); err != nil || !response.OK {
80新增: continue
81新增: }
82新增: return
83新增: }
84新增: if current.Active || current.ConnectionNotice != "" {
85新增: return
86新增: }
87新增: nextCheck = time.Now().Add(time.Second)
88新增: }
89新增: terminal.mu.Lock()
90新增: text := cliStartupText(terminal.history)
91新增: terminal.mu.Unlock()
92新增: dialog := cliStartupDialog(text, record.GuestWorkspace)
93新增: if dialog == "" || completed[dialog] {
94新增: continue
95新增: }
96新增: if seen[dialog].IsZero() {
97新增: seen[dialog] = time.Now()
98新增: continue
99新增: }
100新增: // The CLI ignores keys during a dialog's opening guard interval.
101新增: if time.Since(seen[dialog]) < time.Second {
102新增: continue
103新增: }
104新增: input := "\r"
105新增: if dialog == "project" && strings.Contains(text, "❯No,exit") {
106新增: input = "\x1b[B\r"
107新增: }
108新增: if err := terminal.enqueueInput(ctx, input); err != nil {
109新增: return
110新增: }
111新增: completed[dialog] = true
112新增: }
113新增: }()
114新增:}
新增internal/workbench/cli_connect_test.go+22 −0看文件
@@ -0,0 +1,22 @@
1新增:package workbench
2新增:
3新增:import "testing"
4新增:
5新增:func TestCLIStartupDialogs(t *testing.T) {
6新增: for _, tc := range []struct{ text, want string }{
7新增: {"\x1b[31mWARNING: Loading development channels\x1b[0m\r\nChannels: server:cage\r\nI am using this for local development", "channel"},
8新增: {"Quick safety check: is this a project you created or one you trust?\r\n/work/project\r\nYes, I trust this folder", "project"},
9新增: {"Quick safety check: is this a project you created or one you trust? /other/project Yes, I trust this folder", ""},
10新增: {"WARNING: Loading development channels Channels: server:other I am using this for local development", ""},
11新增: {"WARNING: Loading development channels Channels: server:cage-extra 1. I am using this for local development", ""},
12新增: {"WARNING: Loading development channels Channels: server:cage,server:other 1. I am using this for local development", ""},
13新增: {"WARNING: Loading development channels Channels: server:cage ❯ 1. I am using this for local development", "channel"},
14新增: {"Do you want to proceed? 1. Yes 2. No", ""},
15新增: {"New MCP server found in this project: other Use this MCP server", ""},
16新增: {"Do you want to use this API key?", ""},
17新增: } {
18新增: if got := cliStartupDialog(cliStartupText([]byte(tc.text)), "/work/project"); got != tc.want {
19新增: t.Errorf("dialog %q: %q, want %q", tc.text, got, tc.want)
20新增: }
21新增: }
22新增:}
新增internal/workbench/cloud_guest_share.go+232 −0看文件
@@ -0,0 +1,232 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "context"
5新增: "errors"
6新增: "io"
7新增: "net/http"
8新增: "regexp"
9新增: "runtime"
10新增: "slices"
11新增: "sort"
12新增: "strings"
13新增: "time"
14新增:
15新增: "al.essio.dev/pkg/shellescape"
16新增: "github.com/sylvinus/agent-vm/internal/containerenv"
17新增: "golang.org/x/net/http/httpguts"
18新增:)
19新增:
20新增:// This namespace exists only in the Linux guest. Never resolve its paths on
21新增:// the server host or persist them as grants across connections.
22新增:const clientMountRoot = "/run/cage-client-projects"
23新增:
24新增:var clientMountID = regexp.MustCompile(`^[0-9a-f]{32}$`)
25新增:var errClientMountGone = errors.New("本机项目共享已断开,请在本机重新选择文件夹")
26新增:
27新增:type guestClientMount struct {
28新增: ctx context.Context
29新增: cancel context.CancelFunc
30新增: done chan struct{}
31新增: ready bool // protected by Server.mu
32新增:}
33新增:
34新增:// Caller holds Server.mu. Cancellation closes admission before unmount cleanup.
35新增:func (m *guestClientMount) live() bool { return m.ready && m.ctx.Err() == nil }
36新增:
37新增:func isClientMountPath(path string) bool {
38新增: return path == clientMountRoot || strings.HasPrefix(path, clientMountRoot+"/")
39新增:}
40新增:
41新增:func (s *Server) clientMountWorkspace(path string) (string, error) {
42新增: s.mu.Lock()
43新增: defer s.mu.Unlock()
44新增: if mount := s.clientMounts[path]; mount != nil && mount.live() {
45新增: return path, nil
46新增: }
47新增: return "", errClientMountGone
48新增:}
49新增:
50新增:func (s *Server) appendClientMounts(paths []string) []string {
51新增: s.mu.Lock()
52新增: defer s.mu.Unlock()
53新增: var live []string
54新增: for path, mount := range s.clientMounts {
55新增: if mount.live() && !slices.Contains(paths, path) {
56新增: live = append(live, path)
57新增: }
58新增: }
59新增: sort.Strings(live)
60新增: return append(paths, live...)
61新增:}
62新增:
63新增:func (s *Server) closeClientMounts() {
64新增: s.mu.Lock()
65新增: var mounts []*guestClientMount
66新增: for _, m := range s.clientMounts {
67新增: m.cancel()
68新增: mounts = append(mounts, m)
69新增: }
70新增: s.mu.Unlock()
71新增: for _, m := range mounts {
72新增: <-m.done
73新增: }
74新增:}
75新增:
76新增:// After a controller crash a disconnected FUSE mount may outlive its stream.
77新增:// Only retire exact Cage names in the guest's reserved, root-owned directory.
78新增:// rmdir preserves any unexpected nonempty directory.
79新增:func (s *Server) recoverClientMounts(ctx context.Context) error {
80新增: s.mu.Lock()
81新增: initialized := s.clientMounts != nil
82新增: s.mu.Unlock()
83新增: if initialized {
84新增: return nil
85新增: }
86新增: const recoverScript = `set -eu
87新增:root=` + clientMountRoot + `
88新增:[ ! -L "$root" ] || exit 1
89新增:[ -d "$root" ] || exit 0
90新增:for p in "$root"/*; do
91新增: [[ ${p##*/} =~ ^[a-f0-9]{32}$ ]] || continue
92新增: [ ! -L "$p" ] || continue
93新增: kind=$(findmnt -rn --nocanonicalize -o FSTYPE --mountpoint "$p") || kind=
94新增: case "$kind" in
95新增: fuse.sshfs) sudo -n umount -l -- "$p";;
96新增: "") ;;
97新增: *) continue;;
98新增: esac
99新增: sudo -n rmdir -- "$p" || true
100新增:done`
101新增: if _, err := s.guest(ctx, recoverScript); err != nil {
102新增: return errors.New("无法清理上次连接遗留的本机项目挂载")
103新增: }
104新增: s.mu.Lock()
105新增: if s.clientMounts == nil {
106新增: s.clientMounts = make(map[string]*guestClientMount)
107新增: }
108新增: s.mu.Unlock()
109新增: return nil
110新增:}
111新增:
112新增:func (s *Server) guestClientShare(w http.ResponseWriter, r *http.Request) {
113新增: if runtime.GOOS != "linux" || !containerenv.Configured(s.profile) {
114新增: http.NotFound(w, r)
115新增: return
116新增: }
117新增: id := r.URL.Query().Get("id")
118新增: if !clientMountID.MatchString(id) {
119新增: http.Error(w, "本机项目标识无效", http.StatusBadRequest)
120新增: return
121新增: }
122新增: path := clientMountRoot + "/" + id
123新增: if r.Method == http.MethodGet {
124新增: if _, err := s.clientMountWorkspace(path); err != nil {
125新增: http.Error(w, "本机项目尚未连接", http.StatusConflict)
126新增: return
127新增: }
128新增: jsonReply(w, map[string]string{"workspace": path})
129新增: return
130新增: }
131新增: if !httpguts.HeaderValuesContainsToken(r.Header.Values("Connection"), "upgrade") || !strings.EqualFold(r.Header.Get("Upgrade"), "cage-sftp-v1") || r.ContentLength != 0 {
132新增: http.Error(w, "需要项目共享连接", http.StatusBadRequest)
133新增: return
134新增: }
135新增: if !s.op.TryLock() {
136新增: http.Error(w, "环境正在处理其他操作", http.StatusConflict)
137新增: return
138新增: }
139新增: ctx, cancel := context.WithCancel(r.Context())
140新增: defer cancel()
141新增: mount := &guestClientMount{ctx: ctx, cancel: cancel, done: make(chan struct{})}
142新增: s.mu.Lock()
143新增: available := s.ready && !s.closing && len(s.clientMounts) < 16 && s.clientMounts[path] == nil && !s.busy()
144新增: if available {
145新增: if s.clientMounts == nil {
146新增: s.clientMounts = make(map[string]*guestClientMount)
147新增: }
148新增: s.clientMounts[path] = mount
149新增: }
150新增: s.mu.Unlock()
151新增: s.op.Unlock()
152新增: if !available {
153新增: http.Error(w, "环境未就绪、共享已存在或已达共享上限", http.StatusConflict)
154新增: return
155新增: }
156新增: defer func() {
157新增: s.mu.Lock()
158新增: delete(s.clientMounts, path)
159新增: // Keep a revoked active selection until another project is selected.
160新增: // New tasks must fail, not silently start in the previous cloud folder.
161新增: s.mu.Unlock()
162新增: close(mount.done)
163新增: }()
164新增:
165新增: // A disconnected mount exposes an inaccessible underlying directory until
166新增: // teardown removes it. Never let an old cwd accept writes into the cloud.
167新增: target := shellescape.Quote(path)
168新增: setup, finishSetup := context.WithTimeout(ctx, 10*time.Second)
169新增: _, err := s.guest(setup, "sudo -n install -d -m 0755 "+clientMountRoot+" && sudo -n mkdir -m 000 -- "+target)
170新增: finishSetup()
171新增: if err != nil {
172新增: http.Error(w, "无法准备云端容器挂载位置", http.StatusConflict)
173新增: return
174新增: }
175新增: defer func() {
176新增: ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
177新增: defer cancel()
178新增: _, _ = s.guest(ctx, "if findmnt -rn --nocanonicalize --mountpoint "+target+" >/dev/null; then sudo -n umount -l -- "+target+"; fi; sudo -n rmdir -- "+target)
179新增: }()
180新增: conn, buffer, err := http.NewResponseController(w).Hijack()
181新增: if err != nil {
182新增: http.Error(w, "无法建立项目共享数据流", http.StatusServiceUnavailable)
183新增: return
184新增: }
185新增: defer conn.Close()
186新增: stopClose := context.AfterFunc(ctx, func() { _ = conn.Close() })
187新增: defer stopClose()
188新增: if _, err = buffer.WriteString("HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: cage-sftp-v1\r\n\r\n"); err != nil || buffer.Flush() != nil {
189新增: return
190新增: }
191新增: // sshfs runs inside the guest. Its only SFTP transport is this stream.
192新增: // Keep normal mmap/read-ahead support for compilers and search tools.
193新增: // Present files as the guest user so ownership checks (e.g. Git) work
194新增: // when the workstation uses a different UID or Windows ACLs.
195新增: script := "exec sudo -n sshfs -f :/ " + target + ` -o "slave,allow_other,cache=no,nodev,nosuid,uid=$(id -u),gid=$(id -g)"`
196新增: cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", script)
197新增: cmd.Stdout = conn
198新增: input, err := cmd.StdinPipe()
199新增: if err != nil {
200新增: return
201新增: }
202新增: defer input.Close()
203新增: if err = cmd.Start(); err != nil {
204新增: return
205新增: }
206新增: ingressDone := make(chan struct{})
207新增: go func() {
208新增: defer close(ingressDone)
209新增: _, _ = io.Copy(input, buffer.Reader)
210新增: cancel()
211新增: }()
212新增: // Wait for the actual kernel mount and a successful SFTP stat before
213新增: // admitting any terminal, editor or Claude session to this workspace.
214新增: probed := make(chan struct{})
215新增: go func() {
216新增: defer close(probed)
217新增: probe, end := context.WithTimeout(ctx, 15*time.Second)
218新增: defer end()
219新增: verify := "until [ \"$(findmnt -n -o FSTYPE --mountpoint " + target + ")\" = fuse.sshfs ] && stat -- " + target + "/. >/dev/null 2>&1; do sleep 0.1; done"
220新增: if _, err := s.guest(probe, verify); err != nil {
221新增: cancel()
222新增: return
223新增: }
224新增: s.mu.Lock()
225新增: mount.ready = ctx.Err() == nil
226新增: s.mu.Unlock()
227新增: }()
228新增: _ = cmd.Wait()
229新增: cancel()
230新增: <-ingressDone
231新增: <-probed
232新增:}
新增internal/workbench/cloud_guest_share_test.go+83 −0看文件
@@ -0,0 +1,83 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "context"
5新增: "errors"
6新增: "net/http"
7新增: "os"
8新增: "path/filepath"
9新增: "slices"
10新增: "strings"
11新增: "testing"
12新增:)
13新增:
14新增:// A client project has no directory on the cloud host. It must be usable by
15新增:// the normal project picker and terminal resolver without ever becoming a
16新增:// persisted host-directory grant, even when the user makes it current.
17新增:func TestGuestClientMountActivationAndRevocation(t *testing.T) {
18新增: s := testServer(t)
19新增: s.ready = true
20新增: s.preferences.Workspace = t.TempDir()
21新增: prefsFile := filepath.Join(s.profile, "workbench.json")
22新增: if err := writePrivate(prefsFile, s.preferences); err != nil {
23新增: t.Fatal(err)
24新增: }
25新增: before, err := os.ReadFile(prefsFile)
26新增: if err != nil {
27新增: t.Fatal(err)
28新增: }
29新增: path := clientMountRoot + "/" + strings.Repeat("b", 32)
30新增: ctx, cancel := context.WithCancel(context.Background())
31新增: defer cancel()
32新增: mount := &guestClientMount{ctx: ctx}
33新增: s.clientMounts = map[string]*guestClientMount{path: mount}
34新增: if _, err := s.connectProject(path, true); !errors.Is(err, errClientMountGone) {
35新增: t.Fatalf("accepted project before mount verification: %v", err)
36新增: }
37新增: mount.ready = true
38新增: body := `{"workspace":"` + path + `","add":false,"activate":true}`
39新增: if got := request(s, "POST", "/api/projects/open", s.origin, body, true); got.Code != http.StatusOK {
40新增: t.Fatalf("activate: %d %s", got.Code, got.Body)
41新增: }
42新增: cwd, err := s.connectProject("", false)
43新增: if err != nil || cwd != path {
44新增: t.Fatalf("default terminal workspace = %q, %v", cwd, err)
45新增: }
46新增: if !strings.HasPrefix(terminalScript(cwd, "claude", "claude"), "cd "+path+" &&") ||
47新增: !strings.HasPrefix(managedClaudeTerminalScript(cwd, "claude", "default", "sub", false), "cd "+path+" &&") {
48新增: t.Fatal("CLI would launch outside the mounted workspace")
49新增: }
50新增: after, err := os.ReadFile(prefsFile)
51新增: if err != nil || string(after) != string(before) {
52新增: t.Fatal("activating a client mount persisted it as the default")
53新增: }
54新增: if _, err := os.Stat(filepath.Join(s.profile, "projects.json")); !os.IsNotExist(err) {
55新增: t.Fatal("created a persistent grant for the ephemeral guest path")
56新增: }
57新增: cancel()
58新增: delete(s.clientMounts, path)
59新增: for _, name := range []string{"", path, path + "/..", path + "/subdir"} {
60新增: if _, err := s.connectProject(name, true); !errors.Is(err, errClientMountGone) {
61新增: t.Fatalf("admitted revoked/unregistered guest path %q: %v", name, err)
62新增: }
63新增: }
64新增: paths, err := s.projectPaths()
65新增: if err != nil || slices.Contains(paths, path) {
66新增: t.Fatal("revoked share remained in available projects", err)
67新增: }
68新增:}
69新增:
70新增:func TestGuestClientShareRequiresWorkbenchSessionOriginAndUnlock(t *testing.T) {
71新增: s := testServer(t)
72新增: url := "/api/projects/client-share?id=" + strings.Repeat("c", 32)
73新增: if got := request(s, "POST", url, s.origin, "", false); got.Code != http.StatusUnauthorized {
74新增: t.Fatalf("missing session: HTTP %d", got.Code)
75新增: }
76新增: if got := request(s, "POST", url, "https://untrusted.example", "", true); got.Code != http.StatusForbidden {
77新增: t.Fatalf("foreign origin: HTTP %d", got.Code)
78新增: }
79新增: s.account.lock()
80新增: if got := request(s, "POST", url, s.origin, "", true); got.Code != http.StatusLocked {
81新增: t.Fatalf("locked account: HTTP %d", got.Code)
82新增: }
83新增:}
修改internal/workbench/control_lifecycle.go+30 −1看文件
@@ -11,6 +11,7 @@ import (
1111 "time"
1212
1313 "github.com/sylvinus/agent-vm/internal/containerenv"
14新增: "github.com/sylvinus/agent-vm/internal/guestos"
1415 "github.com/sylvinus/agent-vm/internal/managedproxy"
1516 "github.com/sylvinus/agent-vm/internal/version"
1617)
@@ -66,6 +67,14 @@ func (s *Server) handoff(w http.ResponseWriter, r *http.Request) {
6667
6768// handoffLocked takes ownership of the operation lock and releases it on all paths.
6869func (s *Server) handoffLocked(w http.ResponseWriter) {
70新增: s.handoffWithVMOwnerLocked(w, "")
71新增:}
72新增:
73新增:// Installation activation may retain its newly provisioned, verified guest.
74新增:// Ordinary updates pass no permitted owner and still require a stopped VM.
75新增:func (s *Server) handoffWithVMOwnerLocked(w http.ResponseWriter, permittedOwner string) {
76新增: owners, probeError := controllerVMOwners(s.profile)
77新增: vmBusy := probeError != nil || len(owners) != 0 && (permittedOwner == "" || len(owners) != 1 || owners[0] != permittedOwner)
6978 s.mu.Lock()
7079 if s.closing {
7180 s.mu.Unlock()
@@ -73,8 +82,9 @@ func (s *Server) handoffLocked(w http.ResponseWriter) {
7382 http.Error(w, "后台正在更新,请重新打开 Cage。", http.StatusServiceUnavailable)
7483 return
7584 }
76删除: busy := s.jobs.snapshot().Running || controllerHasVM(s.profile)
85新增: busy := s.jobs.snapshot().Running || vmBusy
7786 busy = busy || s.terminals.hasLive()
87新增: busy = busy || len(s.mobileCLI.activeAccounts()) != 0
7888 if busy || s.shutdown == nil {
7989 s.mu.Unlock()
8090 s.op.Unlock()
@@ -115,6 +125,25 @@ func controllerVMState(profile string) (bool, error) {
115125}
116126
117127func controllerVMOwners(profile string) ([]string, error) {
128新增: binding, err := guestos.LoadWindowsProfile(profile)
129新增: if err != nil {
130新增: return nil, err
131新增: }
132新增: if binding != nil {
133新增: ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
134新增: defer cancel()
135新增: state, err := guestos.WindowsVMResources(ctx, profile, 0, 0)
136新增: if err != nil {
137新增: return nil, err
138新增: }
139新增: if state.State == "" {
140新增: return nil, errors.New("无法确认已绑定 Windows 客机的运行状态,现有环境保持不变")
141新增: }
142新增: if state.State == "Off" || state.State == "Saved" {
143新增: return nil, nil
144新增: }
145新增: return []string{fmt.Sprintf("windows/%s/%s", binding.VMID, state.State)}, nil
146新增: }
118147 if containerenv.Configured(profile) {
119148 environment, err := containerenv.Load(profile)
120149 if err != nil {
修改internal/workbench/control_lifecycle_test.go+9 −0看文件
@@ -115,6 +115,15 @@ func TestDesktopRejectsUnknownAndDifferentBuildsWithoutStoppingThem(t *testing.T
115115 for _, kind := range []string{"same", "same-version-other-build", "legacy"} {
116116 t.Run(kind, func(t *testing.T) {
117117 profile := t.TempDir()
118新增: lock, err := openControllerLock(profile, os.O_CREATE|os.O_RDWR)
119新增: if err != nil {
120新增: t.Fatal(err)
121新增: }
122新增: defer lock.Close()
123新增: if err := lockController(lock); err != nil {
124新增: t.Fatal(err)
125新增: }
126新增: defer unlockController(lock)
118127 identity := current
119128 if kind == "same-version-other-build" {
120129 identity.Build = "different-build"
新增internal/workbench/control_lock.go+80 −0看文件
@@ -0,0 +1,80 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "errors"
5新增: "os"
6新增: "path/filepath"
7新增: "time"
8新增:
9新增: "github.com/sylvinus/agent-vm/internal/host"
10新增:)
11新增:
12新增:// The lock contains no credentials. Old Windows versions created it with the
13新增:// Administrators group as owner. Test the OS lock before repairing its ACL;
14新增:// credential-file ownership must not be used as a process-liveness test.
15新增:func openControllerLock(profile string, flags int) (*os.File, error) {
16新增: path := filepath.Join(profile, "control.lock")
17新增: if info, err := os.Lstat(path); err == nil {
18新增: if !info.Mode().IsRegular() {
19新增: return nil, errors.New("控制锁必须是普通文件")
20新增: }
21新增: } else if !os.IsNotExist(err) {
22新增: return nil, err
23新增: }
24新增: f, err := os.OpenFile(path, flags, 0600)
25新增: if err != nil {
26新增: return nil, err
27新增: }
28新增: opened, statErr := f.Stat()
29新增: current, pathErr := os.Lstat(path)
30新增: if statErr != nil || pathErr != nil || !current.Mode().IsRegular() || !os.SameFile(opened, current) {
31新增: f.Close()
32新增: return nil, errors.New("控制锁路径已变化,请重试")
33新增: }
34新增: return f, nil
35新增:}
36新增:
37新增:// A status probe can briefly own the lock while it checks or repairs its ACL.
38新增:// Let that probe finish before deciding that another controller owns the profile.
39新增:func lockControllerForStart(f *os.File) error {
40新增: deadline := time.Now().Add(2 * time.Second)
41新增: for {
42新增: err := lockController(f)
43新增: if err == nil || !controllerLockContended(err) || !time.Now().Before(deadline) {
44新增: return err
45新增: }
46新增: time.Sleep(10 * time.Millisecond)
47新增: }
48新增:}
49新增:
50新增:func controllerLockStatus(profile string) (free bool, err error) {
51新增: f, err := openControllerLock(profile, os.O_RDWR)
52新增: if err != nil {
53新增: if os.IsNotExist(err) {
54新增: return true, nil
55新增: }
56新增: return false, err
57新增: }
58新增: defer f.Close()
59新增: if err := lockController(f); err != nil {
60新增: if controllerLockContended(err) {
61新增: return false, nil
62新增: }
63新增: return false, err
64新增: }
65新增: defer unlockController(f)
66新增: // Repair legacy ownership only while holding the same lock that protects
67新增: // record publication. Never unlink a live lock or relax its permissions.
68新增: if err := host.ProtectFile(f.Name()); err != nil {
69新增: return false, err
70新增: }
71新增: if err := host.CheckPrivateFile(f.Name()); err != nil {
72新增: return false, err
73新增: }
74新增: return true, nil
75新增:}
76新增:
77新增:func controllerLockFree(profile string) bool {
78新增: free, err := controllerLockStatus(profile)
79新增: return free && err == nil
80新增:}
新增internal/workbench/control_recovery_test.go+213 −0看文件
@@ -0,0 +1,213 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "context"
5新增: "errors"
6新增: "net"
7新增: "net/http"
8新增: "net/http/httptest"
9新增: "os"
10新增: "os/exec"
11新增: "path/filepath"
12新增: "strconv"
13新增: "strings"
14新增: "testing"
15新增: "time"
16新增:)
17新增:
18新增:// Reusing a dead controller's port must not turn an old token into a
19新增:// permanently unopenable profile, including when its PID has been reused.
20新增:func TestDesktopRecoversStaleRecordOnReusedPort(t *testing.T) {
21新增: for _, held := range []bool{false, true} {
22新增: t.Run(strconv.FormatBool(held), func(t *testing.T) {
23新增: profile := t.TempDir()
24新增: server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
25新增: http.Error(w, "old token", http.StatusUnauthorized)
26新增: }))
27新增: defer server.Close()
28新增: _, portText, _ := net.SplitHostPort(server.Listener.Addr().String())
29新增: port, _ := strconv.Atoi(portText)
30新增: if err := writePrivate(filepath.Join(profile, "control.json"), controlFile{Port: port, PID: os.Getpid(), Token: strings.Repeat("a", 64)}); err != nil {
31新增: t.Fatal(err)
32新增: }
33新增: lock, err := os.OpenFile(filepath.Join(profile, "control.lock"), os.O_CREATE|os.O_RDWR, 0600)
34新增: if err != nil {
35新增: t.Fatal(err)
36新增: }
37新增: defer lock.Close()
38新增: if held {
39新增: if err := lockController(lock); err != nil {
40新增: t.Fatal(err)
41新增: }
42新增: defer unlockController(lock)
43新增: }
44新增: started := errors.New("replacement started")
45新增: _, err = desktopLaunch(profile, false, DesktopOptions{}, func() error { return started })
46新增: if held && (err == nil || errors.Is(err, started)) {
47新增: t.Fatalf("replaced a locked unauthenticated controller: %v", err)
48新增: }
49新增: if !held && !errors.Is(err, started) {
50新增: t.Fatalf("stale record prevented restart: %v", err)
51新增: }
52新增: if !held {
53新增: exe, _ := os.Executable()
54新增: st, err := NewDesktopLocalController(filepath.Join(profile, "config.json"), exe).Status(context.Background())
55新增: if err != nil || !st.Known || st.ServiceRunning {
56新增: t.Fatalf("stale port/PID reported as a live controller: %+v %v", st, err)
57新增: }
58新增: }
59新增: })
60新增: }
61新增:}
62新增:
63新增:func TestControllerRestartAfterGracefulAndForcedExit(t *testing.T) {
64新增: for _, forced := range []bool{false, true} {
65新增: t.Run(strconv.FormatBool(forced), func(t *testing.T) {
66新增: profile := t.TempDir()
67新增: config := filepath.Join(profile, "config.json")
68新增: keep := filepath.Join(profile, "personal-data-sentinel")
69新增: if err := os.WriteFile(keep, []byte("preserve projects and account data"), 0600); err != nil {
70新增: t.Fatal(err)
71新增: }
72新增: exe, err := os.Executable()
73新增: if err != nil {
74新增: t.Fatal(err)
75新增: }
76新增: start := func() *exec.Cmd {
77新增: cmd := exec.Command(exe, "-test.run=^TestServeShutdownHandoff$", "-test.timeout=30s")
78新增: cmd.Env = append(os.Environ(), "CAGE_TEST_SHUTDOWN_CONFIG="+config)
79新增: if err := cmd.Start(); err != nil {
80新增: t.Fatal(err)
81新增: }
82新增: t.Cleanup(func() { _ = cmd.Process.Kill(); _ = cmd.Wait() })
83新增: return cmd
84新增: }
85新增: waitReady := func() *controllerClient {
86新增: deadline := time.Now().Add(10 * time.Second)
87新增: for time.Now().Before(deadline) {
88新增: c, err := connectController(profile)
89新增: if err == nil {
90新增: return c
91新增: }
92新增: time.Sleep(25 * time.Millisecond)
93新增: }
94新增: t.Fatal("controller never became ready")
95新增: return nil
96新增: }
97新增: stop := func(c *controllerClient) {
98新增: deadline := time.Now().Add(3 * time.Second)
99新增: for {
100新增: status, err := c.call("POST", "/api/handoff", map[string]string{"token": c.record.Token}, nil)
101新增: if err != nil {
102新增: t.Fatal(err)
103新增: }
104新增: if status == http.StatusOK {
105新增: break
106新增: }
107新增: if status != http.StatusConflict || time.Now().After(deadline) {
108新增: t.Fatalf("idle handoff returned HTTP %d", status)
109新增: }
110新增: time.Sleep(25 * time.Millisecond)
111新增: }
112新增: if err := c.waitForExit(); err != nil {
113新增: t.Fatal(err)
114新增: }
115新增: }
116新增: cmd := start()
117新增: c := waitReady()
118新增: old := c.record
119新增: if forced {
120新增: if err := cmd.Process.Kill(); err != nil {
121新增: t.Fatal(err)
122新增: }
123新增: _ = cmd.Wait()
124新增: if _, err := os.Stat(filepath.Join(profile, "control.json")); err != nil {
125新增: t.Fatalf("forced exit did not leave the expected stale record: %v", err)
126新增: }
127新增: } else {
128新增: stop(c)
129新增: if err := cmd.Wait(); err != nil {
130新增: t.Fatal(err)
131新增: }
132新增: if _, err := os.Stat(filepath.Join(profile, "control.json")); !os.IsNotExist(err) {
133新增: t.Fatalf("normal exit left a connection record: %v", err)
134新增: }
135新增: }
136新增: c.close()
137新增: if !controllerLockFree(profile) {
138新增: t.Fatal("exited process left the OS lock held")
139新增: }
140新增: // Occupy the old port with a different service while reopening Cage.
141新增: listener, err := net.Listen("tcp4", net.JoinHostPort("127.0.0.1", strconv.Itoa(old.Port)))
142新增: if err != nil {
143新增: t.Fatal(err)
144新增: }
145新增: foreign := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { http.Error(w, "different service", 401) }))
146新增: foreign.Listener.Close()
147新增: foreign.Listener = listener
148新增: foreign.Start()
149新增: defer foreign.Close()
150新增: _, err = desktopLaunch(profile, false, DesktopOptions{}, func() error { cmd = start(); return nil })
151新增: if err != nil {
152新增: t.Fatalf("reopen failed: %v", err)
153新增: }
154新增: c = waitReady()
155新增: defer c.close()
156新增: if c.record.PID == old.PID || c.record.Token == old.Token {
157新增: t.Fatal("reopen reused a dead controller's identity")
158新增: }
159新增: stop(c)
160新增: if err := cmd.Wait(); err != nil {
161新增: t.Fatal(err)
162新增: }
163新增: if _, err := os.Stat(filepath.Join(profile, "control.json")); !os.IsNotExist(err) {
164新增: t.Fatalf("reopened controller left a record: %v", err)
165新增: }
166新增: if b, err := os.ReadFile(keep); err != nil || string(b) != "preserve projects and account data" {
167新增: t.Fatalf("personal data changed: %v", err)
168新增: }
169新增: })
170新增: }
171新增:}
172新增:
173新增:func TestDesktopRecoveryRejectsNonRegularLock(t *testing.T) {
174新增: profile := t.TempDir()
175新增: if err := os.Mkdir(filepath.Join(profile, "control.lock"), 0700); err != nil {
176新增: t.Fatal(err)
177新增: }
178新增: if err := os.WriteFile(filepath.Join(profile, "control.json"), []byte("invalid"), 0600); err != nil {
179新增: t.Fatal(err)
180新增: }
181新增: _, err := desktopLaunch(profile, false, DesktopOptions{}, func() error {
182新增: t.Fatal("started with an unusable lock")
183新增: return nil
184新增: })
185新增: if err == nil {
186新增: t.Fatal("unusable lock accepted")
187新增: }
188新增:}
189新增:
190新增:func TestDesktopWaitsForRetiringController(t *testing.T) {
191新增: profile := t.TempDir()
192新增: lock, err := openControllerLock(profile, os.O_CREATE|os.O_RDWR)
193新增: if err != nil {
194新增: t.Fatal(err)
195新增: }
196新增: defer lock.Close()
197新增: if err := lockController(lock); err != nil {
198新增: t.Fatal(err)
199新增: }
200新增: released := make(chan struct{})
201新增: go func() { time.Sleep(100 * time.Millisecond); _ = unlockController(lock); close(released) }()
202新增: defer func() { <-released }()
203新增: started := errors.New("new controller started")
204新增: _, err = desktopLaunch(profile, false, DesktopOptions{}, func() error {
205新增: if !controllerLockFree(profile) {
206新增: t.Error("started before the retiring controller released its lock")
207新增: }
208新增: return started
209新增: })
210新增: if !errors.Is(err, started) {
211新增: t.Fatalf("did not resume after shutdown: %v", err)
212新增: }
213新增:}
新增internal/workbench/control_recovery_windows_test.go+61 −0看文件
@@ -0,0 +1,61 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "context"
5新增: "os"
6新增: "path/filepath"
7新增: "testing"
8新增:
9新增: "github.com/sylvinus/agent-vm/internal/host"
10新增: "golang.org/x/sys/windows"
11新增:)
12新增:
13新增:func TestDesktopLocalAdministratorOwnedLock(t *testing.T) {
14新增: if !windows.GetCurrentProcessToken().IsElevated() {
15新增: t.Skip("requires an elevated Windows token")
16新增: }
17新增: for _, held := range []bool{false, true} {
18新增: name := "idle"
19新增: if held {
20新增: name = "live"
21新增: }
22新增: t.Run(name, func(t *testing.T) {
23新增: profile := t.TempDir()
24新增: if err := host.EnsurePrivateDir(profile); err != nil {
25新增: t.Fatal(err)
26新增: }
27新增: path := filepath.Join(profile, "control.lock")
28新增: lock, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0600)
29新增: if err != nil {
30新增: t.Fatal(err)
31新增: }
32新增: defer lock.Close()
33新增: admin, err := windows.CreateWellKnownSid(windows.WinBuiltinAdministratorsSid)
34新增: if err != nil {
35新增: t.Fatal(err)
36新增: }
37新增: if err := windows.SetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION, admin, nil, nil, nil); err != nil {
38新增: t.Fatal(err)
39新增: }
40新增: if err := host.CheckPrivateFile(path); err == nil {
41新增: t.Fatal("fixture is not an old group-owned lock")
42新增: }
43新增: if held {
44新增: if err := lockController(lock); err != nil {
45新增: t.Fatal(err)
46新增: }
47新增: defer unlockController(lock)
48新增: }
49新增: exe, _ := os.Executable()
50新增: st, err := NewDesktopLocalController(filepath.Join(profile, "config.json"), exe).Status(context.Background())
51新增: if err != nil || st.ServiceRunning != held || st.Known == held {
52新增: t.Fatalf("lock ownership confused with liveness: %+v %v", st, err)
53新增: }
54新增: if !held {
55新增: if err := host.CheckPrivateFile(path); err != nil {
56新增: t.Fatalf("idle lock was not migrated to private current-user ownership: %v", err)
57新增: }
58新增: }
59新增: })
60新增: }
61新增:}
修改internal/workbench/control_shutdown_test.go+31 −0看文件
@@ -22,12 +22,35 @@ func TestServeShutdownHandoff(t *testing.T) {
2222 }
2323 return
2424 }
25新增: for _, tc := range []struct {
26新增: name, saved string
27新增: timezone, language bool
28新增: }{
29新增: {"fresh profile", "", true, true},
30新增: {"legacy missing fields", `{"keyboard":"native"}`, true, false},
31新增: {"saved manual choice", `{"auto_timezone":false,"auto_language":false}`, false, false},
32新增: {"saved automatic choice", `{"auto_timezone":true,"auto_language":true}`, true, true},
33新增: } {
34新增: t.Run(tc.name, func(t *testing.T) { testServeShutdownHandoff(t, tc.saved, tc.timezone, tc.language) })
35新增: }
36新增:}
37新增:
38新增:func testServeShutdownHandoff(t *testing.T, saved string, timezone, language bool) {
39新增: const helperConfig = "CAGE_TEST_SHUTDOWN_CONFIG"
2540
2641 // Keep both the profile and its sibling workspace under the test directory.
2742 // With no VM record, node store or service record, Serve only initializes
2843 // private files; its monitors and handoff cannot reach a running environment.
2944 profile := filepath.Join(t.TempDir(), "profile")
3045 configPath := filepath.Join(profile, "config.json")
46新增: if saved != "" {
47新增: if err := os.MkdirAll(profile, 0700); err != nil {
48新增: t.Fatal(err)
49新增: }
50新增: if err := os.WriteFile(filepath.Join(profile, "workbench.json"), []byte(saved), 0600); err != nil {
51新增: t.Fatal(err)
52新增: }
53新增: }
3154 executable, err := os.Executable()
3255 if err != nil {
3356 t.Fatal(err)
@@ -84,6 +107,14 @@ func TestServeShutdownHandoff(t *testing.T) {
84107 if origin == "" || time.Now().After(deadline) {
85108 t.Fatal("control service did not become ready")
86109 }
110新增: preferencesData, err := os.ReadFile(filepath.Join(profile, "workbench.json"))
111新增: var preferences Preferences
112新增: if err != nil || json.Unmarshal(preferencesData, &preferences) != nil {
113新增: t.Fatalf("initialized preferences: %s, %v", preferencesData, err)
114新增: }
115新增: if preferences.AutoTimezone != timezone || preferences.AutoLanguage != language {
116新增: t.Fatalf("automatic defaults/override: timezone=%t language=%t", preferences.AutoTimezone, preferences.AutoLanguage)
117新增: }
87118
88119 lock, err := os.OpenFile(filepath.Join(profile, "control.lock"), os.O_RDWR, 0600)
89120 if err != nil {
新增internal/workbench/control_startup_test.go+86 −0看文件
@@ -0,0 +1,86 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "bytes"
5新增: "context"
6新增: "net/http"
7新增: "os"
8新增: "os/exec"
9新增: "path/filepath"
10新增: "strings"
11新增: "testing"
12新增: "time"
13新增:)
14新增:
15新增:func TestControllerStartsAfterProbeReleasesLock(t *testing.T) {
16新增: profile := t.TempDir()
17新增: lock, err := openControllerLock(profile, os.O_CREATE|os.O_RDWR)
18新增: if err != nil {
19新增: t.Fatal(err)
20新增: }
21新增: defer lock.Close()
22新增: if err := lockController(lock); err != nil {
23新增: t.Fatal(err)
24新增: }
25新增: defer unlockController(lock)
26新增: exe, err := os.Executable()
27新增: if err != nil {
28新增: t.Fatal(err)
29新增: }
30新增: ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
31新增: defer cancel()
32新增: cmd := exec.CommandContext(ctx, exe, "-test.run=^TestServeShutdownHandoff$", "-test.timeout=12s")
33新增: cmd.Env = append(os.Environ(), "CAGE_TEST_SHUTDOWN_CONFIG="+filepath.Join(profile, "config.json"))
34新增: var output bytes.Buffer
35新增: cmd.Stdout, cmd.Stderr = &output, &output
36新增: if err := cmd.Start(); err != nil {
37新增: t.Fatal(err)
38新增: }
39新增: done := make(chan error, 1)
40新增: go func() { done <- cmd.Wait() }()
41新增: defer func() { cancel(); <-done; t.Log(output.String()) }()
42新增: // Wait until the real server reaches startup while another process still
43新增: // holds the short-lived status-probe lock.
44新增: for {
45新增: log, _ := os.ReadFile(filepath.Join(profile, "logs", "events.jsonl"))
46新增: if strings.Contains(string(log), "service starting") {
47新增: break
48新增: }
49新增: select {
50新增: case err := <-done:
51新增: done <- err
52新增: t.Fatalf("controller exited during startup: %v", err)
53新增: case <-ctx.Done():
54新增: t.Fatal("controller did not reach startup")
55新增: case <-time.After(10 * time.Millisecond):
56新增: }
57新增: }
58新增: select {
59新增: case err := <-done:
60新增: done <- err
61新增: t.Fatalf("controller mistook a status probe for a running service: %v", err)
62新增: case <-time.After(100 * time.Millisecond):
63新增: }
64新增: if err := unlockController(lock); err != nil {
65新增: t.Fatal(err)
66新增: }
67新增: for {
68新增: c, err := connectController(profile)
69新增: if err == nil {
70新增: defer c.close()
71新增: status, err := c.call("POST", "/api/handoff", map[string]string{"token": c.record.Token}, nil)
72新增: if err != nil || status != http.StatusOK {
73新增: t.Fatalf("shutdown: HTTP %d, %v", status, err)
74新增: }
75新增: return
76新增: }
77新增: select {
78新增: case err := <-done:
79新增: done <- err
80新增: t.Fatalf("controller exited before becoming ready: %v", err)
81新增: case <-ctx.Done():
82新增: t.Fatal("controller did not become ready after probe released its lock")
83新增: case <-time.After(25 * time.Millisecond):
84新增: }
85新增: }
86新增:}
修改internal/workbench/desktop.go+44 −3看文件
@@ -61,8 +61,14 @@ func openController(profile string) (*controllerClient, error) {
6161}
6262
6363func connectController(profile string) (*controllerClient, error) {
64新增: if controllerLockFree(profile) {
65新增: return nil, errControllerUnavailable
66新增: }
6467 c, err := openController(profile)
6568 if err != nil {
69新增: if controllerLockFree(profile) {
70新增: return nil, errControllerUnavailable
71新增: }
6672 return nil, err
6773 }
6874 record := c.record
@@ -77,6 +83,15 @@ func connectController(profile string) (*controllerClient, error) {
7783 }
7884 if status != http.StatusOK {
7985 c.close()
86新增: if status == http.StatusServiceUnavailable {
87新增: return nil, errControllerUnavailable
88新增: }
89新增: // A dead controller can leave a record whose port or PID is now reused.
90新增: // Only a free profile lock permits a new controller to replace that
91新增: // record. An occupied or inaccessible lock must preserve its owner.
92新增: if controllerLockFree(profile) {
93新增: return nil, errControllerUnavailable
94新增: }
8095 return nil, errors.New("无法认证已有后台,未尝试终止或替换它。")
8196 }
8297 u, err := url.Parse(c.launch.URL)
@@ -91,6 +106,30 @@ func connectController(profile string) (*controllerClient, error) {
91106 return c, nil
92107}
93108func (c *controllerClient) close() { c.client.CloseIdleConnections() }
109新增:
110新增:// Shutdown removes the record before releasing the profile lock. A new window
111新增:// can arrive in that interval; wait for retirement or a ready service without
112新增:// spawning a replacement against an occupied lock.
113新增:func waitControllerReady(ctx context.Context, profile string) (*controllerClient, error) {
114新增: for {
115新增: c, err := connectController(profile)
116新增: if !errors.Is(err, errControllerUnavailable) {
117新增: return c, err
118新增: }
119新增: free, lockErr := controllerLockStatus(profile)
120新增: if lockErr != nil {
121新增: return nil, lockErr
122新增: }
123新增: if free {
124新增: return nil, errControllerUnavailable
125新增: }
126新增: select {
127新增: case <-ctx.Done():
128新增: return nil, errors.New("本机后台尚未退出或仍未响应,请稍后重试")
129新增: case <-time.After(100 * time.Millisecond):
130新增: }
131新增: }
132新增:}
94133func (c *controllerClient) call(method, path string, input, output any) (int, error) {
95134 return c.callContext(context.Background(), method, path, input, output)
96135}
@@ -140,7 +179,9 @@ func desktopLaunch(profile string, gateway bool, options DesktopOptions, start f
140179 if err != nil {
141180 return DesktopResult{}, err
142181 }
143删除: current, err := connectController(profile)
182新增: ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second)
183新增: defer cancel()
184新增: current, err := waitControllerReady(ctx, profile)
144185 if err == nil {
145186 defer current.close()
146187 if current.launch.DesktopGateway != gateway {
@@ -204,7 +245,7 @@ func desktopLaunch(profile string, gateway bool, options DesktopOptions, start f
204245func PrepareUpdate(configPath string, stop bool) (DesktopResult, error) {
205246 c, err := connectController(filepath.Dir(configPath))
206247 if errors.Is(err, errControllerUnavailable) {
207删除: lock, lockErr := os.OpenFile(filepath.Join(filepath.Dir(configPath), "control.lock"), os.O_RDWR, 0600)
248新增: lock, lockErr := openControllerLock(filepath.Dir(configPath), os.O_RDWR)
208249 if lockErr == nil {
209250 defer lock.Close()
210251 if lockController(lock) != nil {
@@ -357,7 +398,7 @@ func (c *controllerClient) stopAndHandoff() error {
357398 return c.waitForExit()
358399}
359400func (c *controllerClient) waitForExit() error {
360删除: f, err := os.OpenFile(filepath.Join(c.profile, "control.lock"), os.O_RDWR, 0600)
401新增: f, err := openControllerLock(c.profile, os.O_RDWR)
361402 if err != nil {
362403 return errors.New("无法确认后台已退出,未继续更新。")
363404 }
新增internal/workbench/desktop_file_open.go+285 −0看文件
@@ -0,0 +1,285 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "bytes"
5新增: "context"
6新增: "encoding/json"
7新增: "errors"
8新增: "io"
9新增: "net/http"
10新增: "net/url"
11新增: "os"
12新增: "os/exec"
13新增: pathpkg "path"
14新增: "path/filepath"
15新增: "runtime"
16新增: "strings"
17新增: "time"
18新增:)
19新增:
20新增:type desktopFileOpen struct {
21新增: ID string `json:"id,omitempty"`
22新增: Path string `json:"path,omitempty"`
23新增: Action string `json:"action,omitempty"`
24新增: Handled bool `json:"handled,omitempty"`
25新增:}
26新增:
27新增:// Resolve a guest path against directory grants, never against the host root.
28新增:// Both lexical traversal and a host-side symlink out of the project are denied.
29新增:func resolveProjectFilePath(guest string, projects []string) (string, error) {
30新增: if !pathpkg.IsAbs(guest) || pathpkg.Clean(guest) != guest || strings.ContainsAny(guest, "\x00\\") {
31新增: return "", errors.New("文件位置无效")
32新增: }
33新增: for _, project := range projects {
34新增: if isClientMountPath(project) {
35新增: continue
36新增: }
37新增: root := strings.TrimRight(guestPath(project), "/")
38新增: if guest != root && !strings.HasPrefix(guest, root+"/") {
39新增: continue
40新增: }
41新增: hostRoot, err := filepath.EvalSymlinks(project)
42新增: if err != nil {
43新增: continue
44新增: }
45新增: target, err := filepath.EvalSymlinks(filepath.Join(hostRoot, filepath.FromSlash(strings.TrimPrefix(guest, root))))
46新增: if err != nil {
47新增: return "", errors.New("文件已移动、删除或无法访问")
48新增: }
49新增: relative, err := filepath.Rel(hostRoot, target)
50新增: if err != nil || relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) || filepath.IsAbs(relative) {
51新增: return "", errors.New("文件指向 Cage 项目目录之外,无法打开")
52新增: }
53新增: info, err := os.Stat(target)
54新增: if err != nil || (!info.Mode().IsRegular() && !info.IsDir()) {
55新增: return "", errors.New("请选择 Cage 项目中的普通文件或文件夹")
56新增: }
57新增: return target, nil
58新增: }
59新增: return "", errors.New("只能打开 Cage 项目目录中的文件和文件夹")
60新增:}
61新增:
62新增:func (s *Server) resolveDesktopProjectFile(guest string, projects []string) (string, error) {
63新增: if s.macosGuest == nil && s.windowsGuest == nil {
64新增: return resolveProjectFilePath(guest, projects)
65新增: }
66新增: if s.windowsGuest != nil {
67新增: guest = strings.ReplaceAll(guest, "\\", "/")
68新增: if !windowsCLIAbsolutePath(guest) || strings.Contains(guest[2:], ":") {
69新增: return "", errors.New("文件位置无效")
70新增: }
71新增: }
72新增: if pathpkg.Clean(guest) != guest || strings.ContainsAny(guest, "\x00\\") {
73新增: return "", errors.New("文件位置无效")
74新增: }
75新增: for _, project := range projects {
76新增: if isClientMountPath(project) {
77新增: continue
78新增: }
79新增: var root string
80新增: if s.macosGuest != nil {
81新增: root = macOSProjectPath(s.macosGuest.User, project)
82新增: } else {
83新增: binding, err := s.windowsProjectForHost(project)
84新增: if err != nil {
85新增: continue
86新增: }
87新增: root = strings.ReplaceAll(binding.Path, "\\", "/")
88新增: }
89新增: root = strings.TrimRight(root, "/")
90新增: if !cliWorkspaceWithin(guest, root, s.windowsGuest != nil) {
91新增: continue
92新增: }
93新增: mapped := strings.TrimRight(guestPath(project), "/") + guest[len(root):]
94新增: return resolveProjectFilePath(mapped, []string{project})
95新增: }
96新增: return "", errors.New("只能打开已授权 Cage 项目中的文件和文件夹")
97新增:}
98新增:
99新增:func (s *Server) desktopFileOpenAction(w http.ResponseWriter, r *http.Request) {
100新增: var input struct {
101新增: ID string `json:"id"`
102新增: Stage string `json:"stage"`
103新增: Error string `json:"error"`
104新增: }
105新增: if !readJSON(w, r, &input) {
106新增: return
107新增: }
108新增: if !browserFileID.MatchString(input.ID) || (input.Stage != "claim" && input.Stage != "complete") {
109新增: http.Error(w, "文件打开请求无效", 400)
110新增: return
111新增: }
112新增: if !s.fileTargetReady("desktop", "") {
113新增: http.Error(w, "环境尚未就绪", 409)
114新增: return
115新增: }
116新增: ctx, cancel := context.WithTimeout(r.Context(), 30*time.Minute)
117新增: defer cancel()
118新增: body, _ := json.Marshal(input)
119新增: result, err := s.guestFiles(ctx, "desktop", "POST", "/open-"+input.Stage, bytes.NewReader(body), "")
120新增: if err != nil {
121新增: requestError(w, err)
122新增: return
123新增: }
124新增: if input.Stage == "complete" || result["handled"] == true {
125新增: jsonReply(w, result)
126新增: return
127新增: }
128新增: guest, _ := result["path"].(string)
129新增: action, _ := result["action"].(string)
130新增: var target string
131新增: if download, _ := result["download_id"].(string); download != "" && (s.macosGuest != nil || s.windowsGuest != nil) {
132新增: var saved browserDownloadInfo
133新增: saved, err = s.downloadInfo(ctx, download)
134新增: if err == nil && saved.State != "saved" {
135新增: err = errors.New("文件尚未完整保存到主机,请稍后重新打开")
136新增: }
137新增: target = saved.Path
138新增: if err == nil && result["directory"] == true {
139新增: target = filepath.Dir(target)
140新增: }
141新增: } else {
142新增: var projects []string
143新增: projects, err = s.projectPaths()
144新增: if err == nil {
145新增: target, err = s.resolveDesktopProjectFile(guest, projects)
146新增: }
147新增: }
148新增: if action != "open" && action != "reveal" {
149新增: err = errors.New("文件打开操作无效")
150新增: }
151新增: if message, _ := result["error"].(string); message != "" {
152新增: err = errors.New(message)
153新增: }
154新增: if err != nil {
155新增: body, _ = json.Marshal(map[string]string{"id": input.ID, "error": err.Error()})
156新增: cleanup, cancelCleanup := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
157新增: defer cancelCleanup()
158新增: _, _ = s.guestFiles(cleanup, "desktop", "POST", "/open-complete", bytes.NewReader(body), "")
159新增: requestError(w, err)
160新增: return
161新增: }
162新增: jsonReply(w, desktopFileOpen{ID: input.ID, Path: target, Action: action})
163新增:}
164新增:
165新增:// DesktopFileForConnection consumes one pending app request. The web bridge
166新增:// supplies only an opaque ID; the authenticated local controller owns its path.
167新增:func DesktopFileForConnection(configPath, connectionID, id string) (map[string]any, error) {
168新增: if !browserFileID.MatchString(id) {
169新增: return nil, errors.New("文件打开标识无效")
170新增: }
171新增: client, err := connectController(filepath.Dir(configPath))
172新增: if err != nil {
173新增: return nil, err
174新增: }
175新增: defer client.close()
176新增: entry, _ := url.Parse(client.launch.URL)
177新增: status, err := client.call("POST", "/api/session", map[string]string{"token": entry.Fragment}, nil)
178新增: if err != nil || status != 200 {
179新增: return nil, errors.New("无法连接文件操作会话")
180新增: }
181新增: connection, err := client.bindConnection(connectionID)
182新增: if err != nil {
183新增: return nil, err
184新增: }
185新增: var request desktopFileOpen
186新增: err = desktopOpenCall(client, map[string]string{"id": id, "stage": "claim"}, &request)
187新增: if err != nil {
188新增: return nil, err
189新增: }
190新增: if request.Handled {
191新增: return map[string]any{"handled": true}, nil
192新增: }
193新增: if connection.Mode == "remote" {
194新增: err = errors.New("此文件位于远程环境,请先在下载列表中保存到本机")
195新增: } else if request.ID != id || !filepath.IsAbs(request.Path) || (request.Action != "open" && request.Action != "reveal") {
196新增: err = errors.New("文件打开响应无效")
197新增: } else {
198新增: err = openHostFile(request.Path, request.Action)
199新增: }
200新增: message := ""
201新增: if err != nil {
202新增: message = err.Error()
203新增: }
204新增: completeErr := desktopOpenCall(client, map[string]string{"id": id, "stage": "complete", "error": message}, nil)
205新增: if err != nil {
206新增: return nil, err
207新增: }
208新增: if completeErr != nil {
209新增: return nil, completeErr
210新增: }
211新增: return map[string]any{"ok": true}, nil
212新增:}
213新增:
214新增:func desktopOpenCall(client *controllerClient, input map[string]string, output any) error {
215新增: body, _ := json.Marshal(input)
216新增: request, _ := http.NewRequest("POST", client.origin+"/api/input/files/desktop/open", bytes.NewReader(body))
217新增: request.Header.Set("Origin", client.origin)
218新增: request.Header.Set("Content-Type", "application/json")
219新增: response, err := client.client.Do(request)
220新增: if err != nil {
221新增: return errors.New("文件操作连接已中断,请重新打开")
222新增: }
223新增: defer response.Body.Close()
224新增: data, err := io.ReadAll(io.LimitReader(response.Body, 65537))
225新增: if err != nil || len(data) > 65536 {
226新增: return errors.New("文件操作响应无效")
227新增: }
228新增: if response.StatusCode != http.StatusOK {
229新增: message := strings.TrimSpace(string(data))
230新增: if message == "" {
231新增: message = "文件打开请求已失效,请重新操作"
232新增: }
233新增: return errors.New(message)
234新增: }
235新增: if output != nil && json.Unmarshal(data, output) != nil {
236新增: return errors.New("文件操作响应无效")
237新增: }
238新增: return nil
239新增:}
240新增:
241新增:func hostFileCommand(platform, path, action string, directory bool) *exec.Cmd {
242新增: switch platform {
243新增: case "darwin":
244新增: if action == "reveal" {
245新增: return exec.Command("/usr/bin/open", "-R", "--", path)
246新增: }
247新增: return exec.Command("/usr/bin/open", "--", path)
248新增: case "windows":
249新增: if action == "reveal" {
250新增: return exec.Command("explorer.exe", "/select,"+path)
251新增: }
252新增: if directory {
253新增: return exec.Command("explorer.exe", path)
254新增: }
255新增: return exec.Command("rundll32.exe", "url.dll,FileProtocolHandler", path)
256新增: default:
257新增: if action == "reveal" {
258新增: uri := (&url.URL{Scheme: "file", Path: filepath.ToSlash(path)}).String()
259新增: return exec.Command("gdbus", "call", "--session", "--dest", "org.freedesktop.FileManager1", "--object-path", "/org/freedesktop/FileManager1", "--method", "org.freedesktop.FileManager1.ShowItems", "[\""+uri+"\"]", "")
260新增: }
261新增: return exec.Command("gio", "open", path)
262新增: }
263新增:}
264新增:
265新增:func openHostFile(path, action string) error {
266新增: info, err := os.Stat(path)
267新增: if err != nil || (!info.Mode().IsRegular() && !info.IsDir()) {
268新增: return errors.New("文件已移动、删除或无法访问")
269新增: }
270新增: ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
271新增: defer cancel()
272新增: command := hostFileCommand(runtime.GOOS, path, action, info.IsDir())
273新增: cmd := exec.CommandContext(ctx, command.Path, command.Args[1:]...)
274新增: hideCommand(cmd)
275新增: if err = cmd.Run(); err != nil {
276新增: if runtime.GOOS != "linux" || action != "reveal" {
277新增: return errors.New("无法打开本机文件或文件管理器,请检查默认应用和文件权限")
278新增: }
279新增: fallback := exec.CommandContext(ctx, "gio", "open", filepath.Dir(path))
280新增: if fallback.Run() != nil {
281新增: return errors.New("无法打开本机文件管理器,请检查桌面环境和文件权限")
282新增: }
283新增: }
284新增: return nil
285新增:}
新增internal/workbench/desktop_file_open_test.go+180 −0看文件
@@ -0,0 +1,180 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "net/http"
5新增: "net/http/httptest"
6新增: "os"
7新增: "path/filepath"
8新增: "reflect"
9新增: "strings"
10新增: "testing"
11新增:
12新增: "github.com/sylvinus/agent-vm/internal/guestos"
13新增:)
14新增:
15新增:func TestNativeDesktopProjectPathsUseCurrentGuestMount(t *testing.T) {
16新增: for _, system := range []string{"macos", "windows"} {
17新增: t.Run(system, func(t *testing.T) {
18新增: s := testServer(t)
19新增: project := t.TempDir()
20新增: file := filepath.Join(project, "中文 #+%.md")
21新增: if err := os.WriteFile(file, []byte("project document"), 0600); err != nil {
22新增: t.Fatal(err)
23新增: }
24新增: var guest string
25新增: closed := make(chan struct{})
26新增: if system == "macos" {
27新增: s.macosGuest = &guestos.MacOSProfile{User: "cage"}
28新增: guest = macOSProjectPath("cage", project)
29新增: } else {
30新增: s.windowsGuest = &guestos.WindowsProfile{}
31新增: guest = "C:/Cage/Projects/0123456789abcdef"
32新增: s.projectShares = map[string]*projectShare{project: {done: closed, windowsProject: &windowsProjectBinding{Path: guest, ID: "0123456789abcdef", Grant: "test"}}}
33新增: }
34新增: got, err := s.resolveDesktopProjectFile(guest+"/"+filepath.Base(file), []string{project})
35新增: want, _ := filepath.EvalSymlinks(file)
36新增: if err != nil || got != want {
37新增: t.Fatalf("guest mount did not resolve to host original: %q %v", got, err)
38新增: }
39新增: for _, invalid := range []string{guest + "-other/" + filepath.Base(file), guest + "/../outside", guest + "/missing", "relative", "file://" + guest} {
40新增: if _, err := s.resolveDesktopProjectFile(invalid, []string{project}); err == nil {
41新增: t.Fatalf("accepted invalid guest path %q", invalid)
42新增: }
43新增: }
44新增: if system == "windows" {
45新增: close(closed)
46新增: if _, err := s.resolveDesktopProjectFile(guest+"/"+filepath.Base(file), []string{project}); err == nil {
47新增: t.Fatal("revoked Windows share still granted file access")
48新增: }
49新增: }
50新增: })
51新增: }
52新增:}
53新增:
54新增:func TestDesktopFilePathsStayInProjectGrants(t *testing.T) {
55新增: project := t.TempDir()
56新增: file := filepath.Join(project, "中文 Word #+%.docx")
57新增: if err := os.WriteFile(file, []byte("document"), 0600); err != nil {
58新增: t.Fatal(err)
59新增: }
60新增: for _, path := range []string{file, project} {
61新增: got, err := resolveProjectFilePath(guestPath(path), []string{project})
62新增: want, _ := filepath.EvalSymlinks(path)
63新增: if err != nil || got != want {
64新增: t.Fatalf("project file did not map: %q %v", got, err)
65新增: }
66新增: }
67新增: outside := filepath.Join(t.TempDir(), "secret.txt")
68新增: if err := os.WriteFile(outside, []byte("private"), 0600); err != nil {
69新增: t.Fatal(err)
70新增: }
71新增: for _, path := range []string{outside, project + "-sibling/secret.txt", guestPath(project) + "/../secret", "file:///etc/passwd", "relative", guestPath(file) + "\x00", guestPath(project) + "/missing"} {
72新增: if got, err := resolveProjectFilePath(path, []string{project}); err == nil {
73新增: t.Fatalf("ungranted path accepted: %q -> %q", path, got)
74新增: }
75新增: }
76新增: link := filepath.Join(project, "outside-link")
77新增: if err := os.Symlink(filepath.Dir(outside), link); err != nil {
78新增: t.Skip("symlink unavailable: " + err.Error())
79新增: }
80新增: if _, err := resolveProjectFilePath(guestPath(filepath.Join(link, "secret.txt")), []string{project}); err == nil {
81新增: t.Fatal("host-side symlink escaped project")
82新增: }
83新增:}
84新增:
85新增:func TestDesktopFileCommandsPreservePathsAndRevealSemantics(t *testing.T) {
86新增: path := "/tmp/项目/Word #+%; $(touch unsafe).docx"
87新增: for _, tc := range []struct {
88新增: platform, action string
89新增: directory bool
90新增: want []string
91新增: }{
92新增: {"darwin", "open", false, []string{"/usr/bin/open", "--", path}},
93新增: {"darwin", "reveal", false, []string{"/usr/bin/open", "-R", "--", path}},
94新增: {"windows", "open", false, []string{"rundll32.exe", "url.dll,FileProtocolHandler", path}},
95新增: {"windows", "open", true, []string{"explorer.exe", path}},
96新增: {"windows", "reveal", false, []string{"explorer.exe", "/select," + path}},
97新增: {"linux", "open", false, []string{"gio", "open", path}},
98新增: } {
99新增: got := hostFileCommand(tc.platform, path, tc.action, tc.directory).Args
100新增: if !reflect.DeepEqual(got, tc.want) {
101新增: t.Fatalf("%s %s: %#v", tc.platform, tc.action, got)
102新增: }
103新增: }
104新增: args := hostFileCommand("linux", path, "reveal", false).Args
105新增: if args[0] != "gdbus" || !strings.Contains(strings.Join(args, " "), "ShowItems") || !strings.Contains(args[len(args)-2], "%23+%25") {
106新增: t.Fatal("Linux reveal lost selection or URI escaping", args)
107新增: }
108新增:}
109新增:
110新增:func TestDesktopFileOpenAdmissionRejectsUntrustedRequests(t *testing.T) {
111新增: s := testServer(t)
112新增: s.ready = true
113新增: path := "/api/input/files/desktop/open"
114新增: body := `{"id":"` + testBrowserFileID + `","stage":"claim"}`
115新增: for _, tc := range []struct {
116新增: origin string
117新增: auth bool
118新增: body string
119新增: code int
120新增: }{
121新增: {s.origin, false, body, 401},
122新增: {"https://untrusted.example", true, body, 403},
123新增: {s.origin, true, `{"id":"../host-path","stage":"claim"}`, 400},
124新增: {s.origin, true, `{"id":"` + testBrowserFileID + `","stage":"open","path":"/etc/passwd"}`, 400},
125新增: } {
126新增: w := request(s, "POST", path, tc.origin, tc.body, tc.auth)
127新增: if w.Code != tc.code {
128新增: t.Fatal(w.Code, w.Body.String())
129新增: }
130新增: }
131新增: s.account.lock()
132新增: if w := request(s, "POST", path, s.origin, body, true); w.Code != 423 {
133新增: t.Fatal("locked file operation accepted", w.Code)
134新增: }
135新增:}
136新增:
137新增:func TestDesktopFileErrorsReachNativeCaller(t *testing.T) {
138新增: origin := ""
139新增: server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
140新增: if r.Header.Get("Origin") != origin || r.Header.Get(connectionHeader) != "connection-one" {
141新增: t.Error("missing file operation origin or connection binding")
142新增: }
143新增: http.Error(w, "只能打开 Cage 项目目录中的文件和文件夹", 400)
144新增: }))
145新增: defer server.Close()
146新增: origin = server.URL
147新增: client := &controllerClient{origin: server.URL, client: server.Client()}
148新增: client.client.Transport = connectionTransport{base: http.DefaultTransport, id: "connection-one"}
149新增: err := desktopOpenCall(client, map[string]string{"id": testBrowserFileID, "stage": "claim"}, nil)
150新增: if err == nil || err.Error() != "只能打开 Cage 项目目录中的文件和文件夹" {
151新增: t.Fatal("native caller lost useful error", err)
152新增: }
153新增:}
154新增:
155新增:func TestDesktopFileNativeReveal(t *testing.T) {
156新增: if os.Getenv("CAGE_TEST_NATIVE_REVEAL") != "1" {
157新增: t.Skip("explicit desktop integration test")
158新增: }
159新增: project := t.TempDir()
160新增: file := filepath.Join(project, "Cage 生成的 Word 测试.docx")
161新增: if fixture := os.Getenv("CAGE_TEST_NATIVE_REVEAL_PATH"); fixture != "" {
162新增: file, project = fixture, filepath.Dir(fixture)
163新增: } else {
164新增: if err := os.WriteFile(file, []byte("reveal fixture"), 0600); err != nil {
165新增: t.Fatal(err)
166新增: }
167新增: }
168新增: resolved, err := resolveProjectFilePath(guestPath(file), []string{project})
169新增: if err != nil {
170新增: t.Fatal(err)
171新增: }
172新增: if err = openHostFile(resolved, "reveal"); err != nil {
173新增: t.Fatal(err)
174新增: }
175新增: if os.Getenv("CAGE_TEST_NATIVE_OPEN") == "1" {
176新增: if err = openHostFile(resolved, "open"); err != nil {
177新增: t.Fatal(err)
178新增: }
179新增: }
180新增:}
修改internal/workbench/desktop_local.go+30 −29看文件
@@ -12,7 +12,6 @@ import (
1212 "time"
1313
1414 "github.com/sylvinus/agent-vm/internal/containerenv"
15删除: "github.com/sylvinus/agent-vm/internal/host"
1615 "github.com/sylvinus/agent-vm/internal/managedproxy"
1716 "github.com/sylvinus/agent-vm/internal/remotehost"
1817)
@@ -32,22 +31,6 @@ func (d *desktopLocal) available() bool {
3231 return filepath.IsAbs(d.executable) && err == nil && info.Mode().IsRegular() && (runtime.GOOS == "windows" || info.Mode()&0111 != 0)
3332}
3433
35删除:func (d *desktopLocal) controllerLockFree() bool {
36删除: path := filepath.Join(d.profile, "control.lock")
37删除: if err := host.CheckPrivateFile(path); err != nil {
38删除: return os.IsNotExist(err)
39删除: }
40删除: f, err := os.OpenFile(path, os.O_RDWR, 0)
41删除: if err != nil {
42删除: return false
43删除: }
44删除: defer f.Close()
45删除: if lockController(f) != nil {
46删除: return false
47删除: }
48删除: return unlockController(f) == nil
49删除:}
50删除:
5134func (c *controllerClient) localControl(ctx context.Context, action string, input desktopLocalRequest) (desktopLocalReply, error) {
5235 var reply desktopLocalReply
5336 input.Token = c.record.Token
@@ -76,7 +59,12 @@ func (c *controllerClient) localControl(ctx context.Context, action string, inpu
7659// or proxy without a reachable controller is unknown, never a released state.
7760func (d *desktopLocal) offlineStatus(ctx context.Context, available bool) DesktopLocalStatus {
7861 st := DesktopLocalStatus{Available: available, Message: "本机状态待确认,请返回本机检查已有后台"}
79删除: if !d.controllerLockFree() {
62新增: free, err := controllerLockStatus(d.profile)
63新增: if err != nil {
64新增: st.Message = "无法检查本机控制锁或修复旧版权限,请检查配置目录的访问权限:" + err.Error()
65新增: return st
66新增: }
67新增: if !free {
8068 st.ServiceRunning = true
8169 return st
8270 }
@@ -99,6 +87,10 @@ func (d *desktopLocal) offlineStatus(ctx context.Context, available bool) Deskto
9987
10088func (d *desktopLocal) Status(ctx context.Context) (DesktopLocalStatus, error) {
10189 available := d.available()
90新增: free, lockErr := controllerLockStatus(d.profile)
91新增: if free || lockErr != nil {
92新增: return d.offlineStatus(ctx, available), nil
93新增: }
10294 c, err := openController(d.profile)
10395 if errors.Is(err, errControllerUnavailable) {
10496 return d.offlineStatus(ctx, available), nil
@@ -126,6 +118,21 @@ func (d *desktopLocal) Connect(ctx context.Context) (_ *remotehost.Session, retu
126118 if !st.Available {
127119 return nil, errors.New("此安装缺少本机运行组件")
128120 }
121新增: if !st.Known && st.ServiceRunning && st.ControllerID == "" {
122新增: wait, cancel := context.WithTimeout(ctx, 12*time.Second)
123新增: c, waitErr := waitControllerReady(wait, d.profile)
124新增: cancel()
125新增: if c != nil {
126新增: c.close()
127新增: }
128新增: if waitErr != nil && !errors.Is(waitErr, errControllerUnavailable) {
129新增: return nil, waitErr
130新增: }
131新增: st, err = d.Status(ctx)
132新增: if err != nil {
133新增: return nil, err
134新增: }
135新增: }
129136 if !st.Known && st.ServiceRunning && st.ControllerID == "" {
130137 handed, err := d.handoffOldLocal(ctx)
131138 if err != nil {
@@ -139,15 +146,9 @@ func (d *desktopLocal) Connect(ctx context.Context) (_ *remotehost.Session, retu
139146 }
140147 }
141148 // Explicit local selection may reattach an orphan workload to its owner.
142删除: // Untrusted records or a live lock with no reachable service cannot be taken over.
143删除: if !st.Known && !st.ServiceRunning {
144删除: c, recordErr := openController(d.profile)
145删除: if c != nil {
146删除: c.close()
147删除: }
148删除: if (recordErr != nil && !errors.Is(recordErr, errControllerUnavailable)) || !d.controllerLockFree() {
149删除: return nil, errors.New(st.Message)
150删除: }
149新增: // A live or inaccessible lock with no reachable service cannot be taken over.
150新增: if !st.Known && !st.ServiceRunning && !controllerLockFree(d.profile) {
151新增: return nil, errors.New(st.Message)
151152 }
152153 if err = ctx.Err(); err != nil {
153154 return nil, err
@@ -191,7 +192,7 @@ func (d *desktopLocal) Connect(ctx context.Context) (_ *remotehost.Session, retu
191192 if launchID == "" {
192193 return nil, probeErr
193194 }
194删除: } else if !errors.Is(err, errControllerUnavailable) {
195新增: } else if launchID == "" && !errors.Is(err, errControllerUnavailable) {
195196 return nil, err
196197 }
197198 select {
@@ -373,7 +374,7 @@ func (d *desktopLocal) Release(ctx context.Context, expected DesktopLocalStatus,
373374 }
374375 // Unlike a cold selector probe, this explicit release may query an existing
375376 // local container engine to verify that its workload actually stopped.
376删除: if _, err := os.Lstat(filepath.Join(d.profile, "control.json")); !os.IsNotExist(err) || !d.controllerLockFree() {
377新增: if _, err := os.Lstat(filepath.Join(d.profile, "control.json")); !os.IsNotExist(err) || !controllerLockFree(d.profile) {
377378 return errors.New("本机控制服务状态已变化,请重新确认")
378379 }
379380 if running, err := controllerVMState(d.profile); err != nil || running || managedproxy.ConfirmStopped(ctx, d.profile) != nil {
修改internal/workbench/desktop_local_control.go+1 −1看文件
@@ -59,7 +59,7 @@ func (s *Server) desktopLocalSnapshot() desktopLocalReply {
5959 s.mu.Lock()
6060 reply.Busy = s.closing || job.Running
6161 s.mu.Unlock()
62删除: if s.remote != nil && s.remote.isRemote() {
62新增: if len(s.mobileCLI.activeAccounts()) != 0 || (s.remote != nil && s.remote.isRemote()) {
6363 reply.Busy = true
6464 }
6565 if reply.Busy {
修改internal/workbench/diagnostics.go+10 −2看文件
@@ -71,7 +71,10 @@ func (s *Server) diagnosticExport(w http.ResponseWriter, r *http.Request) {
7171 ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
7272 defer cancel()
7373 var err error
74删除: guest, err = s.guest(ctx, `sudo python3 - <<'CAGE_DIAGNOSTIC_JOURNAL'
74新增: if s.macosGuest != nil || s.windowsGuest != nil {
75新增: guest, err = s.nativeGuestDiagnostics(ctx)
76新增: } else {
77新增: guest, err = s.guest(ctx, `sudo python3 - <<'CAGE_DIAGNOSTIC_JOURNAL'
7578import subprocess, sys
7679result = subprocess.run(['journalctl','--namespace=cage','--no-pager','-o','short-iso','-n','150','--since','14 days ago'], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=5, check=True)
7780data = result.stdout
@@ -80,6 +83,7 @@ if len(data) > 49152:
8083 data = data.partition(b'\n')[2]
8184sys.stdout.buffer.write(data)
8285CAGE_DIAGNOSTIC_JOURNAL`)
86新增: }
8387 if err != nil {
8488 guest = nil
8589 guestState = "guest collection failed"
@@ -165,6 +169,9 @@ func ExportDiagnosticsForConnection(configPath, connectionID, destination string
165169 return e
166170 }
167171 err = export()
172新增: if err == nil {
173新增: err = addDesktopDiagnosticFile(f, profile)
174新增: }
168175 if err == nil {
169176 err = f.Sync()
170177 }
@@ -184,7 +191,8 @@ func ExportDiagnosticsForConnection(configPath, connectionID, destination string
184191 return os.Rename(temp, destination)
185192}
186193
187删除:const MaxDiagnosticBundle int64 = 48 << 20
194新增:// Two independently bounded 40 MiB stores plus guest logs and ZIP metadata.
195新增:const MaxDiagnosticBundle int64 = 96 << 20
188196
189197// Preserve streaming and WebSocket behavior while observing error statuses.
190198type diagnosticResponse struct {
新增internal/workbench/diagnostics_guest.go+57 −0看文件
@@ -0,0 +1,57 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "context"
5新增: _ "embed"
6新增: "encoding/json"
7新增: "errors"
8新增: "io"
9新增: "strings"
10新增:
11新增: "al.essio.dev/pkg/shellescape"
12新增: "github.com/sylvinus/agent-vm/internal/guestos"
13新增:)
14新增:
15新增://go:embed macos_diagnostics.py
16新增:var macOSDiagnosticCollector string
17新增:
18新增:func (s *Server) nativeGuestDiagnostics(ctx context.Context) ([]byte, error) {
19新增: var data []byte
20新增: var err error
21新增: if s.windowsGuest != nil {
22新增: cmd, err := guestos.WindowsRelayCommand(ctx, s.profile, "diagnostics")
23新增: if err != nil {
24新增: return nil, err
25新增: }
26新增: cmd.Stdin = strings.NewReader("{\"action\":\"read\"}\n")
27新增: pipe, err := cmd.StdoutPipe()
28新增: if err != nil {
29新增: return nil, err
30新增: }
31新增: if err := cmd.Start(); err != nil {
32新增: return nil, err
33新增: }
34新增: data, err = io.ReadAll(io.LimitReader(pipe, (64<<10)+1))
35新增: if err != nil || len(data) > 64<<10 {
36新增: _ = cmd.Process.Kill()
37新增: }
38新增: err = errors.Join(err, cmd.Wait())
39新增: if err != nil || len(data) > 64<<10 {
40新增: return nil, errors.New("Windows 客机诊断记录未完整返回")
41新增: }
42新增: } else {
43新增: command := "exec " + shellescape.QuoteCommand([]string{macCLIInstall + "/bin/python3", "-I", "-c", macOSDiagnosticCollector})
44新增: data, err = s.guestControl(ctx, command, "guest-diagnostics")
45新增: if err != nil {
46新增: return nil, err
47新增: }
48新增: }
49新增: var result struct {
50新增: Version int `json:"version"`
51新增: Lines string `json:"lines"`
52新增: }
53新增: if json.Unmarshal(data, &result) != nil || result.Version != 1 || len(result.Lines) > 48<<10 || strings.Count(result.Lines, "\n") > 150 {
54新增: return nil, errors.New("客机诊断记录格式或大小无效")
55新增: }
56新增: return []byte(result.Lines), nil
57新增:}
新增internal/workbench/diagnostics_guest_test.go+56 −0看文件
@@ -0,0 +1,56 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "encoding/json"
5新增: "fmt"
6新增: "os"
7新增: "os/exec"
8新增: "path/filepath"
9新增: "strings"
10新增: "testing"
11新增: "time"
12新增:)
13新增:
14新增:func TestMacOSGuestDiagnosticCollectorBoundsAndFilters(t *testing.T) {
15新增: if _, err := exec.LookPath("uv"); err != nil {
16新增: t.Skip("uv is required for the guest collector")
17新增: }
18新增: home := t.TempDir()
19新增: directory := filepath.Join(home, "Library", "Logs", "Cage")
20新增: if err := os.MkdirAll(directory, 0700); err != nil {
21新增: t.Fatal(err)
22新增: }
23新增: var events strings.Builder
24新增: stamp := time.Now().UTC().Format(time.RFC3339)
25新增: for index := 0; index < 150; index++ {
26新增: fmt.Fprintf(&events, "{\"time\":%q,\"source\":\"window\",\"reason\":\"frame_unavailable\"}\n", stamp)
27新增: }
28新增: if err := os.WriteFile(filepath.Join(directory, "window-1.jsonl"), []byte(events.String()), 0600); err != nil {
29新增: t.Fatal(err)
30新增: }
31新增: events.Reset()
32新增: fmt.Fprintf(&events, "{\"time\":%q,\"source\":\"window\",\"reason\":\"after_rotation\"}\n", stamp)
33新增: fmt.Fprintln(&events, `{"time":"2020-01-01T00:00:00Z","source":"window","reason":"old_event"}`)
34新增: fmt.Fprintf(&events, "{\"time\":%q,\"source\":\"window\",\"reason\":\"password=private-secret\"}\n", time.Now().UTC().Format(time.RFC3339))
35新增: fmt.Fprintln(&events, "invalid JSON")
36新增: fmt.Fprintln(&events, `{"time":123,"source":"window","reason":"invalid_timestamp"}`)
37新增: if err := os.WriteFile(filepath.Join(directory, "window.jsonl"), []byte(events.String()), 0600); err != nil {
38新增: t.Fatal(err)
39新增: }
40新增: cmd := exec.Command("uv", "run", "--no-project", "python", "-I", "-c", macOSDiagnosticCollector)
41新增: cmd.Env = append(os.Environ(), "HOME="+home, "USERPROFILE="+home)
42新增: output, err := cmd.Output()
43新增: if err != nil {
44新增: t.Fatal(err)
45新增: }
46新增: var result struct {
47新增: Version int `json:"version"`
48新增: Lines string `json:"lines"`
49新增: }
50新增: if json.Unmarshal(output, &result) != nil || result.Version != 1 || strings.Count(result.Lines, "\n") != 150 || len(result.Lines) > 48<<10 || strings.Contains(result.Lines, "private-secret") || strings.Contains(result.Lines, "old_event") {
51新增: t.Fatalf("guest diagnostics escaped the bounded fixed schema: %s", output)
52新增: }
53新增: if !strings.Contains(result.Lines, "after_rotation") {
54新增: t.Fatal("missing newest event from current file after same-second rotation")
55新增: }
56新增:}
新增internal/workbench/diagnostics_merge.go+122 −0看文件
@@ -0,0 +1,122 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "archive/zip"
5新增: "bytes"
6新增: "errors"
7新增: "io"
8新增: "net/http"
9新增: "os"
10新增: "path"
11新增: "path/filepath"
12新增: "strconv"
13新增: "strings"
14新增:
15新增: "github.com/sylvinus/agent-vm/internal/diagnostics"
16新增: "github.com/sylvinus/agent-vm/internal/version"
17新增:)
18新增:
19新增:// The desktop entry and selected workload have separate log ownership. Keep
20新增:// their source names while exporting both through the normal download route.
21新增:func diagnosticBundleWithDesktop(workload []byte, desktopProfile string) ([]byte, error) {
22新增: var desktop bytes.Buffer
23新增: if err := diagnostics.New(desktopProfile).Export(&desktop, version.Version, nil, "desktop connection service"); err != nil {
24新增: return nil, err
25新增: }
26新增: var output bytes.Buffer
27新增: writer := zip.NewWriter(&output)
28新增: remaining := MaxDiagnosticBundle
29新增: for _, source := range []struct {
30新增: prefix string
31新增: data []byte
32新增: }{{"", workload}, {"desktop/", desktop.Bytes()}} {
33新增: reader, err := zip.NewReader(bytes.NewReader(source.data), int64(len(source.data)))
34新增: if err != nil {
35新增: return nil, errors.New("诊断包未完整生成,请重新导出")
36新增: }
37新增: seen := make(map[string]bool)
38新增: for _, file := range reader.File {
39新增: name := file.Name
40新增: allowed := name == "manifest.json" || name == "README.txt" || name == "guest/services.log" || name == "safety/latest-report.json" ||
41新增: strings.HasPrefix(name, "logs/") && path.Dir(name) == "logs" && strings.HasSuffix(name, ".jsonl")
42新增: if !allowed || strings.ContainsAny(name, "\\\x00") || seen[name] || file.FileInfo().IsDir() || file.UncompressedSize64 > uint64(remaining) {
43新增: return nil, errors.New("诊断包内容或大小不符合导出范围")
44新增: }
45新增: seen[name] = true
46新增: input, err := file.Open()
47新增: if err != nil {
48新增: return nil, err
49新增: }
50新增: target, err := writer.Create(source.prefix + name)
51新增: if err != nil {
52新增: input.Close()
53新增: return nil, err
54新增: }
55新增: written, copyErr := io.Copy(target, io.LimitReader(input, remaining+1))
56新增: closeErr := input.Close()
57新增: if copyErr != nil || closeErr != nil {
58新增: return nil, errors.Join(copyErr, closeErr)
59新增: }
60新增: remaining -= written
61新增: if remaining < 0 || output.Len() > int(MaxDiagnosticBundle) {
62新增: return nil, errors.New("诊断包超过允许大小")
63新增: }
64新增: }
65新增: }
66新增: if err := writer.Close(); err != nil {
67新增: return nil, err
68新增: }
69新增: if output.Len() > int(MaxDiagnosticBundle) {
70新增: return nil, errors.New("诊断包超过允许大小")
71新增: }
72新增: return output.Bytes(), nil
73新增:}
74新增:
75新增:func (s *Server) addDesktopDiagnosticResponse(response *http.Response) error {
76新增: data, err := io.ReadAll(io.LimitReader(response.Body, MaxDiagnosticBundle+1))
77新增: response.Body.Close()
78新增: if err != nil {
79新增: return err
80新增: }
81新增: if int64(len(data)) > MaxDiagnosticBundle {
82新增: return errors.New("诊断包超过允许大小")
83新增: }
84新增: data, err = diagnosticBundleWithDesktop(data, s.profile)
85新增: if err != nil {
86新增: return err
87新增: }
88新增: response.Body = io.NopCloser(bytes.NewReader(data))
89新增: response.ContentLength = int64(len(data))
90新增: response.Header.Set("Content-Length", strconv.Itoa(len(data)))
91新增: return nil
92新增:}
93新增:
94新增:// Plain CLI and offline exports address the workload directly. Include the
95新增:// associated desktop logs if that entry exists, without starting a controller.
96新增:func addDesktopDiagnosticFile(file *os.File, workloadProfile string) error {
97新增: desktopProfile := filepath.Join(workloadProfile, "desktop-entry")
98新增: if _, err := os.Lstat(filepath.Join(desktopProfile, "logs")); os.IsNotExist(err) {
99新增: return nil
100新增: } else if err != nil {
101新增: return err
102新增: }
103新增: if _, err := file.Seek(0, io.SeekStart); err != nil {
104新增: return err
105新增: }
106新增: data, err := io.ReadAll(io.LimitReader(file, MaxDiagnosticBundle+1))
107新增: if err != nil || int64(len(data)) > MaxDiagnosticBundle {
108新增: return errors.New("无法读取完整诊断包")
109新增: }
110新增: data, err = diagnosticBundleWithDesktop(data, desktopProfile)
111新增: if err != nil {
112新增: return err
113新增: }
114新增: if err := file.Truncate(0); err != nil {
115新增: return err
116新增: }
117新增: if _, err := file.Seek(0, io.SeekStart); err != nil {
118新增: return err
119新增: }
120新增: _, err = file.Write(data)
121新增: return err
122新增:}
新增internal/workbench/diagnostics_merge_test.go+97 −0看文件
@@ -0,0 +1,97 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "archive/zip"
5新增: "bytes"
6新增: "io"
7新增: "net/http"
8新增: "net/url"
9新增: "os"
10新增: "path/filepath"
11新增: "strings"
12新增: "testing"
13新增:
14新增: "github.com/sylvinus/agent-vm/internal/diagnostics"
15新增:)
16新增:
17新增:func diagnosticContents(t *testing.T, data []byte) map[string]string {
18新增: t.Helper()
19新增: reader, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
20新增: if err != nil {
21新增: t.Fatal(err)
22新增: }
23新增: result := map[string]string{}
24新增: for _, file := range reader.File {
25新增: input, err := file.Open()
26新增: if err != nil {
27新增: t.Fatal(err)
28新增: }
29新增: content, err := io.ReadAll(input)
30新增: input.Close()
31新增: if err != nil {
32新增: t.Fatal(err)
33新增: }
34新增: result[file.Name] = string(content)
35新增: }
36新增: return result
37新增:}
38新增:
39新增:func TestDiagnosticExportsIncludeSeparateDesktopLog(t *testing.T) {
40新增: profile := t.TempDir()
41新增: desktop := filepath.Join(profile, "desktop-entry")
42新增: if err := diagnostics.New(profile).Record("error", "controller", "workload-sentinel"); err != nil {
43新增: t.Fatal(err)
44新增: }
45新增: if err := diagnostics.New(desktop).Record("error", "frontend", "frontend-sentinel password=private-secret"); err != nil {
46新增: t.Fatal(err)
47新增: }
48新增: output := filepath.Join(t.TempDir(), "offline.zip")
49新增: if err := ExportDiagnostics(filepath.Join(profile, "config.json"), output); err != nil {
50新增: t.Fatal(err)
51新增: }
52新增: data, err := os.ReadFile(output)
53新增: if err != nil {
54新增: t.Fatal(err)
55新增: }
56新增: contents := diagnosticContents(t, data)
57新增: if !strings.Contains(contents["logs/events.jsonl"], "workload-sentinel") || !strings.Contains(contents["desktop/logs/events.jsonl"], "frontend-sentinel") {
58新增: t.Fatal("offline export omitted one log owner")
59新增: }
60新增: if strings.Contains(contents["desktop/logs/events.jsonl"], "private-secret") {
61新增: t.Fatal("desktop diagnostic secret was not redacted")
62新增: }
63新增: var workload bytes.Buffer
64新增: if err := diagnostics.New(profile).Export(&workload, "test", nil, "offline"); err != nil {
65新增: t.Fatal(err)
66新增: }
67新增: s := &Server{profile: desktop}
68新增: response := &http.Response{Body: io.NopCloser(bytes.NewReader(workload.Bytes())), Header: make(http.Header), Request: &http.Request{URL: &url.URL{Path: "/api/diagnostics/export"}}}
69新增: if err := s.addDesktopDiagnosticResponse(response); err != nil {
70新增: t.Fatal(err)
71新增: }
72新增: combined, err := io.ReadAll(response.Body)
73新增: if err != nil {
74新增: t.Fatal(err)
75新增: }
76新增: if response.ContentLength != int64(len(combined)) || !strings.Contains(diagnosticContents(t, combined)["desktop/logs/events.jsonl"], "frontend-sentinel") {
77新增: t.Fatal("gateway export omitted desktop errors or returned the old content length")
78新增: }
79新增:}
80新增:
81新增:func TestDiagnosticMergeRejectsPathsOutsideFixedExport(t *testing.T) {
82新增: for _, name := range []string{"../outside", "logs/../../outside.jsonl", `logs/..\outside.jsonl`, "project.json"} {
83新增: var input bytes.Buffer
84新增: writer := zip.NewWriter(&input)
85新增: file, err := writer.Create(name)
86新增: if err != nil {
87新增: t.Fatal(err)
88新增: }
89新增: _, _ = file.Write([]byte("untrusted"))
90新增: if err := writer.Close(); err != nil {
91新增: t.Fatal(err)
92新增: }
93新增: if _, err := diagnosticBundleWithDesktop(input.Bytes(), t.TempDir()); err == nil {
94新增: t.Fatalf("untrusted ZIP entry accepted: %q", name)
95新增: }
96新增: }
97新增:}
修改internal/workbench/environment_versions.go+21 −1看文件
@@ -44,6 +44,10 @@ type toolVersion struct {
4444
4545// Version commands run only for this explicit request, never in status polling.
4646func (s *Server) environmentVersions(w http.ResponseWriter, r *http.Request) {
47新增: if s.macosGuest != nil || s.windowsGuest != nil {
48新增: s.nativeEnvironmentVersions(w, r)
49新增: return
50新增: }
4751 ctx, cancel := context.WithTimeout(r.Context(), 25*time.Second)
4852 defer cancel()
4953 running := s.vmRunning()
@@ -97,7 +101,9 @@ CAGE_VERSIONS`)
97101 requiredProxy := ""
98102 if core, err := managedproxy.CorePath(); err == nil {
99103 probeCtx, done := context.WithTimeout(ctx, 2*time.Second)
100删除: b, e := exec.CommandContext(probeCtx, core, "-v").Output()
104新增: cmd := exec.CommandContext(probeCtx, core, "-v")
105新增: hideCommand(cmd)
106新增: b, e := cmd.Output()
101107 done()
102108 if e == nil {
103109 fields := strings.Fields(strings.SplitN(string(b), "\n", 2)[0])
@@ -116,13 +122,24 @@ CAGE_VERSIONS`)
116122}
117123
118124func (s *Server) updateEnvironment(w http.ResponseWriter, r *http.Request) {
125新增: if err := s.nativeMaintenancePreflight(); err != nil {
126新增: http.Error(w, err.Error(), http.StatusConflict)
127新增: return
128新增: }
119129 s.launch(w, "environment-update", s.synchronizeEnvironment)
120130}
121131func (s *Server) updateEnvironmentTools(w http.ResponseWriter, r *http.Request) {
132新增: if err := s.nativeMaintenancePreflight(); err != nil {
133新增: http.Error(w, err.Error(), http.StatusConflict)
134新增: return
135新增: }
122136 s.launch(w, "environment-tools", s.upgradeEnvironmentTools)
123137}
124138
125139func (s *Server) synchronizeEnvironment() error {
140新增: if s.macosGuest != nil || s.windowsGuest != nil {
141新增: return s.maintainNativeComponents(false)
142新增: }
126143 if !s.vmRunning() {
127144 return errors.New("请先启动 Cage 环境。")
128145 }
@@ -154,6 +171,9 @@ func (s *Server) toolsNetworkAllowedLocked() bool {
154171 return !s.closing
155172}
156173func (s *Server) upgradeEnvironmentTools() error {
174新增: if s.macosGuest != nil || s.windowsGuest != nil {
175新增: return s.maintainNativeComponents(true)
176新增: }
157177 if !s.vmRunning() {
158178 return errors.New("请先启动 Cage 环境。")
159179 }
修改internal/workbench/environment_versions_test.go+11 −6看文件
@@ -44,6 +44,17 @@ func TestGuestConnectionRequiresSuccessfulMatchingManifest(t *testing.T) {
4444func grantedToolUpdateServer(t *testing.T) (*Server, *cage.EgressGate) {
4545 t.Helper()
4646 s, gate := interfaceMonitorServer(t)
47新增: grantTestGate(t, gate)
48新增: s.ready = true
49新增: required := cage.RequiredGuestManifest()
50新增: s.guestManifest = &required
51新增: s.setJobForTest(Job{ID: "tools", Kind: "environment-tools", Running: true})
52新增: s.publishGate(gate.Status())
53新增: return s, gate
54新增:}
55新增:
56新增:func grantTestGate(t *testing.T, gate *cage.EgressGate) {
57新增: t.Helper()
4758 state := gate.Status()
4859 report := cage.SafetyReport{Policy: cage.SafetyPolicyVersion, ID: "tool-update-test", RunID: state.RunID, CheckID: state.CheckID, Configuration: state.Configuration, CreatedAt: time.Now()}
4960 for _, id := range []string{"egress_policy", "proxy_transport", "dns_transport", "guest_settings", "browser_settings", "filesystem_boundary", "management_boundary", "fail_closed", "udp_policy", "ipv6_policy", "exit_consistency"} {
@@ -52,12 +63,6 @@ func grantedToolUpdateServer(t *testing.T) (*Server, *cage.EgressGate) {
5263 if err := gate.Grant(report); err != nil {
5364 t.Fatal(err)
5465 }
55删除: s.ready = true
56删除: required := cage.RequiredGuestManifest()
57删除: s.guestManifest = &required
58删除: s.setJobForTest(Job{ID: "tools", Kind: "environment-tools", Running: true})
59删除: s.publishGate(gate.Status())
60删除: return s, gate
6166}
6267
6368func TestToolUpdateLeaseHonorsPauseStopAndConfigurationAtRenewal(t *testing.T) {
新增internal/workbench/exit_country_test.go+75 −0看文件
@@ -0,0 +1,75 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "context"
5新增: "errors"
6新增: "net/http"
7新增: "net/http/httptest"
8新增: "sync/atomic"
9新增: "testing"
10新增: "time"
11新增:
12新增: "github.com/sylvinus/agent-vm/internal/cage"
13新增:)
14新增:
15新增:func TestLocationObservationRevokesUnsafeExitAndIgnoresPreviousRoute(t *testing.T) {
16新增: for _, condition := range []string{"mainland", "listed IP", "unknown", "previous route"} {
17新增: t.Run(condition, func(t *testing.T) {
18新增: s, gate := grantedToolUpdateServer(t)
19新增: cfg, _ := loadConfig(s.configPath)
20新增: loc := Location{IP: "8.8.8.8", CountryCode: "CN", CheckedAt: time.Now()}
21新增: s.locations = map[string]Location{"8.8.8.8": {IP: "8.8.8.8", CountryCode: "US", CheckedAt: time.Now()}}
22新增: var probeErr error
23新增: switch condition {
24新增: case "listed IP":
25新增: loc.IP, loc.CountryCode = "223.5.5.5", "US"
26新增: case "unknown":
27新增: loc.CountryCode, probeErr = "", errors.New("location unavailable")
28新增: case "previous route":
29新增: cfg.ProxyRevision = "previous-route"
30新增: }
31新增: if err := s.finishLocationProbe(cfg, loc, probeErr); err != nil {
32新增: t.Fatal(err)
33新增: }
34新增: want := cage.GateClosed
35新增: if condition == "previous route" {
36新增: want = cage.GateOpen
37新增: }
38新增: if gate.Status().Mode != want {
39新增: t.Fatalf("gate mode=%s want=%s", gate.Status().Mode, want)
40新增: }
41新增: if condition == "unknown" || condition == "mainland" {
42新增: if _, exists := s.locations["8.8.8.8"]; exists {
43新增: t.Fatal("stale country evidence survived a new rejection")
44新增: }
45新增: }
46新增: })
47新增: }
48新增:}
49新增:
50新增:func TestExitCountryCannotBeSkippedByStaticOrUnrestrictedMode(t *testing.T) {
51新增: for _, policy := range []cage.ExitPolicy{{Mode: "static", IP: "8.8.8.8"}, {Mode: "dynamic", Scope: "any"}} {
52新增: t.Run(policy.Mode, func(t *testing.T) {
53新增: s := testServer(t)
54新增: var calls atomic.Int32
55新增: proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
56新增: calls.Add(1)
57新增: w.WriteHeader(http.StatusServiceUnavailable)
58新增: }))
59新增: defer proxy.Close()
60新增: cfg := cage.DefaultConfig()
61新增: cfg.ProxyURL, cfg.ExitPolicy = proxy.URL, policy
62新增: if state, _ := s.checkExitPolicy(context.Background(), cfg, "8.8.8.8"); state != cage.CheckUnknown || calls.Load() == 0 {
63新增: t.Fatal("unavailable country lookup did not block or bypassed proxy")
64新增: }
65新增: s.locations = map[string]Location{"8.8.8.8": {IP: "8.8.8.8", CountryCode: "CN", CheckedAt: time.Now()}}
66新增: if state, _ := s.checkExitPolicy(context.Background(), cfg, "8.8.8.8"); state != cage.CheckFailed {
67新增: t.Fatal("mainland geolocation accepted")
68新增: }
69新增: s.locations["8.8.8.8"] = Location{IP: "8.8.8.8", CountryCode: "US", CheckedAt: time.Now()}
70新增: if state, _ := s.checkExitPolicy(context.Background(), cfg, "8.8.8.8"); state != cage.CheckPassed {
71新增: t.Fatal("verified non-mainland exit rejected")
72新增: }
73新增: })
74新增: }
75新增:}
新增internal/workbench/failure_message.go+131 −0看文件
@@ -0,0 +1,131 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "fmt"
5新增: "io"
6新增: "net/http"
7新增: "strings"
8新增: "sync"
9新增:
10新增: "github.com/sylvinus/agent-vm/internal/usererror"
11新增:)
12新增:
13新增:const failureHelp = "在设置中导出诊断包,并附上出错时正在执行的操作。"
14新增:
15新增:// Only recognize known diagnostics. Unrecognized process output stays in the
16新增:// existing operation log and never becomes an arbitrary user-facing message.
17新增:func executionFailure(action string, err error, output string) error {
18新增: lower := strings.ToLower(output)
19新增: for _, rule := range []struct {
20新增: patterns []string
21新增: reason, next string
22新增: }{
23新增: {[]string{"desktop file service state=failed"}, "Claude Desktop 的文件服务已经退出", "请从 Cage 重新打开 Claude Desktop;若应用反复退出,请在设置中查看资源用量并导出诊断包。"},
24新增: {[]string{"curl: (7)", "connection refused"}, "目标服务没有接受连接", "请确认环境及所选代理已启动;文件传递时请重新打开接收文件的应用,再重试。"},
25新增: {[]string{"no space left on device", "not enough space on the disk"}, "磁盘空间不足,无法继续写入", "请释放环境所在磁盘的空间后继续;不要删除 Cage 的个人数据目录。"},
26新增: {[]string{"could not get lock", "unable to acquire the dpkg", "another process using it"}, "环境中已有另一个软件安装或更新进程", "请等待当前安装结束后再继续;不要手动删除安装锁文件。"},
27新增: {[]string{"temporary failure resolving", "could not resolve host", "curl: (6)"}, "下载服务器的域名解析失败", "请在网络与代理设置中检查所选节点和 DNS,再继续安装。"},
28新增: {[]string{"curl: (28)", "connection timed out", "operation timed out"}, "下载或环境连接等待超时", "请检查所选代理是否可用,再继续;已保存的下载会尝试续传。"},
29新增: {[]string{"curl: (60)", "certificate verify failed", "certificate verification failed"}, "下载服务器的证书验证未通过", "请检查电脑时间和所选代理;仍失败时导出诊断包,不要关闭证书验证。"},
30新增: {[]string{"407 proxy authentication", "proxy authentication required"}, "代理服务器拒绝了当前登录凭据", "请在网络与代理设置中更新代理账号或订阅,再应用节点。"},
31新增: {[]string{"permission denied", "access is denied"}, "系统拒绝访问安装所需的文件或程序", "请检查应用及环境目录的权限;若安全软件拦截了 Cage,请先核实其拦截记录。"},
32新增: {[]string{"tried to start delayed item"}, "环境的软件包下载程序反复重试,未能完成安装", "请使用包含 APT 修复的 Cage 构建后继续安装;仍失败时导出诊断包。"},
33新增: } {
34新增: for _, pattern := range rule.patterns {
35新增: if strings.Contains(lower, pattern) {
36新增: return usererror.New(action, rule.reason, rule.next, err)
37新增: }
38新增: }
39新增: }
40新增: return usererror.Wrap(action, err, "打开“操作详情”查看最后的错误;仍无法判断时,"+failureHelp)
41新增:}
42新增:
43新增:func serviceHTTPFailure(action string, status int) error {
44新增: reason, next := fmt.Sprintf("服务返回 HTTP %d,尚未取得可识别的具体原因", status), failureHelp
45新增: switch status {
46新增: case http.StatusUnauthorized, http.StatusForbidden:
47新增: reason, next = "服务拒绝了这次连接的授权", "请重新连接当前环境;若仍出现,更新环境组件后再试。"
48新增: case http.StatusNotFound, http.StatusGone:
49新增: reason, next = "目标窗口、文件或服务接口已不存在", "请重新打开目标窗口或重新选择文件;已有环境较旧时,先更新环境组件。"
50新增: case http.StatusConflict:
51新增: reason, next = "目标状态已变化,或另一个操作尚未结束", "请确认当前页面与目标文件,再重新发起这次操作。"
52新增: case http.StatusRequestEntityTooLarge:
53新增: reason, next = "文件或请求内容超过服务允许的大小", "请缩小文件或分批处理,再重新发起这次操作。"
54新增: case http.StatusTooManyRequests:
55新增: reason, next = "服务暂时限制了请求次数", "请等待片刻后重试,避免连续点击。"
56新增: case http.StatusBadGateway, http.StatusServiceUnavailable:
57新增: reason, next = "环境内的服务尚未就绪或已停止响应", "请先确认环境已启动;等待后仍无法连接时,查看环境设置中的组件状态。"
58新增: case http.StatusGatewayTimeout:
59新增: reason, next = "等待环境内服务响应超时", "请检查环境负载并稍后再试;持续超时则导出诊断包。"
60新增: }
61新增: return usererror.New(action, reason, next, nil)
62新增:}
63新增:
64新增:func fileServiceFailure(status int, data []byte) error {
65新增: known := map[string]string{
66新增: "上传窗口已关闭,请重新选择文件": "上传窗口已关闭。请重新点击应用内的上传按钮,再选择文件。",
67新增: "原文件窗口已关闭": "原文件窗口已关闭。请在接收文件的应用中重新打开文件窗口。",
68新增: "请先完成已打开的文件窗口": "另一个文件窗口尚未处理。请先完成或关闭该窗口,再重新选择文件。",
69新增: "每个文件不能超过 2 GB": "单个文件超过 2 GB 上限。请缩小文件后重新上传。",
70新增: "项目文件夹尚未连接,请重新打开项目": "项目文件夹尚未连接。请先在 Cage 中重新打开该项目,再选择目录。",
71新增: "目标没有接收文件,请点击支持附件的输入框后重试": "目标没有接收文件。请先点击应用内支持附件的输入框,再重新选择文件。",
72新增: "上传已取消": "上传已被取消。需要继续时,请重新选择文件。",
73新增: "当前窗口没有请求文件夹": "当前窗口需要选择文件,不能接收文件夹。请按应用的窗口提示重新选择。",
74新增: "文件夹正在交给应用": "文件夹仍在传给应用。请等待当前操作结束后再选择。",
75新增: "文件位置无法读取": "接收文件的应用无法读取该位置。请确认项目目录已连接,并重新选择。",
76新增: "下载服务不可用": "环境内的下载服务尚未就绪。请重新打开应用;旧环境请先更新环境组件。",
77新增: "文件请求过大": "这次文件请求超过服务允许的大小。请减少一次传递的文件数量。",
78新增: "请选择项目文件夹": "当前操作需要一个已连接的项目文件夹。请先在 Cage 中打开项目,再重新选择目录。",
79新增: }
80新增: if reason := known[strings.TrimSpace(string(data))]; reason != "" {
81新增: return fmt.Errorf("传递文件失败:%s", reason)
82新增: }
83新增: return serviceHTTPFailure("传递文件", status)
84新增:}
85新增:
86新增:func browserOperation(path string) string {
87新增: switch path {
88新增: case "/navigate":
89新增: return "打开网页"
90新增: case "/reload":
91新增: return "刷新网页"
92新增: case "/audit":
93新增: return "读取浏览器检测结果"
94新增: case "/tabs":
95新增: return "读取浏览器标签页"
96新增: case "/paste-image":
97新增: return "粘贴图片"
98新增: case "/editor-restart":
99新增: return "打开编辑器"
100新增: case "/extensions":
101新增: return "读取浏览器扩展"
102新增: default:
103新增: return "执行浏览器操作"
104新增: }
105新增:}
106新增:
107新增:type failureOutput struct {
108新增: mu sync.Mutex
109新增: tail []byte
110新增:}
111新增:
112新增:func (b *failureOutput) Write(data []byte) (int, error) {
113新增: b.mu.Lock()
114新增: defer b.mu.Unlock()
115新增: n := len(data)
116新增: if len(data) > 8192 {
117新增: data = data[len(data)-8192:]
118新增: }
119新增: b.tail = append(b.tail, data...)
120新增: if len(b.tail) > 8192 {
121新增: b.tail = b.tail[len(b.tail)-8192:]
122新增: }
123新增: return n, nil
124新增:}
125新增:func (b *failureOutput) String() string { b.mu.Lock(); defer b.mu.Unlock(); return string(b.tail) }
126新增:func (b *failureOutput) writer(dst io.Writer) io.Writer {
127新增: if dst == nil {
128新增: return b
129新增: }
130新增: return io.MultiWriter(dst, b)
131新增:}
修改internal/workbench/favorites.go+45 −36看文件
@@ -47,10 +47,39 @@ func (s *Server) readFavorites() (Favorites, error) {
4747 return f, nil
4848}
4949
50删除:func (s *Server) getFavorites(w http.ResponseWriter, r *http.Request) {
51删除: s.favoritesMu.Lock()
52删除: defer s.favoritesMu.Unlock()
53删除: f, err := s.readFavorites()
50新增:type favoriteChange struct {
51新增: Action string `json:"action"`
52新增: ID string `json:"id"`
53新增: Title string `json:"title"`
54新增: URL string `json:"url"`
55新增: FolderID string `json:"folder_id"`
56新增:}
57新增:
58新增:func (s *Server) serveFavorites(w http.ResponseWriter, r *http.Request) {
59新增: var change *favoriteChange
60新增: if r.Method == http.MethodPost {
61新增: change = &favoriteChange{}
62新增: if !readJSON(w, r, change) {
63新增: return
64新增: }
65新增: }
66新增: var f Favorites
67新增: var err error
68新增: if r.URL.Path == "/api/mobile/browser/favorites" {
69新增: s.account.mu.Lock()
70新增: s.phones.mu.Lock()
71新增: if !s.mobileAuthorized(r.Context()) || !s.phones.pairedRequestLocked(r) {
72新增: s.phones.mu.Unlock()
73新增: s.account.mu.Unlock()
74新增: http.Error(w, "请用电脑的配对码或二维码连接后打开收藏夹。", http.StatusForbidden)
75新增: return
76新增: }
77新增: f, err = s.changeFavorites(change)
78新增: s.phones.mu.Unlock()
79新增: s.account.mu.Unlock()
80新增: } else {
81新增: f, err = s.changeFavorites(change)
82新增: }
5483 if err != nil {
5584 requestError(w, err)
5685 return
@@ -58,36 +87,22 @@ func (s *Server) getFavorites(w http.ResponseWriter, r *http.Request) {
5887 jsonReply(w, f)
5988}
6089
61删除:// Each mutation reads the current file under the same lock. Two windows adding
62删除:// favorites cannot replace one another's collections with stale snapshots.
63删除:func (s *Server) mutateFavorites(w http.ResponseWriter, r *http.Request) {
64删除: var input struct {
65删除: Action string `json:"action"`
66删除: ID string `json:"id"`
67删除: Title string `json:"title"`
68删除: URL string `json:"url"`
69删除: FolderID string `json:"folder_id"`
70删除: }
71删除: if !readJSON(w, r, &input) {
72删除: return
73删除: }
90新增:// Read and modify the latest host collection under the same lock on both clients.
91新增:func (s *Server) changeFavorites(input *favoriteChange) (Favorites, error) {
7492 s.favoritesMu.Lock()
7593 defer s.favoritesMu.Unlock()
7694 f, err := s.readFavorites()
77删除: if err != nil {
78删除: requestError(w, err)
79删除: return
95新增: if err != nil || input == nil {
96新增: return f, err
8097 }
8198 input.Title = strings.TrimSpace(input.Title)
8299 input.URL = strings.TrimSpace(input.URL)
83100 itemIndex := slices.IndexFunc(f.Items, func(item Favorite) bool { return item.ID == input.ID })
84101 folderIndex := slices.IndexFunc(f.Folders, func(folder FavoriteFolder) bool { return folder.ID == input.ID })
85删除: fail := func(message string) { requestError(w, errors.New(message)) }
86102 switch input.Action {
87103 case "save", "save_folder":
88104 if input.Title == "" || len(input.Title) > 1000 {
89删除: fail("请输入名称;名称过长时请缩短后重试")
90删除: return
105新增: return f, errors.New("请输入名称;名称过长时请缩短后重试")
91106 }
92107 if input.Action == "save_folder" {
93108 if input.ID == "" {
@@ -95,19 +110,16 @@ func (s *Server) mutateFavorites(w http.ResponseWriter, r *http.Request) {
95110 } else if folderIndex >= 0 {
96111 f.Folders[folderIndex].Title = input.Title
97112 } else {
98删除: fail("收藏夹已不存在,请重新打开收藏夹")
99删除: return
113新增: return f, errors.New("收藏夹已不存在,请重新打开收藏夹")
100114 }
101115 break
102116 }
103117 u, parseErr := url.Parse(input.URL)
104118 if parseErr != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" || u.User != nil || len(input.URL) > 16384 {
105删除: fail("收藏地址须为不含用户名和密码的 HTTP(S) 网址")
106删除: return
119新增: return f, errors.New("收藏地址须为不含用户名和密码的 HTTP(S) 网址")
107120 }
108121 if input.FolderID != "" && !slices.ContainsFunc(f.Folders, func(folder FavoriteFolder) bool { return folder.ID == input.FolderID }) {
109删除: fail("所选收藏夹已不存在,请重新选择")
110删除: return
122新增: return f, errors.New("所选收藏夹已不存在,请重新选择")
111123 }
112124 if input.ID == "" {
113125 // Repeated clicks on a page's star update its existing favorite.
@@ -118,8 +130,7 @@ func (s *Server) mutateFavorites(w http.ResponseWriter, r *http.Request) {
118130 input.ID = randomToken()[:24]
119131 }
120132 } else if itemIndex < 0 {
121删除: fail("收藏已不存在,请重新打开收藏夹")
122删除: return
133新增: return f, errors.New("收藏已不存在,请重新打开收藏夹")
123134 }
124135 item := Favorite{ID: input.ID, Title: input.Title, URL: input.URL, FolderID: input.FolderID}
125136 if itemIndex < 0 {
@@ -141,12 +152,10 @@ func (s *Server) mutateFavorites(w http.ResponseWriter, r *http.Request) {
141152 }
142153 }
143154 default:
144删除: fail("未知收藏操作")
145删除: return
155新增: return f, errors.New("未知收藏操作")
146156 }
147157 if err := writePrivate(filepath.Join(s.profile, "favorites.json"), f); err != nil {
148删除: fail("收藏未能保存,请检查磁盘空间和权限后重试")
149删除: return
158新增: return f, errors.New("收藏未能保存,请检查磁盘空间和权限后重试")
150159 }
151删除: jsonReply(w, f)
160新增: return f, nil
152161}
修改internal/workbench/favorites_test.go+44 −0看文件
@@ -1,9 +1,11 @@
11package workbench
22
33import (
4新增: "context"
45 "encoding/json"
56 "fmt"
67 "github.com/sylvinus/agent-vm/internal/host"
8新增: "github.com/sylvinus/agent-vm/internal/mobilelink"
79 "os"
810 "path/filepath"
911 "sync"
@@ -103,3 +105,45 @@ func TestConcurrentFavoritesKeepBothAdditions(t *testing.T) {
103105 t.Fatalf("concurrent additions lost: %+v, %v", f, err)
104106 }
105107}
108新增:
109新增:// Exercise the desktop store through the same paired transport used by the native apps.
110新增:func testSharedPhoneFavorites(t *testing.T, ctx context.Context, s *Server, phone *mobilelink.Client) {
111新增: t.Helper()
112新增: const path = "/api/mobile/browser/favorites"
113新增: call := func(method, body string) Favorites {
114新增: t.Helper()
115新增: reply, err := phone.Do(ctx, method, path, []byte(body))
116新增: if err != nil || reply.Status != 200 {
117新增: t.Fatalf("paired favorites: %+v %v", reply, err)
118新增: }
119新增: var f Favorites
120新增: if err := json.Unmarshal(reply.Body, &f); err != nil {
121新增: t.Fatal(err)
122新增: }
123新增: return f
124新增: }
125新增: if w := pairedHostRequest(s, "GET", path, ""); w.Code != 403 {
126新增: t.Fatal("unpaired connection could read favorites")
127新增: }
128新增: if w := pairedHostRequest(s, "POST", path, `{"action":"save_folder","title":"forbidden"}`); w.Code != 403 {
129新增: t.Fatal("unpaired connection could write favorites")
130新增: }
131新增: w := pairedHostRequest(s, "POST", "/api/favorites", `{"action":"save_folder","title":"Shared"}`)
132新增: if w.Code != 200 {
133新增: t.Fatal(w.Code)
134新增: }
135新增: initial := call("GET", "")
136新增: if len(initial.Folders) != 1 || initial.Folders[0].Title != "Shared" {
137新增: t.Fatal("phone missed desktop folder")
138新增: }
139新增: f := call("POST", fmt.Sprintf(`{"action":"save","title":"Docs","url":"https://example.com/docs","folder_id":%q}`, initial.Folders[0].ID))
140新增: var desktop Favorites
141新增: w = pairedHostRequest(s, "GET", "/api/favorites", "")
142新增: if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &desktop) != nil || len(desktop.Items) != 1 || len(f.Items) != 1 || f.Items[0] != desktop.Items[0] {
143新增: t.Fatal("desktop did not see phone bookmark")
144新增: }
145新增: w = pairedHostRequest(s, "POST", "/api/favorites", fmt.Sprintf(`{"action":"delete","id":%q}`, f.Items[0].ID))
146新增: if w.Code != 200 || len(call("GET", "").Items) != 0 {
147新增: t.Fatal("desktop deletion did not reach phone")
148新增: }
149新增:}
修改internal/workbench/file_input.go+175 −9看文件
@@ -5,17 +5,45 @@ import (
55 "context"
66 "encoding/json"
77 "errors"
8新增: "fmt"
89 "io"
910 "net/http"
1011 "net/url"
1112 "path/filepath"
1213 "regexp"
14新增: "strconv"
1315 "strings"
1416 "time"
1517
1618 "al.essio.dev/pkg/shellescape"
19新增: "github.com/sylvinus/agent-vm/internal/cage"
20新增: "github.com/sylvinus/agent-vm/internal/diagnostics"
21新增: "github.com/sylvinus/agent-vm/internal/usererror"
1722)
1823
24新增:// The broker belongs to Claude Desktop, not to the VM. An unopened desktop
25新增:// is an ordinary empty poll; a failed service must still surface as an error.
26新增:const desktopFilesPoll = `state=$(systemctl is-active cage-claude-desktop.service 2>/dev/null) || true
27新增:case "$state" in
28新增: inactive|activating|deactivating|unknown)
29新增: printf '%s\n' '{"available":false,"uploads":[],"downloads":[],"opens":[]}'
30新增: exit 0 ;;
31新增: active) ;;
32新增: *) printf 'desktop file service state=%s\n' "$state" >&2; exit 1 ;;
33新增:esac
34新增:`
35新增:
36新增:// Drain stderr even beyond the retained prefix; a noisy child must not block.
37新增:type fileControlStderr struct{ data []byte }
38新增:
39新增:func (b *fileControlStderr) Write(p []byte) (int, error) {
40新增: n := len(p)
41新增: if remaining := 4096 - len(b.data); remaining > 0 {
42新增: b.data = append(b.data, p[:min(len(p), remaining)]...)
43新增: }
44新增: return n, nil
45新增:}
46新增:
1947var terminalFileID = regexp.MustCompile(`^[a-f0-9]{16}$`)
2048
2149func validFileTargetID(target, id string) bool {
@@ -28,32 +56,120 @@ func validFileTargetID(target, id string) bool {
2856// Desktop requests use the private session socket, carried over the existing
2957// SSH connection. Directory selections use an authorized project's guest path.
3058func (s *Server) guestFiles(ctx context.Context, target, method, path string, body io.Reader, name string) (map[string]any, error) {
31删除: script := "sudo -H -u cage curl --silent --show-error --fail --max-time 1800 --unix-socket /run/cage-desktop/files.sock -X " + method
59新增: if s.macosGuest != nil && target == "desktop" {
60新增: parsed, err := url.Parse(path)
61新增: if err != nil {
62新增: return nil, errors.New("虚拟 Mac 文件操作无效")
63新增: }
64新增: if method == "POST" && parsed.Path == "/upload" {
65新增: return s.macOSUploadDesktopAttachment(ctx, name, parsed.Query().Get("id"), body)
66新增: }
67新增: var input macOSWindowRequest
68新增: if body != nil {
69新增: data, err := io.ReadAll(io.LimitReader(body, 8193))
70新增: if err != nil || len(data) > 8192 || json.Unmarshal(data, &input) != nil {
71新增: return nil, errors.New("虚拟 Mac 文件操作无效")
72新增: }
73新增: }
74新增: switch {
75新增: case method == "GET" && parsed.Path == "/requests":
76新增: input.Action = "files-poll"
77新增: case method == "POST" && (parsed.Path == "/start" || parsed.Path == "/finish" || parsed.Path == "/finish-image" || parsed.Path == "/cancel" || parsed.Path == "/directory" || parsed.Path == "/download-retry" || parsed.Path == "/open-claim" || parsed.Path == "/open-complete"):
78新增: input.Action = "files-" + strings.TrimPrefix(parsed.Path, "/")
79新增: default:
80新增: return nil, errors.New("虚拟 Mac 文件操作无效")
81新增: }
82新增: input.Files = nil
83新增: return s.macOSDesktopFileCall(ctx, input)
84新增: }
85新增: if s.windowsGuest != nil && target == "terminal" {
86新增: return s.windowsSaveAttachment(ctx, name, body)
87新增: }
88新增: if s.windowsGuest != nil && target == "desktop" {
89新增: parsed, err := url.Parse(path)
90新增: if err != nil {
91新增: return nil, errors.New("Windows 文件操作无效")
92新增: }
93新增: if method == "POST" && parsed.Path == "/upload" {
94新增: return s.windowsUploadAttachment(ctx, name, parsed.Query().Get("id"), body)
95新增: }
96新增: var action string
97新增: switch {
98新增: case method == "GET" && parsed.Path == "/requests":
99新增: action = "files-poll"
100新增: case method == "POST" && (parsed.Path == "/start" || parsed.Path == "/finish" || parsed.Path == "/finish-image" || parsed.Path == "/cancel" || parsed.Path == "/directory" || parsed.Path == "/download-retry" || parsed.Path == "/open-claim" || parsed.Path == "/open-complete"):
101新增: action = "files-" + strings.TrimPrefix(parsed.Path, "/")
102新增: default:
103新增: return nil, errors.New("Windows 原生文件选择框与桌面下载尚未接通")
104新增: }
105新增: input := map[string]any{}
106新增: if body != nil {
107新增: data, readErr := io.ReadAll(io.LimitReader(body, 65537))
108新增: if readErr != nil || len(data) > 65536 || json.Unmarshal(data, &input) != nil {
109新增: return nil, errors.New("Windows 文件操作无效")
110新增: }
111新增: }
112新增: var result map[string]any
113新增: err = s.windowsDesktopRequest(ctx, action, input, &result)
114新增: return result, windowsDesktopFileFailure(err)
115新增: }
116新增: script := "sudo -H -u cage curl --silent --show-error --max-time 1800 --write-out '\\nCAGE_FILE_HTTP:%{http_code}' --unix-socket /run/cage-desktop/files.sock -X " + method
32117 if target == "terminal" {
33118 script = "sudo -H -u cage /usr/local/bin/cage-desktop-files --save-file " + shellescape.Quote(name)
119新增: if s.macosGuest != nil {
120新增: script = "exec " + shellescape.QuoteCommand([]string{macCLIInstall + "/bin/python3", "-I", "-c", cage.DesktopFileReceiver(), "--save-file", name})
121新增: }
34122 } else {
35123 if body != nil {
36124 script += " --upload-file -"
37125 }
38126 script += " " + shellescape.Quote("http://localhost"+path)
39127 }
40删除: cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", script)
128新增: if target != "terminal" && method == "GET" && path == "/requests" {
129新增: script = desktopFilesPoll + script
130新增: }
131新增: command := "exec /bin/bash --noprofile --norc -c " + shellescape.Quote(script)
132新增: cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", command)
133新增: var stderr fileControlStderr
134新增: cmd.Stderr = &stderr
41135 cmd.Stdin = body
42136 pipe, err := cmd.StdoutPipe()
43137 if err != nil {
44138 return nil, err
45139 }
46140 if err = cmd.Start(); err != nil {
47删除: return nil, errors.New("无法连接文件传递服务")
141新增: return nil, usererror.Wrap("连接文件传递服务", err, "请确认 Cage 安装完整,环境已经启动;持续失败时在设置中导出诊断包。")
48142 }
49删除: data, readErr := io.ReadAll(io.LimitReader(pipe, 65537))
50删除: if readErr != nil || len(data) > 65536 {
143新增: data, readErr := io.ReadAll(io.LimitReader(pipe, 65537+64))
144新增: if readErr != nil || len(data) > 65536+64 {
51145 _ = cmd.Process.Kill()
52146 }
53147 err = cmd.Wait()
148新增: httpStatus := 0
149新增: if at := bytes.LastIndex(data, []byte("\nCAGE_FILE_HTTP:")); at >= 0 && target != "terminal" {
150新增: httpStatus, _ = strconv.Atoi(strings.TrimSpace(string(data[at+len("\nCAGE_FILE_HTTP:"):])))
151新增: data = data[:at]
152新增: }
54153 var result map[string]any
55删除: if err != nil || readErr != nil || len(data) > 65536 || json.Unmarshal(data, &result) != nil {
56删除: return nil, errors.New("文件传递未完成,请确认应用已打开;环境组件过旧时请先更新环境")
154新增: decodeErr := json.Unmarshal(data, &result)
155新增: if err != nil || readErr != nil || len(data) > 65536 || decodeErr != nil || result == nil || httpStatus >= 400 {
156新增: // No response body, filename, request ID or query string enters the log.
157新增: route := strings.SplitN(path, "?", 2)[0]
158新增: _ = diagnostics.New(s.profile).Record("error", "desktop-files", fmt.Sprintf("target=%s method=%s route=%s exit=%v read=%v invalid_json=%t oversized=%t context=%v stderr=%s", target, method, route, err, readErr, decodeErr != nil || result == nil, len(data) > 65536, ctx.Err(), stderr.data))
159新增: switch {
160新增: case ctx.Err() != nil:
161新增: return nil, usererror.Wrap("传递文件", ctx.Err(), "请确认环境仍在运行;恢复连接后重新选择文件,并核对目标是否已收到文件。")
162新增: case httpStatus >= 400:
163新增: return nil, fileServiceFailure(httpStatus, data)
164新增: case err != nil:
165新增: return nil, executionFailure("连接文件传递服务", err, string(stderr.data))
166新增: case readErr != nil:
167新增: return nil, usererror.Wrap("读取文件传递结果", readErr, "结果没有完整返回,请恢复连接后核对文件是否已收到。")
168新增: case len(data) > 65536:
169新增: return nil, errors.New("读取文件传递结果失败:服务返回的数据超过 64 KiB。请分批处理文件;持续出现时导出诊断包。")
170新增: default:
171新增: return nil, errors.New("读取文件传递结果失败:服务没有返回有效的文件记录。请重新打开接收文件的应用;旧环境请先更新环境组件。")
172新增: }
57173 }
58174 return result, nil
59175}
@@ -84,6 +200,8 @@ func (s *Server) fileInputAction(w http.ResponseWriter, r *http.Request) {
84200 X float64 `json:"x"`
85201 Y float64 `json:"y"`
86202 Workspace string `json:"workspace"`
203新增: Window uint32 `json:"window,omitempty"`
204新增: PID int32 `json:"pid,omitempty"`
87205 }
88206 if !readJSON(w, r, &input) {
89207 return
@@ -120,6 +238,16 @@ func (s *Server) fileInputAction(w http.ResponseWriter, r *http.Request) {
120238 return
121239 }
122240 }
241新增: if action == "download-retry" && (s.macosGuest != nil || s.windowsGuest != nil) {
242新增: if handled, err := s.retryNativeDownload(input.ID); handled {
243新增: if err != nil {
244新增: requestError(w, err)
245新增: } else {
246新增: jsonReply(w, map[string]bool{"ok": true})
247新增: }
248新增: return
249新增: }
250新增: }
123251 ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
124252 defer cancel()
125253 body, _ := json.Marshal(input)
@@ -134,6 +262,16 @@ func (s *Server) fileInputAction(w http.ResponseWriter, r *http.Request) {
134262 return
135263 }
136264 body, _ = json.Marshal(map[string]string{"id": input.ID, "path": guestPath(workspace)})
265新增: if s.macosGuest != nil {
266新增: body, _ = json.Marshal(map[string]string{"id": input.ID, "path": macOSProjectPath(s.macosGuest.User, workspace)})
267新增: } else if s.windowsGuest != nil {
268新增: project, err := s.windowsProjectForHost(workspace)
269新增: if err != nil {
270新增: requestError(w, err)
271新增: return
272新增: }
273新增: body, _ = json.Marshal(map[string]string{"id": input.ID, "project_id": project.ID, "grant": project.Grant})
274新增: }
137275 }
138276 if input.Target == "terminal" {
139277 jsonReply(w, map[string]any{"ok": true, "id": input.ID})
@@ -169,7 +307,9 @@ func (s *Server) desktopFileRequests(w http.ResponseWriter, r *http.Request) {
169307 defer cancel()
170308 result, err := s.guestFiles(ctx, "desktop", "GET", "/requests", nil, "")
171309 if err != nil {
172删除: requestError(w, err)
310新增: // Service/transport failures are not invalid user input. guestFiles has
311新增: // already recorded the bounded diagnostic, including the real exit code.
312新增: http.Error(w, err.Error(), http.StatusServiceUnavailable)
173313 return
174314 }
175315 if err = s.rememberDesktopDownloads(result); err != nil {
@@ -183,6 +323,7 @@ func (s *Server) desktopFileRequests(w http.ResponseWriter, r *http.Request) {
183323// Guest paths are never accepted as arbitrary host paths.
184324func (s *Server) rememberDesktopDownloads(result map[string]any) error {
185325 items, _ := result["downloads"].([]any)
326新增: visible := make(map[string]bool, len(items))
186327 for _, value := range items {
187328 item, ok := value.(map[string]any)
188329 if !ok {
@@ -193,7 +334,22 @@ func (s *Server) rememberDesktopDownloads(result map[string]any) error {
193334 if !browserFileID.MatchString(id) || !browserFileName(name) {
194335 return errors.New("Desktop 下载记录无效")
195336 }
337新增: visible[id] = true
196338 item["target"] = "desktop"
339新增: if s.macosGuest != nil || s.windowsGuest != nil {
340新增: data, err := json.Marshal(item)
341新增: if err != nil {
342新增: return err
343新增: }
344新增: var native browserDownloadInfo
345新增: if err = json.Unmarshal(data, &native); err != nil {
346新增: return err
347新增: }
348新增: converted := s.nativeDownloadForHost(native)
349新增: item["name"], item["state"], item["path"] = converted.Name, converted.State, converted.Path
350新增: item["retryable"], item["error"] = converted.Retryable, converted.Error
351新增: continue
352新增: }
197353 if item["state"] != "saved" {
198354 delete(item, "path")
199355 continue
@@ -208,6 +364,9 @@ func (s *Server) rememberDesktopDownloads(result map[string]any) error {
208364 }
209365 item["path"] = path
210366 }
367新增: if s.macosGuest != nil || s.windowsGuest != nil {
368新增: s.discardMissingNativeDownloads("desktop", visible)
369新增: }
211370 return nil
212371}
213372
@@ -239,7 +398,14 @@ func (s *Server) fileInputUpload(w http.ResponseWriter, r *http.Request) {
239398 }
240399 if target == "terminal" {
241400 path, _ := result["path"].(string)
242删除: if !strings.HasPrefix(path, "/home/cage/.local/share/cage/attachments/files/") || strings.ContainsAny(path, "\x00\r\n") {
401新增: valid := strings.HasPrefix(path, "/home/cage/.local/share/cage/attachments/files/") && !strings.ContainsAny(path, "\x00\r\n")
402新增: if s.windowsGuest != nil {
403新增: valid = validWindowsAttachmentPath(path, name)
404新增: }
405新增: if s.macosGuest != nil {
406新增: valid = s.validMacOSAttachmentPath(path, name)
407新增: }
408新增: if !valid {
243409 http.Error(w, "文件保存路径无效", 502)
244410 return
245411 }
新增internal/workbench/file_poll_test.go+60 −0看文件
@@ -0,0 +1,60 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "encoding/json"
5新增: "net/http"
6新增: "os/exec"
7新增: "strings"
8新增: "testing"
9新增:)
10新增:
11新增:func TestDesktopFileRequestsReportTransportFailureAsUnavailable(t *testing.T) {
12新增: if _, err := exec.LookPath(sshExecutable()); err != nil {
13新增: t.Skip("SSH unavailable")
14新增: }
15新增: s := testServer(t)
16新增: s.ready = true
17新增: // This isolated profile has no SSH config. The shipped SSH entry fails
18新增: // locally, without connecting to any running VM or host service.
19新增: w := request(s, "GET", "/api/input/files/desktop/requests", "", "", true)
20新增: if w.Code != http.StatusServiceUnavailable {
21新增: t.Fatalf("transport failure became bad user input: %d %s", w.Code, w.Body.String())
22新增: }
23新增:}
24新增:
25新增:func TestDesktopFilePollDistinguishesUnopenedAndBrokenDesktop(t *testing.T) {
26新增: bash, err := exec.LookPath("bash")
27新增: if err != nil {
28新增: t.Skip("bash unavailable")
29新增: }
30新增: fixture := `systemctl() {
31新增: printf '%s\n' "$DESKTOP_STATE"
32新增: [ "$DESKTOP_STATE" = active ]
33新增:}
34新增:`
35新增: for _, state := range []string{"inactive", "activating", "active", "failed", ""} {
36新增: t.Run(state, func(t *testing.T) {
37新增: // The final command stands for contacting the broker. It must only
38新增: // run for an active service; a failed service cannot become empty success.
39新增: script := "DESKTOP_STATE='" + state + "'\n" + fixture + desktopFilesPoll + "printf broker-contacted"
40新增: cmd := exec.Command(bash, "--noprofile", "--norc", "-s")
41新增: cmd.Stdin = strings.NewReader(script)
42新增: out, err := cmd.CombinedOutput()
43新增: switch state {
44新增: case "inactive", "activating":
45新增: var result map[string]any
46新增: if err != nil || json.Unmarshal(out, &result) != nil || result["available"] != false {
47新增: t.Fatalf("unopened desktop became error: %s %v", out, err)
48新增: }
49新增: case "active":
50新增: if err != nil || string(out) != "broker-contacted" {
51新增: t.Fatalf("live broker not polled: %s %v", out, err)
52新增: }
53新增: default:
54新增: if err == nil || strings.Contains(string(out), "broker-contacted") {
55新增: t.Fatalf("broken service hidden: %s %v", out, err)
56新增: }
57新增: }
58新增: })
59新增: }
60新增:}
新增internal/workbench/guest_install.go+359 −0看文件
@@ -0,0 +1,359 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "context"
5新增: "errors"
6新增: "fmt"
7新增: "net/http"
8新增: "os"
9新增: "os/exec"
10新增: "path/filepath"
11新增: "runtime"
12新增: "strings"
13新增:
14新增: "github.com/google/uuid"
15新增: "github.com/sylvinus/agent-vm/internal/cage"
16新增: "github.com/sylvinus/agent-vm/internal/guestos"
17新增: "github.com/sylvinus/agent-vm/internal/host"
18新增: "github.com/sylvinus/agent-vm/internal/hostimage"
19新增:)
20新增:
21新增:type guestInstallRequest struct {
22新增: EditorTerms bool `json:"editor_terms"`
23新增: System string `json:"guest_system"`
24新增: Media string `json:"media"`
25新增: SHA256 string `json:"sha256"`
26新增: CloneKey string `json:"clone_key,omitempty"`
27新增:}
28新增:
29新增:type guestInstallView struct {
30新增: LinuxSystems []string `json:"linux_systems,omitempty"`
31新增: Reselect bool `json:"reselect,omitempty"`
32新增: System string `json:"system,omitempty"`
33新增: Available bool `json:"available"`
34新增: Reason string `json:"reason,omitempty"`
35新增: Fresh bool `json:"fresh"`
36新增: Pending *guestos.Installation `json:"pending,omitempty"`
37新增: Activate bool `json:"activate,omitempty"`
38新增:}
39新增:
40新增:func (s *Server) guestInstallView() (guestInstallView, error) {
41新增: v := guestInstallView{}
42新增: if !s.localVMStorage() || s.macosGuest != nil || s.windowsGuest != nil {
43新增: return v, nil
44新增: }
45新增: pending, err := guestos.LoadInstallation(s.profile)
46新增: if err != nil {
47新增: return v, err
48新增: }
49新增: loc, err := cage.GetStorageLocation(s.profile)
50新增: if err != nil {
51新增: return v, err
52新增: }
53新增: v.Fresh = !loc.HasEnvironment
54新增: v.Pending = pending
55新增: if !v.Fresh && pending == nil {
56新增: return v, nil
57新增: }
58新增: v.LinuxSystems = linuxGuestSystems(runtime.GOOS, runtime.GOARCH)
59新增: switch {
60新增: case runtime.GOOS == "darwin" && runtime.GOARCH == "arm64":
61新增: v.System = guestos.MacOS
62新增: case runtime.GOOS == "windows" && runtime.GOARCH == "amd64":
63新增: v.System = guestos.Windows11
64新增: case runtime.GOOS == "linux" && runtime.GOARCH == "amd64":
65新增: identity, hostErr := hostimage.Host(context.Background())
66新增: if hostErr != nil {
67新增: v.Reason = hostErr.Error()
68新增: } else {
69新增: v.System = identity.System
70新增: }
71新增: default:
72新增: return v, nil
73新增: }
74新增: if pending != nil {
75新增: v.Reselect, err = guestos.UnstartedInstallation(s.profile, *pending)
76新增: if err != nil {
77新增: return v, err
78新增: }
79新增: catalog := pending.SourceKind == guestos.LinuxImageSource && canInstallCatalogLinux(pending.System) && pending.Source.Host.Arch == runtime.GOARCH
80新增: if !catalog && pending.System != v.System {
81新增: return v, errors.New("客户机安装记录与这台宿主不匹配")
82新增: }
83新增: if pending.SourceKind == guestos.LinuxImageSource && !catalog {
84新增: return v, errors.New("客户机镜像架构与这台主机不匹配,请恢复原主机环境")
85新增: }
86新增: mac, err := guestos.LoadMacOSProfile(s.profile)
87新增: if err != nil {
88新增: return v, err
89新增: }
90新增: win, err := guestos.LoadWindowsProfile(s.profile)
91新增: if err != nil {
92新增: return v, err
93新增: }
94新增: v.Activate = (pending.System == guestos.MacOS && mac != nil) || (pending.System == guestos.Windows11 && win != nil)
95新增: if pending.System == guestos.Windows11 && win != nil {
96新增: cleanup, err := guestos.WindowsCloneCleanupPending(s.profile)
97新增: if err != nil {
98新增: return v, err
99新增: }
100新增: v.Activate = !cleanup
101新增: }
102新增: }
103新增: if v.System == "" {
104新增: return v, nil
105新增: }
106新增: if !hostimage.IsLinux(v.System) && !guestos.HasNativeWorkbenchKit(s.exe, v.System) {
107新增: v.Reason = "此构建缺少原生客户机安装组件"
108新增: return v, nil
109新增: }
110新增: v.Available = true
111新增: return v, nil
112新增:}
113新增:
114新增:func (s *Server) guestInstallation(w http.ResponseWriter, r *http.Request) {
115新增: if !s.hasTrustedView(r) || !s.localVMStorage() {
116新增: http.Error(w, "请在本机 Cage 窗口选择客户机系统", http.StatusForbidden)
117新增: return
118新增: }
119新增: v, err := s.guestInstallView()
120新增: if err != nil {
121新增: requestError(w, err)
122新增: return
123新增: }
124新增: if r.Method == http.MethodGet {
125新增: if v.System == guestos.Windows11 && v.Available && v.Pending == nil {
126新增: check := guestos.Inspect(r.Context())
127新增: if !check.HostCheckPassed {
128新增: v.Available = false
129新增: v.Reason = check.Detail
130新增: }
131新增: }
132新增: jsonReply(w, v)
133新增: return
134新增: }
135新增: if r.Method == http.MethodDelete {
136新增: var body struct {
137新增: ID uuid.UUID `json:"id"`
138新增: }
139新增: if !readJSON(w, r, &body) {
140新增: return
141新增: }
142新增: if !v.Reselect || s.busy() || !s.op.TryLock() {
143新增: http.Error(w, "安装任务或磁盘已存在,请继续原安装", http.StatusConflict)
144新增: return
145新增: }
146新增: defer s.op.Unlock()
147新增: if err := guestos.ClearUnstartedInstallation(s.profile, body.ID); err != nil {
148新增: requestError(w, err)
149新增: return
150新增: }
151新增: jsonReply(w, map[string]bool{"cleared": true})
152新增: return
153新增: }
154新增: if !v.Activate || !s.op.TryLock() {
155新增: http.Error(w, "客户机尚未完成安装", http.StatusConflict)
156新增: return
157新增: }
158新增: if v.Pending != nil && v.Pending.System == guestos.Windows11 {
159新增: owner, err := s.installedWindowsVMOwner(*v.Pending)
160新增: if err != nil {
161新增: s.op.Unlock()
162新增: requestError(w, err)
163新增: return
164新增: }
165新增: s.handoffWithVMOwnerLocked(w, owner)
166新增: return
167新增: }
168新增: s.handoffLocked(w)
169新增:}
170新增:
171新增:func (s *Server) installedWindowsVMOwner(install guestos.Installation) (string, error) {
172新增: binding, err := guestos.LoadWindowsProfile(s.profile)
173新增: if err != nil || binding == nil || install.System != guestos.Windows11 || install.ID == uuid.Nil {
174新增: return "", errors.New("Windows 安装绑定尚未确认,请继续原安装;原磁盘和账户已保留")
175新增: }
176新增: state, err := cage.StoragePhysicalPath(filepath.Join(s.profile, "state"))
177新增: if err != nil {
178新增: return "", err
179新增: }
180新增: expected := filepath.Join(state, "windows-"+strings.ReplaceAll(install.ID.String(), "-", ""))
181新增: receipt, err := os.ReadFile(filepath.Join(s.profile, "windows-install-vm.txt"))
182新增: id, parseErr := uuid.Parse(strings.TrimSpace(string(receipt)))
183新增: if err != nil || parseErr != nil || id != binding.VMID || !strings.EqualFold(filepath.Clean(binding.InstanceDirectory), filepath.Clean(expected)) {
184新增: return "", errors.New("Windows 安装记录与原客机不匹配,请核对原环境;现有数据已保留")
185新增: }
186新增: return "windows/" + binding.VMID.String() + "/Running", nil
187新增:}
188新增:
189新增:func (s *Server) beginGuestInstall(w http.ResponseWriter, r *http.Request, in guestInstallRequest) {
190新增: v, err := s.guestInstallView()
191新增: if err != nil {
192新增: requestError(w, err)
193新增: return
194新增: }
195新增: catalog := canInstallCatalogLinux(in.System) && in.CloneKey == ""
196新增: if v.Pending != nil {
197新增: catalog = v.Pending.SourceKind == guestos.LinuxImageSource
198新增: }
199新增: if (!catalog && (!v.Available || v.System != in.System)) || !s.hasTrustedView(r) || (!v.Fresh && v.Pending == nil) || v.Activate {
200新增: http.Error(w, "当前环境无法安装所选客户机系统", http.StatusConflict)
201新增: return
202新增: }
203新增: install := guestos.Installation{Version: 1, System: in.System, Media: in.Media, SHA256: strings.ToLower(in.SHA256), ID: uuid.New(), EditorTerms: in.EditorTerms}
204新增: if v.Pending != nil {
205新增: if v.Pending.System != in.System || (in.Media != "" && in.Media != v.Pending.Media) || (in.SHA256 != "" && !strings.EqualFold(in.SHA256, v.Pending.SHA256)) {
206新增: http.Error(w, "必须使用原先选择的系统和安装介质继续安装", http.StatusConflict)
207新增: return
208新增: }
209新增: install = *v.Pending
210新增: } else if in.CloneKey != "" {
211新增: plan, planErr := s.hostClonePlan(r.Context())
212新增: if planErr != nil {
213新增: requestError(w, planErr)
214新增: return
215新增: }
216新增: if plan.Key() != in.CloneKey || plan.Host.System != in.System {
217新增: requestError(w, errors.New("本机版本或系统镜像信息已变化,请重新检测并匹配"))
218新增: return
219新增: }
220新增: install.Source = plan
221新增: } else if catalog {
222新增: if in.Media != "" || in.SHA256 != "" || in.EditorTerms {
223新增: requestError(w, errors.New("Ubuntu 使用 Cage 校验过的官方镜像,无需另选安装介质"))
224新增: return
225新增: }
226新增: plan, err := linuxGuestImagePlan(r.Context(), s.profile, in.System, runtime.GOARCH)
227新增: if err != nil {
228新增: requestError(w, err)
229新增: return
230新增: }
231新增: install.Source, install.SourceKind = plan, guestos.LinuxImageSource
232新增: }
233新增: if err := install.Validate(); err != nil {
234新增: requestError(w, err)
235新增: return
236新增: }
237新增: s.launch(w, "guest-install", func() error {
238新增: s.jobs.execution().setSetupProgress(&SetupProgress{Phase: "image", System: install.System, Label: "正在准备 " + guestProgressName(install.System) + " 安装材料"})
239新增: if err := requireHostGit(s.operationContext()); err != nil {
240新增: return err
241新增: }
242新增: cfg, err := loadConfig(s.configPath)
243新增: if err != nil {
244新增: return err
245新增: }
246新增: if err := cfg.RequireManagedProxy(s.profile); err != nil {
247新增: return err
248新增: }
249新增: lease, loc, err := cage.AcquireStorageUse(s.profile)
250新增: if err != nil {
251新增: return err
252新增: }
253新增: defer lease.Close()
254新增: current, err := guestos.LoadInstallation(s.profile)
255新增: if err != nil {
256新增: return err
257新增: }
258新增: if current == nil && loc.HasEnvironment || current != nil && *current != install {
259新增: return errors.New("已有其他环境或安装任务,请重新打开安装页面")
260新增: }
261新增: if install.Media != "" {
262新增: f, err := os.Stat(install.Media)
263新增: if err != nil || !f.Mode().IsRegular() {
264新增: return errors.New("原安装镜像不可读,请恢复其原路径后重试")
265新增: }
266新增: }
267新增: if install.System == guestos.Windows11 {
268新增: check := guestos.Inspect(s.operationContext())
269新增: if !check.HostCheckPassed {
270新增: return errors.New(check.Detail)
271新增: }
272新增: }
273新增: if err := guestos.SaveInstallation(s.profile, install); err != nil {
274新增: return err
275新增: }
276新增: if install.Source.Host.System != "" {
277新增: cache := filepath.Join(s.profile, "state", "guest-media", install.System)
278新增: unstarted, err := guestos.UnstartedInstallation(s.profile, install)
279新增: if err != nil {
280新增: return err
281新增: }
282新增: minimumGiB := 32
283新增: if hostimage.IsLinux(install.System) {
284新增: minimumGiB = 16
285新增: }
286新增: if !unstarted {
287新增: minimumGiB = 0
288新增: }
289新增: minimumGiB += int((install.Source.RemainingBytes(cache) + (1 << 30) - 1) / (1 << 30))
290新增: if available, ok := host.FreeGiB(cache); ok && available < minimumGiB {
291新增: return fmt.Errorf("创建所选系统至少需要 %d GiB 可用空间,当前有 %d GiB,请在存储设置中选择空间充足的位置", minimumGiB, available)
292新增: }
293新增: s.setMessage("正在准备 " + guestProgressName(install.System) + " 官方系统镜像…")
294新增: transport, transportErr := s.hostCloneTransport()
295新增: if transportErr != nil {
296新增: return transportErr
297新增: }
298新增: defer transport.CloseIdleConnections()
299新增: prepared, prepareErr := hostimage.Prepare(s.operationContext(), cache, install.Source, s.jobs.execution(), transport)
300新增: if prepareErr != nil {
301新增: return prepareErr
302新增: }
303新增: install.Source, install.Media = prepared, prepared.Path
304新增: install.SHA256 = strings.TrimPrefix(prepared.Digest, "sha256:")
305新增: if err := guestos.RecordPreparedMedia(s.profile, install.ID, prepared); err != nil {
306新增: return err
307新增: }
308新增: }
309新增: var password string
310新增: if install.System == guestos.MacOS {
311新增: saved, err := s.account.savedMacGuestPassword(s.operationContext(), install.ID)
312新增: if err != nil {
313新增: return err
314新增: }
315新增: unstarted, err := guestos.UnstartedInstallation(s.profile, install)
316新增: if err != nil {
317新增: return err
318新增: }
319新增: if saved == "" && !unstarted {
320新增: return errors.New("客机安装凭据缺失,请恢复加密保险箱;现有账户和磁盘已保留")
321新增: }
322新增: password, err = s.account.macGuestPassword(s.operationContext(), install.ID)
323新增: if err != nil {
324新增: return err
325新增: }
326新增: }
327新增: if err := s.prepareEnvironment(); err != nil {
328新增: return err
329新增: }
330新增: if hostimage.IsLinux(install.System) {
331新增: if err := hostimage.WriteLinuxTemplate(filepath.Join(s.profile, "state"), install.Source); err != nil {
332新增: return err
333新增: }
334新增: if err := s.startEnvironment(true); err != nil {
335新增: return err
336新增: }
337新增: return guestos.FinishLinuxInstallation(s.profile, install.ID)
338新增: }
339新增: s.setMessage("正在安装所选客户机系统…")
340新增: s.jobs.execution().setSetupProgress(&SetupProgress{Phase: "packages", System: install.System, Label: "正在安装 " + guestProgressName(install.System) + " 系统"})
341新增: var cmd *exec.Cmd
342新增: if install.System == guestos.MacOS {
343新增: cmd = exec.CommandContext(s.operationContext(), s.exe, "guest-os", "macos", "install")
344新增: cmd.Env = append(os.Environ(), cage.ConfigEnv+"="+s.configPath)
345新增: cmd.Stdin = strings.NewReader(password)
346新增: } else {
347新增: cmd, err = guestos.WindowsInstallCommand(s.operationContext(), s.profile, filepath.Join(filepath.Dir(s.exe), "guest-os"), install)
348新增: if err != nil {
349新增: return err
350新增: }
351新增: }
352新增: cmd.Stdout = s.jobs.execution()
353新增: cmd.Stderr = s.jobs.execution()
354新增: if err := cmd.Run(); err != nil {
355新增: return fmt.Errorf("客户机安装未完成,已保留安装进度和文件。请点击「继续安装」。若仍失败,请在设置中导出诊断包:%w", err)
356新增: }
357新增: return nil
358新增: })
359新增:}
新增internal/workbench/guest_system_start_test.go+35 −0看文件
@@ -0,0 +1,35 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "github.com/google/uuid"
5新增: "github.com/sylvinus/agent-vm/internal/guestos"
6新增: "net/http"
7新增: "strings"
8新增: "testing"
9新增:)
10新增:
11新增:func TestUnsupportedGuestSystemCannotStartDebian(t *testing.T) {
12新增: s := testServer(t)
13新增: for _, system := range []string{"macos", "windows-11", "debian-12", "ubuntu-22.04", "ubuntu-24.04", "unknown"} {
14新增: response := request(s, http.MethodPost, "/api/start", s.origin, `{"guest_system":"`+system+`"}`, true)
15新增: if response.Code != http.StatusConflict || s.jobs.snapshot().ID != "" {
16新增: t.Fatalf("%s: got %d, job %v", system, response.Code, s.jobs.snapshot())
17新增: }
18新增: }
19新增:}
20新增:
21新增:func TestIncompleteInstallationPreventsImplicitLinuxStart(t *testing.T) {
22新增: s := testServer(t)
23新增: if err := guestos.SaveInstallation(s.profile, guestos.Installation{Version: 1, System: guestos.MacOS, ID: uuid.New()}); err != nil {
24新增: t.Fatal(err)
25新增: }
26新增: for _, body := range []string{"{}", `{"guest_system":"debian-13"}`} {
27新增: w := request(s, "POST", "/api/start", s.origin, body, true)
28新增: if w.Code != http.StatusConflict || s.jobs.snapshot().ID != "" {
29新增: t.Fatalf("created a Linux job from pending macOS (%s): %d", body, w.Code)
30新增: }
31新增: }
32新增: if err := s.startEnvironment(false); err == nil || !strings.Contains(err.Error(), "原生客户机") {
33新增: t.Fatalf("indirect Linux start: %v", err)
34新增: }
35新增:}
新增internal/workbench/host_clone.go+100 −0看文件
@@ -0,0 +1,100 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "context"
5新增: "errors"
6新增: "net/http"
7新增: "os"
8新增: "path/filepath"
9新增: "time"
10新增:
11新增: "github.com/sylvinus/agent-vm/internal/cage"
12新增: "github.com/sylvinus/agent-vm/internal/host"
13新增: "github.com/sylvinus/agent-vm/internal/hostimage"
14新增: "github.com/sylvinus/agent-vm/internal/limaembed"
15新增:)
16新增:
17新增:func (s *Server) hostClonePlan(ctx context.Context) (hostimage.Plan, error) {
18新增: identity, err := hostimage.Host(ctx)
19新增: if err != nil {
20新增: return hostimage.Plan{}, err
21新增: }
22新增: home, err := os.UserHomeDir()
23新增: if err != nil {
24新增: return hostimage.Plan{}, err
25新增: }
26新增: var template []byte
27新增: if hostimage.IsLinux(identity.System) {
28新增: template, err = limaembed.ReadImageTemplate(identity.System)
29新增: if err != nil {
30新增: return hostimage.Plan{}, err
31新增: }
32新增: }
33新增: cache := filepath.Join(s.profile, "state", "guest-media", identity.System)
34新增: transport, err := s.hostCloneTransport()
35新增: if err != nil {
36新增: return hostimage.Plan{}, err
37新增: }
38新增: defer transport.CloseIdleConnections()
39新增: return hostimage.Resolve(ctx, identity, cache, filepath.Join(home, "Downloads"), template, transport)
40新增:}
41新增:
42新增:func (s *Server) hostCloneTransport() (*http.Transport, error) {
43新增: cfg, err := loadConfig(s.configPath)
44新增: if err != nil {
45新增: return nil, err
46新增: }
47新增: egress, err := cage.NewEgress(cfg)
48新增: if err != nil {
49新增: return nil, err
50新增: }
51新增: return &http.Transport{Proxy: nil, DialContext: egress.DialContext, ForceAttemptHTTP2: true,
52新增: TLSHandshakeTimeout: 15 * time.Second, ResponseHeaderTimeout: 30 * time.Second}, nil
53新增:}
54新增:
55新增:func (s *Server) hostClone(w http.ResponseWriter, r *http.Request) {
56新增: if !s.hasTrustedView(r) || !s.localVMStorage() {
57新增: http.Error(w, "请在本机 Cage 窗口选择系统创建方式", http.StatusForbidden)
58新增: return
59新增: }
60新增: view, err := s.guestInstallView()
61新增: if err != nil {
62新增: requestError(w, err)
63新增: return
64新增: }
65新增: if !view.Available || (!view.Fresh && view.Pending == nil) {
66新增: requestError(w, errors.New("当前环境无法创建新的本机系统"))
67新增: return
68新增: }
69新增: if view.Pending != nil && view.Pending.SourceKind == "linux-image" {
70新增: requestError(w, errors.New("请继续已选择的 Ubuntu 安装,不能改为自动匹配本机系统版本"))
71新增: return
72新增: }
73新增: var plan hostimage.Plan
74新增: if view.Pending != nil && view.Pending.Source.Host.System != "" {
75新增: plan = view.Pending.Source
76新增: } else {
77新增: plan, err = s.hostClonePlan(r.Context())
78新增: if err != nil {
79新增: requestError(w, err)
80新增: return
81新增: }
82新增: }
83新增: minimumGiB := 32
84新增: if hostimage.IsLinux(plan.Host.System) {
85新增: minimumGiB = 16
86新增: }
87新增: started := view.Pending != nil && !view.Reselect
88新增: if started {
89新增: minimumGiB = 0
90新增: }
91新增: downloadBytes := plan.RemainingBytes(filepath.Join(s.profile, "state", "guest-media", plan.Host.System))
92新增: minimumGiB += int((downloadBytes + (1 << 30) - 1) / (1 << 30))
93新增: freeGiB, measured := host.FreeGiB(filepath.Join(s.profile, "state"))
94新增: jsonReply(w, map[string]any{
95新增: "plan": plan, "key": plan.Key(), "download_bytes": downloadBytes,
96新增: "minimum_free_gib": minimumGiB, "free_gib": freeGiB,
97新增: "installation_started": started,
98新增: "enough_space": !measured || freeGiB >= minimumGiB,
99新增: })
100新增:}
新增internal/workbench/host_clone_test.go+98 −0看文件
@@ -0,0 +1,98 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "encoding/json"
5新增: "net/http"
6新增: "net/http/httptest"
7新增: "os"
8新增: "path/filepath"
9新增: "runtime"
10新增: "strings"
11新增: "testing"
12新增:
13新增: "github.com/google/uuid"
14新增: "github.com/sylvinus/agent-vm/internal/guestos"
15新增: "github.com/sylvinus/agent-vm/internal/hostimage"
16新增:)
17新增:
18新增:func TestHostClonePreviewReusesPendingChoiceAndExistingDisk(t *testing.T) {
19新增: if runtime.GOOS != "darwin" || runtime.GOARCH != "arm64" {
20新增: t.Skip("fixture uses the Apple Silicon installation kit")
21新增: }
22新增: s := testServer(t)
23新增: s.exe = filepath.Join(s.profile, "bin", "cage")
24新增: for _, name := range []string{"prepare-macos-media.sh", "provision-macos-workbench.sh", "project/cage-sshfs", "native-browser/macos-native-browser.mjs", "cage-finish-initial-setup"} {
25新增: path := filepath.Join(filepath.Dir(s.exe), "guest-os", name)
26新增: if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
27新增: t.Fatal(err)
28新增: }
29新增: if err := os.WriteFile(path, []byte("fixture"), 0600); err != nil {
30新增: t.Fatal(err)
31新增: }
32新增: }
33新增: plan := hostimage.Plan{
34新增: Host: hostimage.Identity{System: "macos", Version: "26.5", Build: "25F71", Arch: "arm64"},
35新增: Version: "26.5", Build: "25F71", Format: "ipsw", Bytes: 1 << 30,
36新增: URL: "https://updates.cdn-apple.com/fixture.ipsw", Digest: "sha256:" + strings.Repeat("a", 64),
37新增: }
38新增: install := guestos.Installation{Version: 1, ID: uuid.New(), System: "macos", Source: plan}
39新增: if err := guestos.SaveInstallation(s.profile, install); err != nil {
40新增: t.Fatal(err)
41新增: }
42新增: for _, started := range []bool{false, true} {
43新增: if started {
44新增: if err := os.MkdirAll(filepath.Join(s.profile, "state", "lima", "mac"), 0700); err != nil {
45新增: t.Fatal(err)
46新增: }
47新增: }
48新增: r := httptest.NewRequest(http.MethodGet, "/api/environment/guest-systems/clone", nil)
49新增: r.AddCookie(&http.Cookie{Name: s.cookieName() + "-desktop", Value: trustedViewProof(s.token)})
50新增: w := httptest.NewRecorder()
51新增: s.hostClone(w, r)
52新增: if w.Code != http.StatusOK {
53新增: t.Fatalf("preview: %d %s", w.Code, w.Body.String())
54新增: }
55新增: var result struct {
56新增: Plan hostimage.Plan `json:"plan"`
57新增: MinimumFreeGiB int `json:"minimum_free_gib"`
58新增: InstallationStarted bool `json:"installation_started"`
59新增: }
60新增: if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {
61新增: t.Fatal(err)
62新增: }
63新增: minimum := 33
64新增: if started {
65新增: minimum = 1
66新增: }
67新增: if result.Plan != plan || result.MinimumFreeGiB != minimum || result.InstallationStarted != started {
68新增: t.Fatalf("pending source or remaining disk budget changed: %+v", result)
69新增: }
70新增: }
71新增:}
72新增:
73新增:func TestPendingLinuxCloneRetryReturnsToInstallerAdmission(t *testing.T) {
74新增: if runtime.GOOS == "linux" {
75新增: t.Skip("this case verifies rejection on a different host family")
76新增: }
77新增: s := testServer(t)
78新增: install := guestos.Installation{
79新增: Version: 1, ID: uuid.New(), System: "ubuntu-22.04",
80新增: Source: hostimage.Plan{
81新增: Host: hostimage.Identity{System: "ubuntu-22.04", Version: "22.04", Arch: "amd64"},
82新增: Version: "22.04", Format: "qcow2", Path: filepath.Join(s.profile, "ubuntu.img"),
83新增: Digest: "sha256:" + strings.Repeat("a", 64),
84新增: },
85新增: }
86新增: if err := guestos.SaveInstallation(s.profile, install); err != nil {
87新增: t.Fatal(err)
88新增: }
89新增: for _, body := range []string{`{}`, `{"guest_system":"ubuntu-22.04"}`} {
90新增: r := httptest.NewRequest(http.MethodPost, "/api/start", strings.NewReader(body))
91新增: r.AddCookie(&http.Cookie{Name: s.cookieName() + "-desktop", Value: trustedViewProof(s.token)})
92新增: w := httptest.NewRecorder()
93新增: s.start(w, r)
94新增: if w.Code == http.StatusOK || s.jobs.snapshot().Running {
95新增: t.Fatal("pending clone bypassed installer admission through the generic start path")
96新增: }
97新增: }
98新增:}
修改internal/workbench/image_input.go+179 −8看文件
@@ -15,6 +15,131 @@ import (
1515
1616const maxImageBytes = 20 << 20
1717
18新增:type imageInputRequest struct {
19新增: PNG string `json:"png"`
20新增: Text *string `json:"text,omitempty"`
21新增: Target string `json:"target"`
22新增: ID string `json:"id"`
23新增: Transfer string `json:"transfer,omitempty"`
24新增: Context string `json:"context,omitempty"`
25新增: Window uint32 `json:"window,omitempty"`
26新增: PID int32 `json:"pid,omitempty"`
27新增:}
28新增:
29新增:func (s *Server) pasteInputStart(w http.ResponseWriter, r *http.Request) {
30新增: var input imageInputRequest
31新增: if !readJSON(w, r, &input) {
32新增: return
33新增: }
34新增: if input.Target == "browser" && (input.ID == "" || len(input.ID) > 256) {
35新增: http.Error(w, "请选择粘贴的网页", http.StatusBadRequest)
36新增: return
37新增: }
38新增: if !s.fileTargetReady(input.Target, input.ID) {
39新增: http.Error(w, "图片接收位置已关闭,请重新点击输入框", http.StatusConflict)
40新增: return
41新增: }
42新增: ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
43新增: defer cancel()
44新增: if input.Target == "terminal" {
45新增: jsonReply(w, map[string]any{"available": true, "context": input.ID})
46新增: return
47新增: }
48新增: if input.Target == "desktop" {
49新增: body, _ := json.Marshal(map[string]any{"kind": "image", "window": input.Window, "pid": input.PID})
50新增: result, err := s.guestFiles(ctx, "desktop", "POST", "/start", bytes.NewReader(body), "")
51新增: id, _ := result["id"].(string)
52新增: if err != nil || !browserFileID.MatchString(id) {
53新增: http.Error(w, "图片目标未能绑定,请重新点击输入框;旧客机需要先同步环境组件", http.StatusConflict)
54新增: return
55新增: }
56新增: jsonReply(w, map[string]any{"available": true, "transfer": id})
57新增: return
58新增: }
59新增: if s.macosGuest != nil || s.windowsGuest != nil {
60新增: data, err := s.nativeBrowserClient().request(ctx, "POST", "/paste-start", map[string]any{"id": input.ID, "length": 0})
61新增: var result struct {
62新增: Transfer string `json:"transfer"`
63新增: }
64新增: if err != nil || json.Unmarshal(data, &result) != nil || !validInputToken(result.Transfer) {
65新增: http.Error(w, "图片目标未能绑定,请重新点击输入框;旧客机需要先同步环境组件", http.StatusConflict)
66新增: return
67新增: }
68新增: jsonReply(w, map[string]any{"available": true, "transfer": result.Transfer})
69新增: return
70新增: }
71新增: data, err := s.browserAction(ctx, "ime", &browserInput{Target: "browser", ID: input.ID, Mode: "status"})
72新增: var state struct {
73新增: Available bool `json:"available"`
74新增: Context string `json:"context"`
75新增: }
76新增: if err != nil || json.Unmarshal(data, &state) != nil || !state.Available || !validInputToken(state.Context) {
77新增: http.Error(w, "图片接收位置尚未聚焦,请点击输入框后重试", http.StatusConflict)
78新增: return
79新增: }
80新增: jsonReply(w, map[string]any{"available": true, "context": state.Context})
81新增:}
82新增:
83新增:func (s *Server) pasteInputCancel(w http.ResponseWriter, r *http.Request) {
84新增: var input imageInputRequest
85新增: if !readJSON(w, r, &input) {
86新增: return
87新增: }
88新增: ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
89新增: defer cancel()
90新增: if input.Target == "desktop" && browserFileID.MatchString(input.Transfer) {
91新增: body, _ := json.Marshal(map[string]string{"id": input.Transfer})
92新增: _, _ = s.guestFiles(ctx, "desktop", "POST", "/cancel", bytes.NewReader(body), "")
93新增: } else if input.Target == "browser" && validInputToken(input.Transfer) && (s.macosGuest != nil || s.windowsGuest != nil) {
94新增: _, _ = s.nativeBrowserClient().request(ctx, "POST", "/paste-cancel", map[string]string{"transfer": input.Transfer})
95新增: }
96新增: jsonReply(w, map[string]bool{"ok": true})
97新增:}
98新增:
99新增:func (s *Server) textInput(w http.ResponseWriter, r *http.Request) {
100新增: var input imageInputRequest
101新增: if !readJSON(w, r, &input, 6*(2<<20)+4096) {
102新增: return
103新增: }
104新增: if input.Target != "browser" || input.ID == "" || len(input.ID) > 256 || input.Text == nil || len(*input.Text) > 2<<20 {
105新增: http.Error(w, "粘贴文字或目标无效,文本最多 2 MiB", http.StatusBadRequest)
106新增: return
107新增: }
108新增: if !s.fileTargetReady("browser", input.ID) {
109新增: http.Error(w, "网页已关闭或环境尚未就绪", http.StatusConflict)
110新增: return
111新增: }
112新增: ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
113新增: defer cancel()
114新增: if *input.Text == "" {
115新增: jsonReply(w, map[string]bool{"ok": true})
116新增: return
117新增: }
118新增: var err error
119新增: if s.macosGuest != nil || s.windowsGuest != nil {
120新增: if !validInputToken(input.Transfer) {
121新增: http.Error(w, "粘贴目标尚未绑定,请重新点击输入框", http.StatusConflict)
122新增: return
123新增: }
124新增: _, err = s.nativeBrowserClient().pasteData(ctx, input.ID, []byte(*input.Text), input.Transfer, "text/plain")
125新增: } else {
126新增: if !validInputToken(input.Context) {
127新增: http.Error(w, "粘贴目标尚未绑定,请重新点击输入框", http.StatusConflict)
128新增: return
129新增: }
130新增: body, _ := json.Marshal(map[string]string{"id": input.ID, "text": *input.Text, "context": input.Context})
131新增: s.mu.Lock()
132新增: token := s.credentials.Token
133新增: s.mu.Unlock()
134新增: _, err = s.guestAPI(ctx, token, "POST", "/paste-text", body)
135新增: }
136新增: if err != nil {
137新增: http.Error(w, "文字未能交给原输入位置,请核对页面与客机组件后重试", http.StatusConflict)
138新增: return
139新增: }
140新增: jsonReply(w, map[string]bool{"ok": true})
141新增:}
142新增:
18143func decodeInputImage(encoded string) ([]byte, error) {
19144 if len(encoded) > base64.StdEncoding.EncodedLen(maxImageBytes) {
20145 return nil, errors.New("图片不能超过 20 MB")
@@ -34,11 +159,7 @@ func decodeInputImage(encoded string) ([]byte, error) {
34159}
35160
36161func (s *Server) imageInput(w http.ResponseWriter, r *http.Request) {
37删除: var input struct {
38删除: PNG string `json:"png"`
39删除: Target string `json:"target"`
40删除: ID string `json:"id"`
41删除: }
162新增: var input imageInputRequest
42163 if !readJSON(w, r, &input, int64(base64.StdEncoding.EncodedLen(maxImageBytes)+4096)) {
43164 return
44165 }
@@ -74,7 +195,18 @@ func (s *Server) imageInput(w http.ResponseWriter, r *http.Request) {
74195 ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
75196 defer cancel()
76197 if input.Target == "browser" {
77删除: body, _ := json.Marshal(map[string]string{"id": input.ID, "png": input.PNG})
198新增: if input.Context != "" && s.macosGuest == nil && s.windowsGuest == nil {
199新增: state, checkErr := s.browserAction(ctx, "ime", &browserInput{Target: "browser", ID: input.ID, Mode: "status"})
200新增: var current struct {
201新增: Available bool `json:"available"`
202新增: Context string `json:"context"`
203新增: }
204新增: if checkErr != nil || json.Unmarshal(state, &current) != nil || !current.Available || current.Context != input.Context {
205新增: http.Error(w, "图片接收位置已变化,请重新粘贴", http.StatusConflict)
206新增: return
207新增: }
208新增: }
209新增: body, _ := json.Marshal(map[string]string{"id": input.ID, "png": input.PNG, "transfer": input.Transfer})
78210 if _, err = s.guestAPI(ctx, token, "POST", "/paste-image", body); err != nil {
79211 http.Error(w, "图片未能粘贴,请点击支持图片的输入框后重试;环境组件过旧时请先更新环境", 502)
80212 return
@@ -82,7 +214,24 @@ func (s *Server) imageInput(w http.ResponseWriter, r *http.Request) {
82214 jsonReply(w, map[string]bool{"ok": true})
83215 return
84216 }
85删除: result, err := s.guestImage(ctx, input.Target, data)
217新增: if input.Target == "desktop" {
218新增: if !browserFileID.MatchString(input.Transfer) {
219新增: http.Error(w, "图片目标尚未绑定,请重新点击输入框后粘贴", http.StatusConflict)
220新增: return
221新增: }
222新增: if _, err = s.guestFiles(ctx, "desktop", "POST", "/upload?id="+input.Transfer, bytes.NewReader(data), "image.png"); err == nil {
223新增: body, _ := json.Marshal(map[string]string{"id": input.Transfer})
224新增: var result map[string]any
225新增: result, err = s.guestFiles(ctx, "desktop", "POST", "/finish-image", bytes.NewReader(body), "")
226新增: if err == nil {
227新增: jsonReply(w, result)
228新增: return
229新增: }
230新增: }
231新增: http.Error(w, "图片未能交给原输入位置,请核对窗口和客机组件后重新粘贴", http.StatusConflict)
232新增: return
233新增: }
234新增: result, err := s.guestImage(ctx, input.Target, data, macOSWindowRequest{Window: input.Window, PID: input.PID})
86235 if err != nil {
87236 http.Error(w, err.Error(), 502)
88237 return
@@ -90,7 +239,29 @@ func (s *Server) imageInput(w http.ResponseWriter, r *http.Request) {
90239 jsonReply(w, result)
91240}
92241
93删除:func (s *Server) guestImage(ctx context.Context, target string, data []byte) (map[string]any, error) {
242新增:func (s *Server) guestImage(ctx context.Context, target string, data []byte, window macOSWindowRequest) (map[string]any, error) {
243新增: if s.macosGuest != nil && target == "desktop" {
244新增: return s.macOSPasteDesktopImage(ctx, data, window)
245新增: }
246新增: if s.macosGuest != nil && target == "terminal" {
247新增: result, err := s.guestFiles(ctx, target, "POST", "/upload", bytes.NewReader(data), "image.png")
248新增: if err != nil {
249新增: return nil, err
250新增: }
251新增: path, _ := result["path"].(string)
252新增: if !s.validMacOSAttachmentPath(path, "image.png") {
253新增: return nil, errors.New("图片保存路径无效")
254新增: }
255新增: return result, nil
256新增: }
257新增: if s.windowsGuest != nil {
258新增: if target == "terminal" {
259新增: return s.windowsSaveAttachment(ctx, "image.png", bytes.NewReader(data))
260新增: }
261新增: var result map[string]any
262新增: err := s.windowsDesktopRequest(ctx, "paste-image", map[string]any{"png": base64.StdEncoding.EncodeToString(data)}, &result)
263新增: return result, err
264新增: }
94265 script := "sudo -H -u cage /usr/local/bin/cage-image-input save"
95266 if target == "desktop" {
96267 script = "systemctl is-active --quiet cage-claude-desktop.service && sudo -H -u cage env DISPLAY=:78 XAUTHORITY=/run/cage-desktop/Xauthority /usr/local/bin/cage-image-input paste"
新增internal/workbench/initialization.go+130 −0看文件
@@ -0,0 +1,130 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "encoding/json"
5新增: "errors"
6新增: "net/http"
7新增: "os"
8新增: "path/filepath"
9新增: "time"
10新增:
11新增: "github.com/sylvinus/agent-vm/internal/cage"
12新增: "github.com/sylvinus/agent-vm/internal/guestos"
13新增:)
14新增:
15新增:type initializationRecord struct {
16新增: Version int `json:"version"`
17新增: Completed bool `json:"completed"`
18新增: Started bool `json:"started,omitempty"`
19新增:}
20新增:
21新增:type initializationView struct {
22新增: Required bool `json:"required"`
23新增: Started bool `json:"started"`
24新增: Tracked bool `json:"tracked"`
25新增:}
26新增:
27新增:func (s *Server) initializationState() (initializationView, error) {
28新增: if !s.localVMStorage() {
29新增: return initializationView{}, nil
30新增: }
31新增: data, err := os.ReadFile(filepath.Join(s.profile, "initialization.json"))
32新增: if err == nil {
33新增: var record initializationRecord
34新增: if json.Unmarshal(data, &record) != nil || record.Version != 1 {
35新增: return initializationView{}, errors.New("初始化记录无法读取,请保留现有数据并导出诊断包")
36新增: }
37新增: return initializationView{Required: !record.Completed || s.macSetupPending(), Started: record.Started, Tracked: true}, nil
38新增: }
39新增: if !errors.Is(err, os.ErrNotExist) {
40新增: return initializationView{}, err
41新增: }
42新增: // Existing installations predate this screen. A directory or partial disk
43新增: // alone is not proof of a completed Linux installation.
44新增: pending, err := guestos.LoadInstallation(s.profile)
45新增: if err != nil {
46新增: return initializationView{}, err
47新增: }
48新增: if s.macosGuest != nil || s.windowsGuest != nil {
49新增: return initializationView{Required: s.macSetupPending()}, nil
50新增: }
51新增: return initializationView{Required: pending != nil || !s.environmentPrepared(), Started: pending != nil}, nil
52新增:}
53新增:
54新增:func (s *Server) finishInitialization() error {
55新增: if s.macSetupPending() {
56新增: return errors.New("请先完成客机的系统权限确认")
57新增: }
58新增: s.mu.Lock()
59新增: ready, gate := s.ready, s.safety.Gate
60新增: s.mu.Unlock()
61新增: if !ready || !s.vmRunning() {
62新增: return errors.New("客机尚未就绪,请继续安装并完成启动检查")
63新增: }
64新增: cfg, err := loadConfig(s.configPath)
65新增: if err != nil {
66新增: return err
67新增: }
68新增: if err := cfg.RequireManagedProxy(s.profile); err != nil {
69新增: return err
70新增: }
71新增: if gate == nil || gate.Mode != cage.GateOpen || !gate.PolicyVerified || gate.Fault || gate.Report == nil || !gate.Until.After(time.Now()) || gate.Configuration != cfg.Fingerprint() || gate.Report.Authorizes(gate.RunID, cfg.Fingerprint(), time.Now()) != nil {
72新增: return errors.New("环境网络检查尚未通过,请在初始化界面重新检查")
73新增: }
74新增: return writePrivate(filepath.Join(s.profile, "initialization.json"), initializationRecord{Version: 1, Completed: true})
75新增:}
76新增:
77新增:func (s *Server) initialization(w http.ResponseWriter, r *http.Request) {
78新增: if r.Method == http.MethodGet {
79新增: state, err := s.initializationState()
80新增: if err != nil {
81新增: requestError(w, err)
82新增: return
83新增: }
84新增: jsonReply(w, state)
85新增: return
86新增: }
87新增: if !s.hasTrustedView(r) || !s.localVMStorage() {
88新增: http.Error(w, "请在本机 Cage 窗口完成初始化", http.StatusForbidden)
89新增: return
90新增: }
91新增: var input struct {
92新增: Action string `json:"action"`
93新增: }
94新增: if !readJSON(w, r, &input) {
95新增: return
96新增: }
97新增: if !s.op.TryLock() {
98新增: http.Error(w, "环境操作仍在进行,请等待完成后继续", http.StatusConflict)
99新增: return
100新增: }
101新增: defer s.op.Unlock()
102新增: if s.busy() {
103新增: http.Error(w, "环境操作仍在进行,请等待完成后继续", http.StatusConflict)
104新增: return
105新增: }
106新增: state, err := s.initializationState()
107新增: if err != nil {
108新增: requestError(w, err)
109新增: return
110新增: }
111新增: switch input.Action {
112新增: case "begin":
113新增: if state.Required {
114新增: err = writePrivate(filepath.Join(s.profile, "initialization.json"), initializationRecord{Version: 1, Started: state.Started})
115新增: }
116新增: case "install":
117新增: if state.Required {
118新增: err = writePrivate(filepath.Join(s.profile, "initialization.json"), initializationRecord{Version: 1, Started: true})
119新增: }
120新增: case "complete":
121新增: err = s.finishInitialization()
122新增: default:
123新增: err = errors.New("未知的初始化操作")
124新增: }
125新增: if err != nil {
126新增: requestError(w, err)
127新增: return
128新增: }
129新增: jsonReply(w, map[string]bool{"completed": input.Action == "complete" || !state.Required})
130新增:}
新增internal/workbench/initialization_test.go+130 −0看文件
@@ -0,0 +1,130 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "encoding/json"
5新增: "net/http"
6新增: "net/http/httptest"
7新增: "os"
8新增: "path/filepath"
9新增: "strings"
10新增: "testing"
11新增: "time"
12新增:
13新增: "github.com/sylvinus/agent-vm/internal/cage"
14新增: "github.com/sylvinus/agent-vm/internal/guestos"
15新增:)
16新增:
17新增:func initializationRequest(s *Server, action string, trusted bool) *httptest.ResponseRecorder {
18新增: method, body := http.MethodGet, ""
19新增: if action != "" {
20新增: method, body = http.MethodPost, `{"action":"`+action+`"}`
21新增: }
22新增: r := httptest.NewRequest(method, s.origin+"/api/environment/initialization", strings.NewReader(body))
23新增: r.Header.Set("Origin", s.origin)
24新增: r.Header.Set("Content-Type", "application/json")
25新增: r.AddCookie(&http.Cookie{Name: s.cookieName(), Value: s.session})
26新增: if trusted {
27新增: r.AddCookie(&http.Cookie{Name: s.cookieName() + "-desktop", Value: trustedViewProof(s.token)})
28新增: }
29新增: w := httptest.NewRecorder()
30新增: s.handler().ServeHTTP(w, r)
31新增: return w
32新增:}
33新增:
34新增:func TestInitializationPersistsBeforeDiskCreationAndDoesNotResetExisting(t *testing.T) {
35新增: s := testServer(t)
36新增: read := func() initializationView {
37新增: t.Helper()
38新增: w := initializationRequest(s, "", true)
39新增: var view initializationView
40新增: if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &view) != nil {
41新增: t.Fatalf("initialization: %d %s", w.Code, w.Body.String())
42新增: }
43新增: return view
44新增: }
45新增: if !read().Required {
46新增: t.Fatal("fresh profile bypassed initialization")
47新增: }
48新增: for _, action := range []string{"begin", "install"} {
49新增: if w := initializationRequest(s, action, true); w.Code != 200 {
50新增: t.Fatal(w.Code, w.Body.String())
51新增: }
52新增: }
53新增: if err := os.MkdirAll(filepath.Join(s.profile, "state"), 0700); err != nil {
54新增: t.Fatal(err)
55新增: }
56新增: if err := os.WriteFile(filepath.Join(s.profile, "state", ".agent-vm-base-version"), []byte("fixture"), 0600); err != nil {
57新增: t.Fatal(err)
58新增: }
59新增: view := read()
60新增: if !view.Required || !view.Started || !view.Tracked {
61新增: t.Fatalf("partial installation bypassed durable state: %+v", view)
62新增: }
63新增: // A new controller sees the same state, even after creating its base disk.
64新增: restarted := testServer(t)
65新增: restarted.profile = s.profile
66新增: if next, err := restarted.initializationState(); err != nil || !next.Required || !next.Started {
67新增: t.Fatalf("restart: %+v %v", next, err)
68新增: }
69新增: if err := os.Remove(filepath.Join(s.profile, "initialization.json")); err != nil {
70新增: t.Fatal(err)
71新增: }
72新增: if read().Required {
73新增: t.Fatal("existing Linux installation forced to reinstall")
74新增: }
75新增: s.windowsGuest = &guestos.WindowsProfile{}
76新增: if next, err := s.initializationState(); err != nil || next.Required {
77新增: t.Fatalf("existing Windows installation: %+v %v", next, err)
78新增: }
79新增: s.windowsGuest = nil
80新增: s.macosGuest = &guestos.MacOSProfile{}
81新增: if next, err := s.initializationState(); err != nil || next.Required {
82新增: t.Fatalf("existing Mac installation: %+v %v", next, err)
83新增: }
84新增:}
85新增:
86新增:func TestInitializationCompletionRequiresReadyGuestAndCurrentNetworkEvidence(t *testing.T) {
87新增: s := testServer(t)
88新增: if w := initializationRequest(s, "begin", false); w.Code != http.StatusForbidden {
89新增: t.Fatal("untrusted initialization accepted", w.Code)
90新增: }
91新增: if w := initializationRequest(s, "install", true); w.Code != 200 {
92新增: t.Fatal(w.Code, w.Body.String())
93新增: }
94新增: if w := initializationRequest(s, "complete", true); w.Code == 200 {
95新增: t.Fatal("unready guest accepted")
96新增: }
97新增: s.windowsGuest = &guestos.WindowsProfile{}
98新增: s.windowsState.Running = true
99新增: s.ready = true
100新增: if w := initializationRequest(s, "complete", true); w.Code == 200 {
101新增: t.Fatal("missing network report accepted")
102新增: }
103新增: cfg, err := cage.Load(s.configPath)
104新增: if err != nil {
105新增: t.Fatal(err)
106新增: }
107新增: report := cage.SafetyReport{Policy: cage.SafetyPolicyVersion, ID: "initialization", RunID: "test-vm", CheckID: "test-check", Configuration: cfg.Fingerprint(), CreatedAt: time.Now()}
108新增: for _, id := range []string{"egress_policy", "proxy_transport", "dns_transport", "guest_settings", "browser_settings", "filesystem_boundary", "management_boundary", "fail_closed", "udp_policy", "ipv6_policy", "exit_consistency"} {
109新增: report.Checks = append(report.Checks, cage.SafetyCheck{ID: id, Critical: true, State: cage.CheckPassed, Evidence: "isolated test", CheckedAt: report.CreatedAt})
110新增: }
111新增: s.safety.Gate = &cage.GateStatus{Mode: cage.GateOpen, PolicyVerified: true, RunID: report.RunID, Configuration: cfg.Fingerprint(), Until: time.Now().Add(time.Minute), Report: &report}
112新增: s.setJobForTest(Job{Running: true, Kind: "start"})
113新增: if w := initializationRequest(s, "complete", true); w.Code == 200 {
114新增: t.Fatal("unfinished job accepted")
115新增: }
116新增: s.setJobForTest(Job{})
117新增: s.safety.Gate.Configuration = "another-config"
118新增: if w := initializationRequest(s, "complete", true); w.Code == 200 {
119新增: t.Fatal("stale configuration accepted")
120新增: }
121新增: s.safety.Gate.Configuration = cfg.Fingerprint()
122新增: if w := initializationRequest(s, "complete", true); w.Code != 200 {
123新增: t.Fatal(w.Code, w.Body.String())
124新增: }
125新增: s.ready = false
126新增: s.windowsState.Running = false
127新增: if view, err := s.initializationState(); err != nil || view.Required {
128新增: t.Fatalf("completed stopped environment lost initialization: %+v %v", view, err)
129新增: }
130新增:}
修改internal/workbench/job_manager_test.go+20 −4看文件
@@ -3,6 +3,7 @@ package workbench
33import (
44 "context"
55 "errors"
6新增: "fmt"
67 "strings"
78 "sync"
89 "sync/atomic"
@@ -134,7 +135,7 @@ func TestJobManagerRepeatedStopCanRequestLogout(t *testing.T) {
134135 close(started)
135136 <-release
136137 if stopFails {
137删除: return errors.New("stop failed")
138新增: return errors.New("测试模拟:环境停止失败")
138139 }
139140 return nil
140141 })
@@ -161,7 +162,7 @@ func TestJobManagerRepeatedStopCanRequestLogout(t *testing.T) {
161162 }
162163 state := awaitJobIdle(t, &manager)
163164 if stopFails {
164删除: if locked.Load() != 0 || state.Error != "stop failed" {
165新增: if locked.Load() != 0 || state.Error != "测试模拟:环境停止失败" {
165166 t.Fatalf("failed stop locked account: %+v count=%d", state, locked.Load())
166167 }
167168 } else if locked.Load() != 1 || state.Error != "" {
@@ -248,7 +249,7 @@ func TestJobManagerFinalizationAndOutput(t *testing.T) {
248249 t.Fatal("output without an execution changed state")
249250 }
250251 _, err := manager.submit(&operation, "stop", 0, nil, func() error {
251删除: return errors.New("account could not be locked")
252新增: return errors.New("无法写入账户锁定状态")
252253 }, func() error {
253254 _, _ = manager.execution().Write([]byte(strings.Repeat("a\n", 12500) + "tail"))
254255 return nil
@@ -257,9 +258,24 @@ func TestJobManagerFinalizationAndOutput(t *testing.T) {
257258 t.Fatal(err)
258259 }
259260 state := awaitJobIdle(t, &manager)
260删除: if state.Error != "account could not be locked" || len(state.Log) != 24000 || !strings.HasSuffix(state.Log, "tail\n") {
261新增: if state.Error != "无法写入账户锁定状态" || len(state.Log) > 24000 || !strings.Contains(state.Log, "12499 additional times") || !strings.HasSuffix(state.Log, "tail\n") {
261262 t.Fatalf("finalization error or bounded log lost: %+v", state)
262263 }
264新增: _, err = manager.submit(&operation, "stop", 0, nil, nil, func() error {
265新增: var output strings.Builder
266新增: for i := 0; i < 4000; i++ {
267新增: fmt.Fprintf(&output, "different line %d\n", i)
268新增: }
269新增: _, _ = manager.execution().Write([]byte(output.String()))
270新增: return nil
271新增: })
272新增: if err != nil {
273新增: t.Fatal(err)
274新增: }
275新增: state = awaitJobIdle(t, &manager)
276新增: if len(state.Log) != 24000 || !strings.HasSuffix(state.Log, "different line 3999\n") {
277新增: t.Fatal("distinct output lost its bound or final line")
278新增: }
263279}
264280
265281func TestJobManagerRejectedPreparationDoesNotPublishJob(t *testing.T) {
修改internal/workbench/jobs.go+31 −9看文件
@@ -5,9 +5,11 @@ import (
55 "errors"
66 "fmt"
77 "github.com/sylvinus/agent-vm/internal/diagnostics"
8新增: "github.com/sylvinus/agent-vm/internal/usererror"
89 "runtime/debug"
910 "strings"
1011 "sync"
12新增: "time"
1113)
1214
1315type Job struct {
@@ -56,7 +58,7 @@ func (m *jobManager) submit(operation sync.Locker, kind string, pauseVersion uin
5658 return m.state, nil
5759 }
5860 if kind != "stop" {
59删除: return Job{}, errJobBusy
61新增: return Job{}, fmt.Errorf("%w:当前正在%s。请等待完成,或先停止当前操作。", errJobBusy, jobName(m.state.Kind))
6062 }
6163 }
6264 if prepare != nil {
@@ -76,6 +78,15 @@ func (m *jobManager) submit(operation sync.Locker, kind string, pauseVersion uin
7678 if m.state.ID == execution.id {
7779 if m.state.SetupProgress != nil {
7880 if p := parseSetupProgress(line); p != nil {
81新增: previous := m.state.SetupProgress
82新增: if p.System == "" {
83新增: p.System = previous.System
84新增: }
85新增: now := time.Now()
86新增: if p.Operation != "verify" && p.Label == previous.Label && p.Total == previous.Total && p.Received != nil && previous.Received != nil && *p.Received >= *previous.Received && !execution.progressUpdated.IsZero() {
87新增: p.BytesPerSecond = float64(*p.Received-*previous.Received) / now.Sub(execution.progressUpdated).Seconds()
88新增: }
89新增: execution.progressUpdated = now
7990 m.state.SetupProgress = p
8091 if strings.HasPrefix(line, "CAGE_") {
8192 return
@@ -146,15 +157,25 @@ func (m *jobManager) finishLocked(execution *jobExecution, err error) {
146157 m.state.Message = "已取消"
147158 diagnostics.Log("info", "task", m.state.Kind+" canceled")
148159 case err != nil:
149删除: m.state.Error = err.Error()
150删除: m.state.Message = "操作未完成"
151删除: diagnostics.Log("error", "task", m.state.Kind+": "+err.Error())
160新增: m.state.Error = usererror.Display(jobName(m.state.Kind), err, "打开“操作详情”查看失败记录;仍无法处理时,"+failureHelp).Error()
161新增: m.state.Message = jobName(m.state.Kind) + "失败"
162新增: diagnostics.Log("error", "task", fmt.Sprintf("%s: %v; cause=%v", m.state.Kind, err, errors.Unwrap(err)))
152163 default:
153164 m.state.Message = "已完成"
154165 diagnostics.Log("info", "task", m.state.Kind+" completed")
155166 }
156167}
157168
169新增:func jobName(kind string) string {
170新增: names := map[string]string{
171新增: "start": "启动环境", "stop": "停止环境", "setup": "准备环境", "settings": "应用设置", "project": "连接项目目录", "storage": "迁移环境目录", "restore": "恢复配置", "resources": "应用资源配置", "safety": "检查联网条件", "network-recovery": "恢复联网", "proxy": "应用代理节点", "proxy-network": "恢复代理连接", "environment-update": "更新环境组件", "environment-tools": "更新环境工具", "claude-desktop-install": "安装 Claude Desktop", "claude-desktop-start": "打开 Claude Desktop", "claude-desktop-stop": "关闭 Claude Desktop",
172新增: }
173新增: if name := names[kind]; name != "" {
174新增: return name
175新增: }
176新增: return "本次操作"
177新增:}
178新增:
158179func (m *jobManager) snapshot() Job {
159180 m.mu.Lock()
160181 defer m.mu.Unlock()
@@ -197,11 +218,12 @@ func (m *jobManager) close() {
197218}
198219
199220type jobExecution struct {
200删除: owner *jobManager
201删除: id string
202删除: ctx context.Context
203删除: pauseVersion uint64
204删除: log *diagnostics.Stream
221新增: owner *jobManager
222新增: id string
223新增: ctx context.Context
224新增: pauseVersion uint64
225新增: log *diagnostics.Stream
226新增: progressUpdated time.Time
205227}
206228
207229func (e *jobExecution) message(message string) {
修改internal/workbench/jobs_service.go+1 −1看文件
@@ -19,7 +19,7 @@ func (s *Server) submitJob(kind string, run func() error) (Job, error) {
1919 }
2020 intentFailed := false
2121 job, err := s.jobs.submit(&s.op, kind, s.safety.pauseVersion, func() error {
22删除: if kind == "start" || kind == "safety" || kind == "restore" {
22新增: if kind == "safety" || (s.macosGuest == nil && (kind == "start" || kind == "restore")) {
2323 if err := s.saveNetworkIntentLocked(false); err != nil {
2424 intentFailed = true
2525 return err
修改internal/workbench/jobs_service_test.go+2 −1看文件
@@ -8,6 +8,7 @@ import (
88 "net/http"
99 "net/http/httptest"
1010 "os"
11新增: "strings"
1112 "sync"
1213 "testing"
1314 "time"
@@ -51,7 +52,7 @@ func TestLogoutJoinsRunningStopAndLocksOnlyAfterSuccess(t *testing.T) {
5152 state := awaitJobIdle(t, &s.jobs)
5253 view := s.account.view()
5354 if fail {
54删除: if !view.Unlocked || view.RequireAuthentication || state.Error != "could not stop environment" {
55新增: if !view.Unlocked || view.RequireAuthentication || !strings.Contains(state.Error, "停止环境失败") {
5556 t.Fatalf("failed stop changed account access: %+v, job %+v", view, state)
5657 }
5758 return
修改internal/workbench/lifecycle.go+14 −2看文件
@@ -57,7 +57,11 @@ func (s *Server) startMonitors() {
5757 }()
5858 go func() {
5959 defer s.monitors.Done()
60删除: s.monitorNetwork(ctx)
60新增: // macOS performs both probes from the same tick. Its periodic SSH
61新增: // attestation otherwise races this loop for the lifecycle lock.
62新增: if s.macosGuest == nil && (s.windowsGuest == nil || s.windowsGuest.NetworkPairingFile != "") {
63新增: s.monitorNetwork(ctx)
64新增: }
6165 }()
6266}
6367
@@ -113,6 +117,11 @@ func (s *Server) closeService() error {
113117 s.op.Lock()
114118 defer s.op.Unlock()
115119 s.closeProjectShares()
120新增: s.closeWindowsBrowser()
121新增: if s.windowsGuest != nil {
122新增: s.closeErr = s.closeProxyGate("控制服务正在退出,外网保持关闭")
123新增: }
124新增: s.closeWindowsNetwork()
116125 s.mu.Lock()
117126 browser := s.browserControl
118127 s.ready = false
@@ -121,7 +130,10 @@ func (s *Server) closeService() error {
121130 if browser != nil {
122131 browser.close()
123132 }
124删除: s.closeErr = errors.Join(s.closeProxyGate("控制服务正在退出,外网保持关闭"), managedproxy.Stop(s.profile))
133新增: if s.windowsGuest == nil {
134新增: s.closeErr = s.closeProxyGate("控制服务正在退出,外网保持关闭")
135新增: }
136新增: s.closeErr = errors.Join(s.closeErr, managedproxy.Stop(s.profile))
125137 if s.controlPublished {
126138 if err := os.Remove(filepath.Join(s.profile, "control.json")); err != nil && !os.IsNotExist(err) {
127139 s.closeErr = errors.Join(s.closeErr, err)
新增internal/workbench/linux_guest_image.go+51 −0看文件
@@ -0,0 +1,51 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "context"
5新增: "errors"
6新增: "os"
7新增: "path/filepath"
8新增: "runtime"
9新增:
10新增: "github.com/sylvinus/agent-vm/internal/guestos"
11新增: "github.com/sylvinus/agent-vm/internal/hostimage"
12新增: "github.com/sylvinus/agent-vm/internal/limaembed"
13新增:)
14新增:
15新增:func linuxGuestSystems(platform, arch string) []string {
16新增: if platform == "darwin" && arch == "arm64" || (platform == "windows" || platform == "linux") && arch == "amd64" {
17新增: return []string{guestos.Ubuntu2204}
18新增: }
19新增: return nil
20新增:}
21新增:
22新增:func linuxGuestImagePlan(ctx context.Context, profile, system, arch string) (hostimage.Plan, error) {
23新增: if system != guestos.Ubuntu2204 || arch != "amd64" && arch != "arm64" {
24新增: return hostimage.Plan{}, errors.New("此主机暂不支持所选 Linux 客机镜像")
25新增: }
26新增: template, err := limaembed.ReadImageTemplate(system)
27新增: if err != nil {
28新增: return hostimage.Plan{}, err
29新增: }
30新增: home, err := os.UserHomeDir()
31新增: if err != nil {
32新增: return hostimage.Plan{}, err
33新增: }
34新增: identity := hostimage.Identity{System: system, Version: "22.04", Arch: arch}
35新增: // Resolution of a pinned Linux image is local. Downloads use the existing
36新增: // installer transport only after the user submits the installation.
37新增: return hostimage.Resolve(ctx, identity, filepath.Join(profile, "state", "guest-media", system), filepath.Join(home, "Downloads"), template, nil)
38新增:}
39新增:
40新增:func (s *Server) installedLinuxSystem() (string, error) {
41新增: return hostimage.LinuxSystem(filepath.Join(s.profile, "state"))
42新增:}
43新增:
44新增:func canInstallCatalogLinux(system string) bool {
45新增: for _, candidate := range linuxGuestSystems(runtime.GOOS, runtime.GOARCH) {
46新增: if system == candidate {
47新增: return true
48新增: }
49新增: }
50新增: return false
51新增:}
新增internal/workbench/linux_guest_image_test.go+102 −0看文件
@@ -0,0 +1,102 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "encoding/json"
5新增: "net/http"
6新增: "net/http/httptest"
7新增: "os"
8新增: "path/filepath"
9新增: "runtime"
10新增: "strings"
11新增: "testing"
12新增:
13新增: "github.com/google/uuid"
14新增: "github.com/sylvinus/agent-vm/internal/guestos"
15新增: "github.com/sylvinus/agent-vm/internal/hostimage"
16新增:)
17新增:
18新增:func TestUbuntuGuestChoicesMatchSupportedHostArchitectures(t *testing.T) {
19新增: for _, host := range []struct {
20新增: platform, arch string
21新增: available bool
22新增: }{
23新增: {"darwin", "arm64", true}, {"windows", "amd64", true}, {"linux", "amd64", true},
24新增: {"darwin", "amd64", false}, {"windows", "arm64", false}, {"linux", "arm64", false},
25新增: } {
26新增: if got := linuxGuestSystems(host.platform, host.arch); (len(got) == 1 && got[0] == guestos.Ubuntu2204) != host.available {
27新增: t.Fatalf("%s/%s: %v", host.platform, host.arch, got)
28新增: }
29新增: }
30新增:}
31新增:
32新增:func TestUbuntuCatalogPlanPreservesArchitectureAndResumeChoice(t *testing.T) {
33新增: for _, arch := range []string{"amd64", "arm64"} {
34新增: plan, err := linuxGuestImagePlan(t.Context(), t.TempDir(), guestos.Ubuntu2204, arch)
35新增: if err != nil || plan.Host.Arch != arch || !strings.Contains(plan.URL, "-"+arch+".img") || plan.Bytes <= 0 {
36新增: t.Fatalf("%s: %+v %v", arch, plan, err)
37新增: }
38新增: }
39新增: s := testServer(t)
40新增: plan, err := linuxGuestImagePlan(t.Context(), s.profile, guestos.Ubuntu2204, runtime.GOARCH)
41新增: if err != nil {
42新增: t.Fatal(err)
43新增: }
44新增: install := guestos.Installation{Version: 1, ID: uuid.New(), System: guestos.Ubuntu2204, Source: plan, SourceKind: guestos.LinuxImageSource}
45新增: if err := guestos.SaveInstallation(s.profile, install); err != nil {
46新增: t.Fatal(err)
47新增: }
48新增: view, err := s.guestInstallView()
49新增: if err != nil || view.Pending == nil || view.Pending.SourceKind != guestos.LinuxImageSource || !view.Reselect {
50新增: t.Fatalf("cross-host resume: %+v %v", view, err)
51新增: }
52新增: if err := os.MkdirAll(filepath.Join(s.profile, "state", "lima", "base-building"), 0700); err != nil {
53新增: t.Fatal(err)
54新增: }
55新增: view, err = s.guestInstallView()
56新增: if err != nil || view.Reselect {
57新增: t.Fatalf("started disk can be reselected: %+v %v", view, err)
58新增: }
59新增:}
60新增:
61新增:func TestUbuntuSelectionUsesInstallerAndRequiresTrustedDesktop(t *testing.T) {
62新增: for _, trusted := range []bool{false, true} {
63新增: s := testServer(t)
64新增: // Keep accepted work from touching a real VM or network in this admission test.
65新增: s.op.Lock()
66新增: r := httptest.NewRequest(http.MethodPost, "/api/start", strings.NewReader(`{"guest_system":"ubuntu-22.04"}`))
67新增: r.Header.Set("Content-Type", "application/json")
68新增: if trusted {
69新增: r.AddCookie(&http.Cookie{Name: s.cookieName() + "-desktop", Value: trustedViewProof(s.token)})
70新增: }
71新增: w := httptest.NewRecorder()
72新增: s.start(w, r)
73新增: job := s.jobs.snapshot()
74新增: s.jobs.cancelRunning()
75新增: s.op.Unlock()
76新增: s.jobs.workers.Wait()
77新增: if trusted {
78新增: var response Job
79新增: if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &response) != nil || response.Kind != "guest-install" || job.Kind != "guest-install" {
80新增: t.Fatalf("Ubuntu went through generic Debian startup: %d %s", w.Code, w.Body.String())
81新增: }
82新增: } else if w.Code == http.StatusOK {
83新增: t.Fatal("untrusted page started installation")
84新增: }
85新增: }
86新增:}
87新增:
88新增:func TestUbuntuBoundSystemCannotBeStartedAsDebian(t *testing.T) {
89新增: s := testServer(t)
90新增: plan, err := linuxGuestImagePlan(t.Context(), s.profile, guestos.Ubuntu2204, runtime.GOARCH)
91新增: if err != nil {
92新增: t.Fatal(err)
93新增: }
94新增: plan.Path = filepath.Join(s.profile, "ubuntu.img")
95新增: if err := hostimage.WriteLinuxTemplate(filepath.Join(s.profile, "state"), plan); err != nil {
96新增: t.Fatal(err)
97新增: }
98新增: w := request(s, http.MethodPost, "/api/start", s.origin, `{"guest_system":"debian-13"}`, true)
99新增: if w.Code != http.StatusConflict || s.jobs.snapshot().ID != "" {
100新增: t.Fatalf("changed existing Ubuntu: %d %s", w.Code, w.Body.String())
101新增: }
102新增:}
修改internal/workbench/location.go+11 −81看文件
@@ -2,92 +2,22 @@ package workbench
22
33import (
44 "context"
5删除: "encoding/json"
6删除: "errors"
7删除: "fmt"
8删除: "io"
95 "net"
106 "net/http"
11删除: "strings"
12删除: "time"
7新增:
8新增: "github.com/sylvinus/agent-vm/internal/exitpolicy"
139)
1410
15删除:// Both providers look up the measured address, never their connection's exit.
16删除:// The caller supplies the shared proxy-only client, including for fallback.
1711func lookupLocation(ctx context.Context, client *http.Client, address net.IP) (Location, error) {
18删除: providers := []struct{ name, url string }{
19删除: {"ipwho.is", "https://ipwho.is/" + address.String() + "?fields=success,ip,country,country_code,region,region_code,city,timezone.id"},
20删除: {"IP.SB", "https://api.ip.sb/geoip/" + address.String()},
21删除: }
22删除: failures := make([]string, 0, len(providers))
23删除: for _, provider := range providers {
24删除: if err := ctx.Err(); err != nil {
25删除: return Location{}, err
26删除: }
27删除: loc, err := queryLocation(ctx, client, provider.url, provider.name == "ipwho.is", address)
28删除: if err == nil {
29删除: return loc, nil
30删除: }
31删除: // Only our own summaries reach the UI; transport errors may contain
32删除: // local network details and provider bodies are untrusted text.
33删除: failures = append(failures, provider.name+":"+err.Error())
34删除: }
35删除: if err := ctx.Err(); err != nil {
36删除: return Location{}, err
37删除: }
38删除: return Location{}, fmt.Errorf("已测得出口 IP,但位置查询均失败(%s);请重试或切换节点。未使用直连回退", strings.Join(failures, ";"))
39删除:}
40删除:
41删除:func queryLocation(ctx context.Context, client *http.Client, endpoint string, requireSuccess bool, address net.IP) (Location, error) {
42删除: req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
43删除: if err != nil {
44删除: return Location{}, errors.New("查询地址无效")
45删除: }
46删除: req.Header.Set("User-Agent", "Cage-network-check/1")
47删除: r, err := client.Do(req)
12新增: loc, err := exitpolicy.Lookup(ctx, client, address)
4813 if err != nil {
49删除: return Location{}, errors.New("连接失败或超时")
50删除: }
51删除: defer r.Body.Close()
52删除: if r.StatusCode != http.StatusOK {
53删除: return Location{}, fmt.Errorf("HTTP %d", r.StatusCode)
54删除: }
55删除: var v struct {
56删除: Success *bool `json:"success"`
57删除: IP string `json:"ip"`
58删除: Country string `json:"country"`
59删除: CountryCode string `json:"country_code"`
60删除: Region string `json:"region"`
61删除: RegionCode string `json:"region_code"`
62删除: City string `json:"city"`
63删除: Timezone json.RawMessage `json:"timezone"`
64删除: }
65删除: if json.NewDecoder(io.LimitReader(r.Body, 128<<10)).Decode(&v) != nil ||
66删除: (requireSuccess && (v.Success == nil || !*v.Success)) ||
67删除: net.ParseIP(v.IP) == nil || !net.ParseIP(v.IP).Equal(address) {
68删除: return Location{}, errors.New("响应无效或 IP 不匹配")
69删除: }
70删除: country := strings.ToUpper(strings.TrimSpace(v.CountryCode))
71删除: if len(country) != 2 || country[0] < 'A' || country[0] > 'Z' || country[1] < 'A' || country[1] > 'Z' {
72删除: return Location{}, errors.New("缺少有效国家或地区")
73删除: }
74删除: var timezone string
75删除: if requireSuccess {
76删除: var zone struct {
77删除: ID string `json:"id"`
78删除: }
79删除: if json.Unmarshal(v.Timezone, &zone) == nil {
80删除: timezone = zone.ID
81删除: }
82删除: } else {
83删除: _ = json.Unmarshal(v.Timezone, &timezone)
84删除: }
85删除: if timezone == "" || timezone == "Local" {
86删除: return Location{}, errors.New("缺少有效时区")
87删除: }
88删除: if _, err = time.LoadLocation(timezone); err != nil {
89删除: return Location{}, errors.New("缺少有效时区")
14新增: return Location{}, err
9015 }
91删除: locale, browser := languageSuggestion(country)
92删除: return Location{IP: address.String(), Country: v.Country, CountryCode: country, Region: v.Region, RegionCode: v.RegionCode, City: v.City, Timezone: timezone, CheckedAt: time.Now(), SuggestedLocale: locale, SuggestedBrowserLanguage: browser}, nil
16新增: locale, browser := languageSuggestion(loc.CountryCode)
17新增: return Location{
18新增: IP: loc.IP, Country: loc.Country, CountryCode: loc.CountryCode,
19新增: Region: loc.Region, RegionCode: loc.RegionCode, City: loc.City,
20新增: Timezone: loc.Timezone, CheckedAt: loc.CheckedAt,
21新增: SuggestedLocale: locale, SuggestedBrowserLanguage: browser,
22新增: }, nil
9323}
修改internal/workbench/location_test.go+12 −11看文件
@@ -192,8 +192,8 @@ func TestLocationProvidersLiveIntegration(t *testing.T) {
192192 manual.ExitPolicy = policy
193193 manual.Timezone, manual.Locale, manual.BrowserLanguage = "Asia/Shanghai", "zh_CN.UTF-8", "zh-CN"
194194 loc, err := probeEnvironmentLocation(context.Background(), manual, Preferences{})
195删除: if err != nil || loc.IP == "" || loc.Timezone != "" || loc.CountryCode != "" {
196删除: t.Fatal("manual settings required geolocation or lost measured exit", err)
195新增: if err != nil || loc.IP == "" || loc.Timezone == "" || loc.CountryCode == "" {
196新增: t.Fatal("manual settings skipped mandatory country evidence", err)
197197 }
198198 if manual.Timezone != "Asia/Shanghai" || manual.Locale != "zh_CN.UTF-8" || manual.BrowserLanguage != "zh-CN" {
199199 t.Fatal("manual settings changed during probe")
@@ -242,15 +242,16 @@ func TestLocationProvidersLiveIntegration(t *testing.T) {
242242 t.Fatal("manual mode was not applied")
243243 }
244244 })
245删除: for _, provider := range []struct {
246删除: name, url string
247删除: primary bool
248删除: }{
249删除: {"primary", "https://ipwho.is/8.8.8.8?fields=success,ip,country,country_code,region,region_code,city,timezone.id", true},
250删除: {"backup", "https://api.ip.sb/geoip/8.8.8.8", false},
251删除: } {
252删除: t.Run(provider.name, func(t *testing.T) {
253删除: if _, err := queryLocation(context.Background(), client, provider.url, provider.primary, net.ParseIP("8.8.8.8")); err != nil {
245新增: for _, host := range []string{"ipwho.is", "api.ip.sb"} {
246新增: t.Run(host, func(t *testing.T) {
247新增: only := *client
248新增: only.Transport = browserTransport(func(r *http.Request) (*http.Response, error) {
249新增: if r.URL.Host != host {
250新增: return nil, errors.New("only testing " + host)
251新增: }
252新增: return transport.RoundTrip(r)
253新增: })
254新增: if _, err := lookupLocation(context.Background(), &only, net.ParseIP("8.8.8.8")); err != nil {
254255 t.Fatal(err)
255256 }
256257 })
新增internal/workbench/macos_attachments.go+30 −0看文件
@@ -0,0 +1,30 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "path"
5新增: "strings"
6新增:
7新增: "github.com/google/uuid"
8新增:)
9新增:
10新增:func (s *Server) validMacOSAttachmentPath(value, name string) bool {
11新增: if s.macosGuest == nil || strings.ContainsAny(value, "\\\x00\r\n") || path.Clean(value) != value {
12新增: return false
13新增: }
14新增: root := path.Join("/Users", s.macosGuest.User, ".local/share/cage/attachments/files") + "/"
15新增: relative, ok := strings.CutPrefix(value, root)
16新增: if !ok {
17新增: return false
18新增: }
19新增: parts := strings.Split(relative, "/")
20新增: if len(parts) != 3 || parts[2] != name || !browserFileName(name) {
21新增: return false
22新增: }
23新增: for _, part := range parts[:2] {
24新增: id, err := uuid.Parse(part)
25新增: if err != nil || id == uuid.Nil || id.String() != part {
26新增: return false
27新增: }
28新增: }
29新增: return true
30新增:}
新增internal/workbench/macos_attachments_test.go+58 −0看文件
@@ -0,0 +1,58 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "bytes"
5新增: "encoding/json"
6新增: "os"
7新增: "os/exec"
8新增: "path/filepath"
9新增: "strings"
10新增: "testing"
11新增:
12新增: "github.com/google/uuid"
13新增: "github.com/sylvinus/agent-vm/internal/cage"
14新增: "github.com/sylvinus/agent-vm/internal/guestos"
15新增:)
16新增:
17新增:func TestMacOSAttachmentPathRejectsOtherUsersAndEscapes(t *testing.T) {
18新增: s := &Server{macosGuest: &guestos.MacOSProfile{User: "cage"}}
19新增: root := "/Users/cage/.local/share/cage/attachments/files/" + uuid.NewString() + "/" + uuid.NewString() + "/"
20新增: if !s.validMacOSAttachmentPath(root+"附件.txt", "附件.txt") {
21新增: t.Fatal("bound native attachment rejected")
22新增: }
23新增: for _, value := range []string{strings.Replace(root, "/cage/", "/another/", 1) + "附件.txt", root + "../附件.txt", root + "other.txt", "/Users/cage/.ssh/id_ed25519"} {
24新增: if s.validMacOSAttachmentPath(value, "附件.txt") {
25新增: t.Fatalf("unbound attachment accepted: %q", value)
26新增: }
27新增: }
28新增:}
29新增:
30新增:func TestMacOSTerminalUsesSharedAttachmentReceiver(t *testing.T) {
31新增: if _, err := exec.LookPath("uv"); err != nil {
32新增: t.Skip("uv is required for the shared Python receiver")
33新增: }
34新增: home := t.TempDir()
35新增: contents := []byte("native attachment 中文\x00\x01")
36新增: var previous string
37新增: for attempt := 0; attempt < 2; attempt++ {
38新增: cmd := exec.Command("uv", "run", "--no-project", "python", "-I", "-c", cage.DesktopFileReceiver(), "--save-file", "file.bin")
39新增: cmd.Env = append(os.Environ(), "HOME="+home, "USERPROFILE="+home)
40新增: cmd.Stdin = bytes.NewReader(contents)
41新增: output, err := cmd.Output()
42新增: if err != nil {
43新增: t.Fatal(err)
44新增: }
45新增: var saved struct {
46新增: OK bool `json:"ok"`
47新增: Path string `json:"path"`
48新增: }
49新增: if json.Unmarshal(output, &saved) != nil || !saved.OK || !strings.HasPrefix(saved.Path, filepath.Join(home, ".local", "share", "cage", "attachments", "files")+string(os.PathSeparator)) {
50新增: t.Fatalf("receiver returned invalid attachment: %s", output)
51新增: }
52新增: actual, err := os.ReadFile(saved.Path)
53新增: if err != nil || !bytes.Equal(actual, contents) || saved.Path == previous {
54新增: t.Fatal("attachment bytes changed or duplicate name replaced a prior attachment")
55新增: }
56新增: previous = saved.Path
57新增: }
58新增:}
新增internal/workbench/macos_audio.go+87 −0看文件
@@ -0,0 +1,87 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "bufio"
5新增: "bytes"
6新增: "context"
7新增: "encoding/json"
8新增: "io"
9新增: "net/http"
10新增: "strings"
11新增: "time"
12新增:)
13新增:
14新增:func (s *Server) macOSAudioStatus(w http.ResponseWriter, r *http.Request) {
15新增: ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
16新增: defer cancel()
17新增: cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", macOSWindowSocketCommand)
18新增: cmd.Stdin = strings.NewReader("{\"action\":\"audio-status\"}\n")
19新增: cmd.Stderr = io.Discard
20新增: var data bytes.Buffer
21新增: cmd.Stdout = &boundedWindowsStatusWriter{buffer: &data, remaining: 4096}
22新增: var status struct {
23新增: Supported bool `json:"supported"`
24新增: Available bool `json:"available"`
25新增: Reason string `json:"reason"`
26新增: Error string `json:"error"`
27新增: }
28新增: if cmd.Run() != nil || json.Unmarshal(data.Bytes(), &status) != nil {
29新增: http.Error(w, "虚拟 Mac 声音组件尚未连接,请先完成客机组件更新", http.StatusBadGateway)
30新增: return
31新增: }
32新增: if status.Reason == "" {
33新增: status.Reason = status.Error
34新增: }
35新增: if !status.Supported && status.Reason != "requires_gui_login" && status.Reason != "screen_recording_permission" {
36新增: http.Error(w, "虚拟 Mac 声音组件尚未连接,请先完成客机组件更新", http.StatusBadGateway)
37新增: return
38新增: }
39新增: if !status.Available {
40新增: message := "请先登录并解锁虚拟 Mac 的普通账户"
41新增: if status.Reason == "screen_recording_permission" {
42新增: message = "请在虚拟 Mac 的系统设置中允许 Cage Guest Window 录制屏幕和系统声音"
43新增: }
44新增: http.Error(w, message, http.StatusConflict)
45新增: return
46新增: }
47新增: jsonReply(w, audioFormat)
48新增:}
49新增:
50新增:func (s *Server) macOSAudioCapture(w http.ResponseWriter, r *http.Request, ctx context.Context, cancel context.CancelFunc) {
51新增: cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", macOSWindowSocketCommand)
52新增: cmd.Stderr = io.Discard
53新增: input, err := cmd.StdinPipe()
54新增: if err != nil {
55新增: http.Error(w, "声音连接未能建立", http.StatusBadGateway)
56新增: return
57新增: }
58新增: pipe, err := cmd.StdoutPipe()
59新增: if err != nil {
60新增: input.Close()
61新增: http.Error(w, "声音连接未能建立", http.StatusBadGateway)
62新增: return
63新增: }
64新增: if err = cmd.Start(); err != nil {
65新增: input.Close()
66新增: pipe.Close()
67新增: http.Error(w, "声音连接未能建立", http.StatusBadGateway)
68新增: return
69新增: }
70新增: defer func() { cancel(); input.Close(); pipe.Close(); _ = cmd.Wait() }()
71新增: // Keep the request side open until cancellation so the guest can distinguish
72新增: // a live, output-only subscriber from a disconnected SSH client.
73新增: if _, err = io.WriteString(input, "{\"action\":\"audio-capture\"}\n"); err != nil {
74新增: http.Error(w, "声音连接未能建立", http.StatusBadGateway)
75新增: return
76新增: }
77新增: deadlineDone := make(chan struct{})
78新增: deadline := time.AfterFunc(15*time.Second, func() { defer close(deadlineDone); cancel(); pipe.Close() })
79新增: reader := bufio.NewReaderSize(pipe, 4096)
80新增: err = readAudioReady(reader)
81新增: stopped := cancelWindowsAdmissionDeadline(deadline, deadlineDone)
82新增: if err != nil || !stopped {
83新增: http.Error(w, "虚拟 Mac 声音未能启动,请确认客机已解锁并允许 Cage Guest Window 录制屏幕和系统声音", http.StatusBadGateway)
84新增: return
85新增: }
86新增: s.streamAudio(w, r.WithContext(ctx), bufferedAudio{Reader: reader, Closer: pipe})
87新增:}
新增internal/workbench/macos_audio_test.go+95 −0看文件
@@ -0,0 +1,95 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "bufio"
5新增: "bytes"
6新增: "encoding/json"
7新增: "fmt"
8新增: "io"
9新增: "net/http"
10新增: "net/http/httptest"
11新增: "strings"
12新增: "sync/atomic"
13新增: "testing"
14新增: "time"
15新增:
16新增: "github.com/gorilla/websocket"
17新增: "golang.org/x/crypto/ssh"
18新增:)
19新增:
20新增:func TestMacOSAudioUsesBoundTransportAndClosesCapture(t *testing.T) {
21新增: var allowed atomic.Bool
22新增: allowed.Store(true)
23新增: closed := make(chan struct{}, 1)
24新增: pcm := bytes.Repeat([]byte{1, 2, 3, 4}, 960)
25新增: guest := newMacWorkspaceGuest(t, func(channel ssh.Channel, command string) (uint32, bool) {
26新增: if command != macOSWindowSocketCommand {
27新增: return 1, false
28新增: }
29新增: line, err := bufio.NewReader(channel).ReadString('\n')
30新增: if err != nil {
31新增: return 1, true
32新增: }
33新增: switch strings.TrimSpace(line) {
34新增: case `{"action":"audio-status"}`:
35新增: json.NewEncoder(channel).Encode(map[string]any{"supported": true, "available": allowed.Load(), "reason": "screen_recording_permission"})
36新增: case `{"action":"audio-capture"}`:
37新增: fmt.Fprintln(channel, `{"ready":true,"format":"s16le","sample_rate":48000,"channels":2}`)
38新增: channel.Write(pcm)
39新增: io.Copy(io.Discard, channel)
40新增: closed <- struct{}{}
41新增: default:
42新增: return 1, true
43新增: }
44新增: return 0, true
45新增: })
46新增: s := guest.s
47新增: server := httptest.NewServer(s.handler())
48新增: defer server.Close()
49新增: s.origin = server.URL
50新增: headers := http.Header{
51新增: "Origin": {s.origin},
52新增: "Cookie": {s.cookieName() + "=" + s.session + "; " + s.cookieName() + "-desktop=" + trustedViewProof(s.token)},
53新增: }
54新增: statusRequest, _ := http.NewRequest(http.MethodGet, s.origin+"/api/audio", nil)
55新增: statusRequest.Header = headers.Clone()
56新增: response, err := server.Client().Do(statusRequest)
57新增: if err != nil {
58新增: t.Fatal(err)
59新增: }
60新增: var format map[string]any
61新增: decodeErr := json.NewDecoder(response.Body).Decode(&format)
62新增: response.Body.Close()
63新增: if response.StatusCode != http.StatusOK || decodeErr != nil || format["sample_rate"] != float64(48000) || format["channels"] != float64(2) {
64新增: t.Fatalf("native audio status: %d %v", response.StatusCode, decodeErr)
65新增: }
66新增: ws, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(s.origin, "http")+"/api/audio", headers)
67新增: if err != nil {
68新增: t.Fatal(err)
69新增: }
70新增: defer ws.Close()
71新增: ws.SetReadDeadline(time.Now().Add(5 * time.Second))
72新增: if err := ws.ReadJSON(&format); err != nil || format["format"] != "s16le" {
73新增: t.Fatalf("native audio websocket format: %v", err)
74新增: }
75新增: kind, data, err := ws.ReadMessage()
76新增: if err != nil || kind != websocket.BinaryMessage || !bytes.Equal(data, pcm) {
77新增: t.Fatalf("native PCM changed: %v", err)
78新增: }
79新增: ws.Close()
80新增: select {
81新增: case <-closed:
82新增: case <-time.After(3 * time.Second):
83新增: t.Fatal("closed workbench retained its SSH capture")
84新增: }
85新增: allowed.Store(false)
86新增: response, err = server.Client().Do(statusRequest)
87新增: if err != nil {
88新增: t.Fatal(err)
89新增: }
90新增: message, _ := io.ReadAll(response.Body)
91新增: response.Body.Close()
92新增: if response.StatusCode != http.StatusConflict || !strings.Contains(string(message), "Cage Guest Window") || !strings.Contains(string(message), "系统声音") {
93新增: t.Fatal("missing guest permission did not return an actionable error")
94新增: }
95新增:}
新增internal/workbench/macos_browser.go+129 −0看文件
@@ -0,0 +1,129 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "context"
5新增: "encoding/json"
6新增: "errors"
7新增: "net/http"
8新增: "net/url"
9新增: "path/filepath"
10新增: "time"
11新增:)
12新增:
13新增:type macBrowserRequest struct {
14新增: Timezone string `json:"timezone,omitempty"`
15新增: Network bool `json:"network,omitempty"`
16新增: Action string `json:"action"`
17新增: URL string `json:"url,omitempty"`
18新增: Workspace string `json:"workspace,omitempty"`
19新增: Folder string `json:"folder,omitempty"`
20新增: X int `json:"x"`
21新增: Y int `json:"y"`
22新增: DX int `json:"dx"`
23新增: DY int `json:"dy"`
24新增: Double bool `json:"double,omitempty"`
25新增: Key string `json:"key,omitempty"`
26新增: Text string `json:"text,omitempty"`
27新增: Meta bool `json:"meta,omitempty"`
28新增: Ctrl bool `json:"ctrl,omitempty"`
29新增: Shift bool `json:"shift,omitempty"`
30新增: Alt bool `json:"alt,omitempty"`
31新增:}
32新增:
33新增:// Keep older installed clients on the same guest Chrome session and project grants.
34新增:func (s *Server) macBrowserExchange(ctx context.Context, request macBrowserRequest) ([]byte, error) {
35新增: client := s.nativeBrowserClient()
36新增: if request.Action == "frame" {
37新增: data, err := client.request(ctx, "GET", "/frame", nil)
38新增: if err != nil {
39新增: return nil, err
40新增: }
41新增: var frame struct {
42新增: JPEG string
43新增: URL string
44新增: Title string
45新增: Width, Height int
46新增: }
47新增: if err = json.Unmarshal(data, &frame); err != nil || frame.JPEG == "" {
48新增: return nil, errors.New("请在单个客机浏览器标签中查看画面")
49新增: }
50新增: return json.Marshal(map[string]any{"image": frame.JPEG, "url": frame.URL, "title": frame.Title, "width": frame.Width, "height": frame.Height})
51新增: }
52新增: action := request.Action
53新增: if action == "text" {
54新增: action = "insert-text"
55新增: }
56新增: if action == "editor" {
57新增: _, err := client.request(ctx, "POST", "/editor", map[string]string{"workspace": filepath.Base(request.Folder)})
58新增: if err != nil {
59新增: return nil, err
60新增: }
61新增: return []byte(`{"ok":true}`), nil
62新增: }
63新增: return client.request(ctx, "POST", "/"+action, request)
64新增:}
65新增:
66新增:func (s *Server) registerMacOSBrowserRoutes(mux *http.ServeMux) {
67新增: mux.HandleFunc("POST /api/macos-browser/action", func(w http.ResponseWriter, r *http.Request) {
68新增: if s.macosGuest == nil {
69新增: http.NotFound(w, r)
70新增: return
71新增: }
72新增: s.mu.Lock()
73新增: ready := s.ready && !s.closing
74新增: s.mu.Unlock()
75新增: if !ready {
76新增: http.Error(w, "请先启动 macOS 客机", http.StatusConflict)
77新增: return
78新增: }
79新增: var request macBrowserRequest
80新增: if !readJSON(w, r, &request) {
81新增: return
82新增: }
83新增: // A guest filesystem path is derived only from an already granted host project.
84新增: request.Folder = ""
85新增: switch request.Action {
86新增: case "editor":
87新增: if request.Workspace == "" {
88新增: http.Error(w, "请先打开项目", 400)
89新增: return
90新增: }
91新增: if !s.op.TryLock() {
92新增: http.Error(w, "正在处理其他项目操作", 409)
93新增: return
94新增: }
95新增: project, err := s.connectProject(request.Workspace, false)
96新增: s.op.Unlock()
97新增: if err != nil || isClientMountPath(project) {
98新增: http.Error(w, "请先打开并授权本机项目", 409)
99新增: return
100新增: }
101新增: request.Folder = macOSProjectPath(s.macosGuest.User, project)
102新增: case "navigate":
103新增: u, err := url.Parse(request.URL)
104新增: if err != nil || u == nil || u.Hostname() == "" || u.User != nil || (u.Scheme != "http" && u.Scheme != "https") || len(request.URL) > 4096 {
105新增: http.Error(w, "请输入 HTTP 或 HTTPS 地址", 400)
106新增: return
107新增: }
108新增: case "text", "key", "click", "wheel", "back", "forward", "frame", "reload":
109新增: default:
110新增: http.Error(w, "未知的客机浏览器操作", 400)
111新增: return
112新增: }
113新增: request.Workspace = "" // never expose a host pathname to the guest browser
114新增: if len(request.Text) > 8192 || len(request.Key) > 32 || request.X < 0 || request.Y < 0 || request.X > 1140 || request.Y > 700 || request.DX > 2000 || request.DX < -2000 || request.DY > 2000 || request.DY < -2000 {
115新增: http.Error(w, "输入超出范围", 400)
116新增: return
117新增: }
118新增: ctx, cancel := context.WithTimeout(r.Context(), 28*time.Second)
119新增: defer cancel()
120新增: data, err := s.macBrowserExchange(ctx, request)
121新增: if err != nil {
122新增: http.Error(w, "无法连接客机里的浏览器,请检查客机运行状态", 503)
123新增: return
124新增: }
125新增: w.Header().Set("Content-Type", "application/json")
126新增: w.Header().Set("Cache-Control", "no-store")
127新增: _, _ = w.Write(data)
128新增: })
129新增:}
新增internal/workbench/macos_claude.go+151 −0看文件
@@ -0,0 +1,151 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "bytes"
5新增: "context"
6新增: "encoding/json"
7新增: "errors"
8新增: "io"
9新增: "net/http"
10新增: "strings"
11新增: "time"
12新增:)
13新增:
14新增:const macOSWindowSocketCommand = `exec /usr/bin/nc -U "$HOME/Library/Caches/dev.cage.GuestClaudeWindow/window.sock"`
15新增:
16新增:// The native trial has a dedicated standard-user SSH identity. The guest GUI
17新增:// agent accepts only Claude operations on its protected per-user Unix socket.
18新增:func (s *Server) registerMacOSClaudeRoutes(mux *http.ServeMux) {
19新增: mux.HandleFunc("POST /api/macos/claude/window", s.macOSClaudeWindow)
20新增: mux.HandleFunc("GET /api/macos/claude/connection", s.macOSWindowConnection)
21新增: mux.HandleFunc("GET /api/macos/claude/frames", s.macOSWindowFrames)
22新增:}
23新增:
24新增:type macOSWindowRequest struct {
25新增: Action string `json:"action"`
26新增: Project string `json:"project,omitempty"`
27新增: Nonce string `json:"nonce,omitempty"`
28新增: Width int `json:"width,omitempty"`
29新增: Height int `json:"height,omitempty"`
30新增: Scale float64 `json:"scale,omitempty"`
31新增: Geometry string `json:"geometry,omitempty"`
32新增: Window uint32 `json:"window,omitempty"`
33新增: PID int32 `json:"pid,omitempty"`
34新增: X *float64 `json:"x,omitempty"`
35新增: Y *float64 `json:"y,omitempty"`
36新增: Delta *float64 `json:"delta,omitempty"`
37新增: DeltaX *float64 `json:"deltaX,omitempty"`
38新增: Text string `json:"text,omitempty"`
39新增: Key string `json:"key,omitempty"`
40新增: Code string `json:"code,omitempty"`
41新增: Down *bool `json:"down,omitempty"`
42新增: Phase string `json:"phase,omitempty"`
43新增: Button *int `json:"button,omitempty"`
44新增: Buttons int `json:"buttons,omitempty"`
45新增: Clicks int `json:"clicks,omitempty"`
46新增: Shift bool `json:"shift,omitempty"`
47新增: Cmd bool `json:"command,omitempty"`
48新增: Control bool `json:"control,omitempty"`
49新增: Alt bool `json:"alt,omitempty"`
50新增: Mode string `json:"mode,omitempty"`
51新增: Context string `json:"context,omitempty"`
52新增: Session string `json:"session,omitempty"`
53新增: After string `json:"after,omitempty"`
54新增: KeepAlive bool `json:"keepAlive,omitempty"`
55新增: Refresh bool `json:"refresh,omitempty"`
56新增: Wait bool `json:"wait,omitempty"`
57新增: Binary bool `json:"binary,omitempty"`
58新增: ID string `json:"id,omitempty"`
59新增: Kind string `json:"kind,omitempty"`
60新增: Transfer string `json:"transfer,omitempty"`
61新增: Sequence int `json:"sequence"`
62新增: Path string `json:"path,omitempty"`
63新增: Error string `json:"error,omitempty"`
64新增: Files []string `json:"files,omitempty"`
65新增: Phone *phoneSurfaceInput `json:"phone,omitempty"`
66新增: PhoneToken string `json:"phone_token,omitempty"`
67新增:}
68新增:
69新增:func (s *Server) macOSClaudeWindow(w http.ResponseWriter, r *http.Request) {
70新增: if s.macosGuest == nil {
71新增: http.NotFound(w, r)
72新增: return
73新增: }
74新增: var input macOSWindowRequest
75新增: if !readJSON(w, r, &input) {
76新增: return
77新增: }
78新增: if !validMacOSWindowRequest(input) {
79新增: http.Error(w, "客机窗口操作或尺寸无效", http.StatusBadRequest)
80新增: return
81新增: }
82新增: s.macOSWindowRPC(w, r, macOSWindowClientRequest(input, false))
83新增:}
84新增:
85新增:var (
86新增: errMacWindowInput = errors.New("单次窗口输入过长")
87新增: errMacWindowConnect = errors.New("无法连接虚拟 Mac")
88新增:)
89新增:
90新增:func (s *Server) macOSWindowRPC(w http.ResponseWriter, r *http.Request, input macOSWindowRequest) {
91新增: reply, err := s.macOSWindowCall(r.Context(), input)
92新增: if err != nil {
93新增: code := http.StatusServiceUnavailable
94新增: if errors.Is(err, errMacWindowInput) {
95新增: code = http.StatusBadRequest
96新增: }
97新增: if errors.Is(err, errMacWindowConnect) {
98新增: code = http.StatusBadGateway
99新增: }
100新增: http.Error(w, err.Error(), code)
101新增: return
102新增: }
103新增: w.Header().Set("Cache-Control", "no-store")
104新增: w.Header().Set("Content-Type", "application/json")
105新增: _, _ = w.Write(reply)
106新增:}
107新增:
108新增:func (s *Server) macOSWindowCall(parent context.Context, input macOSWindowRequest) ([]byte, error) {
109新增: body, err := json.Marshal(input)
110新增: limit := 8000
111新增: if strings.HasPrefix(input.Action, "phone-") || input.Action == "text" || input.Action == "ime" {
112新增: // An 8 KiB UTF-8 message can expand sixfold when JSON escapes controls.
113新增: limit = 64 << 10
114新增: }
115新增: if err != nil || len(body) > limit {
116新增: return nil, errMacWindowInput
117新增: }
118新增:
119新增: timeout := 12 * time.Second
120新增: socketWait := "9"
121新增: if input.Action == "launch" || input.Action == "phone-open" {
122新增: // On a cold guest disk macOS verifies the signed Electron bundle
123新增: // before LaunchServices reports success.
124新增: timeout = 55 * time.Second
125新增: socketWait = "50"
126新增: }
127新增: ctx, cancel := context.WithTimeout(parent, timeout)
128新增: defer cancel()
129新增: command := `exec /usr/bin/nc -w ` + socketWait + ` -U "$HOME/Library/Caches/dev.cage.GuestClaudeWindow/window.sock"`
130新增: cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", command)
131新增: cmd.Stdin = bytes.NewReader(append(body, '\n'))
132新增: reader, err := cmd.StdoutPipe()
133新增: if err == nil {
134新增: err = cmd.Start()
135新增: }
136新增: if err != nil {
137新增: return nil, errMacWindowConnect
138新增: }
139新增: // The agent returns one PNG (base64) or a small JSON status. Do not relay
140新增: // partial replies or log input, frame data, or guest application contents.
141新增: const maxReply = 12 << 20
142新增: reply, readErr := io.ReadAll(io.LimitReader(reader, maxReply+1))
143新增: if readErr != nil || len(reply) > maxReply {
144新增: cancel()
145新增: }
146新增: waitErr := cmd.Wait()
147新增: if readErr != nil || waitErr != nil || len(reply) > maxReply || !json.Valid(reply) {
148新增: return nil, errors.New("请先登录虚拟 Mac 的普通账户,并完成 Apple 设置助理。")
149新增: }
150新增: return reply, nil
151新增:}
新增internal/workbench/macos_claude_test.go+32 −0看文件
@@ -0,0 +1,32 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "net/http"
5新增: "net/http/httptest"
6新增: "strings"
7新增: "testing"
8新增:
9新增: "github.com/sylvinus/agent-vm/internal/guestos"
10新增:)
11新增:
12新增:func TestMacOSClaudeRouteCannotRequestProjectPanel(t *testing.T) {
13新增: s := testServer(t)
14新增: body := `{"action":"project-frame","project":"/Users/guest/Cage/Projects/aaaaaaaaaaaaaaaaaaaaaaaa"}`
15新增: // A project grant must be checked by the separate approval route.
16新增: for _, test := range []struct {
17新增: profile *guestos.MacOSProfile
18新增: status int
19新增: }{
20新增: {nil, http.StatusNotFound},
21新增: {&guestos.MacOSProfile{Instance: "mac", User: "guest"}, http.StatusBadRequest},
22新增: } {
23新增: s.macosGuest = test.profile
24新增: response := httptest.NewRecorder()
25新增: request := httptest.NewRequest(http.MethodPost, "/api/macos/claude/window", strings.NewReader(body))
26新增: request.Header.Set("Content-Type", "application/json")
27新增: s.macOSClaudeWindow(response, request)
28新增: if response.Code != test.status {
29新增: t.Fatalf("got %d, want %d", response.Code, test.status)
30新增: }
31新增: }
32新增:}
新增internal/workbench/macos_cli.go+44 −0看文件
@@ -0,0 +1,44 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "path"
5新增:
6新增: "al.essio.dev/pkg/shellescape"
7新增:)
8新增:
9新增:const macCLIInstall = "/usr/local/libexec/cage-cli"
10新增:
11新增:const macOSLegacyWorkspaceNotice = "此历史会话仍使用原来的客机目录,文件保留在虚拟 Mac 内。要使用与主机共享的默认工作区,请从默认工作区新建会话。"
12新增:
13新增:// Only a persisted terminal already bound to the old default workspace keeps
14新增:// that directory. New sessions and other host projects use approved mounts.
15新增:func (s *Server) macOSLegacyWorkspace(record *mobileRecord) string {
16新增: if s.macosGuest == nil || record == nil || !record.Terminal || record.Workspace != s.environmentDir() {
17新增: return ""
18新增: }
19新增: root := path.Join("/Users", s.macosGuest.User, ".local/share/cage/workspace")
20新增: if record.GuestWorkspace != path.Clean(record.GuestWorkspace) || !cliWorkspaceWithin(record.GuestWorkspace, root, false) {
21新增: return ""
22新增: }
23新增: return root
24新增:}
25新增:
26新增:func (s *Server) cliWorkspace(workspace string) string {
27新增: if s.macosGuest == nil {
28新增: return guestPath(workspace)
29新增: }
30新增: return macOSProjectPath(s.macosGuest.User, workspace)
31新增:}
32新增:
33新增:func (s *Server) cliHelperCommand(mode, argument string) string {
34新增: if s.macosGuest == nil {
35新增: return cliChannelCommand(mode, argument)
36新增: }
37新增: return shellescape.QuoteCommand([]string{macCLIInstall + "/bin/python3", "-I", macCLIInstall + "/macos-cli.py", mode, argument})
38新增:}
39新增:
40新增:func (s *Server) macOSClaudeLaunch(workspace, payload string) string {
41新增: // The signed project helper rechecks the exact mount and its GUI user's
42新增: // approval before granting the CLI a controlling terminal and that cwd.
43新增: return "exec " + shellescape.QuoteCommand([]string{"/usr/local/libexec/cage-macos-terminal", "--claude", s.cliWorkspace(workspace), payload})
44新增:}
新增internal/workbench/macos_cli_e2e_test.go+144 −0看文件
@@ -0,0 +1,144 @@
1新增://go:build e2e && darwin && arm64
2新增:
3新增:package workbench
4新增:
5新增:import (
6新增: "context"
7新增: "encoding/json"
8新增: "net/http"
9新增: "net/http/httptest"
10新增: "os"
11新增: "path/filepath"
12新增: "strings"
13新增: "testing"
14新增: "time"
15新增:
16新增: "github.com/sylvinus/agent-vm/internal/guestos"
17新增:)
18新增:
19新增:// Uses an existing test guest, a separate host account/session catalog and a
20新增:// new random guest conversation. No subscription credentials are required.
21新增:func TestMacOSGuestClaudeCode(t *testing.T) {
22新增: profile := os.Getenv("CAGE_TEST_MACOS_CLI_PROFILE")
23新增: if profile == "" {
24新增: t.Skip("set CAGE_TEST_MACOS_CLI_PROFILE to an explicitly selected test guest")
25新增: }
26新增: binding, err := guestos.LoadMacOSProfile(profile)
27新增: if err != nil || binding == nil {
28新增: t.Fatal("test guest binding unavailable")
29新增: }
30新增: s := testServer(t)
31新增: s.macosGuest = binding
32新增: for _, file := range []string{"macos-known-hosts", "state/lima/_config/user", "state/lima/mac/ssh.config", "state/lima/mac/cage-running.json"} {
33新增: dest := filepath.Join(s.profile, file)
34新增: if err := os.MkdirAll(filepath.Dir(dest), 0700); err != nil {
35新增: t.Fatal(err)
36新增: }
37新增: if err := os.Symlink(filepath.Join(profile, file), dest); err != nil {
38新增: t.Fatal(err)
39新增: }
40新增: }
41新增: dir, err := filepath.EvalSymlinks(t.TempDir())
42新增: if err != nil {
43新增: t.Fatal(err)
44新增: }
45新增: if err := writePrivate(filepath.Join(s.profile, "environment.json"), map[string]string{"directory": dir}); err != nil {
46新增: t.Fatal(err)
47新增: }
48新增: s.preferences.Workspace = dir
49新增: s.ready = true
50新增: call := func(method, route, body string, result any) {
51新增: t.Helper()
52新增: req := httptest.NewRequest(method, s.origin+route, strings.NewReader(body))
53新增: req.Header.Set("Content-Type", "application/json")
54新增: req.Header.Set("Origin", s.origin)
55新增: req.AddCookie(&http.Cookie{Name: s.cookieName(), Value: s.session})
56新增: req.AddCookie(&http.Cookie{Name: s.cookieName() + "-desktop", Value: trustedViewProof(s.token)})
57新增: resp := httptest.NewRecorder()
58新增: s.handler().ServeHTTP(resp, req)
59新增: if resp.Code != 200 {
60新增: t.Fatalf("%s: %d %s", route, resp.Code, resp.Body.String())
61新增: }
62新增: if err := json.Unmarshal(resp.Body.Bytes(), result); err != nil {
63新增: t.Fatal(err)
64新增: }
65新增: }
66新增: var tab struct {
67新增: ID string
68新增: Shared string `json:"cli_session_id"`
69新增: }
70新增: call("POST", "/api/terminals", `{"kind":"claude"}`, &tab)
71新增: if tab.ID == "" || !validCLIUUID(tab.Shared) {
72新增: t.Fatal("no shared terminal")
73新增: }
74新增: session := s.terminals.get(tab.ID)
75新增: defer func() {
76新增: s.terminals.close()
77新增: s.activities.Wait()
78新增: s.mobileCLI.mu.Lock()
79新增: rec, err := s.mobileCLI.record(s.profile, tab.Shared)
80新增: s.mobileCLI.mu.Unlock()
81新增: if err != nil || rec.Connection != session.connectionID {
82新增: t.Error("missing QA session binding")
83新增: return
84新增: }
85新增: // Remove only state created by this invocation in the explicitly selected QA guest.
86新增: ctx, cancel := context.WithTimeout(context.Background(), 16*time.Second)
87新增: defer cancel()
88新增: var ended struct{ OK bool }
89新增: for !ended.OK && ctx.Err() == nil {
90新增: err = s.runCLIChannel(ctx, "purge", map[string]string{"cli_id": rec.CLIID, "config": rec.GuestConfig, "workspace": rec.GuestWorkspace, "account": "default"}, &ended)
91新增: if !ended.OK {
92新增: time.Sleep(250 * time.Millisecond)
93新增: }
94新增: }
95新增: if !ended.OK {
96新增: t.Errorf("could not clean up this QA conversation: %v", err)
97新增: }
98新增: }()
99新增: deadline := time.Now().Add(40 * time.Second)
100新增: for {
101新增: session.mu.Lock()
102新增: output := cliStartupText(session.history)
103新增: session.mu.Unlock()
104新增: if strings.Contains(output, "UnabletoconnecttoAnthropic") {
105新增: t.Fatal("the test guest needs a currently authorized network connection")
106新增: }
107新增: if strings.Contains(output, "ClaudeCodev") {
108新增: break
109新增: }
110新增: if time.Now().After(deadline) {
111新增: t.Fatal("official native CLI did not present its interactive terminal")
112新增: }
113新增: time.Sleep(150 * time.Millisecond)
114新增: }
115新增: var index struct {
116新增: Sessions []mobileSummary
117新增: Notice string
118新增: }
119新增: call("GET", "/api/cli/sessions", "", &index)
120新增: found := false
121新增: for _, item := range index.Sessions {
122新增: if item.ID == tab.Shared {
123新增: found = true
124新增: }
125新增: }
126新增: if !found || index.Notice != "" {
127新增: t.Fatalf("CLI catalog did not rediscover the active conversation: %s", index.Notice)
128新增: }
129新增: var reopened mobileSession
130新增: call("POST", "/api/cli/sessions/"+tab.Shared+"/open", `{}`, &reopened)
131新增: if reopened.DesktopTerminalID != tab.ID {
132新增: t.Fatalf("reconnect created a different terminal")
133新增: }
134新增: if n := len(s.terminals.snapshot()); n != 1 {
135新增: t.Fatalf("reconnect published %d terminals", n)
136新增: }
137新增: ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
138新增: defer cancel()
139新增: read, err := s.readClaudeGuestSnapshot(ctx, "default")
140新增: if err != nil {
141新增: t.Fatal(err)
142新增: }
143新增: t.Logf("ordinary macOS account launched the official Claude Code terminal; active session rediscovered and reattached; native account probe succeeded (signed in: %t)", read.LoggedIn)
144新增:}
新增internal/workbench/macos_clipboard_test.go+49 −0看文件
@@ -0,0 +1,49 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "context"
5新增: "encoding/json"
6新增: "io"
7新增: "os"
8新增: "path/filepath"
9新增: "slices"
10新增: "strings"
11新增: "testing"
12新增:
13新增: "github.com/sylvinus/agent-vm/internal/guestos"
14新增:)
15新增:
16新增:func TestMacOSClipboardUsesBoundGUIAgent(t *testing.T) {
17新增: s := testServer(t)
18新增: s.macosGuest = &guestos.MacOSProfile{Instance: "mac", User: "guestdev"}
19新增: if err := os.MkdirAll(s.instanceDir(), 0700); err != nil {
20新增: t.Fatal(err)
21新增: }
22新增: if err := os.WriteFile(filepath.Join(s.instanceDir(), "ssh.config"), []byte("Host lima-mac\n Port 54432\n User root\n"), 0600); err != nil {
23新增: t.Fatal(err)
24新增: }
25新增: selected := []string{"/tmp/中文 ' $(touch unexpected).txt"}
26新增: for _, operation := range []string{"stream", "import", "export", "request"} {
27新增: cmd, source, err := s.clipboardCommand(context.Background(), operation, clipboardFileSelection{Paths: selected, User: "guest"})
28新增: if err != nil || cmd.Err != nil || source != "guest" {
29新增: t.Fatalf("%s transport: %v", operation, err)
30新增: }
31新增: command := cmd.Args[len(cmd.Args)-1]
32新增: if command != "exec '/Applications/Cage Guest Clipboard.app/Contents/MacOS/CageGuestClipboard' --client "+operation ||
33新增: !slices.Contains(cmd.Args, "guestdev") || slices.Contains(cmd.Args, "root") || strings.Contains(command, selected[0]) {
34新增: t.Fatalf("%s escaped its fixed guest transport", operation)
35新增: }
36新增: if operation == "export" {
37新增: data, _ := io.ReadAll(cmd.Stdin)
38新增: var actual []string
39新增: if json.Unmarshal(data, &actual) != nil || !slices.Equal(actual, selected) {
40新增: t.Fatal("file selections did not travel as stdin JSON")
41新增: }
42新增: }
43新增: }
44新增: for _, item := range []struct{ operation, user string }{{"execute", "guest"}, {"export", "root"}, {"export", "cage-browser"}} {
45新增: if _, _, err := s.clipboardCommand(context.Background(), item.operation, clipboardFileSelection{User: item.user}); err == nil {
46新增: t.Fatalf("accepted %s for %s", item.operation, item.user)
47新增: }
48新增: }
49新增:}
新增internal/workbench/macos_credentials.go+46 −0看文件
@@ -0,0 +1,46 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "context"
5新增: "crypto/rand"
6新增: "encoding/base64"
7新增: "errors"
8新增:
9新增: "github.com/google/uuid"
10新增:)
11新增:
12新增:// Guest credentials use the account's existing encrypted vault and installation
13新增:// identity. They are never website entries or returned by the vault API.
14新增:func (a *localAccount) macGuestPassword(ctx context.Context, id uuid.UUID) (string, error) {
15新增: var password string
16新增: err := a.withVault(ctx, true, func(db *vaultData) error {
17新增: if id == uuid.Nil {
18新增: return errors.New("缺少客机安装身份")
19新增: }
20新增: password = db.GuestPasswords[id.String()]
21新增: if password != "" {
22新增: return nil
23新增: }
24新增: var bytes [24]byte
25新增: if _, err := rand.Read(bytes[:]); err != nil {
26新增: return err
27新增: }
28新增: password = base64.RawURLEncoding.EncodeToString(bytes[:])
29新增: clear(bytes[:])
30新增: if db.GuestPasswords == nil {
31新增: db.GuestPasswords = map[string]string{}
32新增: }
33新增: db.GuestPasswords[id.String()] = password
34新增: return nil
35新增: })
36新增: return password, err
37新增:}
38新增:
39新增:func (a *localAccount) savedMacGuestPassword(ctx context.Context, id uuid.UUID) (string, error) {
40新增: var password string
41新增: err := a.withVault(ctx, false, func(db *vaultData) error {
42新增: password = db.GuestPasswords[id.String()]
43新增: return nil
44新增: })
45新增: return password, err
46新增:}
新增internal/workbench/macos_credentials_test.go+68 −0看文件
@@ -0,0 +1,68 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "bytes"
5新增: "context"
6新增: "encoding/json"
7新增: "net/http/httptest"
8新增: "os"
9新增: "path/filepath"
10新增: "testing"
11新增:
12新增: "github.com/google/uuid"
13新增:)
14新增:
15新增:func TestMacGuestCredentialEncryptionResumeAndIsolation(t *testing.T) {
16新增: a := newTestAccount(t)
17新增: ctx := context.Background()
18新增: id := uuid.New()
19新增: password, err := a.macGuestPassword(ctx, id)
20新增: if err != nil || len(password) != 32 {
21新增: t.Fatalf("generate: %v", err)
22新增: }
23新增: raw, _ := os.ReadFile(filepath.Join(filepath.Dir(a.path), "password-vault.json"))
24新增: if bytes.Contains(raw, []byte(password)) {
25新增: t.Fatal("plaintext guest password persisted")
26新增: }
27新增: resumed, err := a.macGuestPassword(ctx, id)
28新增: if err != nil || resumed != password {
29新增: t.Fatal("retry changed guest password", err)
30新增: }
31新增: other, err := a.macGuestPassword(ctx, uuid.New())
32新增: if err != nil || other == password {
33新增: t.Fatal("separate installation reused credential", err)
34新增: }
35新增: s := &Server{account: a}
36新增: w := httptest.NewRecorder()
37新增: s.vaultList(w, httptest.NewRequest("GET", "/api/vault", nil))
38新增: if bytes.Contains(w.Body.Bytes(), []byte(password)) || bytes.Contains(w.Body.Bytes(), []byte("guest_passwords")) {
39新增: t.Fatal("guest credential exposed by website vault API")
40新增: }
41新增: if err := a.withVault(ctx, true, func(db *vaultData) error {
42新增: return db.save(vaultEntry{Origin: "https://example.com", Username: "fixture", Password: "website-password"})
43新增: }); err != nil {
44新增: t.Fatal(err)
45新增: }
46新增: stored, _ := a.savedMacGuestPassword(ctx, id)
47新增: if stored != password {
48新增: t.Fatal("website mutation dropped guest credential")
49新增: }
50新增: if err := a.changePassword("initial-test-password", "replacement-test-password"); err != nil {
51新增: t.Fatal(err)
52新增: }
53新增: a.lock()
54新增: if _, err := a.savedMacGuestPassword(ctx, id); err == nil {
55新增: t.Fatal("locked account decrypted guest credential")
56新增: }
57新增: if err := a.unlock("replacement-test-password"); err != nil {
58新增: t.Fatal(err)
59新增: }
60新增: stored, _ = a.savedMacGuestPassword(ctx, id)
61新增: if stored != password {
62新增: t.Fatal("account password change lost guest credential")
63新增: }
64新增: var view map[string]any
65新增: if json.Unmarshal(w.Body.Bytes(), &view) != nil {
66新增: t.Fatal("invalid vault response")
67新增: }
68新增:}
新增internal/workbench/macos_desktop_files.go+161 −0看文件
@@ -0,0 +1,161 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "bufio"
5新增: "bytes"
6新增: "context"
7新增: "encoding/json"
8新增: "errors"
9新增: "io"
10新增: "path"
11新增: "strings"
12新增: "time"
13新增:)
14新增:
15新增:func macOSFileFailure(reason string) error {
16新增: if err := desktopDownloadFailure(reason); err != nil {
17新增: return err
18新增: }
19新增: switch reason {
20新增: case "requires_gui_login":
21新增: return errors.New("请先登录并解锁虚拟 Mac 的普通账户")
22新增: case "accessibility_permission":
23新增: return errors.New("请在虚拟 Mac 中允许 Cage Guest Window 使用辅助功能,再重新传递文件")
24新增: case "window_changed", "file_dialog_changed", "gui_session_changed", "attachment_cancelled":
25新增: return errors.New("接收文件的 Claude 窗口已变化,请回到原窗口重新选择文件")
26新增: case "file_dialog_navigation_failed", "file_dialog_still_open", "file_dialog_selection_mismatch":
27新增: return errors.New("客机文件选择框尚未接收文件,请检查该选择框后重试")
28新增: case "attachment_incomplete":
29新增: return errors.New("附件尚未完整传入,请重新选择文件")
30新增: case "attachment_limit":
31新增: return errors.New("一次最多传递 100 个附件,请分批选择文件")
32新增: default:
33新增: return errors.New("虚拟 Mac 未能接收附件,请确认 Claude Desktop 已打开,且客机组件已更新")
34新增: }
35新增:}
36新增:
37新增:func (s *Server) macOSDesktopFileCall(ctx context.Context, input macOSWindowRequest) (map[string]any, error) {
38新增: if input.Action == "files-start" && (input.Window == 0 || input.PID <= 0) {
39新增: return nil, macOSFileFailure("window_changed")
40新增: }
41新增: data, err := s.macOSWindowCall(ctx, input)
42新增: if err != nil {
43新增: return nil, err
44新增: }
45新增: var result map[string]any
46新增: if json.Unmarshal(data, &result) != nil {
47新增: return nil, errors.New("虚拟 Mac 附件响应无效")
48新增: }
49新增: if reason, _ := result["error"].(string); reason != "" {
50新增: return nil, macOSFileFailure(reason)
51新增: }
52新增: return result, nil
53新增:}
54新增:
55新增:func validMacOSClipboardAttachment(value, name string) bool {
56新增: if path.Clean(value) != value || strings.ContainsAny(value, "\\\x00\r\n") || path.Base(value) != name {
57新增: return false
58新增: }
59新增: if !(strings.HasPrefix(value, "/var/folders/") || strings.HasPrefix(value, "/private/var/folders/") || strings.HasPrefix(value, "/tmp/") || strings.HasPrefix(value, "/private/tmp/")) {
60新增: return false
61新增: }
62新增: directory := path.Base(path.Dir(value))
63新增: suffix, ok := strings.CutPrefix(directory, "cage-clipboard-")
64新增: return ok && suffix != "" && strings.Trim(suffix, "0123456789") == ""
65新增:}
66新增:
67新增:func (s *Server) macOSUploadDesktopAttachment(ctx context.Context, name, id string, body io.Reader) (map[string]any, error) {
68新增: if _, err := s.macOSDesktopFileCall(ctx, macOSWindowRequest{Action: "files-validate", ID: id}); err != nil {
69新增: return nil, err
70新增: }
71新增: cmd, _, err := s.clipboardCommand(ctx, "upload", clipboardFileSelection{})
72新增: if err != nil {
73新增: return nil, err
74新增: }
75新增: input, err := cmd.StdinPipe()
76新增: if err != nil {
77新增: return nil, err
78新增: }
79新增: output, err := cmd.StdoutPipe()
80新增: if err != nil {
81新增: input.Close()
82新增: return nil, err
83新增: }
84新增: cmd.Stderr = io.Discard
85新增: if err = cmd.Start(); err != nil {
86新增: input.Close()
87新增: output.Close()
88新增: return nil, err
89新增: }
90新增: finished := false
91新增: defer func() {
92新增: input.Close()
93新增: output.Close()
94新增: if !finished {
95新增: _ = cmd.Process.Kill()
96新增: _ = cmd.Wait()
97新增: }
98新增: }()
99新增: if err = json.NewEncoder(input).Encode(map[string]string{"name": name}); err == nil {
100新增: err = writeWindowsAttachmentFrames(input, body)
101新增: }
102新增: if err != nil {
103新增: return nil, err
104新增: }
105新增: input.Close()
106新增: var reply struct {
107新增: Paths []string `json:"paths"`
108新增: }
109新增: reader := bufio.NewScanner(output)
110新增: reader.Buffer(make([]byte, 4096), 65536)
111新增: if !reader.Scan() || json.Unmarshal(reader.Bytes(), &reply) != nil || len(reply.Paths) != 1 || !validMacOSClipboardAttachment(reply.Paths[0], name) {
112新增: return nil, errors.New("虚拟 Mac 附件没有完整保存,请重新传递")
113新增: }
114新增: err = cmd.Wait()
115新增: finished = true
116新增: if err != nil {
117新增: return nil, errors.New("虚拟 Mac 附件传递中断,请重新选择文件")
118新增: }
119新增: if _, err = s.macOSDesktopFileCall(ctx, macOSWindowRequest{Action: "files-add", ID: id, Files: reply.Paths}); err != nil {
120新增: // An upload may finish after its window or batch was canceled. Remove
121新增: // only the private file just returned by this successful upload.
122新增: cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
123新增: defer cancel()
124新增: request, _ := json.Marshal(map[string]any{"operation": "discard", "files": reply.Paths})
125新增: command := s.sshCommand(cleanup, "-T", s.sshTarget(), "--", "exec '/Applications/Cage Guest Clipboard.app/Contents/MacOS/CageGuestClipboard' --client request")
126新增: command.Stdin = bytes.NewReader(append(request, '\n'))
127新增: command.Stdout, command.Stderr = io.Discard, io.Discard
128新增: _ = command.Run()
129新增: return nil, err
130新增: }
131新增: return map[string]any{"ok": true, "id": id, "name": name}, nil
132新增:}
133新增:
134新增:func (s *Server) macOSPasteDesktopImage(ctx context.Context, data []byte, window macOSWindowRequest) (map[string]any, error) {
135新增: if len(data) == 0 || len(data) > maxImageBytes {
136新增: return nil, errors.New("图片大小无效")
137新增: }
138新增: if window.Window == 0 || window.PID <= 0 {
139新增: return nil, macOSFileFailure("window_changed")
140新增: }
141新增: header, _ := json.Marshal(map[string]any{"action": "paste-image", "length": len(data), "pid": window.PID, "window": window.Window})
142新增: cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", macOSWindowSocketCommand)
143新增: cmd.Stdin = io.MultiReader(bytes.NewReader(append(header, '\n')), bytes.NewReader(data))
144新增: cmd.Stderr = io.Discard
145新增: var reply bytes.Buffer
146新增: cmd.Stdout = &boundedWindowsStatusWriter{buffer: &reply, remaining: 65536}
147新增: if cmd.Run() != nil {
148新增: return nil, errors.New("图片未能传入虚拟 Mac,请确认 Claude Desktop 已打开")
149新增: }
150新增: var result map[string]any
151新增: if json.Unmarshal(reply.Bytes(), &result) != nil {
152新增: return nil, errors.New("虚拟 Mac 图片响应无效")
153新增: }
154新增: if reason, _ := result["error"].(string); reason != "" {
155新增: return nil, macOSFileFailure(reason)
156新增: }
157新增: if result["ok"] != true {
158新增: return nil, errors.New("虚拟 Mac 未确认图片粘贴")
159新增: }
160新增: return result, nil
161新增:}
新增internal/workbench/macos_desktop_files_test.go+198 −0看文件
@@ -0,0 +1,198 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "bufio"
5新增: "bytes"
6新增: "encoding/base64"
7新增: "encoding/binary"
8新增: "encoding/json"
9新增: "image"
10新增: "image/png"
11新增: "io"
12新增: "net/http"
13新增: "strings"
14新增: "sync"
15新增: "testing"
16新增:
17新增: "golang.org/x/crypto/ssh"
18新增:)
19新增:
20新增:func TestMacOSDesktopAttachmentsUsePrivateNativeOperations(t *testing.T) {
21新增: const id = "aa447f34-18bc-48ba-b3f8-93bbf7f7a315"
22新增: var mu sync.Mutex
23新增: var uploaded, pasted []byte
24新增: var calls []string
25新增: var rejectAdd, discarded bool
26新增: guest := newMacWorkspaceGuest(t, func(channel ssh.Channel, command string) (uint32, bool) {
27新增: reader := bufio.NewReader(channel)
28新增: if command == "exec '/Applications/Cage Guest Clipboard.app/Contents/MacOS/CageGuestClipboard' --client request" {
29新增: var request struct {
30新增: Operation string
31新增: Files []string
32新增: }
33新增: if json.NewDecoder(reader).Decode(&request) != nil || request.Operation != "discard" || len(request.Files) != 1 || request.Files[0] != "/tmp/cage-clipboard-12345/资料.bin" {
34新增: return 1, true
35新增: }
36新增: mu.Lock()
37新增: discarded = true
38新增: mu.Unlock()
39新增: json.NewEncoder(channel).Encode(map[string]any{"ok": true})
40新增: return 0, true
41新增: }
42新增: if command == "exec '/Applications/Cage Guest Clipboard.app/Contents/MacOS/CageGuestClipboard' --client upload" {
43新增: line, err := reader.ReadBytes('\n')
44新增: var request struct{ Name string }
45新增: if err != nil || json.Unmarshal(line, &request) != nil || (request.Name != "资料.bin" && request.Name != "image.png") {
46新增: return 1, true
47新增: }
48新增: var data bytes.Buffer
49新增: for {
50新增: var header [4]byte
51新增: if _, err := io.ReadFull(reader, header[:]); err != nil {
52新增: return 1, true
53新增: }
54新增: length := binary.LittleEndian.Uint32(header[:])
55新增: if length == 0 {
56新增: break
57新增: }
58新增: if length > 65536 {
59新增: return 1, true
60新增: }
61新增: if _, err := io.CopyN(&data, reader, int64(length)); err != nil {
62新增: return 1, true
63新增: }
64新增: }
65新增: mu.Lock()
66新增: if request.Name == "image.png" {
67新增: pasted = append([]byte(nil), data.Bytes()...)
68新增: } else {
69新增: uploaded = append([]byte(nil), data.Bytes()...)
70新增: }
71新增: mu.Unlock()
72新增: json.NewEncoder(channel).Encode(map[string]any{"paths": []string{"/tmp/cage-clipboard-12345/" + request.Name}})
73新增: return 0, true
74新增: }
75新增: if !strings.Contains(command, `dev.cage.GuestClaudeWindow/window.sock`) {
76新增: return 1, false
77新增: }
78新增: line, err := reader.ReadBytes('\n')
79新增: var request struct {
80新增: Action, ID, Kind string
81新增: Files []string
82新增: Length int
83新增: PID, Window int
84新增: }
85新增: if err != nil || json.Unmarshal(line, &request) != nil {
86新增: return 1, true
87新增: }
88新增: mu.Lock()
89新增: calls = append(calls, request.Action)
90新增: mu.Unlock()
91新增: switch request.Action {
92新增: case "files-start":
93新增: if (request.Kind != "paste" && request.Kind != "image") || request.PID != 100 || request.Window != 7 {
94新增: return 1, true
95新增: }
96新增: json.NewEncoder(channel).Encode(map[string]any{"ok": true, "id": id})
97新增: case "files-validate", "files-finish", "files-finish-image", "files-cancel":
98新增: if request.ID != id {
99新增: return 1, true
100新增: }
101新增: json.NewEncoder(channel).Encode(map[string]any{"ok": true})
102新增: case "files-add":
103新增: if request.ID != id || len(request.Files) != 1 || (request.Files[0] != "/tmp/cage-clipboard-12345/资料.bin" && request.Files[0] != "/tmp/cage-clipboard-12345/image.png") {
104新增: return 1, true
105新增: }
106新增: mu.Lock()
107新增: reject := rejectAdd
108新增: mu.Unlock()
109新增: if reject {
110新增: json.NewEncoder(channel).Encode(map[string]any{"error": "attachment_cancelled"})
111新增: return 0, true
112新增: }
113新增: json.NewEncoder(channel).Encode(map[string]any{"ok": true, "id": id})
114新增: case "files-poll":
115新增: json.NewEncoder(channel).Encode(map[string]any{"available": true, "uploads": []any{map[string]any{"id": id, "kind": "chooser", "multiple": true, "target": "desktop"}}, "downloads": []any{}})
116新增: case "paste-image":
117新增: if request.Length <= 0 || request.Length > maxImageBytes || request.PID != 100 || request.Window != 7 {
118新增: return 1, true
119新增: }
120新增: data := make([]byte, request.Length)
121新增: if _, err := io.ReadFull(reader, data); err != nil {
122新增: return 1, true
123新增: }
124新增: mu.Lock()
125新增: pasted = data
126新增: mu.Unlock()
127新增: json.NewEncoder(channel).Encode(map[string]any{"ok": true})
128新增: default:
129新增: return 1, true
130新增: }
131新增: return 0, true
132新增: })
133新增: s := guest.s
134新增: missingTarget := windowsBrowserRequestForTest(s, http.MethodPost, "/api/input/files/start", []byte(`{"target":"desktop","kind":"paste"}`))
135新增: if missingTarget.Code == http.StatusOK {
136新增: t.Fatal("attachment without an observed window was accepted")
137新增: }
138新增: start := windowsBrowserRequestForTest(s, http.MethodPost, "/api/input/files/start", []byte(`{"target":"desktop","kind":"paste","pid":100,"window":7}`))
139新增: if start.Code != http.StatusOK || !strings.Contains(start.Body.String(), id) {
140新增: t.Fatalf("start failed: %d %s", start.Code, start.Body.String())
141新增: }
142新增: content := []byte{0, 255, 128, 1, 2, 3}
143新增: upload := windowsBrowserRequestForTest(s, http.MethodPost, "/api/input/files/desktop/"+id+"?name=%E8%B5%84%E6%96%99.bin", content)
144新增: if upload.Code != http.StatusOK || strings.Contains(upload.Body.String(), "/tmp/") {
145新增: t.Fatalf("upload failed or exposed private path: %d %s", upload.Code, upload.Body.String())
146新增: }
147新增: for _, action := range []string{"finish", "cancel"} {
148新增: response := windowsBrowserRequestForTest(s, http.MethodPost, "/api/input/files/"+action, []byte(`{"target":"desktop","id":"`+id+`"}`))
149新增: if response.Code != http.StatusOK {
150新增: t.Fatalf("%s failed: %s", action, response.Body.String())
151新增: }
152新增: }
153新增: poll := windowsBrowserRequestForTest(s, http.MethodGet, "/api/input/files/desktop/requests", nil)
154新增: if poll.Code != http.StatusOK || !strings.Contains(poll.Body.String(), `"kind":"chooser"`) {
155新增: t.Fatalf("chooser poll failed: %d %s", poll.Code, poll.Body.String())
156新增: }
157新增: var picture bytes.Buffer
158新增: if err := png.Encode(&picture, image.NewRGBA(image.Rect(0, 0, 3, 2))); err != nil {
159新增: t.Fatal(err)
160新增: }
161新增: prepared := windowsBrowserRequestForTest(s, http.MethodPost, "/api/input/paste/start", []byte(`{"target":"desktop","pid":100,"window":7}`))
162新增: if prepared.Code != http.StatusOK || !strings.Contains(prepared.Body.String(), id) {
163新增: t.Fatalf("image preparation failed: %d %s", prepared.Code, prepared.Body.String())
164新增: }
165新增: body, _ := json.Marshal(map[string]any{"target": "desktop", "png": base64.StdEncoding.EncodeToString(picture.Bytes()), "transfer": id, "pid": 100, "window": 7})
166新增: response := windowsBrowserRequestForTest(s, http.MethodPost, "/api/input/image", body)
167新增: if response.Code != http.StatusOK {
168新增: t.Fatalf("image failed: %d %s", response.Code, response.Body.String())
169新增: }
170新增: mu.Lock()
171新增: if !bytes.Equal(uploaded, content) || !bytes.Equal(pasted, picture.Bytes()) {
172新增: mu.Unlock()
173新增: t.Fatal("private transports changed file or PNG bytes")
174新增: }
175新增: if strings.Join(calls, ",") != "files-start,files-validate,files-add,files-finish,files-cancel,files-poll,files-start,files-validate,files-add,files-finish-image" {
176新增: mu.Unlock()
177新增: t.Fatalf("native operations diverged: %v", calls)
178新增: }
179新增: rejectAdd = true
180新增: mu.Unlock()
181新增: failed := windowsBrowserRequestForTest(s, http.MethodPost, "/api/input/files/desktop/"+id+"?name=%E8%B5%84%E6%96%99.bin", content)
182新增: mu.Lock()
183新增: defer mu.Unlock()
184新增: if failed.Code == http.StatusOK || !discarded {
185新增: t.Fatal("a completed upload abandoned by its window was not cleaned")
186新增: }
187新增:}
188新增:
189新增:func TestMacOSDesktopAttachmentPathsRejectEscapes(t *testing.T) {
190新增: if !validMacOSClipboardAttachment("/var/folders/ab/xyz/T/cage-clipboard-123/资料.bin", "资料.bin") {
191新增: t.Fatal("private guest cache refused")
192新增: }
193新增: for _, value := range []string{"/Users/cage/secret.txt", "/tmp/cage-clipboard-123/../secret.txt", "/tmp/cage-clipboard-123/file:stream", "/tmp/other-123/资料.bin", "/tmp/cage-clipboard-abc/资料.bin"} {
194新增: if validMacOSClipboardAttachment(value, "资料.bin") {
195新增: t.Fatal("unregistered path form accepted")
196新增: }
197新增: }
198新增:}
新增internal/workbench/macos_diagnostics.py+59 −0看文件
@@ -0,0 +1,59 @@
1新增:"""Read only the two Cage GUI helpers' bounded, machine-code diagnostic logs."""
2新增:from collections import deque
3新增:from datetime import datetime, timedelta, timezone
4新增:import heapq
5新增:import itertools
6新增:import json
7新增:import os
8新增:from pathlib import Path
9新增:import re
10新增:import stat
11新增:
12新增:root = Path.home() / "Library/Logs/Cage"
13新增:entries = []
14新增:order = itertools.count()
15新增:cutoff = datetime.now(timezone.utc) - timedelta(days=14)
16新增:if root.exists():
17新增: directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
18新增: try:
19新增: info = os.fstat(directory)
20新增: if info.st_uid != os.getuid() or info.st_mode & 0o077:
21新增: raise ValueError("diagnostic_directory_invalid")
22新增: for source in ("window", "clipboard"):
23新增: # Guest timestamps have second precision. Read rotations oldest
24新增: # first so the newest file wins ties within a source.
25新增: for suffix in ("-4", "-3", "-2", "-1", ""):
26新增: try:
27新增: fd = os.open(source + suffix + ".jsonl", os.O_RDONLY | os.O_NOFOLLOW, dir_fd=directory)
28新增: except FileNotFoundError:
29新增: continue
30新增: with os.fdopen(fd, "r", encoding="utf-8", errors="replace") as stream:
31新增: info = os.fstat(stream.fileno())
32新增: if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_nlink != 1 or info.st_size > (1 << 20) + 4096:
33新增: raise ValueError("diagnostic_file_invalid")
34新增: for line in stream:
35新增: if len(line) > 4096:
36新增: continue
37新增: try:
38新增: value = json.loads(line)
39新增: time = datetime.fromisoformat(value["time"].replace("Z", "+00:00"))
40新增: reason = value["reason"]
41新增: if time.tzinfo is None or time < cutoff or value["source"] != source or not re.fullmatch(r"[a-zA-Z][a-zA-Z0-9_]{0,95}", reason):
42新增: continue
43新增: entry = (time, next(order), dict(time=value["time"], source=source, reason=reason))
44新增: heapq.heappush(entries, entry)
45新增: if len(entries) > 150:
46新增: heapq.heappop(entries)
47新增: except (ValueError, KeyError, TypeError, AttributeError):
48新增: continue
49新增: finally:
50新增: os.close(directory)
51新增:lines = deque()
52新增:size = 0
53新增:for _, _, entry in sorted(entries):
54新增: line = json.dumps(entry, ensure_ascii=True) + "\n"
55新增: lines.append(line)
56新增: size += len(line.encode())
57新增: while len(lines) > 150 or size > 48 << 10:
58新增: size -= len(lines.popleft().encode())
59新增:print(json.dumps(dict(version=1, lines="".join(lines))))
新增internal/workbench/macos_exit_policy.go+104 −0看文件
@@ -0,0 +1,104 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "context"
5新增: "errors"
6新增: "net/http"
7新增: "time"
8新增:
9新增: "github.com/sylvinus/agent-vm/internal/cage"
10新增:)
11新增:
12新增:// Only the measured address is presented to the local trusted view. The run
13新增:// and configuration remain attached to the observation inside the workbench.
14新增:type macOSExitCandidate struct {
15新增: IP string `json:"ip"`
16新增: Fingerprint string `json:"-"`
17新增: Run string `json:"-"`
18新增: Observed time.Time `json:"-"`
19新增:}
20新增:
21新增:func macOSStaticCandidate(config cage.Config, run, host string, terminal, browser networkObservation) *macOSExitCandidate {
22新增: if host == "" || run == "" || terminal.Status != 200 || browser.Status != 200 || host != terminal.IP || host != browser.IP {
23新增: return nil
24新增: }
25新增: if config.ExitPolicy.Mode == "static" && config.ExitPolicy.IP == host {
26新增: return nil
27新增: }
28新增: return &macOSExitCandidate{IP: host, Fingerprint: config.Fingerprint(), Run: run, Observed: time.Now()}
29新增:}
30新增:
31新增:func (s *Server) bindMacOSExit(w http.ResponseWriter, r *http.Request) {
32新增: var input struct {
33新增: IP string `json:"ip"`
34新增: }
35新增: if !readJSON(w, r, &input) {
36新增: return
37新增: }
38新增: s.mu.Lock()
39新增: sample := s.safety.MacOSExitCandidate
40新增: s.mu.Unlock()
41新增: if sample == nil || input.IP != sample.IP {
42新增: http.Error(w, "请先运行联网检查,取得终端、浏览器与当前代理一致的出口", http.StatusConflict)
43新增: return
44新增: }
45新增: s.launch(w, "settings", func() error {
46新增: return s.saveMacOSStaticExit(s.operationContext(), *sample)
47新增: })
48新增:}
49新增:
50新增:func (s *Server) saveMacOSStaticExit(ctx context.Context, sample macOSExitCandidate) error {
51新增: cfg, err := loadConfig(s.configPath)
52新增: if err != nil {
53新增: return err
54新增: }
55新增: if s.macosGuest == nil || sample.IP == "" || cfg.Fingerprint() != sample.Fingerprint || time.Since(sample.Observed) > 10*time.Minute || sample.Observed.After(time.Now()) {
56新增: return errors.New("出口采样已过期或节点已变更,请重新运行联网检查")
57新增: }
58新增: if err := cfg.RequireManagedProxy(s.profile); err != nil {
59新增: return err
60新增: }
61新增: client, err := s.gateClient()
62新增: if err != nil {
63新增: return err
64新增: }
65新增: state, err := client.Status(ctx)
66新增: if err != nil {
67新增: return err
68新增: }
69新增: if state.RunID != sample.Run || state.Configuration != sample.Fingerprint {
70新增: return errors.New("客机或网络配置已变化,请重新运行联网检查")
71新增: }
72新增: loc, err := probeLocation(ctx, cfg)
73新增: if err != nil {
74新增: return err
75新增: }
76新增: observed := loc.exitLocation()
77新增: if observed.IP != sample.IP {
78新增: return errors.New("当前出口与三处采样不一致,请重新确认节点")
79新增: }
80新增: next := (cage.ExitPolicy{Mode: "static"}).BindMissing(observed)
81新增: if verdict, message := next.Evaluate(sample.IP, &observed); verdict != cage.CheckPassed {
82新增: return errors.New(message)
83新增: }
84新增: cfg.ExitPolicy = next
85新增: if err := cfg.Validate(); err != nil {
86新增: return err
87新增: }
88新增: closed, err := client.Close(ctx, "固定出口已确认,重启客机后重新检测")
89新增: if err != nil {
90新增: return err
91新增: }
92新增: s.publishGate(closed)
93新增: if closed.Mode != cage.GateClosed || closed.RunID != sample.Run || closed.Configuration != sample.Fingerprint {
94新增: return errors.New("无法确认当前客机已关闭外网")
95新增: }
96新增: if err := writePrivate(s.configPath, cfg); err != nil {
97新增: return err
98新增: }
99新增: s.mu.Lock()
100新增: s.safety.MacOSExitCandidate = nil
101新增: s.safety.Error = "已保存固定出口。请重启 macOS 客机,登录后重新检测。"
102新增: s.mu.Unlock()
103新增: return nil
104新增:}
新增internal/workbench/macos_extension.go+31 −0看文件
@@ -0,0 +1,31 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "context"
5新增: _ "embed"
6新增: "errors"
7新增: "strings"
8新增: "time"
9新增:)
10新增:
11新增://go:embed macos_extension_probe.pl
12新增:var macOSProbeFSKit string
13新增:
14新增:func (s *Server) checkMacOSSetupProjects(parent context.Context) error {
15新增: ctx, cancel := context.WithTimeout(parent, 15*time.Second)
16新增: defer cancel()
17新增: cmd := s.macOSSSHCommand(ctx, "-T", s.sshTarget(), "--", "exec /usr/bin/perl -")
18新增: cmd.Stdin = strings.NewReader(macOSProbeFSKit)
19新增: err := cmd.Run()
20新增: s.mu.Lock()
21新增: if err != nil {
22新增: s.macSetupProjectsChecked = time.Time{}
23新增: } else {
24新增: s.macSetupProjectsChecked = time.Now()
25新增: }
26新增: s.mu.Unlock()
27新增: if err != nil {
28新增: return errors.New("尚未能挂载并卸载只读测试卷。请在客机设置中启用 macFUSE 和 macFUSE (local),再点验证")
29新增: }
30新增: return nil
31新增:}
新增internal/workbench/macos_extension_probe.pl+70 −0看文件
@@ -0,0 +1,70 @@
1新增:use strict;
2新增:use warnings;
3新增:use File::Temp qw(tempdir);
4新增:use POSIX qw(_exit WNOHANG);
5新增:use Socket qw(AF_UNIX SOCK_STREAM PF_UNSPEC);
6新增:
7新增:# Two child processes connected only to one another. A local, read-only SFTP
8新增:# endpoint substitutes for the project transport and no host files are shared.
9新增:umask 077;
10新增:my $tmp = tempdir('cage-check-XXXXXXXX', DIR => '/private/var/tmp', CLEANUP => 0);
11新增:my $source = "$tmp/source";
12新增:my $mount = "$tmp/mount";
13新增:my @children;
14新增:my $attached = '';
15新增:sub mounted_line {
16新增: open my $list, '-|', '/sbin/mount' or die "mount list";
17新增: my @matches = grep { index($_, " on $mount (") >= 0 } <$list>;
18新增: close $list or die "mount list";
19新增: die "ambiguous mount" if @matches > 1;
20新增: return $matches[0] // '';
21新增:}
22新增:sub spawn_peer {
23新增: my ($side, $other, @cmd) = @_;
24新增: my $pid = fork();
25新增: die "fork" unless defined $pid;
26新增: return $pid if $pid;
27新增: close $other;
28新增: open STDIN, '<&', $side or _exit(125);
29新增: open STDOUT, '>&', $side or _exit(125);
30新增: open STDERR, '>', '/dev/null' or _exit(125);
31新增: close $side;
32新增: exec @cmd or _exit(126);
33新增:}
34新增:my $ok = eval {
35新增: local $SIG{TERM} = local $SIG{HUP} = local $SIG{INT} = sub { die "cancelled" };
36新增: mkdir $source, 0700 or die "source";
37新增: mkdir $mount, 0700 or die "target";
38新增: socketpair(my $a,my $b,AF_UNIX,SOCK_STREAM,PF_UNSPEC) or die "socketpair";
39新增: push @children, spawn_peer($a,$b,'/usr/libexec/sftp-server','-R','-d',$source);
40新增: push @children, spawn_peer($b,$a,'/usr/local/libexec/cage-sshfs',":$source",$mount,'-f','-o','slave,ro,quiet,backend=fskit,nodev,nosuid,dir_cache=no');
41新增: close $a; close $b;
42新增: for (1..35) {
43新增: $attached = mounted_line();
44新增: last if $attached;
45新增: last unless kill 0, $children[1];
46新增: select undef,undef,undef,0.2;
47新增: }
48新增: my $user = getpwuid($<);
49新增: my ($flags) = $attached =~ m{^macfuse://[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12} on \Q$mount\E \(macfuse, ([^\n]+)\)\s*$}i;
50新增: my %options = map { $_ => 1 } split /, /, ($flags // '');
51新增: die "unexpected mount" unless $options{'fskit'} && $options{'read-only'} && $options{"mounted by $user"};
52新增: 1;
53新增:};
54新增:# Never unmount a replacement or remove a mounted tree.
55新增:my $live = mounted_line();
56新增:if ($ok && $live && $live eq $attached) {
57新增: $ok = 0 unless system('/sbin/umount','-f',$mount) == 0;
58新增:}
59新增:for my $pid (@children) {
60新增: if (waitpid($pid,WNOHANG)==0) {kill 'TERM',$pid}
61新增:}
62新增:select undef,undef,undef,0.15;
63新增:for my $pid (@children) {
64新增: if (waitpid($pid,WNOHANG)==0) {kill 'KILL',$pid;waitpid($pid,0)}
65新增:}
66新增:$ok = 0 if mounted_line();
67新增:$ok = 0 unless rmdir $mount;
68新增:$ok = 0 unless rmdir $source;
69新增:$ok = 0 unless rmdir $tmp;
70新增:exit($ok ? 0 : 1);
新增internal/workbench/macos_guest.go+157 −0看文件
@@ -0,0 +1,157 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "context"
5新增: "encoding/json"
6新增: "errors"
7新增: "fmt"
8新增: "os"
9新增: "os/exec"
10新增: "path/filepath"
11新增: "strings"
12新增: "time"
13新增:
14新增: "al.essio.dev/pkg/shellescape"
15新增:
16新增: "github.com/sylvinus/agent-vm/internal/cage"
17新增: "github.com/sylvinus/agent-vm/internal/guestos"
18新增:)
19新增:
20新增:// Only the trusted local workbench can operate the native Mac. Each route
21新增:// must have a native guest implementation or run entirely on the host.
22新增:func macOSWorkbenchRoute(path string) bool {
23新增: if nativeWorkbenchRoute(path) {
24新增: return true
25新增: }
26新增: if id, ok := strings.CutPrefix(path, "/api/input/files/desktop/"); ok {
27新增: return id == "requests" || id == "open" || browserFileID.MatchString(id)
28新增: }
29新增: switch path {
30新增: case "/api/macos/first-setup", "/api/appearance/codex", "/api/macos/project-approval", "/api/macos/exit-policy", "/api/macos/login":
31新增: return true
32新增: }
33新增: return strings.HasPrefix(path, "/api/macos/claude/") || strings.HasPrefix(path, "/api/macos-browser/")
34新增:}
35新增:
36新增:func macOSInstanceRunning(instanceDir string) bool {
37新增: data, err := os.ReadFile(filepath.Join(instanceDir, "cage-running.json"))
38新增: var record struct{ PID int }
39新增: return err == nil && json.Unmarshal(data, &record) == nil && processExists(record.PID)
40新增:}
41新增:
42新增:func (s *Server) macOSSSHCommand(ctx context.Context, args ...string) *exec.Cmd {
43新增: base, err := guestos.MacOSSSHArgs(s.profile, s.macosGuest.User)
44新增: if err != nil {
45新增: return &exec.Cmd{Err: err}
46新增: }
47新增: cmd := exec.CommandContext(ctx, sshExecutable(), append(base, args...)...)
48新增: cmd.Env = sshEnvironment()
49新增: hideCommand(cmd)
50新增: return cmd
51新增:}
52新增:
53新增:func (s *Server) checkMacOSGuest(ctx context.Context) error {
54新增: if !s.vmRunning() {
55新增: return errors.New("macOS 客机尚未启动")
56新增: }
57新增: client, err := s.gateClient()
58新增: if err != nil {
59新增: return errors.New("无法验证 macOS 客机的网络隔离状态")
60新增: }
61新增: state, err := client.Status(ctx)
62新增: if err != nil {
63新增: return errors.New("无法验证 macOS 客机的网络门槛")
64新增: }
65新增: if state.Mode != cage.GateClosed {
66新增: s.mu.Lock()
67新增: ready, paused := s.ready, s.networkPaused
68新增: s.mu.Unlock()
69新增: reason := ""
70新增: switch {
71新增: case s.macSetupPending():
72新增: reason = "首次系统设置期间外网关闭"
73新增: case paused:
74新增: reason = "网络保持暂停,请手动恢复后再联网"
75新增: case !ready:
76新增: reason = "客机重新连接,外网等待重新检查"
77新增: default:
78新增: cfg, cfgErr := loadConfig(s.configPath)
79新增: if state.Mode != cage.GateOpen || cfgErr != nil || state.Report == nil || !time.Now().Before(state.Until) || state.Report.Authorizes(state.RunID, cfg.Fingerprint(), time.Now()) != nil {
80新增: reason = "网络授权未通过当前配置的完整检查"
81新增: }
82新增: }
83新增: if reason != "" {
84新增: state, err = client.Close(ctx, reason)
85新增: if err != nil || state.Mode != cage.GateClosed {
86新增: return errors.New("macOS 客机网络状态不能确认")
87新增: }
88新增: }
89新增: }
90新增: s.publishGate(state)
91新增: probe := `test "$(uname -s)" = Darwin && [[ $(sysctl -n hw.model) == VirtualMac* ]] && test "$(id -un)" = ` +
92新增: shellescape.Quote(s.macosGuest.User) + ` && [[ " $(id -Gn) " != *" admin "* ]]`
93新增: if _, err := s.guest(ctx, probe); err != nil {
94新增: return errors.New("无法以已绑定的普通用户连接到这台虚拟 Mac,请检查客机身份和 SSH 登录")
95新增: }
96新增: return nil
97新增:}
98新增:
99新增:func (s *Server) attachMacOSGuest() error {
100新增: ctx, cancel := s.controlContext()
101新增: defer cancel()
102新增: err := s.checkMacOSGuest(ctx)
103新增: s.mu.Lock()
104新增: newlyReady := !s.ready && err == nil
105新增: checkAfterReconnect := newlyReady && !s.closing && !s.networkPaused && !s.jobs.snapshot().Running
106新增: s.ready = err == nil
107新增: s.guestUpdateError = ""
108新增: if err != nil {
109新增: s.guestUpdateError = err.Error()
110新增: }
111新增: s.mu.Unlock()
112新增: if newlyReady && !s.macSetupPending() {
113新增: s.restoreProjectShares()
114新增: if checkAfterReconnect {
115新增: _, _ = s.submitJob("network-recovery", s.checkNetworkIfWanted)
116新增: }
117新增: }
118新增: return err
119新增:}
120新增:
121新增:func (s *Server) macOSLifecycleCommand(action string) error {
122新增: ctx, cancel := context.WithTimeout(s.operationContext(), 5*time.Minute)
123新增: defer cancel()
124新增: cmd := exec.CommandContext(ctx, s.exe, "guest-os", "macos", action)
125新增: cmd.Env = append(os.Environ(), cage.ConfigEnv+"="+s.configPath)
126新增: job := s.jobs.execution()
127新增: cmd.Stdout, cmd.Stderr = job, job
128新增: if err := cmd.Run(); err != nil {
129新增: return fmt.Errorf("macOS 客机操作失败(%s):%w", action, err)
130新增: }
131新增: return nil
132新增:}
133新增:
134新增:func (s *Server) startMacOSGuest() error {
135新增: if !s.vmRunning() {
136新增: if err := s.macOSLifecycleCommand("start"); err != nil {
137新增: return err
138新增: }
139新增: }
140新增: if err := s.attachMacOSGuest(); err != nil {
141新增: return err
142新增: }
143新增: return s.checkNetworkIfWanted()
144新增:}
145新增:
146新增:func (s *Server) stopMacOSGuest() error {
147新增: s.mu.Lock()
148新增: s.macSetupProjectsChecked = time.Time{}
149新增: s.mu.Unlock()
150新增: s.closeWindowsBrowser()
151新增: s.mu.Lock()
152新增: s.ready = false
153新增: s.mu.Unlock()
154新增: s.terminals.closeAll()
155新增: s.closeProjectShares()
156新增: return s.macOSLifecycleCommand("stop")
157新增:}
新增internal/workbench/macos_guest_test.go+200 −0看文件
@@ -0,0 +1,200 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "bytes"
5新增: "context"
6新增: "encoding/json"
7新增: "net/http"
8新增: "net/http/httptest"
9新增: "os"
10新增: "path/filepath"
11新增: "slices"
12新增: "strings"
13新增: "testing"
14新增:
15新增: "github.com/sylvinus/agent-vm/internal/guestos"
16新增:)
17新增:
18新增:func TestMacOSConnectionIgnoresSSHConfigOverrides(t *testing.T) {
19新增: s := testServer(t)
20新增: s.macosGuest = &guestos.MacOSProfile{Instance: "mac", User: "devuser"}
21新增: if err := os.MkdirAll(s.instanceDir(), 0700); err != nil {
22新增: t.Fatal(err)
23新增: }
24新增: cfg := "Host lima-mac\n User root\n HostName 192.0.2.1\n Port 54432\n ProxyCommand false\n StrictHostKeyChecking no\n ForwardAgent yes\n"
25新增: if err := os.WriteFile(filepath.Join(s.instanceDir(), "ssh.config"), []byte(cfg), 0600); err != nil {
26新增: t.Fatal(err)
27新增: }
28新增: cmd := s.sshCommand(context.Background(), "-tt", s.sshTarget(), "--", "uname -s")
29新增: for _, value := range []string{os.DevNull, "54432", "devuser", "Hostname=127.0.0.1", "HostKeyAlias=cage-macos", "StrictHostKeyChecking=yes", "ForwardAgent=no", "ClearAllForwardings=yes", "cage-macos"} {
30新增: if !slices.Contains(cmd.Args, value) {
31新增: t.Errorf("bound SSH missing %q", value)
32新增: }
33新增: }
34新增: for _, value := range []string{"192.0.2.1", "root", "ForwardAgent=yes", "StrictHostKeyChecking=no", "lima-mac"} {
35新增: if slices.Contains(cmd.Args, value) {
36新增: t.Errorf("untrusted override %q used", value)
37新增: }
38新增: }
39新增: if !strings.Contains(strings.Join(cmd.Args, " "), filepath.Join(s.profile, "macos-known-hosts")) {
40新增: t.Fatal("missing profile-scoped host key")
41新增: }
42新增: for _, bad := range []string{"", "Port 0", "Port 65536", "Port 22\nPort 23", "Port 22 -o Anything"} {
43新增: if _, err := guestos.MacOSSSHPort([]byte(bad)); err == nil {
44新增: t.Errorf("accepted %q", bad)
45新增: }
46新增: }
47新增:}
48新增:
49新增:func TestMacOSWorkbenchLocalViewIsolation(t *testing.T) {
50新增: s := testServer(t)
51新增: s.macosGuest = &guestos.MacOSProfile{Instance: "mac", User: "guestdev"}
52新增: h := s.handler()
53新增: check := func(path string, trusted bool, want int) {
54新增: t.Helper()
55新增: r := httptest.NewRequest("GET", s.origin+path, nil)
56新增: r.AddCookie(&http.Cookie{Name: s.cookieName(), Value: s.session})
57新增: if trusted {
58新增: r.AddCookie(&http.Cookie{Name: s.cookieName() + "-desktop", Value: trustedViewProof(s.token)})
59新增: }
60新增: w := httptest.NewRecorder()
61新增: h.ServeHTTP(w, r)
62新增: if w.Code != want {
63新增: t.Errorf("%s trusted=%v: got %d; want %d", path, trusted, w.Code, want)
64新增: }
65新增: if path == "/api/account" && trusted && !strings.Contains(w.Body.String(), `"guest_system":"macos"`) {
66新增: t.Fatal("trusted view did not select the macOS workbench")
67新增: }
68新增: }
69新增: check("/api/account", false, http.StatusForbidden)
70新增: check("/api/account", true, http.StatusOK)
71新增: r := httptest.NewRequest("GET", s.origin+"/api/account", nil)
72新增: r.AddCookie(&http.Cookie{Name: s.cookieName(), Value: s.session})
73新增: r.AddCookie(&http.Cookie{Name: s.cookieName() + "-desktop", Value: trustedViewProof(s.token)})
74新增: w := httptest.NewRecorder()
75新增: h.ServeHTTP(w, r)
76新增: var account accountView
77新增: if err := json.Unmarshal(w.Body.Bytes(), &account); err != nil || account.MacOSGuestUser != "guestdev" {
78新增: t.Fatalf("actual guest login was not returned: %s", w.Body.String())
79新增: }
80新增:
81新增: check("/api/browser/tabs", true, http.StatusConflict)
82新增: check("/api/proxy", false, http.StatusForbidden)
83新增: check("/api/mobile/pair", true, http.StatusConflict)
84新增:}
85新增:
86新增:func TestMacOSReadyBrowserRoutesUseNativeGuest(t *testing.T) {
87新增: s := testServer(t)
88新增: s.macosGuest = &guestos.MacOSProfile{Instance: "mac", User: "guestdev"}
89新增: s.ready = true
90新增: s.windowsBrowserControl = fixtureWindowsBrowserClient(t)
91新增: r := windowsBrowserRequestForTest(s, http.MethodGet, "/api/browser/tabs", nil)
92新增: if r.Code != http.StatusOK || !json.Valid(r.Body.Bytes()) || s.browserControl != nil {
93新增: t.Fatalf("ready Mac browser failed to use the native transport: %d", r.Code)
94新增: }
95新增: if !macOSWorkbenchRoute("/api/input/files/browser/chunks") || macOSWorkbenchRoute("/api/input/files/desktop/chunks") {
96新增: t.Fatal("native browser upload route boundary mismatch")
97新增: }
98新增:}
99新增:
100新增:func TestMacOSProjectRejectsSiblingProfileAndCredentials(t *testing.T) {
101新增: home := t.TempDir()
102新增: t.Setenv("HOME", home)
103新增: t.Setenv("USERPROFILE", home)
104新增: profile := filepath.Join(home, ".claude-cage", "macos-trial")
105新增: dailyState := filepath.Join(home, ".claude-cage", "state", "lima")
106新增: credentials := filepath.Join(home, ".ssh")
107新增: project := filepath.Join(home, "Cage Projects", "demo")
108新增: for _, dir := range []string{profile, dailyState, credentials, project} {
109新增: if err := os.MkdirAll(dir, 0700); err != nil {
110新增: t.Fatal(err)
111新增: }
112新增: }
113新增: s := &Server{profile: profile, macosGuest: &guestos.MacOSProfile{User: "guestdev"}}
114新增: for _, dir := range []string{dailyState, credentials} {
115新增: if err := s.ensureProjectShare(dir); err == nil || !strings.Contains(err.Error(), "共享") {
116新增: t.Fatalf("%s was not rejected before contacting the guest: %v", dir, err)
117新增: }
118新增: }
119新增: if err := validateHostProjectData(project, profile); err != nil {
120新增: t.Fatal(err)
121新增: }
122新增:}
123新增:
124新增:func TestMacOSProjectApprovalIsBoundToOnePendingShare(t *testing.T) {
125新增: s := testServer(t)
126新增: s.macosGuest = &guestos.MacOSProfile{Instance: "mac", User: "guestdev"}
127新增: s.ready = true
128新增: folder := t.TempDir()
129新增: share := &projectShare{}
130新增: s.projectShares = map[string]*projectShare{folder: share}
131新增: s.beginMacOSProjectApproval(folder, share)
132新增: grant := share.approval
133新增: t.Cleanup(func() { share.approvalTimer.Stop() })
134新增: call := func(path, proof string) int {
135新增: t.Helper()
136新增: body, _ := json.Marshal(map[string]string{"workspace": path, "grant": proof, "action": "cancel"})
137新增: r := httptest.NewRequest("POST", s.origin+"/api/macos/project-approval", bytes.NewReader(body))
138新增: r.Header.Set("Content-Type", "application/json")
139新增: r.Header.Set("Origin", s.origin)
140新增: r.AddCookie(&http.Cookie{Name: s.cookieName(), Value: s.session})
141新增: r.AddCookie(&http.Cookie{Name: s.cookieName() + "-desktop", Value: trustedViewProof(s.token)})
142新增: w := httptest.NewRecorder()
143新增: s.handler().ServeHTTP(w, r)
144新增: return w.Code
145新增: }
146新增: if call(folder, "invalid") != http.StatusConflict || call(folder+"/other", grant) != http.StatusConflict || s.projectShares[folder] != share {
147新增: t.Fatal("unrelated approval canceled the pending host share")
148新增: }
149新增: if call(folder, grant) != 200 || s.projectShares[folder] != nil || call(folder, grant) != http.StatusConflict {
150新增: t.Fatal("a canceled project grant can still be reused")
151新增: }
152新增:}
153新增:
154新增:func TestInitialMacSetupQuarantinesRegularWorkbench(t *testing.T) {
155新增: s := testServer(t)
156新增: s.macosGuest = &guestos.MacOSProfile{User: "cageuser", Instance: "mac", SetupID: "new"}
157新增: // An unreadable binding is also quarantined. Allow only UI bootstrap,
158新增: // account authentication, and the startup/first-setup endpoints.
159新增: for _, path := range []string{"/api/browser/tabs", "/api/terminals", "/api/macos/login", "/api/projects/open", "/api/safety/check", "/api/macos/claude/window"} {
160新增: w := request(s, "GET", path, s.origin, "", true)
161新增: if w.Code != http.StatusConflict {
162新增: t.Errorf("setup exposed %s: %d", path, w.Code)
163新增: }
164新增: }
165新增: s.macosGuest.SetupID = ""
166新增: for _, action := range []string{"open", "finish", "frame", "fill-password"} {
167新增: req := httptest.NewRequest("POST", s.origin+"/api/macos/first-setup", strings.NewReader(`{"action":"`+action+`"}`))
168新增: req.Header.Set("Origin", s.origin)
169新增: req.Header.Set("Content-Type", "application/json")
170新增: req.AddCookie(&http.Cookie{Name: s.cookieName(), Value: s.session})
171新增: req.AddCookie(&http.Cookie{Name: s.cookieName() + "-desktop", Value: trustedViewProof(s.token)})
172新增: w := httptest.NewRecorder()
173新增: s.handler().ServeHTTP(w, req)
174新增: if w.Code != http.StatusGone {
175新增: t.Errorf("completed setup allowed %s: %d", action, w.Code)
176新增: }
177新增: }
178新增:}
179新增:
180新增:func TestMacOSSetupAdministratorIdentity(t *testing.T) {
181新增: for _, user := range []string{"cage", "cageprovision"} {
182新增: t.Run(user, func(t *testing.T) {
183新增: s := testServer(t)
184新增: s.macosGuest = &guestos.MacOSProfile{Instance: "mac", User: "cage"}
185新增: if err := os.MkdirAll(s.instanceDir(), 0700); err != nil {
186新增: t.Fatal(err)
187新增: }
188新增: if err := os.WriteFile(filepath.Join(s.instanceDir(), "ssh.config"), []byte("User "+user+"\nPort 12345\n"), 0600); err != nil {
189新增: t.Fatal(err)
190新增: }
191新增: cmd := s.macOSSetupAdminCommand(t.Context())
192新增: if cmd.Err != nil {
193新增: t.Fatal(cmd.Err)
194新增: }
195新增: if !slices.Contains(cmd.Args, user) || cmd.Args[len(cmd.Args)-1] != "exec /usr/bin/sudo -S -p '' /usr/local/libexec/cage-finish-initial-setup < /Users/"+user+"/password" {
196新增: t.Fatalf("incorrect setup identity: %v", cmd.Args)
197新增: }
198新增: })
199新增: }
200新增:}
新增internal/workbench/macos_input_contract_test.go+127 −0看文件
@@ -0,0 +1,127 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "bufio"
5新增: "bytes"
6新增: "encoding/json"
7新增: "net/http"
8新增: "net/http/httptest"
9新增: "strings"
10新增: "testing"
11新增: "time"
12新增:
13新增: "github.com/gorilla/websocket"
14新增: "golang.org/x/crypto/ssh"
15新增:)
16新增:
17新增:func TestMacOSWindowInputContract(t *testing.T) {
18新增: x, y, button, down := 0.2, 0.3, 2, true
19新增: target := macOSWindowRequest{PID: 42, Window: 7, Geometry: "geometry"}
20新增: pointer := target
21新增: pointer.Action, pointer.Phase, pointer.X, pointer.Y = "pointer", "down", &x, &y
22新增: pointer.Button, pointer.Buttons, pointer.Clicks = &button, 2, 2
23新增: if !validMacOSWindowRequest(pointer) {
24新增: t.Fatal("targeted right double-click was rejected")
25新增: }
26新增: pointer.Phase, pointer.Button = "move", nil
27新增: if !validMacOSWindowRequest(pointer) {
28新增: t.Fatal("targeted drag move was rejected")
29新增: }
30新增: pointer.Geometry = ""
31新增: if validMacOSWindowRequest(pointer) {
32新增: t.Fatal("pointer without captured geometry was accepted")
33新增: }
34新增: key := target
35新增: key.Action, key.Key, key.Code, key.Down = "key", "/", "Slash", &down
36新增: if !validMacOSWindowRequest(key) {
37新增: t.Fatal("physical key transition was rejected")
38新增: }
39新增: key.Down = nil
40新增: if validMacOSWindowRequest(key) {
41新增: t.Fatal("physical key without a transition was accepted")
42新增: }
43新增: ime := target
44新增: ime.Action, ime.Mode, ime.Context, ime.Session = "ime", "begin", strings.Repeat("a", 32), strings.Repeat("b", 32)
45新增: if !validMacOSWindowRequest(ime) {
46新增: t.Fatal("targeted composition was rejected")
47新增: }
48新增: ime.Mode, ime.Sequence = "commit", -1
49新增: if validMacOSWindowRequest(ime) {
50新增: t.Fatal("negative composition sequence was accepted")
51新增: }
52新增: if !validMacOSWindowRequest(macOSWindowRequest{Action: "input-reset"}) || !validMacOSWindowRequest(macOSWindowRequest{Action: "status"}) {
53新增: t.Fatal("connection cleanup or existing status request was rejected")
54新增: }
55新增:}
56新增:
57新增:func TestMacOSWindowInputRoutesPreserveCompositionSequence(t *testing.T) {
58新增: guest := newMacWorkspaceGuest(t, func(channel ssh.Channel, command string) (uint32, bool) {
59新增: if !strings.Contains(command, "window.sock") {
60新增: return 0, false
61新增: }
62新增: reader := bufio.NewReader(channel)
63新增: for {
64新增: var input macOSWindowRequest
65新增: if json.NewDecoder(reader).Decode(&input) != nil {
66新增: return 0, true
67新增: }
68新增: if json.NewEncoder(channel).Encode(input) != nil || !input.KeepAlive {
69新增: return 0, true
70新增: }
71新增: }
72新增: })
73新增: s := guest.s
74新增: server := httptest.NewServer(http.HandlerFunc(s.macOSWindowConnection))
75新增: defer server.Close()
76新增: s.origin = server.URL
77新增: ws, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(server.URL, "http"), http.Header{"Origin": {server.URL}})
78新增: if err != nil {
79新增: t.Fatal(err)
80新增: }
81新增: defer ws.Close()
82新增: for sequence, mode := range []string{"begin", "update", "commit"} {
83新增: input := macOSWindowRequest{Action: "ime", PID: 42, Window: 7, Geometry: "geometry", Mode: mode,
84新增: Context: strings.Repeat("a", 32), Session: strings.Repeat("b", 32), Sequence: sequence,
85新增: Project: "ungranted", PhoneToken: "ungranted", Path: "ungranted", Transfer: "ungranted", KeepAlive: true, Wait: true, Binary: true}
86新增: if mode == "commit" {
87新增: input.Text = strings.Repeat("\x01", 8192)
88新增: }
89新增: if err := ws.WriteJSON(map[string]any{"id": sequence + 1, "request": input}); err != nil {
90新增: t.Fatal(err)
91新增: }
92新增: var response struct {
93新增: ID int `json:"id"`
94新增: Result macOSWindowRequest `json:"result"`
95新增: }
96新增: _ = ws.SetReadDeadline(time.Now().Add(5 * time.Second))
97新增: if err := ws.ReadJSON(&response); err != nil {
98新增: t.Fatal(err)
99新增: }
100新增: check := func(actual macOSWindowRequest, keepAlive bool) {
101新增: t.Helper()
102新增: if actual.Sequence != sequence || actual.Session != input.Session || actual.Text != input.Text || actual.Geometry != input.Geometry {
103新增: t.Fatalf("composition changed in transit for %s, sequence %d", mode, actual.Sequence)
104新增: }
105新增: if actual.Project != "" || actual.Path != "" || actual.PhoneToken != "" || actual.Transfer != "" || actual.Wait || actual.Binary || actual.KeepAlive != keepAlive {
106新增: t.Fatalf("public input retained privileged fields for %s", mode)
107新增: }
108新增: }
109新增: check(response.Result, true)
110新增: data, err := json.Marshal(input)
111新增: if err != nil {
112新增: t.Fatal(err)
113新增: }
114新增: recorder := httptest.NewRecorder()
115新增: request := httptest.NewRequest(http.MethodPost, "/api/macos/claude/window", bytes.NewReader(data))
116新增: request.Header.Set("Content-Type", "application/json")
117新增: s.macOSClaudeWindow(recorder, request)
118新增: if recorder.Code != http.StatusOK {
119新增: t.Fatalf("HTTP input returned %d: %s", recorder.Code, recorder.Body.String())
120新增: }
121新增: var actual macOSWindowRequest
122新增: if err := json.Unmarshal(recorder.Body.Bytes(), &actual); err != nil {
123新增: t.Fatal(err)
124新增: }
125新增: check(actual, false)
126新增: }
127新增:}
新增internal/workbench/macos_login.go+226 −0看文件
@@ -0,0 +1,226 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "context"
5新增: "encoding/json"
6新增: "errors"
7新增: "github.com/sylvinus/agent-vm/internal/cage"
8新增: "io"
9新增: "net"
10新增: "net/http"
11新增: "os/exec"
12新增: "path/filepath"
13新增: "strings"
14新增: "time"
15新增:
16新增: "github.com/sylvinus/agent-vm/internal/guestos"
17新增:)
18新增:
19新增:// Only installer-created bindings carry this identity. A damaged binding stays
20新增:// quarantined; the VM process independently requires a valid matching binding.
21新增:func (s *Server) macSetupPending() bool {
22新增: if s.macosGuest == nil || s.macosGuest.SetupID == "" {
23新增: return false
24新增: }
25新增: current, err := guestos.LoadMacOSProfile(s.profile)
26新增: return err != nil || current == nil || current.SetupID != ""
27新增:}
28新增:
29新增:func macOSSetupRoute(path string) bool {
30新增: if !strings.HasPrefix(path, "/api/") {
31新增: return true
32新增: }
33新增: switch path {
34新增: case "/api/account", "/api/appearance", "/api/session", "/api/launch", "/api/handoff", "/api/remote/manifest", "/api/status", "/api/start", "/api/stop", "/api/macos/first-setup", "/api/environment/initialization":
35新增: return true
36新增: }
37新增: return strings.HasPrefix(path, "/api/account/") || strings.HasPrefix(path, "/api/diagnostics")
38新增:}
39新增:
40新增:type macSetupPermissions struct {
41新增: Screen bool `json:"screen"`
42新增: Input bool `json:"input"`
43新增: Projects bool `json:"projects"`
44新增: Error string `json:"error,omitempty"`
45新增: ManagedCredential bool `json:"managed_credential,omitempty"`
46新增:}
47新增:
48新增:func (s *Server) macSetupPermissions(ctx context.Context) (macSetupPermissions, error) {
49新增: var status macSetupPermissions
50新增: data, err := s.macOSWindowCall(ctx, macOSWindowRequest{Action: "setup-status"})
51新增: if err != nil {
52新增: return status, err
53新增: }
54新增: if json.Unmarshal(data, &status) != nil || status.Error != "" {
55新增: return status, errors.New("请在首次设置画面中登录客机账户")
56新增: }
57新增: s.mu.Lock()
58新增: status.Projects = !s.macSetupProjectsChecked.IsZero() && time.Since(s.macSetupProjectsChecked) < 2*time.Minute
59新增: probeDue := time.Since(s.macSetupProjectsAttempt) > 15*time.Second
60新增: s.mu.Unlock()
61新增: if status.Screen && status.Input && !status.Projects && probeDue && s.op.TryLock() {
62新增: s.mu.Lock()
63新增: s.macSetupProjectsAttempt = time.Now()
64新增: s.mu.Unlock()
65新增: _ = s.checkMacOSSetupProjects(ctx)
66新增: s.op.Unlock()
67新增: s.mu.Lock()
68新增: status.Projects = !s.macSetupProjectsChecked.IsZero()
69新增: s.mu.Unlock()
70新增: }
71新增: if install, err := guestos.LoadInstallation(s.profile); err == nil && install != nil {
72新增: password, err := s.account.savedMacGuestPassword(ctx, install.ID)
73新增: status.ManagedCredential = err == nil && password != ""
74新增: }
75新增: return status, nil
76新增:}
77新增:
78新增:func (s *Server) macOSLoginWindow(w http.ResponseWriter, r *http.Request) {
79新增: if s.macosGuest == nil || !s.hasTrustedView(r) {
80新增: http.NotFound(w, r)
81新增: return
82新增: }
83新增: var input guestos.MacLoginRequest
84新增: if !readJSON(w, r, &input) {
85新增: return
86新增: }
87新增: input.Setup = r.URL.Path == "/api/macos/first-setup"
88新增: if input.Setup && !s.macSetupPending() {
89新增: http.Error(w, "首次设置入口已关闭", http.StatusGone)
90新增: return
91新增: }
92新增: // Passwords are supplied exclusively from encrypted storage, never from HTTP.
93新增: input.Password = ""
94新增: if input.Action == "show-password" {
95新增: install, err := guestos.LoadInstallation(s.profile)
96新增: bound, bindingErr := guestos.LoadMacOSProfile(s.profile)
97新增: if err != nil || bindingErr != nil || install == nil || bound == nil || bound.MachineID != s.macosGuest.MachineID {
98新增: http.Error(w, "客机身份已改变", 409)
99新增: return
100新增: }
101新增: password, err := s.account.savedMacGuestPassword(r.Context(), install.ID)
102新增: if err != nil || password == "" {
103新增: http.Error(w, "客机凭据不可用,请核对安装记录与保险箱", 409)
104新增: return
105新增: }
106新增: w.Header().Set("Cache-Control", "no-store")
107新增: jsonReply(w, map[string]string{"password": password})
108新增: return
109新增: }
110新增: if input.Setup {
111新增: gate, err := s.gateClient()
112新增: if err != nil {
113新增: http.Error(w, "请先启动客机,确认首次设置期间外网已关闭", 409)
114新增: return
115新增: }
116新增: check, cancel := context.WithTimeout(r.Context(), 2*time.Second)
117新增: state, err := gate.Status(check)
118新增: cancel()
119新增: if err != nil || state.Mode != cage.GateClosed {
120新增: http.Error(w, "首次设置仅在客机断网时可用", 409)
121新增: return
122新增: }
123新增: switch input.Action {
124新增: case "fill-password":
125新增: // The native runner fills macOS's own authorization dialog. The browser
126新增: // never receives the stored credential; no submit key is sent.
127新增: install, err := guestos.LoadInstallation(s.profile)
128新增: if err != nil || install == nil || install.ID.String() != s.macosGuest.SetupID {
129新增: http.Error(w, "首次设置身份已改变", 409)
130新增: return
131新增: }
132新增: password, err := s.account.savedMacGuestPassword(r.Context(), install.ID)
133新增: if err != nil || password == "" {
134新增: http.Error(w, "客机凭据不可用,请核对安装记录与保险箱", 409)
135新增: return
136新增: }
137新增: input.Password = password
138新增: case "permissions", "verify-projects", "finish":
139新增: perm, err := s.macSetupPermissions(r.Context())
140新增: if err != nil {
141新增: http.Error(w, err.Error(), 409)
142新增: return
143新增: }
144新增: if input.Action == "permissions" {
145新增: jsonReply(w, perm)
146新增: return
147新增: }
148新增: if input.Action == "finish" && (!perm.Screen || !perm.Input) {
149新增: http.Error(w, "请先完成窗口录制、辅助功能和文件系统扩展三项授权", 409)
150新增: return
151新增: }
152新增: if !s.op.TryLock() {
153新增: http.Error(w, "正在处理其他客机操作,请重试", 409)
154新增: return
155新增: }
156新增: defer s.op.Unlock()
157新增: if err = s.checkMacOSSetupProjects(r.Context()); err != nil {
158新增: http.Error(w, err.Error(), 409)
159新增: return
160新增: }
161新增: if input.Action == "verify-projects" {
162新增: perm.Projects = true
163新增: jsonReply(w, perm)
164新增: return
165新增: }
166新增: // The cleanup executable is fixed, root-owned and verifies the temporary
167新增: // setup administrator before retiring it. Its output contains no credentials.
168新增: ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
169新增: defer cancel()
170新增: cmd := s.macOSSetupAdminCommand(ctx)
171新增: if err = cmd.Run(); err != nil {
172新增: http.Error(w, "临时设置账户未关闭,请重试完成设置", 409)
173新增: return
174新增: }
175新增: case "screen", "input", "projects":
176新增: s.macOSWindowRPC(w, r, macOSWindowRequest{Action: "setup-" + input.Action})
177新增: return
178新增: case "open", "close", "frame", "click", "key", "scroll":
179新增: default:
180新增: http.Error(w, "无效的首次设置操作", 400)
181新增: return
182新增: }
183新增: } else if input.Action == "finish" {
184新增: http.Error(w, "无效的登录操作", 400)
185新增: return
186新增: }
187新增: if len(input.Session) > 80 {
188新增: http.Error(w, "无效的登录会话", 400)
189新增: return
190新增: }
191新增: ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
192新增: defer cancel()
193新增: var dial net.Dialer
194新增: conn, err := dial.DialContext(ctx, "unix", filepath.Join(s.instanceDir(), "cage-login.sock"))
195新增: if err != nil {
196新增: http.Error(w, "这台客机尚未启动带登录控件的运行器", 409)
197新增: return
198新增: }
199新增: defer conn.Close()
200新增: _ = conn.SetDeadline(time.Now().Add(8 * time.Second))
201新增: var result guestos.MacLoginReply
202新增: if json.NewEncoder(conn).Encode(input) != nil || json.NewDecoder(io.LimitReader(conn, 6<<20)).Decode(&result) != nil {
203新增: http.Error(w, "客机登录界面无法响应", 503)
204新增: return
205新增: }
206新增: if input.Setup && input.Action == "finish" && result.Error == "" && !s.macSetupPending() {
207新增: s.restoreProjectShares()
208新增: }
209新增: w.Header().Set("Cache-Control", "no-store")
210新增: jsonReply(w, result)
211新增:}
212新增:
213新增:func (s *Server) macOSSetupAdminCommand(ctx context.Context) *exec.Cmd {
214新增: user, err := guestos.MacOSProvisionUser(s.profile)
215新增: if err != nil {
216新增: return &exec.Cmd{Err: err}
217新增: }
218新增: args, err := guestos.MacOSSSHArgs(s.profile, user)
219新增: if err != nil {
220新增: return &exec.Cmd{Err: err}
221新增: }
222新增: cmd := exec.CommandContext(ctx, sshExecutable(), append(args, "-T", "cage-macos", "--", "exec /usr/bin/sudo -S -p '' /usr/local/libexec/cage-finish-initial-setup < /Users/"+user+"/password")...)
223新增: cmd.Env = sshEnvironment()
224新增: hideCommand(cmd)
225新增: return cmd
226新增:}
新增internal/workbench/macos_mobile_browser.go+21 −0看文件
@@ -0,0 +1,21 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "context"
5新增: "os/exec"
6新增:
7新增: "al.essio.dev/pkg/shellescape"
8新增:)
9新增:
10新增:func (s *Server) macOSPhoneBrowserClient(parent context.Context) *windowsBrowserClient {
11新增: ctx, cancel := context.WithCancel(parent)
12新增: return &windowsBrowserClient{ctx: ctx, cancel: cancel, start: func(ctx context.Context) (*exec.Cmd, error) {
13新增: const base = "/usr/local/libexec/cage-workbench-browser-4.145.0-pw1.65.0/"
14新增: configuration, err := loadConfig(s.configPath)
15新增: if err != nil {
16新增: return nil, err
17新增: }
18新增: command := "exec " + shellescape.QuoteCommand([]string{"env", "LANG=" + configuration.Locale, "LC_ALL=" + configuration.Locale, base + "editor/lib/node", base + "controller/macos-phone-browser.mjs"})
19新增: return s.macOSSSHCommand(ctx, "-T", s.sshTarget(), "--", command), nil
20新增: }}
21新增:}
新增internal/workbench/macos_mobile_test.go+72 −0看文件
@@ -0,0 +1,72 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "context"
5新增: "net/http"
6新增: "path/filepath"
7新增: "strings"
8新增: "testing"
9新增:
10新增: "github.com/sylvinus/agent-vm/internal/guestos"
11新增:)
12新增:
13新增:func TestMacOSPhoneRequiresCurrentRoomAndAccountUnlock(t *testing.T) {
14新增: s := testServer(t)
15新增: s.macosGuest = &guestos.MacOSProfile{Instance: "mac", User: "cage"}
16新增: workspace := t.TempDir()
17新增: if err := writePrivate(filepath.Join(s.profile, "environment.json"), map[string]string{"directory": workspace}); err != nil {
18新增: t.Fatal(err)
19新增: }
20新增: room, cancel := context.WithCancel(context.Background())
21新增: t.Cleanup(cancel)
22新增: s.phones.record = &phoneRecord{}
23新增: s.phones.roomCtx, s.phones.roomProof = room, "current-private-room"
24新增: path := "/api/mobile/cli/projects"
25新增: for _, proof := range []string{"", "expired-private-room"} {
26新增: if response := windowsPhoneRequest(t, s, http.MethodGet, path, "", proof); response.Code != http.StatusForbidden {
27新增: t.Fatalf("untrusted phone admitted: %d", response.Code)
28新增: }
29新增: }
30新增: response := windowsPhoneRequest(t, s, http.MethodGet, path, "", s.phones.roomProof)
31新增: if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), `"shared_sessions":true`) {
32新增: t.Fatalf("Mac phone could not read shared projects: %d %s", response.Code, response.Body.String())
33新增: }
34新增: if response := windowsPhoneRequest(t, s, http.MethodGet, "/api/settings", "", s.phones.roomProof); response.Code != http.StatusForbidden {
35新增: t.Fatal("phone proof allowed desktop administration")
36新增: }
37新增: s.account.trustedSession = true
38新增: if response := windowsPhoneRequest(t, s, http.MethodGet, path, "", s.phones.roomProof); response.Code != http.StatusLocked {
39新增: t.Fatal("phone inherited a desktop-only account unlock")
40新增: }
41新增: s.account.trustedSession = false
42新增: cancel()
43新增: if response := windowsPhoneRequest(t, s, http.MethodGet, path, "", s.phones.roomProof); response.Code != http.StatusForbidden {
44新增: t.Fatal("revoked phone retained access")
45新增: }
46新增:}
47新增:
48新增:func TestMacOSPhoneMediaUsesBoundGuestProject(t *testing.T) {
49新增: s := testServer(t)
50新增: s.macosGuest = &guestos.MacOSProfile{Instance: "mac", User: "cage"}
51新增: workspace := t.TempDir()
52新增: guest := s.cliWorkspace(workspace)
53新增: name, err := mediaFileName(guest, guest, guest+"/images/example.png")
54新增: if err != nil || name != filepath.Join("images", "example.png") {
55新增: t.Fatalf("guest media did not resolve within host project: %q %v", name, err)
56新增: }
57新增: if _, err := mediaFileName(guest, guest, guest+"/../outside.png"); err == nil {
58新增: t.Fatal("guest media escaped its bound project")
59新增: }
60新增:}
61新增:
62新增:func TestMacOSPhoneBrowserPreservesPublicNetworkDenial(t *testing.T) {
63新增: s := &Server{macosGuest: &guestos.MacOSProfile{User: "cage"}}
64新增: s.phones.browser.nativeBrowser = fixtureWindowsBrowserClient(t)
65新增: _, status, err := s.phoneSurfaceGuest(context.Background(), phoneBrowser, "", "frame", phoneSurfaceInput{ID: "550e8400-e29b-41d4-a716-446655440000"})
66新增: if err != nil || status != http.StatusForbidden {
67新增: t.Fatalf("native public-network denial changed: %d %v", status, err)
68新增: }
69新增: if !macOSWorkbenchRoute("/api/mobile/browser/550e8400-e29b-41d4-a716-446655440000/frame") {
70新增: t.Fatal("native phone browser route remains unavailable")
71新增: }
72新增:}
新增internal/workbench/macos_phone_desktop.go+79 −0看文件
@@ -0,0 +1,79 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "bytes"
5新增: "context"
6新增: "encoding/base64"
7新增: "encoding/json"
8新增: "image/jpeg"
9新增: "net/http"
10新增:)
11新增:
12新增:// The phone uses its own host-generated secret on the private signed GUI agent.
13新增:// The ordinary desktop window endpoint cannot submit these actions.
14新增:func (s *Server) macOSPhoneDesktop(ctx context.Context, token, op string, input phoneSurfaceInput) ([]byte, int, error) {
15新增: if token == "" {
16新增: return nil, http.StatusGone, nil
17新增: }
18新增: out, err := s.macOSWindowCall(ctx, macOSWindowRequest{Action: "phone-" + op, Phone: &input, PhoneToken: token})
19新增: if err != nil {
20新增: return nil, http.StatusBadGateway, err
21新增: }
22新增: return macOSPhoneDesktopReply(out, op, input.ID)
23新增:}
24新增:
25新增:func macOSPhoneDesktopReply(out []byte, op, id string) ([]byte, int, error) {
26新增: limit := 4096
27新增: if op == "frame" {
28新增: limit = 3 << 20
29新增: }
30新增: var reply struct {
31新增: Error string `json:"error"`
32新增: ID string `json:"id"`
33新增: Document string `json:"document"`
34新增: Image string `json:"image"`
35新增: Width int `json:"width"`
36新增: Height int `json:"height"`
37新增: ContentWidth float64 `json:"content_width"`
38新增: ContentHeight float64 `json:"content_height"`
39新增: }
40新增: if len(out) > limit || json.Unmarshal(out, &reply) != nil {
41新增: return nil, http.StatusBadGateway, nil
42新增: }
43新增: if reply.Error != "" {
44新增: status := http.StatusBadGateway
45新增: switch reply.Error {
46新增: case "phone_session_ended", "gui_session_changed", "requires_gui_login":
47新增: status = http.StatusGone
48新增: case "window_changed", "phone_document_changed", "phone_focus_changed", "not_running", "no_visible_window":
49新增: status = http.StatusConflict
50新增: case "screen_recording_permission", "accessibility_permission":
51新增: status = http.StatusForbidden
52新增: case "invalid_input":
53新增: status = http.StatusBadRequest
54新增: case "not_installed":
55新增: status = http.StatusNotImplemented
56新增: }
57新增: return nil, status, nil
58新增: }
59新增: if reply.ID != id {
60新增: return nil, http.StatusBadGateway, nil
61新增: }
62新增: if op == "frame" {
63新增: if reply.Document == "" || len(reply.Document) > 128 || reply.Width < 240 || reply.Width > 1440 || reply.Height < 160 || reply.Height > 1600 {
64新增: return nil, http.StatusBadGateway, nil
65新增: }
66新增: if reply.ContentWidth <= 0 || reply.ContentWidth > 2560 || reply.ContentHeight <= 0 || reply.ContentHeight > 1600 {
67新增: return nil, http.StatusBadGateway, nil
68新增: }
69新增: image, err := base64.StdEncoding.DecodeString(reply.Image)
70新增: if err != nil {
71新增: return nil, http.StatusBadGateway, nil
72新增: }
73新增: config, err := jpeg.DecodeConfig(bytes.NewReader(image))
74新增: if err != nil || config.Width < 1 || config.Height < 1 || config.Width > 5120 || config.Height > 3200 {
75新增: return nil, http.StatusBadGateway, nil
76新增: }
77新增: }
78新增: return out, http.StatusOK, nil
79新增:}
新增internal/workbench/macos_phone_desktop_test.go+214 −0看文件
@@ -0,0 +1,214 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "bufio"
5新增: "bytes"
6新增: "context"
7新增: "encoding/base64"
8新增: "encoding/json"
9新增: "fmt"
10新增: "image"
11新增: "image/jpeg"
12新增: "net/http"
13新增: "strings"
14新增: "sync"
15新增: "testing"
16新增: "time"
17新增:
18新增: "github.com/google/uuid"
19新增: "github.com/sylvinus/agent-vm/internal/cage"
20新增: "golang.org/x/crypto/ssh"
21新增:)
22新增:
23新增:func macPhoneFrame(t *testing.T, id string) []byte {
24新增: t.Helper()
25新增: var data bytes.Buffer
26新增: if err := jpeg.Encode(&data, image.NewRGBA(image.Rect(0, 0, 900, 600)), nil); err != nil {
27新增: t.Fatal(err)
28新增: }
29新增: body, err := json.Marshal(map[string]any{"id": id, "document": "captured-geometry", "width": 390, "height": 640,
30新增: "content_width": 900, "content_height": 600, "image": base64.StdEncoding.EncodeToString(data.Bytes()),
31新增: "focus": "real-ax-focus", "shared": true, "login_supported": false, "pixel_ratio_control": true})
32新增: if err != nil {
33新增: t.Fatal(err)
34新增: }
35新增: return body
36新增:}
37新增:
38新增:func TestMacOSPhoneDesktopUsesPrivateRPCAndUTF8Envelope(t *testing.T) {
39新增: id := uuid.NewString()
40新增: frame := macPhoneFrame(t, id)
41新增: var mu sync.Mutex
42新增: var calls []macOSWindowRequest
43新增: guest := newMacWorkspaceGuest(t, func(channel ssh.Channel, command string) (uint32, bool) {
44新增: if !strings.Contains(command, "window.sock") {
45新增: return 0, false
46新增: }
47新增: var input macOSWindowRequest
48新增: if err := json.NewDecoder(bufio.NewReader(channel)).Decode(&input); err != nil {
49新增: t.Error(err)
50新增: return 1, true
51新增: }
52新增: mu.Lock()
53新增: calls = append(calls, input)
54新增: mu.Unlock()
55新增: if input.Phone == nil || input.PhoneToken == "" {
56新增: t.Error("phone lease missing")
57新增: }
58新增: if input.Action == "phone-frame" {
59新增: _, _ = channel.Write(frame)
60新增: } else {
61新增: fmt.Fprintf(channel, `{"id":%q}`, id)
62新增: }
63新增: return 0, true
64新增: })
65新增: s := guest.s
66新增: secret := randomToken()
67新增: for _, op := range []string{"open", "frame", "action", "action", "close"} {
68新增: input := phoneSurfaceInput{ID: id, Width: 390, Height: 640}
69新增: if op == "action" {
70新增: input.Type, input.Focus, input.Document = "text", "real-ax-focus", "captured-geometry"
71新增: input.Text = strings.Repeat("\x01", 8192)
72新增: mu.Lock()
73新增: if len(calls) == 3 {
74新增: input.Text = strings.Repeat("中", 2730) + "ab"
75新增: }
76新增: mu.Unlock()
77新增: }
78新增: out, status, err := s.phoneSurfaceGuest(t.Context(), phoneDesktop, secret, op, input)
79新增: if err != nil || status != http.StatusOK || !bytes.Contains(out, []byte(id)) {
80新增: t.Fatalf("%s: %d %v", op, status, err)
81新增: }
82新增: }
83新增: mu.Lock()
84新增: defer mu.Unlock()
85新增: if len(calls) != 5 || len(calls[2].Phone.Text) != 8192 || len(calls[3].Phone.Text) != 8192 {
86新增: t.Fatal("8KiB phone text was truncated")
87新增: }
88新增: for _, call := range calls {
89新增: if call.PhoneToken != secret || !strings.HasPrefix(call.Action, "phone-") {
90新增: t.Fatal("phone RPC escaped its lease")
91新增: }
92新增: }
93新增: if validMacOSWindowRequest(macOSWindowRequest{Action: "phone-open"}) {
94新增: t.Fatal("desktop public endpoint admitted phone RPC")
95新增: }
96新增:}
97新增:
98新增:func TestMacOSPhoneDesktopRejectsInvalidFramesAndMapsNativeFailures(t *testing.T) {
99新增: id := uuid.NewString()
100新增: frame := macPhoneFrame(t, id)
101新增: for _, code := range []string{"phone_session_ended", "gui_session_changed", "requires_gui_login", "phone_focus_changed", "phone_document_changed", "accessibility_permission", "screen_recording_permission"} {
102新增: want := http.StatusGone
103新增: if strings.Contains(code, "changed") && code != "gui_session_changed" {
104新增: want = http.StatusConflict
105新增: }
106新增: if strings.Contains(code, "permission") {
107新增: want = http.StatusForbidden
108新增: }
109新增: _, status, _ := macOSPhoneDesktopReply([]byte(`{"error":"`+code+`"}`), "frame", id)
110新增: if status != want {
111新增: t.Fatalf("%s: %d", code, status)
112新增: }
113新增: }
114新增: for _, mutation := range []func(map[string]any){
115新增: func(v map[string]any) { v["id"] = uuid.NewString() },
116新增: func(v map[string]any) { v["image"] = "iVBORw0KGgo=" },
117新增: func(v map[string]any) { v["document"] = "" },
118新增: func(v map[string]any) { v["content_width"] = 0 },
119新增: func(v map[string]any) { v["image"] = strings.Repeat("a", 3<<20) },
120新增: } {
121新增: var value map[string]any
122新增: _ = json.Unmarshal(frame, &value)
123新增: mutation(value)
124新增: raw, _ := json.Marshal(value)
125新增: if _, status, _ := macOSPhoneDesktopReply(raw, "frame", id); status != http.StatusBadGateway {
126新增: t.Fatal("invalid frame accepted")
127新增: }
128新增: }
129新增:}
130新增:
131新增:func TestMacOSPhoneDesktopHandlerHonorsRoomGateAndRevocation(t *testing.T) {
132新增: id := uuid.NewString()
133新增: frame := macPhoneFrame(t, id)
134新增: var mu sync.Mutex
135新增: var secret string
136新增: guest := newMacWorkspaceGuest(t, func(channel ssh.Channel, command string) (uint32, bool) {
137新增: if !strings.Contains(command, "window.sock") {
138新增: return 0, false
139新增: }
140新增: var input macOSWindowRequest
141新增: if err := json.NewDecoder(channel).Decode(&input); err != nil {
142新增: return 1, true
143新增: }
144新增: mu.Lock()
145新增: defer mu.Unlock()
146新增: if input.Action == "phone-open" {
147新增: secret = input.PhoneToken
148新增: }
149新增: if secret == "" || input.PhoneToken != secret {
150新增: t.Error("host failed to bind private lease")
151新增: }
152新增: if input.Action == "phone-frame" {
153新增: _, _ = channel.Write(frame)
154新增: } else {
155新增: fmt.Fprintf(channel, `{"id":%q}`, id)
156新增: }
157新增: return 0, true
158新增: })
159新增: s := guest.s
160新增: room, cancel := context.WithCancel(t.Context())
161新增: defer cancel()
162新增: s.phones.record = &phoneRecord{}
163新增: s.phones.roomCtx, s.phones.roomProof = room, "current-room"
164新增: open := fmt.Sprintf(`{"id":%q,"width":390,"height":640}`, id)
165新增: if response := windowsPhoneRequest(t, s, "POST", "/api/mobile/desktop/open", open, "old-room"); response.Code != 403 {
166新增: t.Fatalf("old room accepted: %d", response.Code)
167新增: }
168新增: if response := windowsPhoneRequest(t, s, "POST", "/api/mobile/desktop/open", open, "current-room"); response.Code != 409 {
169新增: t.Fatalf("closed gate accepted: %d %s", response.Code, response.Body.String())
170新增: }
171新增: cfg, err := loadConfig(s.configPath)
172新增: if err != nil {
173新增: t.Fatal(err)
174新增: }
175新增: gate, err := cage.NewEgressGate(cfg)
176新增: if err != nil {
177新增: t.Fatal(err)
178新增: }
179新增: stop, err := cage.StartGateControl(s.configPath, s.instanceDir(), gate)
180新增: if err != nil {
181新增: t.Fatal(err)
182新增: }
183新增: defer stop()
184新增: if err := gate.BeginCheck(); err != nil {
185新增: t.Fatal(err)
186新增: }
187新增: state := gate.Status()
188新增: report := cage.SafetyReport{Policy: cage.SafetyPolicyVersion, ID: "phone-fixture", RunID: state.RunID, CheckID: state.CheckID, Configuration: state.Configuration, CreatedAt: time.Now()}
189新增: for _, check := range []string{"egress_policy", "proxy_transport", "dns_transport", "guest_settings", "browser_settings", "filesystem_boundary", "management_boundary", "fail_closed", "udp_policy", "ipv6_policy", "exit_consistency"} {
190新增: report.Checks = append(report.Checks, cage.SafetyCheck{ID: check, Title: check, Critical: true, State: cage.CheckPassed, Evidence: "isolated fixture", CheckedAt: report.CreatedAt})
191新增: }
192新增: if err := gate.Grant(report); err != nil {
193新增: t.Fatal(err)
194新增: }
195新增: for _, path := range []string{"/api/mobile/desktop/open", "/api/mobile/desktop/" + id + "/frame"} {
196新增: method, body := "GET", ""
197新增: if strings.HasSuffix(path, "open") {
198新增: method, body = "POST", open
199新增: }
200新增: response := windowsPhoneRequest(t, s, method, path, body, "current-room")
201新增: if response.Code != 200 {
202新增: t.Fatalf("native handler: %d %s", response.Code, response.Body.String())
203新增: }
204新增: }
205新增: s.account.trustedSession = true
206新增: if response := windowsPhoneRequest(t, s, "GET", "/api/mobile/desktop/"+id+"/frame", "", "current-room"); response.Code != 423 {
207新增: t.Fatal("desktop-only unlock leaked to phone")
208新增: }
209新增: s.account.trustedSession = false
210新增: cancel()
211新增: if response := windowsPhoneRequest(t, s, "GET", "/api/mobile/desktop/"+id+"/frame", "", "current-room"); response.Code != 403 {
212新增: t.Fatal("revoked phone retained frames")
213新增: }
214新增:}
新增internal/workbench/macos_project_approval.go+87 −0看文件
@@ -0,0 +1,87 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "net/http"
5新增: "time"
6新增:)
7新增:
8新增:// A pending project is tied to a single live, already user-selected SFTP
9新增:// stream. An abandoned picker must not leave that host directory accessible.
10新增:func (s *Server) beginMacOSProjectApproval(path string, share *projectShare) {
11新增: s.mu.Lock()
12新增: defer s.mu.Unlock()
13新增: if share.approval != "" {
14新增: return
15新增: }
16新增: grant := randomToken()
17新增: share.approval = grant
18新增: share.approvalTimer = time.AfterFunc(5*time.Minute, func() {
19新增: s.op.Lock()
20新增: defer s.op.Unlock()
21新增: s.cancelMacOSProjectApproval(path, grant)
22新增: })
23新增:}
24新增:
25新增:func (s *Server) cancelMacOSProjectApproval(path, grant string) bool {
26新增: s.mu.Lock()
27新增: share := s.projectShares[path]
28新增: if share == nil || !equalSecret(share.approval, grant) {
29新增: s.mu.Unlock()
30新增: return false
31新增: }
32新增: delete(s.projectShares, path)
33新增: share.approval = ""
34新增: s.mu.Unlock()
35新增: share.close()
36新增: return true
37新增:}
38新增:
39新增:func (s *Server) macOSProjectApproval(w http.ResponseWriter, r *http.Request) {
40新增: var req struct {
41新增: Workspace string `json:"workspace"`
42新增: Grant string `json:"grant"`
43新增: Action string `json:"action"`
44新增: Window uint32 `json:"window,omitempty"`
45新增: PID int32 `json:"pid,omitempty"`
46新增: Nonce string `json:"nonce,omitempty"`
47新增: X *float64 `json:"x,omitempty"`
48新增: Y *float64 `json:"y,omitempty"`
49新增: }
50新增: if !readJSON(w, r, &req) {
51新增: return
52新增: }
53新增: if !s.op.TryLock() {
54新增: http.Error(w, "正在处理其他客机操作,请重试", http.StatusConflict)
55新增: return
56新增: }
57新增: defer s.op.Unlock()
58新增: if req.Action == "cancel" {
59新增: if !s.cancelMacOSProjectApproval(req.Workspace, req.Grant) {
60新增: http.Error(w, "项目授权已结束", http.StatusConflict)
61新增: return
62新增: }
63新增: jsonReply(w, map[string]bool{"ok": true})
64新增: return
65新增: }
66新增: s.mu.Lock()
67新增: share := s.projectShares[req.Workspace]
68新增: active := s.macosGuest != nil && s.ready && !s.closing && share != nil && equalSecret(share.approval, req.Grant)
69新增: s.mu.Unlock()
70新增: if !active {
71新增: http.Error(w, "项目授权已结束,请重新打开项目", http.StatusConflict)
72新增: return
73新增: }
74新增: select {
75新增: case <-share.done:
76新增: http.Error(w, "项目挂载已断开", http.StatusConflict)
77新增: return
78新增: default:
79新增: }
80新增: switch req.Action {
81新增: case "frame", "click":
82新增: input := macOSWindowRequest{Action: "project-" + req.Action, Project: macOSProjectPath(s.macosGuest.User, req.Workspace), Window: req.Window, PID: req.PID, Nonce: req.Nonce, X: req.X, Y: req.Y}
83新增: s.macOSWindowRPC(w, r, input)
84新增: default:
85新增: http.Error(w, "未知的项目授权操作", http.StatusBadRequest)
86新增: }
87新增:}
新增internal/workbench/macos_projects.go+160 −0看文件
@@ -0,0 +1,160 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "context"
5新增: "crypto/sha256"
6新增: "errors"
7新增: "fmt"
8新增: "os"
9新增: "os/exec"
10新增: "path"
11新增: "path/filepath"
12新增: "strings"
13新增: "time"
14新增:
15新增: "github.com/google/uuid"
16新增:
17新增: "al.essio.dev/pkg/shellescape"
18新增:)
19新增:
20新增:func macOSProjectPath(user, hostDirectory string) string {
21新增: digest := sha256.Sum256([]byte(hostDirectory))
22新增: return path.Join("/Users", user, "Cage", "Projects", fmt.Sprintf("%x", digest[:12]))
23新增:}
24新增:
25新增:// A mount which is ready in FSKit can still be unreadable by the guest app.
26新增:// Keep the live restricted connection while macOS waits for the user's folder
27新增:// approval; do not accept an APFS directory or a stale mount as this project.
28新增:var errMacOSProjectApproval = errors.New("请在虚拟 Mac 的项目授权窗口中选中此项目,然后重新打开")
29新增:
30新增:const macProjectAgent = "/Applications/CageProjectAccess.app/Contents/MacOS/CageProjectAccess"
31新增:
32新增:func (s *Server) ensureMacOSProjectShare(hostDir string) error {
33新增: ctx, cancel := context.WithTimeout(s.operationContext(), 18*time.Second)
34新增: defer cancel()
35新增: guestDir := macOSProjectPath(s.macosGuest.User, hostDir)
36新增: s.mu.Lock()
37新增: share := s.projectShares[hostDir]
38新增: s.mu.Unlock()
39新增: if share != nil {
40新增: select {
41新增: case <-share.done:
42新增: share.close()
43新增: share = nil
44新增: default:
45新增: }
46新增: }
47新增: if share == nil {
48新增: var err error
49新增: share, err = s.startMacOSProjectShare(ctx, hostDir, guestDir)
50新增: if err != nil {
51新增: return err
52新增: }
53新增: s.mu.Lock()
54新增: if s.projectShares == nil {
55新增: s.projectShares = make(map[string]*projectShare)
56新增: }
57新增: s.projectShares[hostDir] = share
58新增: s.mu.Unlock()
59新增: }
60新增: err := s.probeMacOSProject(ctx, hostDir, guestDir, share)
61新增: if err == nil && share.detach == nil {
62新增: // FSKit assigns an independent volume UUID after mount. Pin the volume
63新增: // only after the signed-in app returned this host directory's challenge.
64新增: share.detach, err = s.macOSMountCleanup(ctx, guestDir)
65新增: }
66新增: if errors.Is(err, errMacOSProjectApproval) {
67新增: s.beginMacOSProjectApproval(hostDir, share)
68新增: } else if err == nil {
69新增: s.mu.Lock()
70新增: share.approval = ""
71新增: if share.approvalTimer != nil {
72新增: share.approvalTimer.Stop()
73新增: share.approvalTimer = nil
74新增: }
75新增: s.mu.Unlock()
76新增: }
77新增: if err != nil && !errors.Is(err, errMacOSProjectApproval) {
78新增: share.close()
79新增: s.mu.Lock()
80新增: delete(s.projectShares, hostDir)
81新增: s.mu.Unlock()
82新增: }
83新增: return err
84新增:}
85新增:
86新增:func (s *Server) startMacOSProjectShare(ctx context.Context, hostDir, guestDir string) (*projectShare, error) {
87新增: folder := shellescape.Quote(guestDir)
88新增:
89新增: prepare := `set -e; test "$(/usr/bin/stat -f %u /dev/console)" = "$(/usr/bin/id -u)" || exit 73
90新增: /bin/launchctl print "gui/$(/usr/bin/id -u)" >/dev/null 2>&1 || exit 73
91新增: test -x /usr/local/libexec/cage-sshfs; test -x ` + macProjectAgent +
92新增: `; p=` + folder + `; if /sbin/mount | /usr/bin/grep -Fq " on $p ("; then exit 2; fi; for d in "$HOME/Cage" "$HOME/Cage/Projects" "$p"; do
93新增: test ! -L "$d"; if test ! -e "$d"; then /bin/mkdir -m 700 "$d"; fi; test -d "$d" && test -O "$d" || exit 1
94新增: done; test -z "$(/bin/ls -A "$p")"; /usr/bin/open -gj -a /Applications/CageProjectAccess.app`
95新增: _, err := s.guestControl(ctx, prepare, "macos-project-prepare")
96新增: if err != nil {
97新增: var exit *exec.ExitError
98新增: if errors.As(err, &exit) && exit.ExitCode() == 73 {
99新增: return nil, errors.New("请先在虚拟 Mac 中登录已绑定的普通账户,再重新打开项目")
100新增: }
101新增: return nil, errors.New("无法准备 macOS 实时挂载。请检查客机项目助手、SSHFS 及目标目录")
102新增: }
103新增: command := "exec /usr/local/libexec/cage-sshfs " + shellescape.Quote(":"+filepath.ToSlash(hostDir)) + " " + folder +
104新增: " -f -o slave,backend=fskit,nodev,nosuid,dir_cache=no"
105新增: conn, err := startProjectTransport(s.sshCommand(s.lifetimeContext(), "-T", s.sshTarget(), "--", command), hostDir)
106新增: if err != nil {
107新增: return nil, err
108新增: }
109新增:
110新增: return conn, nil
111新增:}
112新增:
113新增:func (s *Server) macOSMountCleanup(ctx context.Context, guestDir string) (func(), error) {
114新增: query := "/sbin/mount | /usr/bin/grep -F -- " + shellescape.Quote(" on "+guestDir+" (")
115新增: out, err := s.guest(ctx, query)
116新增: line := strings.TrimSpace(string(out))
117新增: device, options, ok := strings.Cut(line, " on "+guestDir+" (")
118新增: id := strings.TrimPrefix(device, "macfuse://")
119新增: if _, parseErr := uuid.Parse(id); err != nil || !ok || id == device || parseErr != nil || strings.Contains(line, "\n") ||
120新增: !strings.Contains(options, "fskit") || !strings.Contains(options, "mounted by "+s.macosGuest.User+")") {
121新增: return nil, errors.New("无法核对本次挂载的 macOS 卷标识")
122新增: }
123新增: detach := "if test \"$(" + query + ")\" = " + shellescape.Quote(line) + "; then /sbin/umount -f " + shellescape.Quote(guestDir) + "; fi"
124新增: return func() {
125新增: cleanup, cancel := context.WithTimeout(context.Background(), 3*time.Second)
126新增: defer cancel()
127新增: _, _ = s.guest(cleanup, detach)
128新增: }, nil
129新增:}
130新增:
131新增:func (s *Server) probeMacOSProject(ctx context.Context, hostDir, guestDir string, share *projectShare) error {
132新增: probe, err := os.CreateTemp(hostDir, ".cage-mount-probe-*")
133新增: if err != nil {
134新增: return err
135新增: }
136新增: defer os.Remove(probe.Name())
137新增: challenge := randomToken()
138新增: _, writeErr := probe.WriteString(challenge)
139新增: if err := errors.Join(writeErr, probe.Close()); err != nil {
140新增: return err
141新增: }
142新增: cmd := shellescape.QuoteCommand([]string{macProjectAgent, "probe", guestDir, filepath.Base(probe.Name()), challenge})
143新增: for {
144新增: output, err := s.guest(ctx, cmd)
145新增: if err == nil && strings.TrimSpace(string(output)) == "OK" {
146新增: return nil
147新增: }
148新增: var exit *exec.ExitError
149新增: if errors.As(err, &exit) && exit.ExitCode() == 75 {
150新增: return errMacOSProjectApproval
151新增: }
152新增: select {
153新增: case <-ctx.Done():
154新增: return errors.New("虚拟 Mac 的项目助手未能读回宿主项目文件")
155新增: case <-share.done:
156新增: return errors.New("macOS 实时挂载已断开,请检查客机文件系统扩展授权")
157新增: case <-time.After(200 * time.Millisecond):
158新增: }
159新增: }
160新增:}
新增internal/workbench/macos_resources.go+165 −0看文件
@@ -0,0 +1,165 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "context"
5新增: _ "embed"
6新增: "encoding/json"
7新增: "errors"
8新增: "net/http"
9新增: "os"
10新增: "path/filepath"
11新增: "sync"
12新增: "time"
13新增:
14新增: "al.essio.dev/pkg/shellescape"
15新增: "github.com/docker/go-units"
16新增: "github.com/sylvinus/agent-vm/internal/cage"
17新增: "github.com/sylvinus/agent-vm/internal/vm"
18新增: "go.yaml.in/yaml/v3"
19新增:)
20新增:
21新增://go:embed macos_resources.py
22新增:var macOSResourceProbe string
23新增:
24新增:type macOSResourceSample struct {
25新增: Version int `json:"version"`
26新增: Total uint64 `json:"total_bytes"`
27新增: Available uint64 `json:"available_bytes"`
28新增: Free uint64 `json:"free_bytes"`
29新增: Inactive uint64 `json:"inactive_bytes"`
30新增: Wired uint64 `json:"wired_bytes"`
31新增: Compressed uint64 `json:"compressed_bytes"`
32新增: SwapTotal *uint64 `json:"swap_total_bytes,omitempty"`
33新增: SwapFree *uint64 `json:"swap_free_bytes,omitempty"`
34新增: CPUs int `json:"cpus"`
35新增: CPUTicks [4]uint32 `json:"cpu_ticks"`
36新增: Boot int64 `json:"boot_seconds"`
37新增: Pressure *uint32 `json:"pressure_level,omitempty"`
38新增:}
39新增:
40新增:type macOSResourceObserver struct {
41新增: mu sync.Mutex
42新增: previous macOSResourceSample
43新增: observedAt time.Time
44新增:}
45新增:
46新增:func parseMacOSResourceSample(data []byte, memory uint64, cpus int) (macOSResourceSample, error) {
47新增: var sample macOSResourceSample
48新增: if json.Unmarshal(data, &sample) != nil || sample.Version != 1 || sample.Total != memory || sample.CPUs != cpus || sample.Boot <= 0 ||
49新增: sample.Available > sample.Total || sample.Free > sample.Total || sample.Inactive > sample.Total-sample.Free ||
50新增: sample.Available != sample.Free+sample.Inactive || sample.Wired > sample.Total || sample.Compressed > sample.Total ||
51新增: (sample.SwapTotal == nil) != (sample.SwapFree == nil) || sample.SwapTotal != nil && *sample.SwapFree > *sample.SwapTotal {
52新增: return sample, errors.New("macOS 客机返回的资源用量不完整或与启动配置不一致")
53新增: }
54新增: return sample, nil
55新增:}
56新增:
57新增:func (observer *macOSResourceObserver) observation(sample macOSResourceSample, now time.Time) map[string]any {
58新增: var percent *float64
59新增: previous := observer.previous
60新增: if previous.Boot == sample.Boot && previous.CPUs == sample.CPUs && now.Sub(observer.observedAt) <= 10*time.Second {
61新增: var total, idle uint64
62新增: valid := true
63新增: for index, value := range sample.CPUTicks {
64新增: if value < previous.CPUTicks[index] {
65新增: valid = false
66新增: break
67新增: }
68新增: delta := uint64(value - previous.CPUTicks[index])
69新增: total += delta
70新增: if index == 2 {
71新增: idle = delta
72新增: }
73新增: }
74新增: if valid && total > 0 {
75新增: value := 100 * float64(total-idle) / float64(total)
76新增: percent = &value
77新增: }
78新增: }
79新增: observer.previous, observer.observedAt = sample, now
80新增: result := map[string]any{"version": 1, "observed_at": now, "cpus": sample.CPUs, "cpu_percent": percent, "guest": sample}
81新增: if sample.Pressure != nil {
82新增: result["pressure"] = *sample.Pressure > 1
83新增: }
84新增: return result
85新增:}
86新增:
87新增:func (s *Server) readMacOSResources(ctx context.Context, memory uint64, cpus int) (map[string]any, error) {
88新增: observer := &s.macResources
89新增: observer.mu.Lock()
90新增: defer observer.mu.Unlock()
91新增: ctx, cancel := context.WithTimeout(ctx, 4*time.Second)
92新增: defer cancel()
93新增: command := "exec " + shellescape.QuoteCommand([]string{macCLIInstall + "/bin/python3", "-I", "-c", macOSResourceProbe})
94新增: data, err := s.guestControl(ctx, command, "macos-resources")
95新增: if err != nil {
96新增: return nil, errors.New("暂时无法读取 macOS 客机资源用量,请确认客机已启动并完成组件安装")
97新增: }
98新增: sample, err := parseMacOSResourceSample(data, memory, cpus)
99新增: if err != nil {
100新增: return nil, err
101新增: }
102新增: return observer.observation(sample, time.Now()), nil
103新增:}
104新增:
105新增:func (s *Server) resourceAllocationLimits(allocation cage.ResourceAllocation) (int, int, error) {
106新增: if s.macosGuest == nil {
107新增: return allocation.Limits()
108新增: }
109新增: requirements, err := vm.ReadMacOSResourceRequirements(s.instanceDir())
110新增: if err != nil {
111新增: return 0, 0, err
112新增: }
113新增: return requirements.Limits(allocation)
114新增:}
115新增:
116新增:func (s *Server) macOSResourceStatus(w http.ResponseWriter, r *http.Request) {
117新增: requirements, err := vm.ReadMacOSResourceRequirements(s.instanceDir())
118新增: if err != nil {
119新增: requestError(w, err)
120新增: return
121新增: }
122新增: allocation, err := cage.LoadResourceAllocation(s.configPath)
123新增: if err != nil {
124新增: requestError(w, err)
125新增: return
126新增: }
127新增: memory, cpus, allocationErr := allocation.Limits()
128新增: if allocationErr == nil {
129新增: _, _, allocationErr = requirements.Limits(allocation)
130新增: } else {
131新增: memory, cpus = allocation.MemoryGiB, allocation.CPUs
132新增: }
133新增: var configured struct {
134新增: Memory string `yaml:"memory"`
135新增: CPUs int `yaml:"cpus"`
136新增: }
137新增: data, err := os.ReadFile(filepath.Join(s.instanceDir(), "lima.yaml"))
138新增: if err != nil || yaml.Unmarshal(data, &configured) != nil {
139新增: requestError(w, errors.New("无法读取 macOS 客机启动配置"))
140新增: return
141新增: }
142新增: maximum, err := units.RAMInBytes(configured.Memory)
143新增: if err != nil || maximum < 1<<30 || configured.CPUs < 1 {
144新增: requestError(w, errors.New("macOS 客机启动资源配置无效"))
145新增: return
146新增: }
147新增: running := s.vmRunning()
148新增: var observation map[string]any
149新增: if running {
150新增: observation, err = s.readMacOSResources(r.Context(), uint64(maximum), configured.CPUs)
151新增: allocationErr = errors.Join(allocationErr, err)
152新增: }
153新增: resourceError := ""
154新增: if allocationErr != nil {
155新增: resourceError = allocationErr.Error()
156新增: }
157新增: maxMemory, maxCPUs := cage.ResourceLimits()
158新增: jsonReply(w, map[string]any{"runtime": "vz-macos", "memory_policy": "fixed", "automatic_reclaim": false,
159新增: "running": running, "automatic": allocation.Automatic, "memory_gib": memory, "cpus": cpus,
160新增: "min_memory_gib": requirements.MemoryGiB, "min_cpus": requirements.CPUs, "minimum_requirements": requirements,
161新增: "max_memory_gib": maxMemory, "max_cpus": maxCPUs, "recommended_memory_bytes": uint64(maxMemory) << 30, "recommended_cpus": maxCPUs,
162新增: "configured_memory_bytes": maximum, "configured_cpus": configured.CPUs, "resource_error": resourceError,
163新增: "restart_required": running && (maximum != int64(memory)<<30 || configured.CPUs != cpus), "observation": observation,
164新增: "unavailable_observations": []string{"balloon_bytes", "oom_kills", "memory_stall_percent", "host_pressure"}})
165新增:}
新增internal/workbench/macos_resources.py+91 −0看文件
@@ -0,0 +1,91 @@
1新增:"""Read macOS guest metrics through the public Mach and sysctl interfaces."""
2新增:import ctypes
3新增:import json
4新增:import os
5新增:
6新增:
7新增:lib = ctypes.CDLL("/usr/lib/libSystem.B.dylib", use_errno=True)
8新增:u32 = ctypes.c_uint32
9新增:u64 = ctypes.c_uint64
10新增:
11新增:
12新增:class VMStatistics(ctypes.Structure):
13新增: # HOST_VM_INFO64_REV1_COUNT, available on every supported macOS guest.
14新增: _fields_ = [
15新增: ("free", u32), ("active", u32), ("inactive", u32), ("wired", u32),
16新增: ("zero_fill", u64), ("reactivations", u64), ("pageins", u64),
17新增: ("pageouts", u64), ("faults", u64), ("cow_faults", u64),
18新增: ("lookups", u64), ("hits", u64), ("purges", u64),
19新增: ("purgeable", u32), ("speculative", u32),
20新增: ("decompressions", u64), ("compressions", u64),
21新增: ("swapins", u64), ("swapouts", u64),
22新增: ("compressor", u32), ("throttled", u32), ("external", u32),
23新增: ("internal", u32), ("uncompressed", u64),
24新增: ]
25新增:
26新增:
27新增:class BootTime(ctypes.Structure):
28新增: _fields_ = [("seconds", ctypes.c_long), ("microseconds", ctypes.c_int32)]
29新增:
30新增:
31新增:class SwapUsage(ctypes.Structure):
32新增: _fields_ = [("total", u64), ("available", u64), ("used", u64),
33新增: ("page_size", u32), ("encrypted", ctypes.c_int32)]
34新增:
35新增:
36新增:lib.sysctlbyname.argtypes = [ctypes.c_char_p, ctypes.c_void_p,
37新增: ctypes.POINTER(ctypes.c_size_t), ctypes.c_void_p, ctypes.c_size_t]
38新增:lib.sysctlbyname.restype = ctypes.c_int
39新增:lib.mach_host_self.argtypes = []
40新增:lib.mach_host_self.restype = u32
41新增:lib.host_statistics.argtypes = [u32, ctypes.c_int, ctypes.c_void_p, ctypes.POINTER(u32)]
42新增:lib.host_statistics.restype = ctypes.c_int
43新增:lib.host_statistics64.argtypes = lib.host_statistics.argtypes
44新增:lib.host_statistics64.restype = ctypes.c_int
45新增:
46新增:
47新增:def sysctl(name, kind):
48新增: value = kind()
49新增: size = ctypes.c_size_t(ctypes.sizeof(value))
50新增: if lib.sysctlbyname(name.encode(), ctypes.byref(value), ctypes.byref(size), None, 0) != 0:
51新增: raise OSError(ctypes.get_errno(), "sysctl " + name)
52新增: if size.value != ctypes.sizeof(value):
53新增: raise ValueError("unexpected sysctl size for " + name)
54新增: return value
55新增:
56新增:
57新增:host = lib.mach_host_self()
58新增:vm = VMStatistics()
59新增:count = u32(ctypes.sizeof(vm) // ctypes.sizeof(u32))
60新增:if lib.host_statistics64(host, 4, ctypes.byref(vm), ctypes.byref(count)) != 0 or count.value != 38:
61新增: raise OSError("host_statistics64 did not return complete VM counters")
62新增:ticks = (u32 * 4)()
63新增:count = u32(4)
64新增:if lib.host_statistics(host, 3, ctypes.byref(ticks), ctypes.byref(count)) != 0 or count.value != 4:
65新增: raise OSError("host_statistics did not return complete CPU counters")
66新增:boot = sysctl("kern.boottime", BootTime)
67新增:page_size = os.sysconf("SC_PAGE_SIZE")
68新增:# Mach free_count already includes speculative_count. Inactive pages form an
69新增:# availability estimate and are counted once, separately from compressed pages.
70新增:result = {
71新增: "version": 1,
72新增: "total_bytes": sysctl("hw.memsize", u64).value,
73新增: "available_bytes": (vm.free + vm.inactive) * page_size,
74新增: "free_bytes": vm.free * page_size,
75新增: "inactive_bytes": vm.inactive * page_size,
76新增: "wired_bytes": vm.wired * page_size,
77新增: "compressed_bytes": vm.compressor * page_size,
78新增: "cpus": sysctl("hw.logicalcpu", u32).value,
79新增: "cpu_ticks": list(ticks),
80新增: "boot_seconds": boot.seconds,
81新增:}
82新增:try:
83新增: swap = sysctl("vm.swapusage", SwapUsage)
84新增: result.update(swap_total_bytes=swap.total, swap_free_bytes=swap.available)
85新增:except OSError:
86新增: pass
87新增:try:
88新增: result["pressure_level"] = sysctl("kern.memorystatus_vm_pressure_level", u32).value
89新增:except OSError:
90新增: pass
91新增:print(json.dumps(result, separators=(",", ":")))
新增internal/workbench/macos_resources_test.go+150 −0看文件
@@ -0,0 +1,150 @@
1新增:package workbench
2新增:
3新增:import (
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新增:
17新增:func 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新增:
84新增:func 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新增:
122新增:func 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新增:}
新增internal/workbench/macos_restart_network_test.go+117 −0看文件
@@ -0,0 +1,117 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "fmt"
5新增: "os"
6新增: "path/filepath"
7新增: "runtime"
8新增: "strings"
9新增: "testing"
10新增: "time"
11新增:
12新增: "github.com/sylvinus/agent-vm/internal/cage"
13新增: "github.com/sylvinus/agent-vm/internal/managedproxy"
14新增: "golang.org/x/crypto/ssh"
15新增:)
16新增:
17新增:func TestMacOSStartAndControllerReconnectRequireFreshNetworkCheck(t *testing.T) {
18新增: if runtime.GOOS != "darwin" {
19新增: t.Skip("native Mac startup uses the host shell and OpenSSH")
20新增: }
21新增: for _, tc := range []struct {
22新增: name string
23新增: start, paused, setup bool
24新增: }{
25新增: {"cold start", true, false, false},
26新增: {"cold start retains pause", true, true, false},
27新增: {"first setup starts offline", true, false, true},
28新增: {"controller adopts running guest", false, false, false},
29新增: {"controller adopts paused guest", false, true, false},
30新增: {"controller adopts unfinished setup", false, false, true},
31新增: } {
32新增: t.Run(tc.name, func(t *testing.T) {
33新增: g := newMacWorkspaceGuest(t, func(_ ssh.Channel, command string) (uint32, bool) {
34新增: return 0, strings.Contains(command, "uname -s")
35新增: })
36新增: s := g.s
37新增: s.ready = false
38新增: if tc.setup {
39新增: s.macosGuest.SetupID = "awaiting-first-setup"
40新增: }
41新增: if err := writePrivate(filepath.Join(s.profile, "network-intent.json"), networkIntent{Version: 1, Paused: tc.paused, PauseVersion: 7}); err != nil {
42新增: t.Fatal(err)
43新增: }
44新增: if err := s.restoreNetworkIntent(); err != nil {
45新增: t.Fatal(err)
46新增: }
47新增: cfg, err := loadConfig(s.configPath)
48新增: if err != nil {
49新增: t.Fatal(err)
50新增: }
51新增: gate, err := cage.NewEgressGate(cfg)
52新增: if err != nil {
53新增: t.Fatal(err)
54新增: }
55新增: stop, err := cage.StartGateControl(s.configPath, s.instanceDir(), gate)
56新增: if err != nil {
57新增: t.Fatal(err)
58新增: }
59新增: defer stop()
60新增: if err = gate.BeginCheck(); err != nil {
61新增: t.Fatal(err)
62新增: }
63新增: grantTestGate(t, gate)
64新增: // Preserve the same configuration fingerprint and old report, but
65新增: // reject the new check before any proxy process or external traffic.
66新增: store, err := managedproxy.Load(s.profile)
67新增: if err != nil {
68新增: t.Fatal(err)
69新增: }
70新增: store.Selected = ""
71新增: if err = store.Save(s.profile); err != nil {
72新增: t.Fatal(err)
73新增: }
74新增: checkFailure := cfg.RequireManagedProxy(s.profile)
75新增: if checkFailure == nil {
76新增: t.Fatal("fixture still has a selected exit")
77新增: }
78新增: wantCheck := !tc.paused && !tc.setup
79新增: if tc.start {
80新增: marker := filepath.Join(s.instanceDir(), "cage-running.json")
81新增: if err := os.Remove(marker); err != nil {
82新增: t.Fatal(err)
83新增: }
84新增: s.exe = filepath.Join(t.TempDir(), "cage")
85新增: script := fmt.Sprintf("#!/bin/sh\n[ \"$*\" = 'guest-os macos start' ] || exit 1\nprintf '{\"pid\":%d}' > '%s'\n", os.Getpid(), marker)
86新增: if err := os.WriteFile(s.exe, []byte(script), 0700); err != nil {
87新增: t.Fatal(err)
88新增: }
89新增: s.setJobForTest(Job{ID: "starting", Kind: "start", Running: true})
90新增: err := s.startMacOSGuest()
91新增: if wantCheck && (err == nil || err.Error() != checkFailure.Error()) || !wantCheck && err != nil {
92新增: t.Fatalf("start result = %v, want fresh check = %t", err, wantCheck)
93新增: }
94新增: } else {
95新增: s.op.Lock()
96新增: err := s.attachMacOSGuest()
97新增: job := s.jobs.snapshot()
98新增: s.op.Unlock()
99新增: defer s.jobs.close()
100新增: if err != nil {
101新增: t.Fatal(err)
102新增: }
103新增: if (job.Running && job.Kind == "network-recovery") != wantCheck {
104新增: t.Fatalf("controller reconnect job = %+v, want fresh check = %t", job, wantCheck)
105新增: }
106新增: if wantCheck {
107新增: if result := awaitJobIdle(t, &s.jobs); result.Error != checkFailure.Error() {
108新增: t.Fatalf("reconnect completed without the expected proxy check: %+v", result)
109新增: }
110新增: }
111新增: }
112新增: if state := gate.Status(); !s.ready || state.Mode != cage.GateClosed || !time.Now().After(state.Until) || s.networkPaused != tc.paused || s.safety.pauseVersion != 7 {
113新增: t.Fatalf("ready=%t mode=%s paused=%t generation=%d", s.ready, state.Mode, s.networkPaused, s.safety.pauseVersion)
114新增: }
115新增: })
116新增: }
117新增:}
新增internal/workbench/macos_safety.go+282 −0看文件
@@ -0,0 +1,282 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "bytes"
5新增: "context"
6新增: _ "embed"
7新增: "encoding/base64"
8新增: "encoding/json"
9新增: "errors"
10新增: "os"
11新增: "os/exec"
12新增: "path/filepath"
13新增: "strings"
14新增: "time"
15新增:
16新增: "al.essio.dev/pkg/shellescape"
17新增: "github.com/sylvinus/agent-vm/internal/cage"
18新增: "github.com/sylvinus/agent-vm/internal/guestos"
19新增: "github.com/sylvinus/agent-vm/internal/managedproxy"
20新增: "go.yaml.in/yaml/v3"
21新增:)
22新增:
23新增://go:embed macos_safety_probe.cjs
24新增:var macOSSafetyProbe string
25新增:
26新增:func macOSZone(zone string) string {
27新增: switch zone {
28新增: case "+00:00", "GMT", "UTC", "Etc/GMT", "Etc/UTC":
29新增: return "UTC"
30新增: default:
31新增: return zone
32新增: }
33新增:}
34新增:func macOSLocale(raw string) string {
35新增: return strings.ToLower(strings.ReplaceAll(strings.TrimSuffix(raw, ".UTF-8"), "_", "-"))
36新增:}
37新增:
38新增:func (s *Server) guestSettingsOK(v guestObservation, cfg cage.Config) bool {
39新增: if s.windowsGuest != nil {
40新增: return windowsGuestSettingsMatch(v, cfg)
41新增: }
42新增: if s.macosGuest == nil {
43新增: return guestSettingsMatch(v, cfg)
44新增: }
45新增: return macOSZone(v.TZ) == macOSZone(cfg.Timezone) && macOSZone(v.SystemTimezone) == macOSZone(cfg.Timezone) &&
46新增: macOSLocale(v.ProcessLocale) == macOSLocale(cfg.Locale) && macOSLocale(v.SystemLocale) == macOSLocale(cfg.Locale)
47新增:}
48新增:
49新增:func (s *Server) browserSettingsIssue(v browserObservation, cfg cage.Config) string {
50新增: if s.windowsGuest != nil {
51新增: if !strings.HasPrefix(v.Platform, "Win") {
52新增: return "客机浏览器没有报告 Windows 平台"
53新增: }
54新增: if effectiveWindowsZone(v.Timezone) != effectiveWindowsZone(cfg.Timezone) || effectiveWindowsZone(v.ExpectedTimezone) != effectiveWindowsZone(cfg.Timezone) {
55新增: return "客机浏览器实际时区与配置不符"
56新增: }
57新增: if !strings.EqualFold(v.Language, cfg.BrowserLanguage) {
58新增: return "客机浏览器实际语言与配置不符"
59新增: }
60新增: return ""
61新增: }
62新增: if s.macosGuest == nil {
63新增: return browserSettingsMismatch(v, cfg)
64新增: }
65新增: if !strings.HasPrefix(v.Platform, "Mac") {
66新增: return "客机浏览器没有报告 macOS 平台"
67新增: }
68新增: // Intl canonicalizes IANA aliases, including Etc/UTC -> UTC. The browser
69新增: // must independently report the same effective zone as the applied config.
70新增: if macOSZone(v.Timezone) != macOSZone(cfg.Timezone) || macOSZone(v.ExpectedTimezone) != macOSZone(cfg.Timezone) {
71新增: return "客机浏览器实际时区与配置不符"
72新增: }
73新增: if !strings.EqualFold(v.Language, cfg.BrowserLanguage) {
74新增: return "客机浏览器实际语言与配置不符"
75新增: }
76新增: return ""
77新增:}
78新增:
79新增:func (s *Server) macOSGuestObservation(ctx context.Context, in map[string]any) (guestObservation, error) {
80新增: var result guestObservation
81新增: data, err := json.Marshal(in)
82新增: if err != nil {
83新增: return result, err
84新增: }
85新增: node := "/usr/local/libexec/cage-workbench-browser-4.145.0-pw1.65.0/editor/lib/node"
86新增: out, err := s.guestControl(ctx, "exec "+shellescape.QuoteCommand([]string{node, "-e", macOSSafetyProbe, base64.StdEncoding.EncodeToString(data)}), "safety-probe")
87新增: if err != nil || json.Unmarshal(out, &result) != nil {
88新增: return result, errors.New("macOS 客机未返回完整的网络观测")
89新增: }
90新增: if in["stage"] == "boundary" {
91新增: private, _ := in["private_file"].(string)
92新增: result.PrivateFile = s.checkMacOSPrivateFile(ctx, private)
93新增: shared, _ := in["shared_file"].(string)
94新增: challenge, _ := in["challenge"].(string)
95新增: result.SharedFile = s.checkMacOSSharedFile(ctx, shared, challenge)
96新增: }
97新增: return result, nil
98新增:}
99新增:
100新增:// Use only the VM provisioning identity for this fixed read-only operation.
101新增:// The GUI user never receives an administrator key, password, or root shell.
102新增:func (s *Server) checkMacOSPrivateFile(ctx context.Context, private string) string {
103新增: if filepath.Dir(private) != s.profile || !strings.HasPrefix(filepath.Base(private), ".cage-private-probe-") {
104新增: return "unknown"
105新增: }
106新增: user, err := guestos.MacOSProvisionUser(s.profile)
107新增: if err != nil {
108新增: return "unknown"
109新增: }
110新增: base, err := guestos.MacOSSSHArgs(s.profile, user)
111新增: if err != nil {
112新增: return "unknown"
113新增: }
114新增: perl := `$> == 0 or exit 1; if (sysopen(my $fh,$ARGV[0],O_RDONLY|O_NONBLOCK)) {print "readable"} elsif ($! == ENOENT || $! == EACCES || $! == ENOTDIR) {print "unreachable"} else {print "unknown"}`
115新增: op := shellescape.QuoteCommand([]string{"/usr/bin/sudo", "-S", "-p", "", "/usr/bin/env", "-i", "PATH=/usr/bin:/bin", "/usr/bin/perl", "-MFcntl=:DEFAULT", "-MErrno=ENOENT,EACCES,ENOTDIR", "-e", perl, "--", private})
116新增: cmd := exec.CommandContext(ctx, sshExecutable(), append(base, "-T", s.sshTarget(), "--", "exec "+op+` < "$HOME/password"`)...)
117新增: cmd.Env = sshEnvironment()
118新增: out, err := cmd.Output()
119新增: if err != nil {
120新增: return "unknown"
121新增: }
122新增: result := strings.TrimSpace(string(out))
123新增: if result != "unreachable" && result != "readable" {
124新增: return "unknown"
125新增: }
126新增: return result
127新增:}
128新增:
129新增:// The approved GUI login, rather than sshd, has the security-scoped bookmark.
130新增:// Open the real project's terminal and send only the bounded marker operation.
131新增:func (s *Server) checkMacOSSharedFile(ctx context.Context, shared, challenge string) bool {
132新增: host := filepath.Dir(shared)
133新增: name := filepath.Base(shared)
134新增: if !strings.HasPrefix(name, ".cage-share-probe-") || challenge == "" {
135新增: return false
136新增: }
137新增: s.mu.Lock()
138新增: share := s.projectShares[host]
139新增: approved := share != nil && share.detach != nil
140新增: s.mu.Unlock()
141新增: if !approved {
142新增: return false
143新增: }
144新增: probe, err := os.Open(shared)
145新增: if err != nil {
146新增: return false
147新增: }
148新增: defer probe.Close()
149新增: info, err := probe.Stat()
150新增: if err != nil || !info.Mode().IsRegular() {
151新增: return false
152新增: }
153新增: dir := macOSProjectPath(s.macosGuest.User, host)
154新增: op := `p=` + shellescape.Quote(name) + `; if test -f "$p" && test ! -L "$p" && test "$(cat "$p")" = ` + shellescape.Quote(challenge) + `; then printf %s ` + shellescape.Quote(challenge+":guest") + ` > "$p"; fi; exit`
155新增: cmd := s.macOSSSHCommand(ctx, "-tt", s.sshTarget(), "--", "exec /usr/local/libexec/cage-macos-terminal "+shellescape.Quote(dir))
156新增: tty, err := startTerminal(cmd, 80, 24)
157新增: if err != nil {
158新增: return false
159新增: }
160新增: defer func() { _ = tty.Close(); _ = tty.Kill(); _ = tty.Wait() }()
161新增: // OpenSSH switches its outer terminal to raw mode during authentication.
162新增: // Sending before it does so can discard typeahead. Wait for the mounted
163新增: // project's own login shell to emit its first prompt through the broker.
164新增: ready := make(chan bool, 1)
165新增: go func() { var buf [4096]byte; n, err := tty.Read(buf[:]); ready <- n > 0 && err == nil }()
166新增: select {
167新增: case ok := <-ready:
168新增: if !ok {
169新增: return false
170新增: }
171新增: case <-ctx.Done():
172新增: return false
173新增: case <-time.After(5 * time.Second):
174新增: return false
175新增: }
176新增: if _, err := tty.Write([]byte(op + "\r")); err != nil {
177新增: return false
178新增: }
179新增: timer := time.NewTimer(6 * time.Second)
180新增: defer timer.Stop()
181新增: tick := time.NewTicker(80 * time.Millisecond)
182新增: defer tick.Stop()
183新增: for {
184新增: select {
185新增: case <-ctx.Done():
186新增: return false
187新增: case <-timer.C:
188新增: return false
189新增: case <-tick.C:
190新增: var buf [257]byte
191新增: n, _ := probe.ReadAt(buf[:], 0)
192新增: if bytes.Equal(buf[:n], []byte(challenge+":guest")) {
193新增: return true
194新增: }
195新增: }
196新增: }
197新增:}
198新增:
199新增:func (s *Server) macOSVMLayout() (bool, bool) {
200新增: data, err := os.ReadFile(filepath.Join(s.instanceDir(), "lima.yaml"))
201新增: if err != nil {
202新增: return false, false
203新增: }
204新增: var spec struct {
205新增: OS string `yaml:"os"`
206新增: Driver string `yaml:"vmType"`
207新增: Mounts, Networks []any
208新增: Extra []any `yaml:"additionalDisks"`
209新增: }
210新增: if yaml.Unmarshal(data, &spec) != nil || spec.OS != "Darwin" || spec.Driver != "vz" {
211新增: return false, false
212新增: }
213新增: return spec.Mounts != nil && len(spec.Mounts) == 0 && len(spec.Extra) == 0, spec.Networks != nil && len(spec.Networks) == 0
214新增:}
215新增:
216新增:func (s *Server) macOSBrowserObservation(ctx context.Context, cfg cage.Config, network bool) (browserObservation, error) {
217新增: var observation browserObservation
218新增: data, err := s.nativeBrowserClient().request(ctx, "POST", "/audit", map[string]any{"timezone": cfg.Timezone, "network": network})
219新增: if err != nil || json.Unmarshal(data, &observation) != nil || observation.Platform == "" {
220新增: return observation, errors.New("无法在虚拟 Mac 的实际浏览器页面读取观测结果")
221新增: }
222新增: return observation, nil
223新增:}
224新增:
225新增:func macOSIPv6LinkVerified(v guestObservation, before, after cage.GateStatus) bool {
226新增: if !after.PolicyVerified || before.Mode != cage.GateChecking || after.Mode != cage.GateChecking || before.RunID == "" || after.RunID != before.RunID || before.CheckID == "" || after.CheckID != before.CheckID || after.IPv6LinkProbeCheck != before.CheckID {
227新增: return false
228新增: }
229新增: if v.IPv6Connected || !v.IPv6UnscopedAbsent || !v.IPv6LinkSent || v.IPv6LinkInterface == "" || v.IPv6Unbound.Result != "no-route" || v.IPv6Unbound.GlobalSources != 0 || v.IPv6DefaultRoutes != len(v.IPv6Scoped) {
230新增: return false
231新增: }
232新增: seen := map[string]bool{}
233新增: for _, p := range v.IPv6Scoped {
234新增: if !strings.HasPrefix(p.Name, "utun") || seen[p.Name] || !p.RouteVerified || p.BoundIndex <= 0 || p.GlobalSources != 0 || (p.Result != "no-route" && p.Result != "timeout") {
235新增: return false
236新增: }
237新增: seen[p.Name] = true
238新增: }
239新增: return true
240新增:}
241新增:
242新增:// Called only from the explicitly requested safety check. Restart the existing
243新增:// selected core without selecting another node or changing its revision.
244新增:func (s *Server) checkMacOSNetwork() error {
245新增: cfg, err := loadConfig(s.configPath)
246新增: if err != nil {
247新增: return err
248新增: }
249新增: if err = cfg.RequireManagedProxy(s.profile); err != nil {
250新增: return err
251新增: }
252新增: store, err := managedproxy.Load(s.profile)
253新增: if err != nil {
254新增: return err
255新增: }
256新增: if store.Selected == "" || store.Revision != cfg.ProxyRevision || store.Endpoint() != cfg.ProxyURL {
257新增: return errors.New("请先为这台 macOS 客机选择并应用代理节点")
258新增: }
259新增: if s.vmRunning() {
260新增: client, err := s.gateClient()
261新增: if err != nil {
262新增: return err
263新增: }
264新增: state, err := client.Status(s.operationContext())
265新增: if err != nil {
266新增: return err
267新增: }
268新增: if state.Configuration != cfg.Fingerprint() {
269新增: return errors.New("网络设置已保存,请重启 macOS 客机,登录后重新检测")
270新增: }
271新增: }
272新增: ctx := s.operationContext()
273新增: if !managedproxy.Running(ctx, s.profile, store) {
274新增: if err = validateProxyCore(ctx, s.profile, store); err != nil {
275新增: return err
276新增: }
277新增: if err = startProxyCore(ctx, s.profile, store); err != nil {
278新增: return err
279新增: }
280新增: }
281新增: return s.runSafetyCheck()
282新增:}
新增internal/workbench/macos_safety_probe.cjs+179 −0看文件
@@ -0,0 +1,179 @@
1新增:// Runs with the provisioned guest Node runtime over pinned SSH. The fixed IP
2新增:// is intercepted by the VM network layer only during an authorized check.
3新增:const fs = require("node:fs");
4新增:const net = require("node:net");
5新增:const dgram = require("node:dgram");
6新增:const dns = require("node:dns").promises;
7新增:const http = require("node:http");
8新增:const { execFileSync, execFile, spawnSync } = require("node:child_process");
9新增:const runFile = require("node:util").promisify(execFile);
10新增:const input = JSON.parse(Buffer.from(process.argv[1], "base64").toString());
11新增:function read(command, args) {
12新增: try {
13新增: return execFileSync(command, args, {
14新增: timeout: 2500,
15新增: encoding: "utf8",
16新增: stdio: ["ignore", "pipe", "ignore"],
17新增: }).trim();
18新增: } catch {
19新增: return "";
20新增: }
21新增:}
22新增:function tcp(host, port) {
23新增: return new Promise((resolve) => {
24新增: const socket = net.connect({ host, port });
25新增: const finish = (value) => {
26新增: socket.destroy();
27新增: resolve(value);
28新增: };
29新增: socket.setTimeout(1800, () => finish(false));
30新增: socket.once("connect", () => finish(true));
31新增: socket.once("error", () => finish(false));
32新增: });
33新增:}
34新增:function udp() {
35新增: return new Promise((resolve) => {
36新增: const socket = dgram.createSocket("udp4");
37新增: socket.send(
38新增: Buffer.from("Cage network boundary probe"),
39新增: 3478,
40新增: "1.1.1.1",
41新增: (err) => {
42新增: socket.close();
43新增: resolve(!err);
44新增: },
45新增: );
46新增: });
47新增:}
48新增:function probe(path) {
49新增: return new Promise((resolve) => {
50新增: const req = http.get(
51新增: { host: "198.18.0.254", port: 80, path, agent: false },
52新增: (res) => {
53新增: let data = "";
54新增: res.on("data", (chunk) => {
55新增: data += chunk;
56新增: if (data.length > 4096) req.destroy(new Error("oversized probe"));
57新增: });
58新增: res.on("error", () => resolve({ status: 0 }));
59新增: res.on("end", () => {
60新增: try {
61新增: const body = JSON.parse(data);
62新增: resolve({ status: res.statusCode, ip: body.ip || "" });
63新增: } catch {
64新增: resolve({ status: res.statusCode });
65新增: }
66新增: });
67新增: },
68新增: );
69新增: req.setTimeout(16000, () => req.destroy(new Error("probe timeout")));
70新增: req.once("error", () => resolve({ status: 0 }));
71新增: });
72新增:}
73新增:(async () => {
74新增: const result = {};
75新增: if (input.stage === "boundary" || input.stage === "environment") {
76新增: result.tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
77新增: result.process_locale = Intl.DateTimeFormat().resolvedOptions().locale;
78新增: result.system_locale = read("/usr/bin/defaults", [
79新增: "read",
80新增: "-g",
81新增: "AppleLocale",
82新增: ]).split("@")[0];
83新增: try {
84新增: const zone = fs.readlinkSync("/etc/localtime").split("/zoneinfo/")[1];
85新增: if (zone) result.system_timezone = zone;
86新增: } catch {}
87新增: }
88新增: if (input.stage === "boundary") {
89新增: [
90新增: result.public_connected,
91新增: result.management_connected,
92新增: result.ipv6_connected,
93新增: result.udp_attempted,
94新增: ] = await Promise.all([
95新增: tcp("1.1.1.1", 443),
96新增: tcp(input.management_host, input.control_port),
97新增: tcp("2606:4700:4700::1111", 443),
98新增: udp(),
99新增: ]);
100新增: const routes = read("/usr/sbin/netstat", ["-rn", "-f", "inet6"]);
101新增: result.ipv6_default_routes = /Internet6:/.test(routes)
102新增: ? (routes.match(/^default\s+/gm) || []).length
103新增: : -1;
104新增: const helper = "/usr/local/libexec/cage-macos-ipv6-check";
105新增: const lookup = spawnSync(
106新增: "/sbin/route",
107新增: ["-n", "get", "-inet6", "2606:4700:4700::1111"],
108新增: { encoding: "utf8", timeout: 2000 },
109新增: );
110新增: result.ipv6_unscoped_absent =
111新增: !lookup.error &&
112新增: /not in table|network is unreachable/i.test(
113新增: lookup.stderr + " " + lookup.stdout,
114新增: );
115新增: const rows = routes.split("\n").filter((row) => /^default\s/.test(row));
116新增: result.ipv6_scoped = await Promise.all(
117新增: rows.slice(0, 16).map(async (row) => {
118新增: const [, gateway, flags, name] = row.trim().split(/\s+/);
119新增: if (
120新增: !/^utun[0-9]+$/.test(name) ||
121新增: !flags.includes("I") ||
122新增: !gateway.startsWith("fe80:")
123新增: )
124新增: return { name };
125新增: const detail = read("/sbin/route", [
126新增: "-n",
127新增: "get",
128新增: "-inet6",
129新增: "-ifscope",
130新增: name,
131新增: "2606:4700:4700::1111",
132新增: ]);
133新增: try {
134新增: const { stdout } = await runFile(helper, [name], { timeout: 2500 });
135新增: const data = JSON.parse(stdout);
136新增: return {
137新增: name,
138新增: routeVerified: new RegExp(
139新增: "interface:\\s*" + name + "\\s*$",
140新增: "m",
141新增: ).test(detail),
142新增: result: data.result,
143新增: globalSources: data.globalSources,
144新增: boundIndex: data.boundIndex,
145新增: };
146新增: } catch {
147新增: return { name };
148新增: }
149新增: }),
150新增: );
151新增: try {
152新增: result.ipv6_unbound = JSON.parse(read(helper, ["default"]));
153新增: } catch {}
154新增: const iface = read("/sbin/route", [
155新增: "-n",
156新增: "get",
157新增: "-inet",
158新增: "198.18.0.254",
159新增: ]).match(/interface:\s*(en[0-9]+)\s*$/m)?.[1];
160新增: if (iface && input.run_id && input.check_id) {
161新增: result.ipv6_link_interface = iface;
162新增: result.ipv6_link_sent =
163新增: read(helper, ["link", iface, input.run_id, input.check_id]) === "sent";
164新增: }
165新增: try {
166新增: await dns.lookup(input.nonce + ".example.com");
167新增: result.public_dns_answered = true;
168新增: } catch {
169新增: result.public_dns_answered = false;
170新增: }
171新增: }
172新增: if (input.stage === "network") {
173新增: [result.egress, result.dns] = await Promise.all([
174新增: probe("/egress"),
175新增: probe("/dns"),
176新增: ]);
177新增: }
178新增: console.log(JSON.stringify(result));
179新增:})().catch(() => process.exit(1));
新增internal/workbench/macos_safety_test.go+78 −0看文件
@@ -0,0 +1,78 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "context"
5新增: "errors"
6新增: "github.com/sylvinus/agent-vm/internal/cage"
7新增: "github.com/sylvinus/agent-vm/internal/guestos"
8新增: "testing"
9新增: "time"
10新增:)
11新增:
12新增:func TestMacIPv6ScopedRoutesRequireCompleteLiveEvidence(t *testing.T) {
13新增: base := guestObservation{IPv6DefaultRoutes: 1, IPv6UnscopedAbsent: true, IPv6LinkSent: true, IPv6LinkInterface: "en0",
14新增: IPv6Unbound: macIPv6Probe{Result: "no-route"}, IPv6Scoped: []macIPv6Probe{{Name: "utun0", RouteVerified: true, BoundIndex: 7, Result: "timeout"}}}
15新增: before := cage.GateStatus{Mode: cage.GateChecking, RunID: "selected-vm", CheckID: "current-check"}
16新增: after := before
17新增: after.PolicyVerified = true
18新增: after.IPv6LinkProbeCheck = before.CheckID
19新增: if !macOSIPv6LinkVerified(base, before, after) {
20新增: t.Fatal("live matching IPv6 drop proof rejected")
21新增: }
22新增: for _, change := range []func(*guestObservation, *cage.GateStatus){
23新增: func(_ *guestObservation, a *cage.GateStatus) { a.IPv6LinkProbeCheck = "old-check" },
24新增: func(_ *guestObservation, a *cage.GateStatus) { a.RunID = "another-vm" },
25新增: func(b *guestObservation, _ *cage.GateStatus) { b.IPv6Scoped[0].GlobalSources = 1 },
26新增: func(b *guestObservation, _ *cage.GateStatus) { b.IPv6Scoped[0].Result = "connected" },
27新增: func(b *guestObservation, _ *cage.GateStatus) { b.IPv6Scoped[0].BoundIndex = 0 },
28新增: func(b *guestObservation, _ *cage.GateStatus) { b.IPv6UnscopedAbsent = false },
29新增: func(b *guestObservation, _ *cage.GateStatus) { b.IPv6DefaultRoutes++ },
30新增: } {
31新增: v, a := base, after
32新增: v.IPv6Scoped = append([]macIPv6Probe(nil), base.IPv6Scoped...)
33新增: change(&v, &a)
34新增: if macOSIPv6LinkVerified(v, before, a) {
35新增: t.Fatal("accepted incomplete interface or ingress observations")
36新增: }
37新增: }
38新增:}
39新增:
40新增:func TestMacOSStaticExitRequiresThreeMatchingSuccessfulSamples(t *testing.T) {
41新增: cfg := cage.DefaultConfig()
42新增: host := "8.8.8.8"
43新增: ok := networkObservation{Status: 200, IP: host}
44新增: sample := macOSStaticCandidate(cfg, "this-run", host, ok, ok)
45新增: if sample == nil || sample.IP != host || sample.Run != "this-run" || sample.Fingerprint != cfg.Fingerprint() {
46新增: t.Fatal("missing verified candidate")
47新增: }
48新增: for _, bad := range []networkObservation{{Status: 503, IP: host}, {Status: 200, IP: "8.8.4.4"}, {Status: 200}} {
49新增: if macOSStaticCandidate(cfg, "this-run", host, bad, ok) != nil || macOSStaticCandidate(cfg, "this-run", host, ok, bad) != nil {
50新增: t.Fatal("accepted different or incomplete egress samples")
51新增: }
52新增: }
53新增: cfg.ExitPolicy = cage.ExitPolicy{Mode: "static", IP: host}
54新增: if macOSStaticCandidate(cfg, "this-run", host, ok, ok) != nil {
55新增: t.Fatal("offered the existing binding again")
56新增: }
57新增:}
58新增:
59新增:func TestMacOSWorkloadStartsNetworkSupervision(t *testing.T) {
60新增: s := testServer(t)
61新增: s.macosGuest = &guestos.MacOSProfile{Instance: "mac", User: "guestdev"}
62新增: checked := make(chan struct{}, 1)
63新增: previous := physicalProxyInterface
64新增: physicalProxyInterface = func(ctx context.Context) (string, error) {
65新增: select {
66新增: case checked <- struct{}{}:
67新增: default:
68新增: }
69新增: return "", errors.New("network disconnected")
70新增: }
71新增: defer func() { s.closeBackground(); physicalProxyInterface = previous }()
72新增: s.startMonitors()
73新增: select {
74新增: case <-checked:
75新增: case <-time.After(7 * time.Second):
76新增: t.Fatal("the running macOS workbench never started its real network monitor")
77新增: }
78新增:}
新增internal/workbench/macos_stop_test.go+124 −0看文件
@@ -0,0 +1,124 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "fmt"
5新增: "net/http"
6新增: "os"
7新增: "path/filepath"
8新增: "runtime"
9新增: "strings"
10新增: "testing"
11新增:
12新增: "al.essio.dev/pkg/shellescape"
13新增: "github.com/sylvinus/agent-vm/internal/cage"
14新增: "github.com/sylvinus/agent-vm/internal/guestos"
15新增: "github.com/sylvinus/agent-vm/internal/managedproxy"
16新增: "golang.org/x/crypto/ssh"
17新增:)
18新增:
19新增:func TestMacOSExplicitStopReleasesProxyAfterGuestStops(t *testing.T) {
20新增: if runtime.GOOS != "darwin" {
21新增: t.Skip("launchd proxy lifecycle")
22新增: }
23新增: for _, failGuest := range []bool{false, true} {
24新增: t.Run(fmt.Sprintf("guest_failure_%t", failGuest), func(t *testing.T) {
25新增: s := testServer(t)
26新增: s.macosGuest = &guestos.MacOSProfile{User: "cage", Instance: "mac"}
27新增: s.ready = true
28新增: bin := t.TempDir()
29新增: marker := filepath.Join(bin, "proxy-stopped")
30新增: t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
31新增: launcher := "#!/bin/sh\nif [ \"$1\" = bootout ]; then printf stopped > " + shellescape.Quote(marker) + "; fi\nexit 0\n"
32新增: if err := os.WriteFile(filepath.Join(bin, "launchctl"), []byte(launcher), 0700); err != nil {
33新增: t.Fatal(err)
34新增: }
35新增: s.exe = filepath.Join(bin, "cage")
36新增: code := 0
37新增: if failGuest {
38新增: code = 1
39新增: }
40新增: if err := os.WriteFile(s.exe, []byte(fmt.Sprintf("#!/bin/sh\nexit %d\n", code)), 0700); err != nil {
41新增: t.Fatal(err)
42新增: }
43新增: if err := os.MkdirAll(managedproxy.Dir(s.profile), 0700); err != nil {
44新增: t.Fatal(err)
45新增: }
46新增: if err := os.WriteFile(filepath.Join(managedproxy.Dir(s.profile), "managed-service.plist"), []byte("isolated test service"), 0600); err != nil {
47新增: t.Fatal(err)
48新增: }
49新增: response := windowsBrowserRequestForTest(s, http.MethodPost, "/api/stop", []byte(`{}`))
50新增: job := awaitJobIdle(t, &s.jobs)
51新增: if response.Code != http.StatusOK || (job.Error != "") != failGuest {
52新增: t.Fatalf("stop response %d, job %+v", response.Code, job)
53新增: }
54新增: _, err := os.Stat(marker)
55新增: if failGuest && !os.IsNotExist(err) || !failGuest && err != nil {
56新增: t.Fatalf("proxy cleanup must follow successful guest shutdown: %v", err)
57新增: }
58新增: })
59新增: }
60新增:}
61新增:
62新增:func TestMacOSStopStartPreservesUserNetworkIntent(t *testing.T) {
63新增: if runtime.GOOS != "darwin" {
64新增: t.Skip("native Mac control uses host OpenSSH")
65新增: }
66新增: for _, paused := range []bool{false, true} {
67新增: t.Run(fmt.Sprintf("paused_%t", paused), func(t *testing.T) {
68新增: guest := newMacWorkspaceGuest(t, func(_ ssh.Channel, command string) (uint32, bool) {
69新增: return 0, strings.Contains(command, "uname -s")
70新增: })
71新增: s := guest.s
72新增: s.exe = filepath.Join(t.TempDir(), "cage")
73新增: if err := os.WriteFile(s.exe, []byte("#!/bin/sh\nexit 0\n"), 0700); err != nil {
74新增: t.Fatal(err)
75新增: }
76新增: if err := writePrivate(filepath.Join(s.profile, "network-intent.json"), networkIntent{Version: 1, Paused: paused, PauseVersion: 1}); err != nil {
77新增: t.Fatal(err)
78新增: }
79新增: if err := s.restoreNetworkIntent(); err != nil {
80新增: t.Fatal(err)
81新增: }
82新增: config, err := loadConfig(s.configPath)
83新增: if err != nil {
84新增: t.Fatal(err)
85新增: }
86新增: gate, err := cage.NewEgressGate(config)
87新增: if err != nil {
88新增: t.Fatal(err)
89新增: }
90新增: stop, err := cage.StartGateControl(s.configPath, s.instanceDir(), gate)
91新增: if err != nil {
92新增: t.Fatal(err)
93新增: }
94新增: defer stop()
95新增: store, err := managedproxy.Load(s.profile)
96新增: if err != nil {
97新增: t.Fatal(err)
98新增: }
99新增: store.Selected = ""
100新增: if err := store.Save(s.profile); err != nil {
101新增: t.Fatal(err)
102新增: }
103新增: checkFailure := config.RequireManagedProxy(s.profile)
104新增: if checkFailure == nil {
105新增: t.Fatal("fixture did not require a fresh network check")
106新增: }
107新增: for _, route := range []string{"/api/stop", "/api/start"} {
108新增: response := windowsBrowserRequestForTest(s, http.MethodPost, route, []byte(`{}`))
109新增: job := awaitJobIdle(t, &s.jobs)
110新增: wantCheck := route == "/api/start" && !paused
111新增: if response.Code != http.StatusOK || wantCheck && !strings.Contains(job.Error, checkFailure.Error()) || !wantCheck && job.Error != "" {
112新增: t.Fatalf("%s completed without the expected network decision: %d %+v", route, response.Code, job)
113新增: }
114新增: reloaded := reloadedIntentServer(t, s)
115新增: if err := reloaded.restoreNetworkIntent(); err != nil || reloaded.networkPaused != paused {
116新增: t.Fatalf("%s changed saved user pause: %t, %v", route, reloaded.networkPaused, err)
117新增: }
118新增: }
119新增: if !s.ready || gate.Status().Mode != cage.GateClosed {
120新增: t.Fatal("guest must be ready while fresh authorization remains absent")
121新增: }
122新增: })
123新增: }
124新增:}
新增internal/workbench/macos_window_connection.go+143 −0看文件
@@ -0,0 +1,143 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "bufio"
5新增: "context"
6新增: "encoding/json"
7新增: "math"
8新增: "net/http"
9新增: "time"
10新增:)
11新增:
12新增:func validMacOSWindowRequest(input macOSWindowRequest) bool {
13新增: switch input.Action {
14新增: case "status", "launch", "stop", "request-screen", "request-input", "frame", "text", "key", "click", "scroll", "pointer", "ime", "input-reset":
15新增: default:
16新增: return false
17新增: }
18新增: if len(input.After) > 128 || len(input.Geometry) > 128 || input.Width < 0 || input.Width > 2560 || input.Height < 0 || input.Height > 1600 || input.Scale < 0 || input.Scale > 2 {
19新增: return false
20新增: }
21新增: if len(input.Text) > 8192 || len(input.Key) > 64 || len(input.Code) > 64 {
22新增: return false
23新增: }
24新增: if input.Action == "pointer" || input.Action == "ime" || (input.Action == "key" && input.Code != "") {
25新增: if input.PID <= 0 || input.Window == 0 || input.Geometry == "" {
26新增: return false
27新增: }
28新增: }
29新增: if input.Action == "pointer" {
30新增: if input.Phase != "down" && input.Phase != "move" && input.Phase != "up" {
31新增: return false
32新增: }
33新增: if input.Buttons < 0 || input.Buttons > 7 || input.X == nil || input.Y == nil ||
34新增: math.IsNaN(*input.X) || math.IsNaN(*input.Y) || *input.X < 0 || *input.X >= 1 || *input.Y < 0 || *input.Y >= 1 {
35新增: return false
36新增: }
37新增: if input.Phase != "move" && (input.Button == nil || *input.Button < 0 || *input.Button > 2 || input.Clicks < 1 || input.Clicks > 3) {
38新增: return false
39新增: }
40新增: }
41新增: if input.Action == "key" && input.Code != "" && input.Down == nil {
42新增: return false
43新增: }
44新增: if input.Action == "ime" {
45新增: if input.Mode != "status" && input.Mode != "begin" && input.Mode != "update" && input.Mode != "commit" && input.Mode != "cancel" {
46新增: return false
47新增: }
48新增: if input.Mode != "status" && (!validInputToken(input.Session) || input.Sequence < 0) {
49新增: return false
50新增: }
51新增: if input.Mode == "begin" && !validInputToken(input.Context) {
52新增: return false
53新增: }
54新增: }
55新增: return (input.Width == 0 && input.Height == 0 && input.Scale == 0) ||
56新增: (input.Action == "frame" && input.Width >= 320 && input.Height >= 240 && input.Scale >= 1)
57新增:}
58新增:
59新增:func macOSWindowClientRequest(input macOSWindowRequest, keepAlive bool) macOSWindowRequest {
60新增: input.Project, input.Nonce = "", ""
61新增: input.Phone, input.PhoneToken = nil, ""
62新增: input.Transfer, input.Path, input.Error = "", "", ""
63新增: input.Wait, input.Binary, input.KeepAlive = false, false, keepAlive
64新增: if input.Action != "ime" {
65新增: input.Sequence = 0
66新增: }
67新增: return input
68新增:}
69新增:
70新增:// One authenticated WebSocket owns one ordinary-user SSH channel. Requests are
71新增:// ordered on that channel, including input and capture geometry changes.
72新增:func (s *Server) macOSWindowConnection(w http.ResponseWriter, r *http.Request) {
73新增: if s.macosGuest == nil {
74新增: http.NotFound(w, r)
75新增: return
76新增: }
77新增: ws, err := s.upgrade(w, r)
78新增: if err != nil {
79新增: return
80新增: }
81新增: defer ws.Close()
82新增: ws.SetReadLimit(64 << 10)
83新增: ctx, cancel := context.WithCancel(r.Context())
84新增: defer cancel()
85新增: stop := context.AfterFunc(s.lifetimeContext(), func() { cancel(); ws.Close() })
86新增: defer stop()
87新增: cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", `exec /usr/bin/nc -U "$HOME/Library/Caches/dev.cage.GuestClaudeWindow/window.sock"`)
88新增: input, err := cmd.StdinPipe()
89新增: if err != nil {
90新增: return
91新增: }
92新增: defer input.Close()
93新增: output, err := cmd.StdoutPipe()
94新增: if err != nil {
95新增: return
96新增: }
97新增: defer output.Close()
98新增: if err = cmd.Start(); err != nil {
99新增: return
100新增: }
101新增: defer func() { cancel(); input.Close(); output.Close(); _ = cmd.Wait() }()
102新增: scanner := bufio.NewScanner(output)
103新增: scanner.Buffer(make([]byte, 64<<10), 12<<20)
104新增: for {
105新增: var message struct {
106新增: ID uint64 `json:"id"`
107新增: Request macOSWindowRequest `json:"request"`
108新增: }
109新增: if err = ws.ReadJSON(&message); err != nil {
110新增: return
111新增: }
112新增: if !validMacOSWindowRequest(message.Request) {
113新增: return
114新增: }
115新增: message.Request = macOSWindowClientRequest(message.Request, true)
116新增: body, err := json.Marshal(message.Request)
117新增: if err != nil || len(body) > 64<<10 {
118新增: return
119新增: }
120新增: limit := 12 * time.Second
121新增: if message.Request.Action == "launch" {
122新增: limit = 55 * time.Second
123新增: }
124新增: timer := time.AfterFunc(limit, func() { cancel(); output.Close(); ws.Close() })
125新增: _, err = input.Write(append(body, '\n'))
126新增: if err != nil || !scanner.Scan() {
127新增: timer.Stop()
128新增: return
129新增: }
130新增: timer.Stop()
131新增: data := append(json.RawMessage(nil), scanner.Bytes()...)
132新增: if !json.Valid(data) {
133新增: return
134新增: }
135新增: _ = ws.SetWriteDeadline(time.Now().Add(12 * time.Second))
136新增: if ws.WriteJSON(struct {
137新增: ID uint64 `json:"id"`
138新增: Result json.RawMessage `json:"result"`
139新增: }{message.ID, data}) != nil {
140新增: return
141新增: }
142新增: }
143新增:}
新增internal/workbench/macos_window_frames.go+245 −0看文件
@@ -0,0 +1,245 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "bufio"
5新增: "bytes"
6新增: "context"
7新增: "encoding/binary"
8新增: "encoding/json"
9新增: "errors"
10新增: "image"
11新增: "io"
12新增: "net/http"
13新增: "sync"
14新增: "time"
15新增:
16新增: "github.com/gorilla/websocket"
17新增:)
18新增:
19新增:type macOSFrameHeader struct {
20新增: ImageLength int `json:"imageLength"`
21新增: MIME string `json:"mime,omitempty"`
22新增: Sequence string `json:"sequence,omitempty"`
23新增: Geometry string `json:"geometry,omitempty"`
24新增: Window uint32 `json:"window,omitempty"`
25新增: PID int32 `json:"pid,omitempty"`
26新增: ContentWidth float64 `json:"contentWidth,omitempty"`
27新增: ContentHeight float64 `json:"contentHeight,omitempty"`
28新增: PixelWidth int `json:"pixelWidth,omitempty"`
29新增: PixelHeight int `json:"pixelHeight,omitempty"`
30新增: Unchanged bool `json:"unchanged,omitempty"`
31新增: Error string `json:"error,omitempty"`
32新增: Revision uint64 `json:"revision,omitempty"`
33新增:}
34新增:
35新增:// Each record contains a big-endian JSON length, metadata, and the original
36新增:// encoded image. Validate dimensions without decompressing the image pixels.
37新增:func readMacOSFrame(reader io.Reader) (macOSFrameHeader, []byte, error) {
38新增: var header macOSFrameHeader
39新增: var size uint32
40新增: if err := binary.Read(reader, binary.BigEndian, &size); err != nil {
41新增: return header, nil, err
42新增: }
43新增: if size == 0 || size > 16<<10 {
44新增: return header, nil, errors.New("窗口画面元数据过大")
45新增: }
46新增: metadata := make([]byte, size)
47新增: if _, err := io.ReadFull(reader, metadata); err != nil {
48新增: return header, nil, err
49新增: }
50新增: if err := json.Unmarshal(metadata, &header); err != nil {
51新增: return header, nil, err
52新增: }
53新增: if header.ImageLength < 0 || header.ImageLength >= 8<<20 || len(header.Sequence) > 128 || len(header.Geometry) > 128 {
54新增: return header, nil, errors.New("窗口画面元数据无效")
55新增: }
56新增: if header.Error != "" || header.Unchanged {
57新增: if header.ImageLength != 0 {
58新增: return header, nil, errors.New("窗口状态包含无效画面")
59新增: }
60新增: return header, nil, nil
61新增: }
62新增: if header.ImageLength == 0 || header.Sequence == "" || header.Geometry == "" || header.Window == 0 || header.PID <= 0 ||
63新增: header.ContentWidth <= 0 || header.ContentHeight <= 0 || header.ContentWidth > 8192 || header.ContentHeight > 8192 ||
64新增: header.PixelWidth < 1 || header.PixelHeight < 1 || header.PixelWidth > 8192 || header.PixelHeight > 8192 ||
65新增: int64(header.PixelWidth)*int64(header.PixelHeight) > 40_000_000 {
66新增: return header, nil, errors.New("窗口画面尺寸无效")
67新增: }
68新增: data := make([]byte, header.ImageLength)
69新增: if _, err := io.ReadFull(reader, data); err != nil {
70新增: return header, nil, err
71新增: }
72新增: config, format, err := image.DecodeConfig(bytes.NewReader(data))
73新增: if err != nil || (format != "png" && format != "jpeg") || header.MIME != "image/"+format ||
74新增: config.Width != header.PixelWidth || config.Height != header.PixelHeight {
75新增: return header, nil, errors.New("窗口画面编码无效")
76新增: }
77新增: return header, data, nil
78新增:}
79新增:
80新增:type macOSFrameSubscription struct {
81新增: Width int `json:"width"`
82新增: Height int `json:"height"`
83新增: Scale float64 `json:"scale"`
84新增: Revision uint64 `json:"revision"`
85新增: Ack string `json:"ack"`
86新增:}
87新增:
88新增:// Frame waits have their own SSH channel so input never queues behind capture.
89新增:// Only one image is in flight until the browser decodes it or changes size.
90新增:func (s *Server) macOSWindowFrames(w http.ResponseWriter, r *http.Request) {
91新增: if s.macosGuest == nil {
92新增: http.NotFound(w, r)
93新增: return
94新增: }
95新增: ws, err := s.upgrade(w, r)
96新增: if err != nil {
97新增: return
98新增: }
99新增: defer ws.Close()
100新增: ws.SetReadLimit(1024)
101新增: ctx, cancel := context.WithCancel(r.Context())
102新增: defer cancel()
103新增: stop := context.AfterFunc(s.lifetimeContext(), func() { cancel(); ws.Close() })
104新增: defer stop()
105新增: cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", `exec /usr/bin/nc -U "$HOME/Library/Caches/dev.cage.GuestClaudeWindow/window.sock"`)
106新增: input, err := cmd.StdinPipe()
107新增: if err != nil {
108新增: return
109新增: }
110新增: defer input.Close()
111新增: output, err := cmd.StdoutPipe()
112新增: if err != nil {
113新增: return
114新增: }
115新增: defer output.Close()
116新增: if cmd.Start() != nil {
117新增: return
118新增: }
119新增: defer func() { cancel(); input.Close(); output.Close(); _ = cmd.Wait() }()
120新增: relayMacOSFrames(ctx, ws, input, output)
121新增:}
122新增:
123新增:func relayMacOSFrames(parent context.Context, ws *websocket.Conn, input io.WriteCloser, output io.ReadCloser) {
124新增: ctx, cancel := context.WithCancel(parent)
125新增: defer cancel()
126新增: stop := context.AfterFunc(ctx, func() { input.Close(); output.Close(); ws.Close() })
127新增: defer stop()
128新增: var mutex sync.Mutex
129新增: var latest macOSFrameSubscription
130新增: changed := make(chan struct{}, 1)
131新增: acknowledged := make(chan string, 1)
132新增: readerDone := make(chan struct{})
133新增: go func() {
134新增: defer close(readerDone)
135新增: defer cancel()
136新增: for {
137新增: var next macOSFrameSubscription
138新增: if ws.ReadJSON(&next) != nil {
139新增: return
140新增: }
141新增: if next.Ack != "" {
142新增: if len(next.Ack) > 128 {
143新增: return
144新增: }
145新增: select {
146新增: case acknowledged <- next.Ack:
147新增: case <-ctx.Done():
148新增: return
149新增: }
150新增: continue
151新增: }
152新增: if next.Revision == 0 || next.Width < 320 || next.Width > 2560 || next.Height < 240 || next.Height > 1600 || next.Scale < 1 || next.Scale > 2 {
153新增: return
154新增: }
155新增: mutex.Lock()
156新增: valid := next.Revision > latest.Revision
157新增: if valid {
158新增: latest = next
159新增: }
160新增: mutex.Unlock()
161新增: if !valid {
162新增: return
163新增: }
164新增: select {
165新增: case changed <- struct{}{}:
166新增: default:
167新增: }
168新增: }
169新增: }()
170新增: defer func() { cancel(); input.Close(); output.Close(); ws.Close(); <-readerDone }()
171新增: select {
172新增: case <-ctx.Done():
173新增: return
174新增: case <-changed:
175新增: }
176新增: reader := bufio.NewReaderSize(output, 64<<10)
177新增: var revision uint64
178新增: after := ""
179新增: for ctx.Err() == nil {
180新增: mutex.Lock()
181新增: config := latest
182新增: mutex.Unlock()
183新增: if revision != config.Revision {
184新增: after, revision = "", config.Revision
185新增: }
186新增: request := macOSWindowRequest{Action: "frame", Width: config.Width, Height: config.Height, Scale: config.Scale,
187新增: After: after, KeepAlive: true, Wait: true, Binary: true, Refresh: true}
188新增: body, _ := json.Marshal(request)
189新增: timer := time.AfterFunc(12*time.Second, func() { cancel(); output.Close(); ws.Close() })
190新增: _, err := input.Write(append(body, '\n'))
191新增: if err != nil {
192新增: timer.Stop()
193新增: return
194新增: }
195新增: header, pixels, err := readMacOSFrame(reader)
196新增: timer.Stop()
197新增: if err != nil {
198新增: return
199新增: }
200新增: mutex.Lock()
201新增: stale := config.Revision != latest.Revision
202新增: mutex.Unlock()
203新增: if stale {
204新增: continue
205新增: }
206新增: if header.Unchanged {
207新增: if after == "" || header.Sequence != after {
208新增: return
209新增: }
210新增: continue
211新增: }
212新增: header.Revision = config.Revision
213新增: metadata, _ := json.Marshal(header)
214新增: _ = ws.SetWriteDeadline(time.Now().Add(6 * time.Second))
215新增: writer, err := ws.NextWriter(websocket.BinaryMessage)
216新增: if err != nil {
217新增: return
218新增: }
219新增: err = binary.Write(writer, binary.BigEndian, uint32(len(metadata)))
220新增: if err == nil {
221新增: _, err = writer.Write(metadata)
222新增: }
223新增: if err == nil {
224新增: _, err = writer.Write(pixels)
225新增: }
226新增: closeErr := writer.Close()
227新增: if err != nil || closeErr != nil || header.Error != "" {
228新增: return
229新增: }
230新增: after = header.Sequence
231新增: consumed := false
232新增: for !consumed {
233新增: select {
234新增: case <-ctx.Done():
235新增: return
236新增: case ack := <-acknowledged:
237新增: consumed = ack == after
238新增: case <-changed:
239新增: mutex.Lock()
240新增: consumed = config.Revision != latest.Revision
241新增: mutex.Unlock()
242新增: }
243新增: }
244新增: }
245新增:}
新增internal/workbench/macos_window_frames_test.go+186 −0看文件
@@ -0,0 +1,186 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "bufio"
5新增: "bytes"
6新增: "encoding/binary"
7新增: "encoding/json"
8新增: "image"
9新增: "image/png"
10新增: "net"
11新增: "net/http"
12新增: "net/http/httptest"
13新增: "strings"
14新增: "testing"
15新增: "time"
16新增:
17新增: "github.com/gorilla/websocket"
18新增:)
19新增:
20新增:func macFrameFixture(t *testing.T) (macOSFrameHeader, []byte) {
21新增: t.Helper()
22新增: var data bytes.Buffer
23新增: if err := png.Encode(&data, image.NewRGBA(image.Rect(0, 0, 64, 48))); err != nil {
24新增: t.Fatal(err)
25新增: }
26新增: return macOSFrameHeader{ImageLength: data.Len(), MIME: "image/png", Sequence: "first", Geometry: "geometry", Window: 7, PID: 23,
27新增: ContentWidth: 32, ContentHeight: 24, PixelWidth: 64, PixelHeight: 48}, data.Bytes()
28新增:}
29新增:
30新增:func macFrameRecord(t *testing.T, header macOSFrameHeader, pixels []byte) []byte {
31新增: t.Helper()
32新增: metadata, err := json.Marshal(header)
33新增: if err != nil {
34新增: t.Fatal(err)
35新增: }
36新增: packet := make([]byte, 4+len(metadata)+len(pixels))
37新增: binary.BigEndian.PutUint32(packet, uint32(len(metadata)))
38新增: copy(packet[4:], metadata)
39新增: copy(packet[4+len(metadata):], pixels)
40新增: return packet
41新增:}
42新增:
43新增:func TestMacOSBinaryFramePreservesBytesAndRejectsInvalidRecords(t *testing.T) {
44新增: header, pixels := macFrameFixture(t)
45新增: decoded, actual, err := readMacOSFrame(bytes.NewReader(macFrameRecord(t, header, pixels)))
46新增: if err != nil || decoded != header || !bytes.Equal(actual, pixels) {
47新增: t.Fatalf("frame changed in transit: %v", err)
48新增: }
49新增: for _, mutation := range []func(*macOSFrameHeader){
50新增: func(h *macOSFrameHeader) { h.ImageLength = 8 << 20 },
51新增: func(h *macOSFrameHeader) { h.ImageLength++ },
52新增: func(h *macOSFrameHeader) { h.PixelWidth++ },
53新增: func(h *macOSFrameHeader) { h.MIME = "image/jpeg" },
54新增: func(h *macOSFrameHeader) { h.Unchanged = true },
55新增: func(h *macOSFrameHeader) { h.Geometry = "" },
56新增: } {
57新增: invalid := header
58新增: mutation(&invalid)
59新增: if _, _, err := readMacOSFrame(bytes.NewReader(macFrameRecord(t, invalid, pixels))); err == nil {
60新增: t.Fatalf("accepted invalid frame metadata %+v", invalid)
61新增: }
62新增: }
63新增: if _, _, err := readMacOSFrame(bytes.NewReader([]byte{0, 1, 0, 0})); err == nil {
64新增: t.Fatal("accepted an oversized header")
65新增: }
66新增:}
67新增:
68新增:func TestMacOSFrameStreamAcknowledgementResizeAndDisconnect(t *testing.T) {
69新增: s := testServer(t)
70新增: transport, guest := net.Pipe()
71新增: defer guest.Close()
72新增: requests := make(chan macOSWindowRequest, 4)
73新增: responses := make(chan []byte, 4)
74新增: guestDone := make(chan struct{})
75新增: go func() {
76新增: defer close(guestDone)
77新增: scanner := bufio.NewScanner(guest)
78新增: for scanner.Scan() {
79新增: var request macOSWindowRequest
80新增: if json.Unmarshal(scanner.Bytes(), &request) != nil {
81新增: return
82新增: }
83新增: requests <- request
84新增: response, ok := <-responses
85新增: if !ok {
86新增: return
87新增: }
88新增: if _, err := guest.Write(response); err != nil {
89新增: return
90新增: }
91新增: }
92新增: }()
93新增: defer func() { close(responses); guest.Close(); <-guestDone }()
94新增: finished := make(chan struct{})
95新增: server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
96新增: defer close(finished)
97新增: ws, err := s.upgrade(w, r)
98新增: if err != nil {
99新增: return
100新增: }
101新增: defer ws.Close()
102新增: relayMacOSFrames(r.Context(), ws, transport, transport)
103新增: }))
104新增: defer server.Close()
105新增: s.origin = server.URL
106新增: ws, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(server.URL, "http"), http.Header{"Origin": {server.URL}})
107新增: if err != nil {
108新增: t.Fatal(err)
109新增: }
110新增: defer ws.Close()
111新增: send := func(message any) {
112新增: t.Helper()
113新增: if err := ws.WriteJSON(message); err != nil {
114新增: t.Fatal(err)
115新增: }
116新增: }
117新增: next := func() macOSWindowRequest {
118新增: t.Helper()
119新增: select {
120新增: case request := <-requests:
121新增: if !request.Wait || !request.Binary || !request.KeepAlive || !request.Refresh {
122新增: t.Fatalf("frame stream lost its wire contract: %+v", request)
123新增: }
124新增: return request
125新增: case <-time.After(2 * time.Second):
126新增: t.Fatal("guest did not receive a request")
127新增: return macOSWindowRequest{}
128新增: }
129新增: }
130新增: read := func() macOSFrameHeader {
131新增: t.Helper()
132新增: _ = ws.SetReadDeadline(time.Now().Add(2 * time.Second))
133新增: kind, record, err := ws.ReadMessage()
134新增: if err != nil || kind != websocket.BinaryMessage {
135新增: t.Fatalf("frame response: %v", err)
136新增: }
137新增: header, _, err := readMacOSFrame(bytes.NewReader(record))
138新增: if err != nil {
139新增: t.Fatal(err)
140新增: }
141新增: return header
142新增: }
143新增: send(macOSFrameSubscription{Width: 800, Height: 600, Scale: 2, Revision: 1})
144新增: if first := next(); first.After != "" || first.Width != 800 {
145新增: t.Fatalf("bad first request: %+v", first)
146新增: }
147新增: header, pixels := macFrameFixture(t)
148新增: responses <- macFrameRecord(t, header, pixels)
149新增: if read().Revision != 1 {
150新增: t.Fatal("lost subscription revision")
151新增: }
152新增: select {
153新增: case <-requests:
154新增: t.Fatal("captured another image before decode acknowledgement")
155新增: case <-time.After(100 * time.Millisecond):
156新增: }
157新增: send(macOSFrameSubscription{Ack: "first"})
158新增: if next().After != "first" {
159新增: t.Fatal("lost the consumed frame sequence")
160新增: }
161新增: responses <- macFrameRecord(t, macOSFrameHeader{Unchanged: true, Sequence: "first"}, nil)
162新增: next()
163新增: // Resize while the guest is waiting for the next changed frame. The old
164新增: // response must be consumed without forwarding it to the new viewport.
165新增: send(macOSFrameSubscription{Width: 900, Height: 640, Scale: 2, Revision: 2})
166新增: time.Sleep(50 * time.Millisecond)
167新增: header.Sequence = "old-size"
168新增: responses <- macFrameRecord(t, header, pixels)
169新增: resized := next()
170新增: if resized.Width != 900 || resized.After != "" {
171新增: t.Fatalf("stale resize request: %+v", resized)
172新增: }
173新增: header.Sequence = "new-size"
174新增: responses <- macFrameRecord(t, header, pixels)
175新增: if result := read(); result.Sequence != "new-size" || result.Revision != 2 {
176新增: t.Fatalf("forwarded a stale or unchanged frame: %+v", result)
177新增: }
178新增: send(macOSFrameSubscription{Ack: "new-size"})
179新增: next()
180新增: ws.Close()
181新增: select {
182新增: case <-finished:
183新增: case <-time.After(2 * time.Second):
184新增: t.Fatal("disconnect left a blocked guest read")
185新增: }
186新增:}
新增internal/workbench/macos_workbench_e2e_test.go+401 −0看文件
@@ -0,0 +1,401 @@
1新增://go:build e2e && darwin && arm64
2新增:
3新增:package workbench
4新增:
5新增:import (
6新增: "bytes"
7新增: "context"
8新增: _ "embed"
9新增: "encoding/base64"
10新增: "encoding/json"
11新增: "fmt"
12新增: "io"
13新增: "net/http"
14新增: "net/http/httptest"
15新增: "net/url"
16新增: "os"
17新增: "os/exec"
18新增: "path/filepath"
19新增: "strings"
20新增: "testing"
21新增: "time"
22新增:
23新增: "al.essio.dev/pkg/shellescape"
24新增: "github.com/gorilla/websocket"
25新增: "github.com/sylvinus/agent-vm/internal/guestos"
26新增:)
27新增:
28新增://go:embed testdata/macos_editor_file.swift
29新增:var macOSEditorFileLocator []byte
30新增:
31新增:// Exercises the same local-view HTTP admission, SSH PTY and WebSocket stream
32新增:// as the installed Mac workbench. Requires an already started, bound guest.
33新增:func TestMacOSWorkbenchTerminal(t *testing.T) {
34新增: profile := os.Getenv("CAGE_TEST_MACOS_WORKBENCH_PROFILE")
35新增: if profile == "" {
36新增: t.Skip("select a prepared test profile with CAGE_TEST_MACOS_WORKBENCH_PROFILE")
37新增: }
38新增: binding, err := guestos.LoadMacOSProfile(profile)
39新增: if err != nil || binding == nil {
40新增: t.Fatalf("unavailable macOS test profile: %v", err)
41新增: }
42新增: s := testServer(t)
43新增: s.profile, s.macosGuest = profile, binding
44新增: s.token, s.session = randomToken(), randomToken()
45新增: s.preferences.Workspace = s.environmentDir()
46新增: ctx, cancel := s.controlContext()
47新增: defer cancel()
48新增: if err := s.checkMacOSGuest(ctx); err != nil {
49新增: t.Fatal(err)
50新增: }
51新增: s.ready = true
52新增: defer s.terminals.close()
53新增: server := httptest.NewServer(s.handler())
54新增: defer server.Close()
55新增: s.origin = server.URL
56新增: cookie := s.cookieName() + "=" + s.session + "; " + s.cookieName() + "-desktop=" + trustedViewProof(s.token)
57新增: post := func(route string, body map[string]any) (int, string) {
58新增: t.Helper()
59新增: data, err := json.Marshal(body)
60新增: if err != nil {
61新增: t.Fatal(err)
62新增: }
63新增: r, err := http.NewRequest("POST", server.URL+"/api/"+route, bytes.NewReader(data))
64新增: if err != nil {
65新增: t.Fatal(err)
66新增: }
67新增: r.Header.Set("Content-Type", "application/json")
68新增: r.Header.Set("Origin", server.URL)
69新增: r.Header.Set("Cookie", cookie)
70新增: resp, err := http.DefaultClient.Do(r)
71新增: if err != nil {
72新增: t.Fatal(err)
73新增: }
74新增: defer resp.Body.Close()
75新增: out, err := io.ReadAll(io.LimitReader(resp.Body, 5<<20))
76新增: if err != nil {
77新增: t.Fatal(err)
78新增: }
79新增: return resp.StatusCode, string(out)
80新增: }
81新增: defer s.closeProjectShares()
82新增: project := os.Getenv("CAGE_TEST_MACOS_WORKBENCH_PROJECT")
83新增: var fixture string
84新增: if project != "" {
85新增: fixture, err = os.MkdirTemp(project, ".cage-live-workbench-")
86新增: if err != nil {
87新增: t.Fatal(err)
88新增: }
89新增: defer os.RemoveAll(fixture)
90新增: if err = os.Mkdir(filepath.Join(fixture, ".git"), 0700); err != nil {
91新增: t.Fatal(err)
92新增: }
93新增: if err = os.WriteFile(filepath.Join(fixture, "from-host"), []byte("host-data"), 0600); err != nil {
94新增: t.Fatal(err)
95新增: }
96新增: deadline := time.Now().Add(4 * time.Minute)
97新增: for {
98新增: code, message := post("projects/open", map[string]any{"workspace": project, "add": true})
99新增: if code == 200 && !strings.Contains(message, `"approval":`) {
100新增: break
101新增: }
102新增: if code == 200 && strings.Contains(message, `"approval":`) && time.Now().Before(deadline) {
103新增: time.Sleep(2 * time.Second)
104新增: continue
105新增: }
106新增: if strings.TrimSpace(message) != errMacOSProjectApproval.Error() || time.Now().After(deadline) {
107新增: if strings.Contains(message, `"approval":`) {
108新增: t.Fatal("waiting for guest project approval timed out")
109新增: }
110新增: t.Fatalf("mount: %d %s", code, message)
111新增: }
112新增: time.Sleep(2 * time.Second)
113新增: }
114新增: }
115新增: code, reply := post("terminals", map[string]any{"kind": "shell", "workspace": project})
116新增: if code != 200 {
117新增: t.Fatalf("terminal: %d %s", code, reply)
118新增: }
119新增: var tab struct{ ID string }
120新增: if err := json.Unmarshal([]byte(reply), &tab); err != nil || tab.ID == "" {
121新增: t.Fatalf("invalid terminal response: %v", err)
122新增: }
123新增: h := http.Header{"Origin": {s.origin}, "Cookie": {cookie}}
124新增: ws, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(server.URL, "http")+"/api/terminals/"+tab.ID+"/stream", h)
125新增: if err != nil {
126新增: t.Fatal(err)
127新增: }
128新增: defer ws.Close()
129新增: if err := ws.WriteJSON(map[string]any{"type": "resize", "cols": 92, "rows": 31}); err != nil {
130新增: t.Fatal(err)
131新增: }
132新增: // The literal expected string is absent from the submitted command; an
133新增: // echoed keystroke cannot satisfy the guest identity or compilation check.
134新增: cmd := `d=$(mktemp -d) && printf '%s\n' 'return 6 * 7' > "$d/source.applescript" && /usr/bin/osacompile -o "$d/test.scpt" "$d/source.applescript" && printf 'CAGE_TRIAL_%s_%s_%s_END\n' "$(uname -s)" "$(sw_vers -productVersion)" "$(osascript "$d/test.scpt")"; rm -f "$d/source.applescript" "$d/test.scpt"; rmdir "$d"`
135新增: expected := "_42_END"
136新增: if project != "" {
137新增: base := filepath.Base(fixture)
138新增: cmd = fmt.Sprintf(`d=%s; test "$(cat "$d/from-host")" = host-data && ! touch "$d/.git/forbidden" && printf guest-data > "$d/from-guest.tmp" && mv "$d/from-guest.tmp" "$d/from-guest" && printf 'CAGE_PROJECT_%%s_%%s_%%s_END\n' "$(uname -s)" "$(./run.sh)" "$(stty size)"`, base)
139新增: expected = "CAGE_PROJECT_Darwin_132_31 92_END"
140新增: }
141新增: if err := ws.WriteJSON(map[string]string{"type": "input", "data": cmd + "\r"}); err != nil {
142新增: t.Fatal(err)
143新增: }
144新增: _ = ws.SetReadDeadline(time.Now().Add(35 * time.Second))
145新增: var output strings.Builder
146新增: for !strings.Contains(output.String(), expected) {
147新增: _, chunk, err := ws.ReadMessage()
148新增: if err != nil {
149新增: t.Fatal(err)
150新增: }
151新增: output.Write(chunk)
152新增: }
153新增: if project != "" {
154新增: data, err := os.ReadFile(filepath.Join(fixture, "from-guest"))
155新增: if err != nil || string(data) != "guest-data" {
156新增: t.Fatal("lost atomic guest save")
157新增: }
158新增: if _, err = os.Stat(filepath.Join(fixture, ".git", "forbidden")); !os.IsNotExist(err) {
159新增: t.Fatal("guest modified protected Git metadata")
160新增: }
161新增: if os.Getenv("CAGE_TEST_MACOS_WORKBENCH_BOUNDARY") == "1" {
162新增: ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
163新增: defer cancel()
164新增: probe, err := os.CreateTemp(project, ".cage-share-probe-*")
165新增: if err != nil {
166新增: t.Fatal(err)
167新增: }
168新增: defer os.Remove(probe.Name())
169新增: challenge := randomToken()
170新增: _, err = probe.WriteString(challenge)
171新增: probe.Close()
172新增: if err != nil {
173新增: t.Fatal(err)
174新增: }
175新增: private, err := os.CreateTemp(s.profile, ".cage-private-probe-*")
176新增: if err != nil {
177新增: t.Fatal(err)
178新增: }
179新增: private.Close()
180新增: defer os.Remove(private.Name())
181新增: client, err := s.gateClient()
182新增: if err != nil {
183新增: t.Fatal(err)
184新增: }
185新增: before, err := client.Status(ctx)
186新增: if err != nil || before.Mode != "closed" {
187新增: t.Fatal("require an offline test guest")
188新增: }
189新增: boundary, err := s.guestObservation(ctx, boundaryProbeInput(17777, randomToken()[:16], private.Name(), probe.Name(), challenge))
190新增: if err != nil {
191新增: t.Fatal(err)
192新增: }
193新增: after, err := client.Status(ctx)
194新增: if err != nil || after.Mode != "closed" {
195新增: t.Fatal("test network unexpectedly opened")
196新增: }
197新增: files, network := s.inspectVMLayout()
198新增: t.Logf("policy files=%t network=%t; shared=%t private=%s process TZ=%s locale=%s system TZ=%s locale=%s; IPv6 default routes=%d connected=%t; UDP attempted=%t; denied tcp/udp/dns counters %d/%d/%d -> %d/%d/%d", files, network, boundary.SharedFile, boundary.PrivateFile, boundary.TZ, boundary.ProcessLocale, boundary.SystemTimezone, boundary.SystemLocale, boundary.IPv6DefaultRoutes, boundary.IPv6Connected, boundary.UDPAttempted, before.Counters.TCPDenied, before.Counters.UDPDenied, before.Counters.DNSDenied, after.Counters.TCPDenied, after.Counters.UDPDenied, after.Counters.DNSDenied)
199新增: if !files || !network || !boundary.SharedFile || boundary.PrivateFile != "unreachable" || boundary.PublicConnected || boundary.ManagementConnected || boundary.PublicDNSAnswered || !boundary.UDPAttempted || after.Counters.UDPDenied <= before.Counters.UDPDenied || after.Counters.DNSDenied <= before.Counters.DNSDenied {
200新增: t.Fatal("guest boundary evidence incomplete")
201新增: }
202新增: }
203新增:
204新增: if os.Getenv("CAGE_TEST_MACOS_WORKBENCH_EDITOR") == "1" {
205新增: defer s.closeWindowsBrowser()
206新增: doc, err := os.CreateTemp(project, "qa-*.txt")
207新增: if err != nil {
208新增: t.Fatal(err)
209新增: }
210新增: doc.Close()
211新增: defer os.Remove(doc.Name())
212新增: base := filepath.Base(doc.Name())
213新增: code, raw := post("macos-browser/action", map[string]any{"action": "editor", "workspace": project})
214新增: var opened struct {
215新增: OK bool
216新增: Error string
217新增: }
218新增: if code != 200 || json.Unmarshal([]byte(raw), &opened) != nil || !opened.OK {
219新增: t.Fatalf("guest editor could not open the authorized folder: status=%d error=%q", code, opened.Error)
220新增: }
221新增: code, raw = post("macos-browser/action", map[string]any{"action": "frame"})
222新增: var frame struct {
223新增: URL, Image string
224新增: Width, Height int
225新增: }
226新增: if err := json.Unmarshal([]byte(raw), &frame); code != 200 || err != nil {
227新增: t.Fatalf("editor frame: status=%d err=%v", code, err)
228新增: }
229新增: guestURL, err := url.Parse(frame.URL)
230新增: img, imgErr := base64.StdEncoding.DecodeString(frame.Image)
231新增: if err != nil || guestURL.Hostname() != filepath.Base(macOSProjectPath(binding.User, project))+".cage-editor.localhost" || guestURL.Query().Get("folder") != macOSProjectPath(binding.User, project) || imgErr != nil || len(img) < 1024 || frame.Width < 1 || frame.Height < 1 {
232新增: t.Fatal("browser did not show the expected guest-local project")
233新增: }
234新增:
235新增: action := func(body map[string]any) map[string]any {
236新增: t.Helper()
237新增: status, raw := post("macos-browser/action", body)
238新增: var result map[string]any
239新增: if status != 200 || json.Unmarshal([]byte(raw), &result) != nil || result["error"] != nil {
240新增: t.Fatalf("browser %s: %d %v", body["action"], status, result["error"])
241新增: }
242新增: return result
243新增: }
244新增: snapshot := func(name string) map[string]any {
245新增: result := action(map[string]any{"action": "frame"})
246新增: if dir := os.Getenv("CAGE_TEST_MACOS_EDITOR_FRAMES"); dir != "" {
247新增: jpg, _ := result["image"].(string)
248新增: data, err := base64.StdEncoding.DecodeString(jpg)
249新增: if err != nil {
250新增: t.Fatal(err)
251新增: }
252新增: if err = os.WriteFile(filepath.Join(dir, name+".jpg"), data, 0600); err != nil {
253新增: t.Fatal(err)
254新增: }
255新增: }
256新增: return result
257新增: }
258新增: deadline := time.Now().Add(18 * time.Second)
259新增: for {
260新增: state := snapshot("ready")
261新增: title, _ := state["title"].(string)
262新增: if strings.Contains(title, "code-server") {
263新增: break
264新增: }
265新增: if time.Now().After(deadline) {
266新增: t.Fatal("workspace window did not initialize")
267新增: }
268新增: time.Sleep(450 * time.Millisecond)
269新增: }
270新增: scratch := t.TempDir()
271新增: source := filepath.Join(scratch, "find.swift")
272新增: finder := filepath.Join(scratch, "find")
273新增: if err := os.WriteFile(source, macOSEditorFileLocator, 0600); err != nil {
274新增: t.Fatal(err)
275新增: }
276新增: if out, err := exec.Command("/usr/bin/xcrun", "swiftc", source, "-o", finder).CombinedOutput(); err != nil {
277新增: t.Fatalf("Vision file locator: %v %s", err, out)
278新增: }
279新增: jpeg := filepath.Join(scratch, "editor.jpg")
280新增: deadline = time.Now().Add(22 * time.Second)
281新增: for {
282新增: state := snapshot("explorer")
283新增: data, err := base64.StdEncoding.DecodeString(state["image"].(string))
284新增: if err != nil {
285新增: t.Fatal(err)
286新增: }
287新增: if err := os.WriteFile(jpeg, data, 0600); err != nil {
288新增: t.Fatal(err)
289新增: }
290新增: result, err := exec.Command(finder, jpeg, base).Output()
291新增: var x, y int
292新增: if _, scan := fmt.Sscanf(string(result), "%d %d", &x, &y); err == nil && scan == nil {
293新增: action(map[string]any{"action": "click", "double": true, "x": x, "y": y})
294新增: break
295新增: }
296新增: if time.Now().After(deadline) {
297新增: t.Fatal("temporary file not visible in the guest editor Explorer")
298新增: }
299新增: time.Sleep(400 * time.Millisecond)
300新增: }
301新增:
302新增: deadline = time.Now().Add(15 * time.Second)
303新增: for {
304新增: frame := snapshot("file-editor")
305新增: title, _ := frame["title"].(string)
306新增: if strings.Contains(title, base) {
307新增: break
308新增: }
309新增: if time.Now().After(deadline) {
310新增: t.Fatalf("unique test file did not acquire editor focus (title=%q)", title)
311新增: }
312新增: time.Sleep(450 * time.Millisecond)
313新增: }
314新增: marker := "guest-editor-write-" + randomToken()[:12]
315新增: action(map[string]any{"action": "text", "text": marker})
316新增: action(map[string]any{"action": "key", "meta": true, "key": "s"})
317新增: deadline = time.Now().Add(10 * time.Second)
318新增: for {
319新增: content, err := os.ReadFile(doc.Name())
320新增: if err == nil && strings.TrimSpace(string(content)) == marker {
321新增: break
322新增: }
323新增: if time.Now().After(deadline) {
324新增: t.Fatal("browser editor save was not observed on host")
325新增: }
326新增: time.Sleep(150 * time.Millisecond)
327新增: }
328新增: t.Log("Selected a unique project file in the guest editor, confirmed its title and read its saved contents back on the host")
329新增:
330新增: t.Logf("guest-local code-server opened the selected project; JPEG %dx%d, %d bytes", frame.Width, frame.Height, len(img))
331新增: }
332新增: t.Log(expected)
333新增: return
334新增: }
335新增: got := output.String()
336新增: from := strings.Index(got, "CAGE_TRIAL_Darwin_")
337新增: if from < 0 {
338新增: t.Fatal("guest did not report Darwin")
339新增: }
340新增: to := strings.Index(got[from:], "_42_END")
341新增: if to < 0 {
342新增: t.Fatal("guest program output did not match")
343新增: }
344新增: t.Log(got[from : from+to+len("_42_END")])
345新增:}
346新增:
347新增:func TestMacOSGuestIPv6LinkDrop(t *testing.T) {
348新增: profile := os.Getenv("CAGE_TEST_MACOS_LINK_PROFILE")
349新增: if profile == "" {
350新增: t.Skip("select a bound, closed macOS test instance")
351新增: }
352新增: binding, err := guestos.LoadMacOSProfile(profile)
353新增: if err != nil || binding == nil {
354新增: t.Fatal("invalid macOS test profile")
355新增: }
356新增: s := &Server{profile: profile, macosGuest: binding}
357新增: client, err := s.gateClient()
358新增: if err != nil {
359新增: t.Fatal(err)
360新增: }
361新增: ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second)
362新增: defer cancel()
363新增: original, err := client.Status(ctx)
364新增: if err != nil || original.Mode != "closed" {
365新增: t.Fatal("test requires a closed gate")
366新增: }
367新增: state, err := client.BeginCheck(ctx)
368新增: if err != nil {
369新增: t.Fatal(err)
370新增: }
371新增: defer func() {
372新增: closeCtx, stop := context.WithTimeout(context.Background(), 3*time.Second)
373新增: defer stop()
374新增: closed, err := client.Close(closeCtx, "链路验证结束,外网关闭")
375新增: if err != nil || closed.Mode != "closed" {
376新增: t.Error("gate closure could not be verified")
377新增: }
378新增: }()
379新增: // Both IDs come from the selected instance's gate controller. No general
380新增: // diagnostic request can publish observed-frame evidence.
381新增: command := `iface=$(/sbin/route -n get -inet 198.18.0.254 | /usr/bin/awk '/interface:/{print $2}'); [[ "$iface" =~ ^en[0-9]+$ ]] || exit 1; /usr/local/libexec/cage-macos-ipv6-check link "$iface" ` + shellescape.Quote(state.RunID) + " " + shellescape.Quote(state.CheckID)
382新增: out, err := s.guest(ctx, command)
383新增: if err != nil || strings.TrimSpace(string(out)) != "sent" {
384新增: t.Fatalf("guest failed to submit the one-hop datagram: %v", err)
385新增: }
386新增: for i := 0; i < 15; i++ {
387新增: after, err := client.Status(ctx)
388新增: if err != nil {
389新增: t.Fatal(err)
390新增: }
391新增: if after.Mode != state.Mode || after.RunID != state.RunID || after.CheckID != state.CheckID {
392新增: t.Fatal("checking epoch changed during observation")
393新增: }
394新增: if after.IPv6LinkProbeCheck == state.CheckID {
395新增: t.Log("guest sent the live nonce on its VZ link; host IPv4-only stack confirmed the matching ingress drop")
396新增: return
397新增: }
398新增: time.Sleep(120 * time.Millisecond)
399新增: }
400新增: t.Fatal("no matching IPv6 ingress evidence on the current host agent")
401新增:}
新增internal/workbench/macos_workspace_test.go+397 −0看文件
@@ -0,0 +1,397 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "bufio"
5新增: "crypto/ed25519"
6新增: "crypto/rand"
7新增: "encoding/json"
8新增: "encoding/pem"
9新增: "fmt"
10新增: "io"
11新增: "net"
12新增: "net/http"
13新增: "os"
14新增: "path"
15新增: "path/filepath"
16新增: "strings"
17新增: "sync"
18新增: "sync/atomic"
19新增: "testing"
20新增:
21新增: "github.com/google/uuid"
22新增: "github.com/kballard/go-shellquote"
23新增: "github.com/pkg/sftp"
24新增: "github.com/sylvinus/agent-vm/internal/guestos"
25新增: "golang.org/x/crypto/ssh"
26新增:)
27新增:
28新增:// This guest substitute uses the real bound OpenSSH transport and the confined
29新增:// host SFTP server. FSKit approval and native application execution are simulated.
30新增:type macWorkspaceGuest struct {
31新增: s *Server
32新增: hostPath string
33新增: guestPath string
34新增: approved atomic.Bool
35新增: resourceTicks atomic.Uint32
36新增: resourceFailure atomic.Bool
37新增: mu sync.Mutex
38新增: files *sftp.Client
39新增: command func(ssh.Channel, string) (uint32, bool)
40新增:}
41新增:
42新增:func newMacWorkspaceGuest(t *testing.T, commands ...func(ssh.Channel, string) (uint32, bool)) *macWorkspaceGuest {
43新增: t.Helper()
44新增: if _, err := os.Stat(sshExecutable()); err != nil {
45新增: t.Skip("OpenSSH is unavailable")
46新增: }
47新增: s := testServer(t)
48新增: s.macosGuest = &guestos.MacOSProfile{Instance: "mac", User: "cage"}
49新增: hostPath, err := filepath.EvalSymlinks(t.TempDir())
50新增: if err != nil {
51新增: t.Fatal(err)
52新增: }
53新增: if err = writePrivate(filepath.Join(s.profile, "environment.json"), map[string]string{"directory": hostPath}); err != nil {
54新增: t.Fatal(err)
55新增: }
56新增: s.preferences.Workspace, s.ready = hostPath, true
57新增: guest := &macWorkspaceGuest{s: s, hostPath: hostPath, guestPath: macOSProjectPath("cage", hostPath)}
58新增: if len(commands) > 0 {
59新增: guest.command = commands[0]
60新增: }
61新增: listener, err := net.Listen("tcp", "127.0.0.1:0")
62新增: if err != nil {
63新增: t.Fatal(err)
64新增: }
65新增: _, key, err := ed25519.GenerateKey(rand.Reader)
66新增: if err != nil {
67新增: t.Fatal(err)
68新增: }
69新增: signer, err := ssh.NewSignerFromKey(key)
70新增: if err != nil {
71新增: t.Fatal(err)
72新增: }
73新增: config := &ssh.ServerConfig{NoClientAuth: true}
74新增: config.AddHostKey(signer)
75新增: if err = os.MkdirAll(s.instanceDir(), 0700); err != nil {
76新增: t.Fatal(err)
77新增: }
78新增: identity, err := ssh.MarshalPrivateKey(key, "workspace-fixture")
79新增: if err != nil {
80新增: t.Fatal(err)
81新增: }
82新增: if err = os.MkdirAll(filepath.Join(s.profile, "state", "lima", "_config"), 0700); err != nil {
83新增: t.Fatal(err)
84新增: }
85新增: if err = os.WriteFile(filepath.Join(s.profile, "state", "lima", "_config", "user"), pem.EncodeToMemory(identity), 0600); err != nil {
86新增: t.Fatal(err)
87新增: }
88新增: for name, value := range map[string]string{
89新增: "state/lima/mac/ssh.config": fmt.Sprintf("Port %d\nUser cage\n", listener.Addr().(*net.TCPAddr).Port),
90新增: "macos-known-hosts": "cage-macos " + string(ssh.MarshalAuthorizedKey(signer.PublicKey())),
91新增: } {
92新增: if err = os.WriteFile(filepath.Join(s.profile, name), []byte(value), 0600); err != nil {
93新增: t.Fatal(err)
94新增: }
95新增: }
96新增: if err = writePrivate(filepath.Join(s.instanceDir(), "cage-running.json"), map[string]int{"pid": os.Getpid()}); err != nil {
97新增: t.Fatal(err)
98新增: }
99新增: var active sync.WaitGroup
100新增: acceptDone := make(chan struct{})
101新增: go func() {
102新增: defer close(acceptDone)
103新增: for {
104新增: conn, err := listener.Accept()
105新增: if err != nil {
106新增: return
107新增: }
108新增: active.Add(1)
109新增: go func() {
110新增: defer active.Done()
111新增: server, channels, requests, err := ssh.NewServerConn(conn, config)
112新增: if err != nil {
113新增: conn.Close()
114新增: return
115新增: }
116新增: defer server.Close()
117新增: go ssh.DiscardRequests(requests)
118新增: for incoming := range channels {
119新增: channel, requests, err := incoming.Accept()
120新增: if err != nil {
121新增: return
122新增: }
123新增: for request := range requests {
124新增: if request.Type != "exec" {
125新增: request.Reply(true, nil)
126新增: continue
127新增: }
128新增: var command struct{ Command string }
129新增: if ssh.Unmarshal(request.Payload, &command) != nil {
130新增: request.Reply(false, nil)
131新增: break
132新增: }
133新增: request.Reply(true, nil)
134新增: go ssh.DiscardRequests(requests)
135新增: status := guest.execute(channel, command.Command)
136新增: channel.SendRequest("exit-status", false, ssh.Marshal(struct{ Status uint32 }{status}))
137新增: break
138新增: }
139新增: channel.Close()
140新增: }
141新增: }()
142新增: }
143新增: }()
144新增: t.Cleanup(func() {
145新增: s.beginClose()
146新增: s.terminals.close()
147新增: s.closeWindowsBrowser()
148新增: s.closeProjectShares()
149新增: listener.Close()
150新增: <-acceptDone
151新增: active.Wait()
152新增: })
153新增: return guest
154新增:}
155新增:
156新增:func (g *macWorkspaceGuest) execute(channel ssh.Channel, command string) uint32 {
157新增: if g.command != nil {
158新增: if status, handled := g.command(channel, command); handled {
159新增: return status
160新增: }
161新增: }
162新增: args, err := shellquote.Split(command)
163新增: if err != nil {
164新增: return 1
165新增: }
166新增: if strings.HasPrefix(command, "exec /bin/bash --noprofile --norc -c ") {
167新增: command = args[len(args)-1]
168新增: args, err = shellquote.Split(command)
169新增: if err != nil {
170新增: return 1
171新增: }
172新增: }
173新增: switch {
174新增: case strings.HasPrefix(command, "exec /usr/local/libexec/cage-cli/bin/python3 -I -c "):
175新增: if g.resourceFailure.Load() {
176新增: fmt.Fprintln(channel, `{}`)
177新增: return 0
178新增: }
179新增: ticks := g.resourceTicks.Add(10)
180新增: json.NewEncoder(channel).Encode(macOSResourceSample{Version: 1, Total: 4 << 30, Available: 2 << 30,
181新增: Free: 1 << 30, Inactive: 1 << 30, CPUs: 2, Boot: 10, CPUTicks: [4]uint32{ticks, 10, 80 + ticks, 0}})
182新增: return 0
183新增: case strings.HasPrefix(command, "set -e;"):
184新增: return 0
185新增: case strings.HasPrefix(command, "exec /usr/local/libexec/cage-sshfs "):
186新增: files, err := sftp.NewClientPipe(channel, channel)
187新增: if err != nil {
188新增: return 1
189新增: }
190新增: g.mu.Lock()
191新增: g.files = files
192新增: g.mu.Unlock()
193新增: _ = files.Wait()
194新增: return 0
195新增: case len(args) == 5 && args[0] == macProjectAgent && args[1] == "probe":
196新增: if !g.approved.Load() {
197新增: return 75
198新增: }
199新增: g.mu.Lock()
200新增: files := g.files
201新增: g.mu.Unlock()
202新增: if files == nil || args[2] != g.guestPath {
203新增: return 1
204新增: }
205新增: file, err := files.Open(filepath.Join(g.hostPath, args[3]))
206新增: if err != nil {
207新增: return 1
208新增: }
209新增: body, err := io.ReadAll(file)
210新增: file.Close()
211新增: if err != nil || string(body) != args[4] {
212新增: return 1
213新增: }
214新增: fmt.Fprint(channel, "OK")
215新增: return 0
216新增: case strings.HasPrefix(command, "/sbin/mount |"):
217新增: fmt.Fprintf(channel, "macfuse://3c7e13b5-dc9f-4d09-b7c3-707987db4e34 on %s (fskit, nodev, nosuid, mounted by cage)\n", g.guestPath)
218新增: return 0
219新增: case strings.HasPrefix(command, "if test "):
220新增: return 0
221新增: case strings.HasPrefix(command, "exec /usr/local/libexec/cage-macos-terminal "):
222新增: if len(args) != 3 || args[2] != g.guestPath || !g.approved.Load() {
223新增: return 1
224新增: }
225新增: fmt.Fprintln(channel, "shared-workspace-ready")
226新增: var input strings.Builder
227新增: buffer := make([]byte, 1024)
228新增: for {
229新增: n, err := channel.Read(buffer)
230新增: if err != nil {
231新增: return 0
232新增: }
233新增: input.Write(buffer[:n])
234新增: if strings.Contains(input.String(), "fixture-boundary:guest") {
235新增: g.mu.Lock()
236新增: files := g.files
237新增: g.mu.Unlock()
238新增: file, err := files.OpenFile(filepath.Join(g.hostPath, ".cage-share-probe-boundary"), os.O_WRONLY|os.O_TRUNC)
239新增: if err != nil {
240新增: return 1
241新增: }
242新增: _, err = file.Write([]byte("fixture-boundary:guest"))
243新增: file.Close()
244新增: if err != nil {
245新增: return 1
246新增: }
247新增: return 0
248新增: }
249新增: }
250新增: case strings.Contains(command, "macos-native-browser.mjs"):
251新增: scanner := bufio.NewScanner(channel)
252新增: for scanner.Scan() {
253新增: var request struct {
254新增: Path string
255新增: Input map[string]any
256新增: }
257新增: if json.Unmarshal(scanner.Bytes(), &request) != nil {
258新增: return 1
259新增: }
260新增: json.NewEncoder(channel).Encode(map[string]any{"ok": true, "workspace": request.Input["workspace"]})
261新增: }
262新增: return 0
263新增: default:
264新增: fmt.Fprintln(channel.Stderr(), "unexpected fixture command")
265新增: return 1
266新增: }
267新增:}
268新增:
269新增:func TestMacOSDefaultWorkspaceUsesApprovedSharedProject(t *testing.T) {
270新增: guest := newMacWorkspaceGuest(t)
271新增: s := guest.s
272新增: marker := filepath.Join(guest.hostPath, "keep.txt")
273新增: if err := os.WriteFile(marker, []byte("original-host-data"), 0600); err != nil {
274新增: t.Fatal(err)
275新增: }
276新增: body, _ := json.Marshal(map[string]any{"workspace": guest.hostPath, "activate": true})
277新增: response := windowsBrowserRequestForTest(s, http.MethodPost, "/api/projects/open", body)
278新增: var pending struct{ Workspace, Approval string }
279新增: if response.Code != 200 || json.Unmarshal(response.Body.Bytes(), &pending) != nil || pending.Approval == "" || pending.Workspace != guest.hostPath {
280新增: t.Fatalf("default workspace bypassed project approval: %d %s", response.Code, response.Body.String())
281新增: }
282新增: if s.projectShares[guest.hostPath].detach != nil {
283新增: t.Fatal("unapproved share was accepted")
284新增: }
285新增: guest.approved.Store(true)
286新增: response = windowsBrowserRequestForTest(s, http.MethodPost, "/api/projects/open", body)
287新增: if response.Code != 200 || strings.Contains(response.Body.String(), "approval") || s.projectShares[guest.hostPath].detach == nil {
288新增: t.Fatalf("approved default workspace failed: %d %s", response.Code, response.Body.String())
289新增: }
290新增: if got := s.cliWorkspace(guest.hostPath); got != guest.guestPath {
291新增: t.Fatalf("Claude cwd=%q", got)
292新增: }
293新增: for _, route := range []string{"/api/browser/editor", "/api/macos-browser/action"} {
294新增: fields := map[string]string{"workspace": guest.hostPath}
295新增: if route == "/api/macos-browser/action" {
296新增: fields["action"] = "editor"
297新增: }
298新增: input, _ := json.Marshal(fields)
299新增: response = windowsBrowserRequestForTest(s, http.MethodPost, route, input)
300新增: if response.Code != 200 {
301新增: t.Fatalf("default editor %s: %d %s", route, response.Code, response.Body.String())
302新增: }
303新增: if route == "/api/browser/editor" && !strings.Contains(response.Body.String(), path.Base(guest.guestPath)) {
304新增: t.Fatal("editor lost shared project identity")
305新增: }
306新增: }
307新增: terminal, err := s.createTerminal(terminalRequest{Workspace: guest.hostPath, Kind: "shell"})
308新增: if err != nil {
309新增: t.Fatal(err)
310新增: }
311新增: sub := terminal.subscribe()
312新增: defer sub.Close()
313新增: readTerminalUntil(t, sub, "shared-workspace-ready")
314新增: probe := filepath.Join(guest.hostPath, ".cage-share-probe-boundary")
315新增: if err = os.WriteFile(probe, []byte("fixture-boundary"), 0600); err != nil {
316新增: t.Fatal(err)
317新增: }
318新增: if !s.checkMacOSSharedFile(t.Context(), probe, "fixture-boundary") {
319新增: t.Fatal("default workspace failed shared-file round trip")
320新增: }
321新增: got, err := os.ReadFile(marker)
322新增: if err != nil || string(got) != "original-host-data" {
323新增: t.Fatal("existing host data changed")
324新增: }
325新增:}
326新增:
327新增:func TestMacOSDefaultWorkspaceRestoresWithVisibleFailureAndRetry(t *testing.T) {
328新增: guest := newMacWorkspaceGuest(t)
329新增: s := guest.s
330新增: s.restoreProjectShares()
331新增: if len(s.projectErrors) != 1 || s.projectErrors[0].Path != guest.hostPath || s.projectShares[guest.hostPath] == nil {
332新增: t.Fatal("default workspace restoration omitted its pending authorization")
333新增: }
334新增: guest.approved.Store(true)
335新增: if _, err := s.connectProject(guest.hostPath, false); err != nil {
336新增: t.Fatal(err)
337新增: }
338新增: if len(s.projectErrors) != 0 {
339新增: t.Fatal("successful retry retained the old project error")
340新增: }
341新增:}
342新增:
343新增:func TestMacOSDefaultWorkspaceNewAndLegacyConversations(t *testing.T) {
344新增: s := testServer(t)
345新增: s.macosGuest = &guestos.MacOSProfile{Instance: "mac", User: "cage"}
346新增: host, _ := filepath.EvalSymlinks(t.TempDir())
347新增: if err := writePrivate(filepath.Join(s.profile, "environment.json"), map[string]string{"directory": host}); err != nil {
348新增: t.Fatal(err)
349新增: }
350新增: s.preferences.Workspace = host
351新增: script, fresh, err := s.prepareTerminalConversation(host, claudeSelection{}, "")
352新增: if err != nil {
353新增: t.Fatal(err)
354新增: }
355新增: if fresh.GuestWorkspace != macOSProjectPath("cage", host) || !strings.Contains(script, "cage-macos-terminal --claude") || fresh.ConnectionNotice != "" {
356新增: t.Fatal("new default conversation did not use shared project")
357新增: }
358新增: legacyRoot := "/Users/cage/.local/share/cage/workspace"
359新增: for _, directory := range []string{legacyRoot, legacyRoot + "/nested"} {
360新增: id := uuid.NewString()
361新增: if _, err = s.mobileCLI.create(s.profile, host, id); err != nil {
362新增: t.Fatal(err)
363新增: }
364新增: record, err := s.mobileCLI.record(s.profile, id)
365新增: if err != nil {
366新增: t.Fatal(err)
367新增: }
368新增: record.Terminal, record.Resume, record.GuestWorkspace = true, true, directory
369新增: if err = writePrivate(mobileRecordPath(s.profile, id), record); err != nil {
370新增: t.Fatal(err)
371新增: }
372新增: script, resumed, err := s.prepareTerminalConversation(host, claudeSelection{}, id)
373新增: if err != nil {
374新增: t.Fatal(err)
375新增: }
376新增: if resumed.GuestWorkspace != directory || resumed.ConnectionNotice != macOSLegacyWorkspaceNotice || strings.Contains(script, "cage-macos-terminal") || !strings.Contains(script, "cd -- "+legacyRoot) {
377新增: t.Fatal("legacy conversation lost original directory or notice")
378新增: }
379新增: s.terminals.sessions = map[string]*terminalSession{"legacy": {id: "legacy", sharedID: id, workspace: host}}
380新增: if s.terminalSummaries()[0]["workspace_notice"] != macOSLegacyWorkspaceNotice {
381新增: t.Fatal("desktop terminal omitted the legacy workspace notice")
382新增: }
383新增: if _, _, err = s.prepareTerminalConversation(host+"/other", claudeSelection{}, id); err == nil {
384新增: t.Fatal("another project reused a legacy workspace binding")
385新增: }
386新增: }
387新增: for _, record := range []*mobileRecord{
388新增: {Terminal: true, GuestWorkspace: legacyRoot + "/../escape", mobileSession: mobileSession{mobileSummary: mobileSummary{Workspace: host}}},
389新增: {Terminal: true, GuestWorkspace: legacyRoot + "-other", mobileSession: mobileSession{mobileSummary: mobileSummary{Workspace: host}}},
390新增: {Terminal: true, GuestWorkspace: legacyRoot, mobileSession: mobileSession{mobileSummary: mobileSummary{Workspace: host + "/other"}}},
391新增: {GuestWorkspace: legacyRoot, mobileSession: mobileSession{mobileSummary: mobileSummary{Workspace: host}}},
392新增: } {
393新增: if s.macOSLegacyWorkspace(record) != "" {
394新增: t.Fatal("legacy compatibility accepted an unrelated or unbound directory")
395新增: }
396新增: }
397新增:}
修改internal/workbench/maintenance.go+31 −7看文件

改动太大,不在线显示。

修改internal/workbench/maintenance_test.go+6 −3看文件

改动太大,不在线显示。

新增internal/workbench/mobile_browser.go+537 −0看文件

改动太大,不在线显示。

新增internal/workbench/mobile_browser_test.go+265 −0看文件

改动太大,不在线显示。

新增internal/workbench/mobile_cli.go+369 −0看文件

改动太大,不在线显示。

新增internal/workbench/mobile_cli_adopt.go+107 −0看文件

改动太大,不在线显示。

新增internal/workbench/mobile_cli_adopt_test.go+18 −0看文件

改动太大,不在线显示。

新增internal/workbench/mobile_cli_android_e2e_test.go+183 −0看文件

改动太大,不在线显示。

新增internal/workbench/mobile_cli_e2e_test.go+436 −0看文件

改动太大,不在线显示。

新增internal/workbench/mobile_cli_http.go+466 −0看文件

改动太大,不在线显示。

新增internal/workbench/mobile_cli_identity.go+22 −0看文件

改动太大,不在线显示。

新增internal/workbench/mobile_cli_identity.py+438 −0看文件

改动太大,不在线显示。

新增internal/workbench/mobile_cli_identity_test.go+422 −0看文件

改动太大,不在线显示。

新增internal/workbench/mobile_cli_media.go+169 −0看文件

改动太大,不在线显示。

新增internal/workbench/mobile_cli_media_test.go+78 −0看文件

改动太大,不在线显示。

新增internal/workbench/mobile_cli_store.go+345 −0看文件

改动太大,不在线显示。

新增internal/workbench/mobile_cli_supervisor.py+150 −0看文件

改动太大,不在线显示。

新增internal/workbench/mobile_cli_test.go+203 −0看文件

改动太大,不在线显示。

新增internal/workbench/mobile_pair.go+350 −0看文件

改动太大,不在线显示。

新增internal/workbench/mobile_pair_test.go+214 −0看文件

改动太大,不在线显示。

新增internal/workbench/mobile_transcript_browser_test.go+114 −0看文件

改动太大,不在线显示。

新增internal/workbench/monitor_timing.go+55 −0看文件

改动太大,不在线显示。

新增internal/workbench/monitor_timing_test.go+152 −0看文件

改动太大,不在线显示。

新增internal/workbench/native_component_probe.py+71 −0看文件

改动太大,不在线显示。

新增internal/workbench/native_desktop_downloads.go+133 −0看文件

改动太大,不在线显示。

新增internal/workbench/native_desktop_downloads_test.go+265 −0看文件

改动太大,不在线显示。

新增internal/workbench/native_display_e2e_test.go+152 −0看文件

改动太大,不在线显示。

新增internal/workbench/native_download_test.go+506 −0看文件

改动太大,不在线显示。

新增internal/workbench/native_maintenance.go+192 −0看文件

改动太大,不在线显示。

新增internal/workbench/native_maintenance_test.go+232 −0看文件

改动太大,不在线显示。

新增internal/workbench/native_routes.go+32 −0看文件

改动太大,不在线显示。

新增internal/workbench/native_tight.go+80 −0看文件

改动太大,不在线显示。

新增internal/workbench/native_tight_test.go+122 −0看文件

改动太大,不在线显示。

修改internal/workbench/network_intent.go+6 −2看文件

改动太大,不在线显示。

修改internal/workbench/network_recovery.go+15 −1看文件

改动太大,不在线显示。

修改internal/workbench/network_recovery_test.go+149 −0看文件

改动太大,不在线显示。

修改internal/workbench/network_status_test.go+63 −6看文件

改动太大,不在线显示。

修改internal/workbench/platform_unix.go+3 −1看文件

改动太大,不在线显示。

修改internal/workbench/platform_windows.go+2 −1看文件

改动太大,不在线显示。

新增internal/workbench/project_authorization_test.go+80 −0看文件

改动太大,不在线显示。

修改internal/workbench/project_directories.go+9 −0看文件

改动太大,不在线显示。

修改internal/workbench/projects.go+96 −26看文件

改动太大,不在线显示。

修改internal/workbench/proxy.go+4 −3看文件

改动太大,不在线显示。

新增internal/workbench/proxy_import_test.go+144 −0看文件

改动太大,不在线显示。

修改internal/workbench/proxy_interface.go+1 −1看文件

改动太大,不在线显示。

修改internal/workbench/proxy_interface_test.go+1 −1看文件

改动太大,不在线显示。

新增internal/workbench/readable_errors_test.go+47 −0看文件

改动太大,不在线显示。

修改internal/workbench/remote_entry.go+6 −1看文件

改动太大,不在线显示。

修改internal/workbench/remote_gateway.go+41 −7看文件

改动太大,不在线显示。

修改internal/workbench/resources.go+80 −4看文件

改动太大,不在线显示。

新增internal/workbench/resources_test.go+67 −0看文件

改动太大,不在线显示。

修改internal/workbench/runtime.go+194 −56看文件

改动太大,不在线显示。

新增internal/workbench/runtime_failure_test.go+66 −0看文件

改动太大,不在线显示。

修改internal/workbench/safety.go+296 −36看文件

改动太大,不在线显示。

修改internal/workbench/server.go+253 −28看文件

改动太大,不在线显示。

修改internal/workbench/server_test.go+37 −1看文件

改动太大,不在线显示。

新增internal/workbench/session_metadata.go+333 −0看文件

改动太大,不在线显示。

新增internal/workbench/session_metadata_test.go+176 −0看文件

改动太大,不在线显示。

新增internal/workbench/session_summary_accounts_test.go+54 −0看文件

改动太大,不在线显示。

修改internal/workbench/settings.go+43 −12看文件

改动太大,不在线显示。

修改internal/workbench/setup_progress.go+67 −5看文件

改动太大,不在线显示。

修改internal/workbench/setup_progress_test.go+49 −0看文件

改动太大,不在线显示。

新增internal/workbench/shared_clipboard.go+588 −0看文件

改动太大,不在线显示。

新增internal/workbench/shared_clipboard_test.go+314 −0看文件

改动太大,不在线显示。

修改internal/workbench/storage.go+13 −1看文件

改动太大,不在线显示。

修改internal/workbench/storage_paths.go+27 −0看文件

改动太大,不在线显示。

新增internal/workbench/tailnet.go+83 −0看文件

改动太大,不在线显示。

新增internal/workbench/tailnet_install.go+53 −0看文件

改动太大,不在线显示。

新增internal/workbench/tailnet_test.go+70 −0看文件

改动太大,不在线显示。

修改internal/workbench/terminal.go+40 −6看文件

改动太大,不在线显示。

新增internal/workbench/terminal_ccs_accounts_test.go+35 −0看文件

改动太大,不在线显示。

修改internal/workbench/terminal_http_test.go+45 −0看文件

改动太大,不在线显示。

修改internal/workbench/terminal_service.go+148 −6看文件

改动太大,不在线显示。

修改internal/workbench/terminal_session.go+40 −6看文件

改动太大,不在线显示。

新增internal/workbench/testdata/macos_editor_file.swift+23 −0看文件

改动太大,不在线显示。

修改internal/workbench/trusted_login.go+13 −4看文件

改动太大,不在线显示。

修改internal/workbench/trusted_login_test.go+107 −3看文件

改动太大,不在线显示。

修改internal/workbench/vault_http.go+1 −0看文件

改动太大,不在线显示。

修改internal/workbench/vault_store.go+3 −2看文件

改动太大,不在线显示。

修改internal/workbench/vnc.go+4 −0看文件

改动太大,不在线显示。

还有 53 个文件没有列出(一次最多显示 300 个)。