| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/base64" |
| 7 | "encoding/json" |
| 8 | "image/png" |
| 9 | "net/http" |
| 10 | "net/http/cookiejar" |
| 11 | "net/http/httptest" |
| 12 | "net/url" |
| 13 | "os" |
| 14 | "os/exec" |
| 15 | "path/filepath" |
| 16 | "regexp" |
| 17 | "runtime" |
| 18 | "strings" |
| 19 | "testing" |
| 20 | "time" |
| 21 | |
| 22 | "github.com/sylvinus/agent-vm/internal/cage" |
| 23 | "github.com/sylvinus/agent-vm/internal/guestos" |
| 24 | "github.com/sylvinus/agent-vm/internal/managedproxy" |
| 25 | "github.com/sylvinus/agent-vm/internal/remotehost" |
| 26 | ) |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | func TestWindowsFreshWorkbenchApps(t *testing.T) { |
| 32 | profile, executable := os.Getenv("CAGE_TEST_WINDOWS_FRESH_PROFILE"), os.Getenv("CAGE_WINDOWS_GUEST_QA_EXECUTABLE") |
| 33 | if runtime.GOOS != "windows" || profile == "" || executable == "" { |
| 34 | t.Skip("requires an isolated first-run Windows guest") |
| 35 | } |
| 36 | binding, err := guestos.LoadWindowsProfile(profile) |
| 37 | if err != nil || binding == nil || binding.NetworkPairingFile == "" { |
| 38 | t.Fatal("fresh, paired Windows guest required") |
| 39 | } |
| 40 | expected := "Cage-" + strings.ReplaceAll(binding.VMID.String(), "-", "")[:10] |
| 41 | if binding.GUIUser != expected { |
| 42 | t.Fatal("use the independently provisioned standard workbench account") |
| 43 | } |
| 44 | s := testServer(t) |
| 45 | s.profile, s.configPath, s.exe, s.windowsGuest = profile, filepath.Join(profile, "config.json"), executable, binding |
| 46 | s.preferences = Preferences{Keyboard: "native"} |
| 47 | s.lifetimeContext() |
| 48 | defer s.lifeCancel() |
| 49 | defer s.closeWindowsBrowser() |
| 50 | defer s.closeWindowsNetwork() |
| 51 | defer s.closeProjectShares() |
| 52 | defer s.terminals.close() |
| 53 | defer managedproxy.Stop(profile) |
| 54 | if err := s.prepareEnvironment(); err != nil { |
| 55 | t.Fatal(err) |
| 56 | } |
| 57 | if err := s.attachWindowsGuest(); err != nil { |
| 58 | t.Fatalf("production attach: %v", err) |
| 59 | } |
| 60 | |
| 61 | call := func(t *testing.T, method, path string, input, reply any) { |
| 62 | t.Helper() |
| 63 | var body []byte |
| 64 | if input != nil { |
| 65 | body, err = json.Marshal(input) |
| 66 | if err != nil { |
| 67 | t.Fatal(err) |
| 68 | } |
| 69 | } |
| 70 | w := windowsBrowserRequestForTest(s, method, path, body) |
| 71 | if w.Code != http.StatusOK { |
| 72 | t.Fatalf("%s %s: HTTP %d: %.400s", method, path, w.Code, w.Body.String()) |
| 73 | } |
| 74 | if reply != nil && json.Unmarshal(w.Body.Bytes(), reply) != nil { |
| 75 | t.Fatalf("%s returned an invalid response", path) |
| 76 | } |
| 77 | } |
| 78 | waitJob := func(t *testing.T) { |
| 79 | t.Helper() |
| 80 | deadline := time.Now().Add(3 * time.Minute) |
| 81 | for s.jobs.snapshot().Running && time.Now().Before(deadline) { |
| 82 | time.Sleep(250 * time.Millisecond) |
| 83 | } |
| 84 | job := s.jobs.snapshot() |
| 85 | if job.Running || job.Error != "" { |
| 86 | t.Fatalf("workbench job %s did not complete: %s", job.Kind, job.Error) |
| 87 | } |
| 88 | } |
| 89 | online := os.Getenv("CAGE_WINDOWS_FRESH_BIND_MEASURED_EXIT") == "1" |
| 90 | if online { |
| 91 | |
| 92 | |
| 93 | var settings Settings |
| 94 | call(t, "GET", "/api/settings", nil, &settings) |
| 95 | var loc Location |
| 96 | call(t, "POST", "/api/settings/probe", settings, &loc) |
| 97 | if settings.ExitPolicy.NeedsBinding() { |
| 98 | settings.ExitPolicy = cage.ExitPolicy{Mode: "static", IP: loc.IP} |
| 99 | call(t, "POST", "/api/settings", settings, nil) |
| 100 | waitJob(t) |
| 101 | } |
| 102 | call(t, "GET", "/api/settings", nil, &settings) |
| 103 | if loc.IP == "" || settings.ExitPolicy.Mode != "static" || settings.ExitPolicy.IP != loc.IP { |
| 104 | t.Fatal("selected managed exit does not match this QA account's fixed public address") |
| 105 | } |
| 106 | call(t, "POST", "/api/safety/check", struct{}{}, nil) |
| 107 | waitJob(t) |
| 108 | s.mu.Lock() |
| 109 | report, gate := s.safety.Report, s.safety.Gate |
| 110 | s.mu.Unlock() |
| 111 | cfg, e := loadConfig(s.configPath) |
| 112 | if e != nil || report == nil || gate == nil || gate.Mode != cage.GateOpen || report.Authorizes(gate.RunID, cfg.Fingerprint(), time.Now()) != nil { |
| 113 | t.Fatal("actual safety report did not authorize this exit") |
| 114 | } |
| 115 | for _, check := range report.Checks { |
| 116 | t.Logf("actual check %s: %s", check.ID, check.State) |
| 117 | } |
| 118 | } |
| 119 | frame := func(t *testing.T, name string, f windowsWindowFrame) { |
| 120 | t.Helper() |
| 121 | img, e := nativeFrameImage(f) |
| 122 | if e != nil { |
| 123 | t.Fatalf("%s: %v", name, e) |
| 124 | } |
| 125 | if img.Bounds().Dx() < 240 || img.Bounds().Dy() < 180 { |
| 126 | t.Fatalf("small %s frame: %v", name, img.Bounds()) |
| 127 | } |
| 128 | if directory := os.Getenv("CAGE_WINDOWS_GUEST_QA_EVIDENCE"); directory != "" { |
| 129 | dst, err := os.Create(filepath.Join(directory, name+".png")) |
| 130 | if err != nil { |
| 131 | t.Fatal(err) |
| 132 | } |
| 133 | defer dst.Close() |
| 134 | if err := png.Encode(dst, img); err != nil { |
| 135 | t.Fatal(err) |
| 136 | } |
| 137 | } |
| 138 | t.Logf("owned %s frame: %dx%d", name, img.Bounds().Dx(), img.Bounds().Dy()) |
| 139 | } |
| 140 | project := s.environmentDir() |
| 141 | fixture, err := os.CreateTemp(project, "invoice-*.js") |
| 142 | if err != nil { |
| 143 | t.Fatal(err) |
| 144 | } |
| 145 | defer os.Remove(fixture.Name()) |
| 146 | if _, err = fixture.WriteString("console.log(120 * 1.1)\n"); err != nil { |
| 147 | fixture.Close() |
| 148 | t.Fatal(err) |
| 149 | } |
| 150 | if err = fixture.Close(); err != nil { |
| 151 | t.Fatal(err) |
| 152 | } |
| 153 | call(t, "POST", "/api/projects/open", map[string]any{"workspace": project, "activate": true}, nil) |
| 154 | t.Run("ClaudeDesktop", func(t *testing.T) { |
| 155 | var d claudeDesktopState |
| 156 | call(t, "GET", "/api/claude-desktop", nil, &d) |
| 157 | if !d.Installed || !d.NativeUserSession || d.Version == "" { |
| 158 | t.Fatal("signed guest desktop app not registered") |
| 159 | } |
| 160 | if online && d.Running && os.Getenv("CAGE_WINDOWS_FRESH_RELAUNCH_DESKTOP") == "1" { |
| 161 | call(t, "POST", "/api/claude-desktop/stop", struct{}{}, nil) |
| 162 | waitJob(t) |
| 163 | call(t, "GET", "/api/claude-desktop", nil, &d) |
| 164 | } |
| 165 | if !d.Running { |
| 166 | call(t, "POST", "/api/claude-desktop/start", struct{}{}, nil) |
| 167 | deadline := time.Now().Add(time.Minute) |
| 168 | for time.Now().Before(deadline) { |
| 169 | if s.jobs.snapshot().Error != "" { |
| 170 | t.Fatal(s.jobs.snapshot().Error) |
| 171 | } |
| 172 | time.Sleep(700 * time.Millisecond) |
| 173 | call(t, "GET", "/api/claude-desktop", nil, &d) |
| 174 | if d.Running { |
| 175 | break |
| 176 | } |
| 177 | } |
| 178 | } |
| 179 | if !d.Running { |
| 180 | t.Fatal("official Claude window did not open") |
| 181 | } |
| 182 | |
| 183 | |
| 184 | var f windowsWindowFrame |
| 185 | ctx, cancel := context.WithTimeout(context.Background(), 75*time.Second) |
| 186 | defer cancel() |
| 187 | for { |
| 188 | if err := s.windowsDesktopRequest(ctx, "frame", nil, &f); err == nil { |
| 189 | break |
| 190 | } |
| 191 | select { |
| 192 | case <-ctx.Done(): |
| 193 | t.Fatal("official Windows window did not render readable content") |
| 194 | case <-time.After(500 * time.Millisecond): |
| 195 | } |
| 196 | } |
| 197 | frame(t, "windows-fresh-claude", f) |
| 198 | if script := os.Getenv("CAGE_WINDOWS_QA_UI_SCRIPT"); online && script != "" { |
| 199 | |
| 200 | |
| 201 | s.token, s.session = randomToken(), randomToken() |
| 202 | server := httptest.NewServer(s.handler()) |
| 203 | defer server.Close() |
| 204 | s.origin = strings.Replace(server.URL, "127.0.0.1", "localhost", 1) |
| 205 | authCookies := func(target *Server) []*http.Cookie { |
| 206 | return []*http.Cookie{ |
| 207 | {Name: target.cookieName(), Value: target.session, Path: "/", HttpOnly: true}, |
| 208 | {Name: target.cookieName() + "-desktop", Value: trustedViewProof(target.token), Path: "/", HttpOnly: true}, |
| 209 | } |
| 210 | } |
| 211 | jar, _ := cookiejar.New(nil) |
| 212 | upstream, _ := url.Parse(s.origin) |
| 213 | jar.SetCookies(upstream, authCookies(s)) |
| 214 | session, e := remotehost.LocalSession(s.lifetimeContext(), s.origin, remotehost.PublicManifest{Platform: "windows", InstanceID: randomToken()}, jar) |
| 215 | if e != nil { |
| 216 | t.Fatal(e) |
| 217 | } |
| 218 | defer session.Close() |
| 219 | gateway := testServer(t) |
| 220 | gateway.token, gateway.session = randomToken(), randomToken() |
| 221 | gateway.desktopEntry = true |
| 222 | gateway.remote = newDesktopGateway(gateway.profile, &desktopLocal{profile: s.profile}) |
| 223 | d := gateway.remote.desktop |
| 224 | d.active = &desktopTarget{id: d.generation, mode: "local", ctx: s.lifetimeContext(), session: session} |
| 225 | gatewayServer := httptest.NewServer(gateway.handler()) |
| 226 | defer gatewayServer.Close() |
| 227 | gateway.origin = gatewayServer.URL |
| 228 | payload, _ := json.Marshal(map[string]any{ |
| 229 | "url": gateway.origin, "evidence": os.Getenv("CAGE_WINDOWS_GUEST_QA_EVIDENCE"), |
| 230 | "cookies": []map[string]string{ |
| 231 | {"name": gateway.cookieName(), "value": gateway.session}, {"name": gateway.cookieName() + "-desktop", "value": trustedViewProof(gateway.token)}, |
| 232 | }, |
| 233 | }) |
| 234 | uiCtx, stop := context.WithTimeout(context.Background(), 2*time.Minute) |
| 235 | defer stop() |
| 236 | cmd := exec.CommandContext(uiCtx, os.Getenv("CAGE_WINDOWS_QA_NODE"), script) |
| 237 | cmd.Stdin = bytes.NewReader(payload) |
| 238 | if out, e := cmd.CombinedOutput(); e != nil { |
| 239 | t.Fatalf("shared workbench click: %v (%.600s)", e, out) |
| 240 | } |
| 241 | t.Log("tested actual shared React/noVNC window interaction") |
| 242 | call(t, "POST", "/api/claude-desktop/resize", map[string]int{"width": 1100, "height": 760}, nil) |
| 243 | resizeCtx, release := context.WithTimeout(context.Background(), 12*time.Second) |
| 244 | defer release() |
| 245 | var resized windowsWindowFrame |
| 246 | if e := s.windowsDesktopRequest(resizeCtx, "frame", nil, &resized); e != nil { |
| 247 | t.Fatal(e) |
| 248 | } |
| 249 | frame(t, "windows-fresh-resized-claude", resized) |
| 250 | if resized.Width != 1100 || resized.Height != 760 { |
| 251 | t.Errorf("Windows returned %dx%d for a 1100x760 panel", resized.Width, resized.Height) |
| 252 | } |
| 253 | } |
| 254 | }) |
| 255 | t.Run("BrowserAndEditor", func(t *testing.T) { |
| 256 | request := func(action string, payload map[string]any) string { |
| 257 | t.Helper() |
| 258 | var tab struct { |
| 259 | ID string `json:"id"` |
| 260 | } |
| 261 | call(t, "POST", "/api/browser/"+action, payload, &tab) |
| 262 | if tab.ID == "" { |
| 263 | t.Fatalf("%s did not create a tab", action) |
| 264 | } |
| 265 | return tab.ID |
| 266 | } |
| 267 | startURL := "about:blank" |
| 268 | if online { |
| 269 | startURL = "https://example.com/" |
| 270 | } |
| 271 | tab := request("new", map[string]any{"url": startURL}) |
| 272 | defer call(t, "POST", "/api/browser/close", map[string]any{"id": tab}, nil) |
| 273 | read := func(name string) { |
| 274 | t.Helper() |
| 275 | ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) |
| 276 | defer cancel() |
| 277 | b, e := s.nativeBrowserClient().request(ctx, "GET", "/frame", nil) |
| 278 | if e != nil { |
| 279 | t.Fatal(e) |
| 280 | } |
| 281 | var f windowsWindowFrame |
| 282 | if json.Unmarshal(b, &f) != nil { |
| 283 | t.Fatal("invalid guest browser frame") |
| 284 | } |
| 285 | frame(t, name, f) |
| 286 | } |
| 287 | if online { |
| 288 | time.Sleep(3 * time.Second) |
| 289 | } |
| 290 | read("windows-fresh-browser") |
| 291 | editor := request("editor", map[string]any{"workspace": project}) |
| 292 | defer call(t, "POST", "/api/browser/close", map[string]any{"id": editor}, nil) |
| 293 | time.Sleep(3 * time.Second) |
| 294 | read("windows-fresh-editor") |
| 295 | }) |
| 296 | t.Run("PowerShell7", func(t *testing.T) { |
| 297 | var session struct { |
| 298 | ID string `json:"id"` |
| 299 | } |
| 300 | call(t, "POST", "/api/terminals", map[string]any{"kind": "shell", "workspace": project}, &session) |
| 301 | terminal := s.terminals.get(session.ID) |
| 302 | if terminal == nil { |
| 303 | t.Fatal("workbench shell was not created") |
| 304 | } |
| 305 | defer s.terminals.remove(session.ID) |
| 306 | const marker = "CageInstalledShellVerified" |
| 307 | encoded := base64.StdEncoding.EncodeToString([]byte(marker)) |
| 308 | line := "$v = (& pwsh --version).Trim(); if ($v -match '^PowerShell 7[.]') { [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('" + encoded + "')) + $v }" |
| 309 | ctx, cancel := context.WithTimeout(context.Background(), time.Minute) |
| 310 | defer cancel() |
| 311 | if e := terminal.enqueueInput(ctx, terminalInputLine(line)); e != nil { |
| 312 | t.Fatal(e) |
| 313 | } |
| 314 | version := regexp.MustCompile(marker + `PowerShell 7[.][0-9]+[.][0-9]+`) |
| 315 | for ctx.Err() == nil { |
| 316 | terminal.mu.Lock() |
| 317 | m := version.Find(terminal.history) |
| 318 | terminal.mu.Unlock() |
| 319 | if m != nil { |
| 320 | t.Log("standard user's pwsh --version:", string(m[len(marker):])) |
| 321 | return |
| 322 | } |
| 323 | time.Sleep(250 * time.Millisecond) |
| 324 | } |
| 325 | t.Fatal("PowerShell 7 was not directly executable in the normal workbench terminal") |
| 326 | }) |
| 327 | t.Run("ClaudeCode", func(t *testing.T) { |
| 328 | var session struct { |
| 329 | ID string `json:"id"` |
| 330 | Conversation string `json:"cli_session_id"` |
| 331 | } |
| 332 | call(t, "POST", "/api/terminals", map[string]any{"kind": "claude", "workspace": project}, &session) |
| 333 | terminal := s.terminals.get(session.ID) |
| 334 | if terminal == nil || session.Conversation == "" { |
| 335 | t.Fatal("shared Claude Code terminal not created") |
| 336 | } |
| 337 | defer s.terminals.remove(session.ID) |
| 338 | deadline := time.Now().Add(time.Minute) |
| 339 | for time.Now().Before(deadline) { |
| 340 | terminal.mu.Lock() |
| 341 | text := strings.ToLower(string(terminal.history)) |
| 342 | closed := terminal.closed |
| 343 | terminal.mu.Unlock() |
| 344 | plain := regexp.MustCompile("\\x1b\\[[0-9;>?]*[a-zA-Z]").ReplaceAllString(text, "") |
| 345 | plain = strings.Join(strings.Fields(plain), "") |
| 346 | if strings.Contains(plain, "welcometoclaudecode") || strings.Contains(text, "claude code") || strings.Contains(text, "login method") || strings.Contains(text, "choose the text style") { |
| 347 | t.Log("shared terminal delivered official Claude Code onboarding") |
| 348 | return |
| 349 | } |
| 350 | if closed { |
| 351 | break |
| 352 | } |
| 353 | time.Sleep(400 * time.Millisecond) |
| 354 | } |
| 355 | t.Fatal("workbench did not receive official Claude Code onboarding") |
| 356 | |
| 357 | }) |
| 358 | } |