| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "bytes" |
| 6 | "context" |
| 7 | "encoding/base64" |
| 8 | "encoding/json" |
| 9 | "fmt" |
| 10 | "io" |
| 11 | "net/http" |
| 12 | "os" |
| 13 | "os/exec" |
| 14 | "path/filepath" |
| 15 | "strings" |
| 16 | "testing" |
| 17 | |
| 18 | "github.com/google/uuid" |
| 19 | "github.com/sylvinus/agent-vm/internal/guestos" |
| 20 | "golang.org/x/crypto/ssh" |
| 21 | ) |
| 22 | |
| 23 | func init() { |
| 24 | if directory := os.Getenv("CAGE_TEST_NATIVE_DESKTOP_DOWNLOAD"); directory != "" { |
| 25 | if len(os.Args) != 4 || os.Args[1] != "--relay-profile" || os.Args[3] != "desktop" { |
| 26 | os.Exit(2) |
| 27 | } |
| 28 | serveDesktopDownloadFixture(os.Stdin, os.Stdout, directory) |
| 29 | os.Exit(0) |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | func serveDesktopDownloadFixture(input io.Reader, output io.Writer, directory string) { |
| 34 | connection := uuid.NewString() |
| 35 | trace, err := os.OpenFile(filepath.Join(directory, "requests.jsonl"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) |
| 36 | if err != nil { |
| 37 | return |
| 38 | } |
| 39 | defer trace.Close() |
| 40 | reader := bufio.NewScanner(input) |
| 41 | for reader.Scan() { |
| 42 | var request struct { |
| 43 | Action, ID, Transfer string |
| 44 | IDs []string |
| 45 | Sequence int |
| 46 | KeepAlive bool |
| 47 | } |
| 48 | if json.Unmarshal(reader.Bytes(), &request) != nil { |
| 49 | return |
| 50 | } |
| 51 | _ = json.NewEncoder(trace).Encode(map[string]any{"connection": connection, "action": request.Action, "sequence": request.Sequence}) |
| 52 | data, err := os.ReadFile(filepath.Join(directory, "record.json")) |
| 53 | var record browserDownloadInfo |
| 54 | if err != nil || json.Unmarshal(data, &record) != nil { |
| 55 | return |
| 56 | } |
| 57 | payload, err := os.ReadFile(filepath.Join(directory, "payload")) |
| 58 | if err != nil { |
| 59 | return |
| 60 | } |
| 61 | transfer := strings.ReplaceAll(record.ID, "-", "") |
| 62 | var reply any |
| 63 | switch request.Action { |
| 64 | case "files-poll": |
| 65 | reply = map[string]any{"available": true, "uploads": []any{}, "opens": []any{}, "downloads": []browserDownloadInfo{record}} |
| 66 | if _, err := os.Stat(filepath.Join(directory, "supports-ack")); err == nil { |
| 67 | var item map[string]any |
| 68 | _ = json.Unmarshal(data, &item) |
| 69 | _, err := os.Stat(filepath.Join(directory, "acknowledged")) |
| 70 | item["acknowledged"] = err == nil |
| 71 | reply = map[string]any{"available": true, "downloadAck": true, "downloads": []any{item}} |
| 72 | } |
| 73 | case "files-download-ack": |
| 74 | if len(request.IDs) != 1 || request.IDs[0] != record.ID { |
| 75 | return |
| 76 | } |
| 77 | if _, err := os.Stat(filepath.Join(directory, "fail-ack")); err == nil { |
| 78 | reply = map[string]string{"error": "desktop_download_manifest_failed"} |
| 79 | } else { |
| 80 | if os.WriteFile(filepath.Join(directory, "acknowledged"), nil, 0600) != nil { |
| 81 | return |
| 82 | } |
| 83 | reply = map[string]bool{"ok": true} |
| 84 | } |
| 85 | case "files-download-open": |
| 86 | if request.ID != record.ID { |
| 87 | return |
| 88 | } |
| 89 | reply = map[string]any{"transfer": transfer, "size": len(payload), "name": record.Name} |
| 90 | case "files-download-read": |
| 91 | if request.Transfer != transfer { |
| 92 | return |
| 93 | } |
| 94 | start := request.Sequence * (64 << 10) |
| 95 | if start < 0 || start > len(payload) { |
| 96 | return |
| 97 | } |
| 98 | end := min(start+(64<<10), len(payload)) |
| 99 | reply = map[string]any{"data": base64.StdEncoding.EncodeToString(payload[start:end]), "sequence": request.Sequence + 1, "eof": end == len(payload)} |
| 100 | if _, err := os.Stat(filepath.Join(directory, "fail-read")); err == nil { |
| 101 | reply = map[string]string{"error": "desktop_download_changed"} |
| 102 | } |
| 103 | case "files-download-close", "files-download-retry": |
| 104 | reply = map[string]bool{"ok": true} |
| 105 | case "files-open-claim": |
| 106 | reply = map[string]any{"id": request.ID, "download_id": record.ID, "action": "open"} |
| 107 | case "files-open-complete": |
| 108 | reply = map[string]bool{"ok": true} |
| 109 | default: |
| 110 | return |
| 111 | } |
| 112 | if json.NewEncoder(output).Encode(reply) != nil || !request.KeepAlive { |
| 113 | return |
| 114 | } |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | func TestNativeDesktopDownloadAcknowledgesOnlySavedHostReceipts(t *testing.T) { |
| 119 | for _, system := range []string{"macos", "windows"} { |
| 120 | t.Run(system, func(t *testing.T) { |
| 121 | s, record, _, directory := nativeDesktopDownloadFixture(t, system) |
| 122 | poll := func() { |
| 123 | t.Helper() |
| 124 | response := windowsBrowserRequestForTest(s, http.MethodGet, "/api/input/files/desktop/requests", nil) |
| 125 | if response.Code != http.StatusOK { |
| 126 | t.Fatalf("poll failed: %d %s", response.Code, response.Body.String()) |
| 127 | } |
| 128 | } |
| 129 | marker := func(name string) { |
| 130 | t.Helper() |
| 131 | if err := os.WriteFile(filepath.Join(directory, name), nil, 0600); err != nil { |
| 132 | t.Fatal(err) |
| 133 | } |
| 134 | } |
| 135 | ackCount := func() int { |
| 136 | t.Helper() |
| 137 | trace, err := os.ReadFile(filepath.Join(directory, "requests.jsonl")) |
| 138 | if err != nil { |
| 139 | t.Fatal(err) |
| 140 | } |
| 141 | return bytes.Count(trace, []byte(`"action":"files-download-ack"`)) |
| 142 | } |
| 143 | marker("supports-ack") |
| 144 | poll() |
| 145 | if ackCount() != 0 { |
| 146 | t.Fatal("guest-only saved state acknowledged before a durable host copy") |
| 147 | } |
| 148 | if _, err := s.downloadInfo(t.Context(), record.ID); err != nil { |
| 149 | t.Fatal(err) |
| 150 | } |
| 151 | marker("fail-ack") |
| 152 | poll() |
| 153 | if ackCount() != 1 { |
| 154 | t.Fatal("saved host receipt was not acknowledged") |
| 155 | } |
| 156 | if saved, err := readSavedDownload(s.profile, record.ID); err != nil || saved.Path == "" { |
| 157 | t.Fatal("failed acknowledgment invalidated the host receipt", err) |
| 158 | } |
| 159 | if err := os.Remove(filepath.Join(directory, "fail-ack")); err != nil { |
| 160 | t.Fatal(err) |
| 161 | } |
| 162 | poll() |
| 163 | if ackCount() != 2 { |
| 164 | t.Fatal("failed acknowledgment was not retried") |
| 165 | } |
| 166 | poll() |
| 167 | if ackCount() != 2 { |
| 168 | t.Fatal("acknowledged guest record generated another acknowledgment") |
| 169 | } |
| 170 | if err := os.Remove(filepath.Join(directory, "supports-ack")); err != nil { |
| 171 | t.Fatal(err) |
| 172 | } |
| 173 | poll() |
| 174 | if ackCount() != 2 { |
| 175 | t.Fatal("legacy helper received an unsupported acknowledgment") |
| 176 | } |
| 177 | }) |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | func nativeDesktopDownloadFixture(t *testing.T, system string) (*Server, browserDownloadInfo, []byte, string) { |
| 182 | t.Helper() |
| 183 | directory := t.TempDir() |
| 184 | var s *Server |
| 185 | if system == "macos" { |
| 186 | guest := newMacWorkspaceGuest(t, func(channel ssh.Channel, command string) (uint32, bool) { |
| 187 | if !strings.Contains(command, "dev.cage.GuestClaudeWindow/window.sock") { |
| 188 | return 1, false |
| 189 | } |
| 190 | serveDesktopDownloadFixture(channel, channel, directory) |
| 191 | return 0, true |
| 192 | }) |
| 193 | s = guest.s |
| 194 | } else { |
| 195 | s = testServer(t) |
| 196 | binding := guestos.WindowsProfile{Version: 1, VMID: uuid.New(), GUIUserSID: "S-1-5-21-1-2-3-1001", GUIUser: "Guest", InstanceDirectory: filepath.Join(s.profile, "unused-vm"), PairingFile: filepath.Join(s.profile, "unused-pair"), RelayExecutable: os.Args[0]} |
| 197 | if err := guestos.BindWindowsProfile(s.profile, binding); err != nil { |
| 198 | t.Fatal(err) |
| 199 | } |
| 200 | s.windowsGuest = &binding |
| 201 | t.Setenv("CAGE_TEST_NATIVE_DESKTOP_DOWNLOAD", directory) |
| 202 | } |
| 203 | workspace, err := filepath.EvalSymlinks(t.TempDir()) |
| 204 | if err != nil { |
| 205 | t.Fatal(err) |
| 206 | } |
| 207 | if err := writePrivate(filepath.Join(s.profile, "environment.json"), map[string]string{"directory": workspace}); err != nil { |
| 208 | t.Fatal(err) |
| 209 | } |
| 210 | |
| 211 | |
| 212 | browserDirectory := t.TempDir() |
| 213 | if err := os.WriteFile(filepath.Join(browserDirectory, "catalog.json"), []byte(`{"downloads":[]}`), 0600); err != nil { |
| 214 | t.Fatal(err) |
| 215 | } |
| 216 | client := newWindowsBrowserClient(t.Context(), "desktop-download-browser-fixture") |
| 217 | client.start = func(ctx context.Context) (*exec.Cmd, error) { |
| 218 | cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestNativeDownloadRelay$") |
| 219 | cmd.Env = append(os.Environ(), "CAGE_TEST_NATIVE_DESKTOP_DOWNLOAD=", "CAGE_NATIVE_DOWNLOAD_FIXTURE="+browserDirectory) |
| 220 | return cmd, nil |
| 221 | } |
| 222 | s.windowsBrowserControl, s.ready = client, true |
| 223 | t.Cleanup(func() { s.beginClose(); client.close(); s.activities.Wait() }) |
| 224 | record := browserDownloadInfo{ID: uuid.NewString(), Name: "生成文件.bin", State: "saved", Path: "private-guest-cache"} |
| 225 | payload := bytes.Repeat([]byte{0, 255, 17, 42}, 32773) |
| 226 | if err := writePrivate(filepath.Join(directory, "record.json"), record); err != nil { |
| 227 | t.Fatal(err) |
| 228 | } |
| 229 | if err := os.WriteFile(filepath.Join(directory, "payload"), payload, 0600); err != nil { |
| 230 | t.Fatal(err) |
| 231 | } |
| 232 | return s, record, payload, directory |
| 233 | } |
| 234 | |
| 235 | func TestNativeDesktopDownloadUsesProducerAndOneStreamingConnection(t *testing.T) { |
| 236 | for _, system := range []string{"macos", "windows"} { |
| 237 | t.Run(system, func(t *testing.T) { |
| 238 | s, record, payload, directory := nativeDesktopDownloadFixture(t, system) |
| 239 | response := windowsBrowserRequestForTest(s, http.MethodGet, "/api/browser/files/downloads/"+record.ID+"/content", nil) |
| 240 | if response.Code != http.StatusOK || !bytes.Equal(response.Body.Bytes(), payload) { |
| 241 | t.Fatalf("download failed: %d, %d bytes", response.Code, response.Body.Len()) |
| 242 | } |
| 243 | trace, err := os.ReadFile(filepath.Join(directory, "requests.jsonl")) |
| 244 | if err != nil { |
| 245 | t.Fatal(err) |
| 246 | } |
| 247 | connections := map[string]bool{} |
| 248 | reads := 0 |
| 249 | for _, line := range bytes.Split(bytes.TrimSpace(trace), []byte("\n")) { |
| 250 | var request struct{ Connection, Action string } |
| 251 | if json.Unmarshal(line, &request) != nil { |
| 252 | t.Fatal("invalid request trace") |
| 253 | } |
| 254 | if strings.HasPrefix(request.Action, "files-download-") { |
| 255 | connections[request.Connection] = true |
| 256 | } |
| 257 | if request.Action == "files-download-read" { |
| 258 | reads++ |
| 259 | } |
| 260 | } |
| 261 | if len(connections) != 1 || reads != 3 { |
| 262 | t.Fatalf("chunk transfer opened %d connections for %d reads", len(connections), reads) |
| 263 | } |
| 264 | s.ready = false |
| 265 | if err := os.Remove(filepath.Join(directory, "payload")); err != nil { |
| 266 | t.Fatal(err) |
| 267 | } |
| 268 | response = windowsBrowserRequestForTest(s, http.MethodGet, "/api/browser/files/downloads/"+record.ID+"/content", nil) |
| 269 | if response.Code != http.StatusOK || !bytes.Equal(response.Body.Bytes(), payload) { |
| 270 | t.Fatal("saved Desktop file depended on the running guest") |
| 271 | } |
| 272 | }) |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | func TestNativeDesktopDownloadFailureRetriesThroughFileEntry(t *testing.T) { |
| 277 | for _, system := range []string{"macos", "windows"} { |
| 278 | t.Run(system, func(t *testing.T) { |
| 279 | s, record, payload, directory := nativeDesktopDownloadFixture(t, system) |
| 280 | failure := filepath.Join(directory, "fail-read") |
| 281 | if err := os.WriteFile(failure, nil, 0600); err != nil { |
| 282 | t.Fatal(err) |
| 283 | } |
| 284 | if _, err := s.downloadInfo(t.Context(), record.ID); err == nil { |
| 285 | t.Fatal("failed source read became a successful download") |
| 286 | } |
| 287 | if _, err := readSavedDownload(s.profile, record.ID); err == nil { |
| 288 | t.Fatal("partial Desktop transfer was published") |
| 289 | } |
| 290 | if _, err := s.browserStateForHost([]byte(`{"tabs":[],"downloads":[]}`)); err != nil { |
| 291 | t.Fatal(err) |
| 292 | } |
| 293 | s.mu.Lock() |
| 294 | retained := s.nativeDownloads[record.ID] != nil |
| 295 | s.mu.Unlock() |
| 296 | if !retained { |
| 297 | t.Fatal("browser polling discarded the Desktop retry record") |
| 298 | } |
| 299 | if err := os.Remove(failure); err != nil { |
| 300 | t.Fatal(err) |
| 301 | } |
| 302 | body := []byte(fmt.Sprintf(`{"target":"desktop","id":%q}`, record.ID)) |
| 303 | response := windowsBrowserRequestForTest(s, http.MethodPost, "/api/input/files/download-retry", body) |
| 304 | if response.Code != http.StatusOK { |
| 305 | t.Fatalf("retry failed: %d %s", response.Code, response.Body.String()) |
| 306 | } |
| 307 | saved, err := s.downloadInfo(t.Context(), record.ID) |
| 308 | if err != nil { |
| 309 | t.Fatal(err) |
| 310 | } |
| 311 | data, err := os.ReadFile(saved.Path) |
| 312 | if err != nil || !bytes.Equal(data, payload) { |
| 313 | t.Fatal("retried Desktop file differs from producer", err) |
| 314 | } |
| 315 | }) |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | func TestNativeDesktopOpenDownloadClaimsTheSavedHostFile(t *testing.T) { |
| 320 | for _, system := range []string{"macos", "windows"} { |
| 321 | t.Run(system, func(t *testing.T) { |
| 322 | s, record, payload, _ := nativeDesktopDownloadFixture(t, system) |
| 323 | openID := uuid.NewString() |
| 324 | body, _ := json.Marshal(map[string]string{"id": openID, "stage": "claim"}) |
| 325 | response := windowsBrowserRequestForTest(s, http.MethodPost, "/api/input/files/desktop/open", body) |
| 326 | var opened desktopFileOpen |
| 327 | if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &opened) != nil { |
| 328 | t.Fatalf("open claim failed: %d %s", response.Code, response.Body.String()) |
| 329 | } |
| 330 | if opened.ID != openID || opened.Action != "open" || !filepath.IsAbs(opened.Path) { |
| 331 | t.Fatalf("invalid native open response: %+v", opened) |
| 332 | } |
| 333 | content, err := os.ReadFile(opened.Path) |
| 334 | if err != nil || !bytes.Equal(content, payload) { |
| 335 | t.Fatal("open did not await a complete host copy", err) |
| 336 | } |
| 337 | saved, err := readSavedDownload(s.profile, record.ID) |
| 338 | if err != nil || saved.Path != opened.Path { |
| 339 | t.Fatal("open did not use the producer's download identity", err) |
| 340 | } |
| 341 | body, _ = json.Marshal(map[string]string{"id": openID, "stage": "complete"}) |
| 342 | response = windowsBrowserRequestForTest(s, http.MethodPost, "/api/input/files/desktop/open", body) |
| 343 | if response.Code != http.StatusOK { |
| 344 | t.Fatal("open completion failed", response.Body.String()) |
| 345 | } |
| 346 | }) |
| 347 | } |
| 348 | } |