| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "github.com/sylvinus/agent-vm/internal/cage" |
| 6 | "io" |
| 7 | "net" |
| 8 | "net/http" |
| 9 | "slices" |
| 10 | "strings" |
| 11 | |
| 12 | "al.essio.dev/pkg/shellescape" |
| 13 | "os" |
| 14 | "path/filepath" |
| 15 | "testing" |
| 16 | |
| 17 | "github.com/lima-vm/sshocker/pkg/reversesshfs" |
| 18 | "github.com/pkg/sftp" |
| 19 | ) |
| 20 | |
| 21 | func TestProjectSelectionKeepsOneVMAndExistingSessionsOffline(t *testing.T) { |
| 22 | s := testServer(t) |
| 23 | cfg, _ := loadConfig(s.configPath) |
| 24 | s.preferences.Workspace = s.environmentDir() |
| 25 | s.ready, s.networkPaused = true, true |
| 26 | marker := filepath.Join(s.profile, "state", "lima", cage.InstanceName(s.profile, s.environmentDir()), "cage-running.json") |
| 27 | if err := writePrivate(marker, map[string]int{"pid": os.Getpid()}); err != nil { |
| 28 | t.Fatal(err) |
| 29 | } |
| 30 | originalVM := cage.InstanceName(s.profile, s.environmentDir()) |
| 31 | terminal := &terminalSession{id: "keep", title: "existing terminal"} |
| 32 | s.terminals.sessions = map[string]*terminalSession{terminal.id: terminal} |
| 33 | a, _ := filepath.EvalSymlinks(t.TempDir()) |
| 34 | b, _ := filepath.EvalSymlinks(t.TempDir()) |
| 35 | s.projectShares = map[string]*projectShare{a: {done: make(chan struct{})}, b: {done: make(chan struct{})}} |
| 36 | for _, dir := range []string{a, b, a} { |
| 37 | next := s.preferences |
| 38 | next.Workspace = dir |
| 39 | |
| 40 | if err := s.apply(savedProfile{cfg, next}, true); err != nil { |
| 41 | t.Fatal(err) |
| 42 | } |
| 43 | if !s.ready || !s.vmRunning() || !s.networkPaused || cage.InstanceName(s.profile, s.environmentDir()) != originalVM { |
| 44 | t.Fatal("project selection changed environment lifecycle or networking") |
| 45 | } |
| 46 | if s.terminals.get(terminal.id) != terminal || terminal.closed { |
| 47 | t.Fatal("project selection interrupted the old terminal") |
| 48 | } |
| 49 | } |
| 50 | var saved sharedProjects |
| 51 | data, err := os.ReadFile(filepath.Join(s.profile, "projects.json")) |
| 52 | if err != nil || json.Unmarshal(data, &saved) != nil || len(saved.Paths) != 2 { |
| 53 | t.Fatal("explicitly opened projects were not persisted uniquely") |
| 54 | } |
| 55 | next := s.preferences |
| 56 | next.Workspace = s.profile |
| 57 | if err := s.apply(savedProfile{cfg, next}, true); err == nil { |
| 58 | t.Fatal("private directory accepted as a project") |
| 59 | } |
| 60 | if s.workspace() != a || terminal.closed || !s.ready { |
| 61 | t.Fatal("failed project selection changed the active environment") |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | func TestLiveProjectTransportConfinesReadsAndAllowsGitWrites(t *testing.T) { |
| 66 | parent := t.TempDir() |
| 67 | root := filepath.Join(parent, "project") |
| 68 | if err := os.MkdirAll(filepath.Join(root, ".git"), 0700); err != nil { |
| 69 | t.Fatal(err) |
| 70 | } |
| 71 | outside := filepath.Join(parent, "secret") |
| 72 | if err := os.WriteFile(outside, []byte("private"), 0600); err != nil { |
| 73 | t.Fatal(err) |
| 74 | } |
| 75 | if err := os.Symlink(parent, filepath.Join(root, "escape")); err != nil { |
| 76 | t.Fatal(err) |
| 77 | } |
| 78 | server, conn := net.Pipe() |
| 79 | done := make(chan struct{}) |
| 80 | go func() { |
| 81 | defer close(done) |
| 82 | _ = reversesshfs.ServeConfined(server, root, false, nil) |
| 83 | }() |
| 84 | client, err := sftp.NewClientPipe(conn, conn) |
| 85 | if err != nil { |
| 86 | t.Fatal(err) |
| 87 | } |
| 88 | defer func() { _ = client.Close(); _ = conn.Close(); <-done }() |
| 89 | file, err := client.Create(filepath.Join(root, "note.txt")) |
| 90 | if err != nil { |
| 91 | t.Fatal(err) |
| 92 | } |
| 93 | if _, err = file.Write([]byte("shared")); err != nil { |
| 94 | t.Fatal(err) |
| 95 | } |
| 96 | _ = file.Close() |
| 97 | data, err := os.ReadFile(filepath.Join(root, "note.txt")) |
| 98 | if err != nil || string(data) != "shared" { |
| 99 | t.Fatal("project write did not reach the host") |
| 100 | } |
| 101 | for _, p := range []string{outside, filepath.Join(root, "escape", "secret")} { |
| 102 | f, err := client.Open(p) |
| 103 | if err == nil { |
| 104 | _ = f.Close() |
| 105 | t.Fatalf("read escaped selected project: %s", p) |
| 106 | } |
| 107 | } |
| 108 | if err := exerciseProjectGitWrites(client, filepath.ToSlash(root)); err != nil { |
| 109 | t.Fatal(err) |
| 110 | } |
| 111 | f, err := client.Open(filepath.Join(root, "note.txt")) |
| 112 | if err != nil { |
| 113 | t.Fatal(err) |
| 114 | } |
| 115 | defer f.Close() |
| 116 | got, err := io.ReadAll(f) |
| 117 | if err != nil || string(got) != "shared" { |
| 118 | t.Fatal("shared file read failed") |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | |
| 123 | |
| 124 | func exerciseProjectGitWrites(client *sftp.Client, root string) error { |
| 125 | for _, dir := range []string{".git/objects/ab", ".git/refs/heads", ".git/logs/refs/heads", ".git/hooks", ".vscode", ".claude", ".hg/store"} { |
| 126 | if err := client.MkdirAll(root + "/" + dir); err != nil { |
| 127 | return err |
| 128 | } |
| 129 | } |
| 130 | for _, name := range []string{".git/config", ".git/index", ".git/HEAD", ".git/refs/heads/main", ".git/logs/refs/heads/main", ".git/objects/ab/object", ".git/hooks/pre-commit", ".env", ".vscode/settings.json", ".claude/settings.json", ".hg/store/data", "private.key"} { |
| 131 | file, err := client.Create(root + "/" + name + ".lock") |
| 132 | if err != nil { |
| 133 | return err |
| 134 | } |
| 135 | _, err = file.Write([]byte("git-write")) |
| 136 | closeErr := file.Close() |
| 137 | if err != nil { |
| 138 | return err |
| 139 | } |
| 140 | if closeErr != nil { |
| 141 | return closeErr |
| 142 | } |
| 143 | if err = client.PosixRename(root+"/"+name+".lock", root+"/"+name); err != nil { |
| 144 | return err |
| 145 | } |
| 146 | } |
| 147 | return client.Remove(root + "/.git/objects/ab/object") |
| 148 | } |
| 149 | |
| 150 | func TestProjectListComesFromSavedDirectories(t *testing.T) { |
| 151 | s := testServer(t) |
| 152 | var expected []string |
| 153 | expected = append(expected, s.environmentDir()) |
| 154 | for i := 0; i < 15; i++ { |
| 155 | path := t.TempDir() |
| 156 | if err := s.rememberSharedProject(path); err != nil { |
| 157 | t.Fatal(err) |
| 158 | } |
| 159 | expected = append(expected, path) |
| 160 | } |
| 161 | s.preferences.Workspace = expected[2] |
| 162 | if err := s.rememberSharedProject(expected[2]); err != nil { |
| 163 | t.Fatal(err) |
| 164 | } |
| 165 | |
| 166 | reloaded := testServer(t) |
| 167 | reloaded.profile = s.profile |
| 168 | reloaded.preferences = s.preferences |
| 169 | w := request(reloaded, "GET", "/api/status", "", "", true) |
| 170 | var status struct { |
| 171 | Projects []string `json:"projects"` |
| 172 | } |
| 173 | if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &status) != nil || !slices.Equal(status.Projects, expected) { |
| 174 | t.Fatalf("saved project list was truncated, reordered, or lost: %s", w.Body.String()) |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | func TestRestoreProjectSharesReportsTheFailedDirectoryAndReason(t *testing.T) { |
| 179 | s := testServer(t) |
| 180 | connected, _ := filepath.EvalSymlinks(t.TempDir()) |
| 181 | executable, err := os.Executable() |
| 182 | if err != nil { |
| 183 | t.Fatal(err) |
| 184 | } |
| 185 | executable, err = filepath.EvalSymlinks(executable) |
| 186 | if err != nil { |
| 187 | t.Fatal(err) |
| 188 | } |
| 189 | blocked := filepath.Dir(executable) |
| 190 | s.preferences.Workspace = connected |
| 191 | s.projectShares = map[string]*projectShare{connected: {done: make(chan struct{})}} |
| 192 | for _, path := range []string{blocked, connected} { |
| 193 | if err := s.rememberSharedProject(path); err != nil { |
| 194 | t.Fatal(err) |
| 195 | } |
| 196 | } |
| 197 | s.restoreProjectShares() |
| 198 | w := request(s, "GET", "/api/status", "", "", true) |
| 199 | var status struct { |
| 200 | ProjectError string `json:"project_error"` |
| 201 | ProjectErrors []projectShareError `json:"project_errors"` |
| 202 | } |
| 203 | if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &status) != nil { |
| 204 | t.Fatalf("cannot read project status: %s", w.Body.String()) |
| 205 | } |
| 206 | if status.ProjectError == "" || len(status.ProjectErrors) != 1 || status.ProjectErrors[0].Path != blocked || !strings.Contains(status.ProjectErrors[0].Message, "正在运行的工作台程序") { |
| 207 | t.Fatalf("failure did not identify the blocked project and executable protection: %+v", status) |
| 208 | } |
| 209 | if s.projectShares[connected] == nil { |
| 210 | t.Fatal("one failed directory disconnected a healthy project") |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | func TestProjectReconnectClearsOnlyItsOwnWarning(t *testing.T) { |
| 215 | s := testServer(t) |
| 216 | connected, _ := filepath.EvalSymlinks(t.TempDir()) |
| 217 | parent, _ := filepath.EvalSymlinks(t.TempDir()) |
| 218 | missing := filepath.Join(parent, "missing") |
| 219 | s.projectErrors = []projectShareError{ |
| 220 | {Path: connected, Message: "previous connection failed"}, |
| 221 | {Path: missing, Message: "directory unavailable"}, |
| 222 | } |
| 223 | s.projectShares = map[string]*projectShare{connected: {done: make(chan struct{})}} |
| 224 | if err := s.ensureProjectShare(missing); err == nil || len(s.projectErrors) != 2 { |
| 225 | t.Fatal("a failed reconnect cleared a warning") |
| 226 | } |
| 227 | if err := s.ensureProjectShare(connected); err != nil { |
| 228 | t.Fatal(err) |
| 229 | } |
| 230 | if len(s.projectErrors) != 1 || s.projectErrors[0].Path != missing { |
| 231 | t.Fatalf("reconnect did not preserve the other directory's warning: %+v", s.projectErrors) |
| 232 | } |
| 233 | if err := os.Mkdir(missing, 0700); err != nil { |
| 234 | t.Fatal(err) |
| 235 | } |
| 236 | s.projectShares[missing] = &projectShare{done: make(chan struct{})} |
| 237 | if err := s.ensureProjectShare(missing); err != nil || len(s.projectErrors) != 0 { |
| 238 | t.Fatalf("successful reconnect left a stale warning: %v, %+v", err, s.projectErrors) |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | func TestProjectActionsUseExplicitDirectoryWithoutSwitchingProject(t *testing.T) { |
| 243 | s := testServer(t) |
| 244 | a, _ := filepath.EvalSymlinks(t.TempDir()) |
| 245 | b, _ := filepath.EvalSymlinks(t.TempDir()) |
| 246 | s.preferences.Workspace = b |
| 247 | s.ready = true |
| 248 | if err := s.rememberSharedProject(a); err != nil { |
| 249 | t.Fatal(err) |
| 250 | } |
| 251 | s.projectShares = map[string]*projectShare{a: {done: make(chan struct{})}} |
| 252 | marker := filepath.Join(s.profile, "state", "lima", cage.InstanceName(s.profile, s.environmentDir()), "cage-running.json") |
| 253 | if err := writePrivate(marker, map[string]int{"pid": os.Getpid()}); err != nil { |
| 254 | t.Fatal(err) |
| 255 | } |
| 256 | |
| 257 | body, _ := json.Marshal(map[string]string{"workspace": a}) |
| 258 | w := request(s, "POST", "/api/terminals", s.origin, string(body), true) |
| 259 | var terminal struct{ ID, Workspace string } |
| 260 | if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &terminal) != nil || terminal.Workspace != a { |
| 261 | t.Fatalf("terminal did not use the explicit directory: %s", w.Body.String()) |
| 262 | } |
| 263 | session := s.terminals.get(terminal.ID) |
| 264 | defer session.close() |
| 265 | if script := session.cmd.Args[len(session.cmd.Args)-1]; !strings.HasPrefix(script, "cd "+shellescape.Quote(guestPath(a))+" &&") { |
| 266 | t.Fatalf("terminal command opened a different directory: %s", script) |
| 267 | } |
| 268 | var editorWorkspace string |
| 269 | s.browserControl = browserClientForTest(t, s, browserTransport(func(r *http.Request) (*http.Response, error) { |
| 270 | var input struct { |
| 271 | Workspace string `json:"workspace"` |
| 272 | } |
| 273 | if err := json.NewDecoder(r.Body).Decode(&input); err != nil { |
| 274 | t.Fatal(err) |
| 275 | } |
| 276 | editorWorkspace = input.Workspace |
| 277 | return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"id":"editor"}`)), Header: http.Header{}}, nil |
| 278 | })) |
| 279 | for _, action := range []string{"editor", "editor-restart"} { |
| 280 | w = request(s, "POST", "/api/browser/"+action, s.origin, string(body), true) |
| 281 | if w.Code != 200 || editorWorkspace != guestPath(a) || s.workspace() != b { |
| 282 | t.Fatalf("%s changed the selected project or ignored its directory: %s", action, w.Body.String()) |
| 283 | } |
| 284 | } |
| 285 | for _, path := range []string{t.TempDir(), s.profile} { |
| 286 | body, _ = json.Marshal(map[string]string{"workspace": path}) |
| 287 | for _, endpoint := range []string{"/api/terminals", "/api/browser/editor", "/api/browser/editor-restart"} { |
| 288 | w = request(s, "POST", endpoint, s.origin, string(body), true) |
| 289 | if w.Code != 400 { |
| 290 | t.Fatalf("unopened directory accepted by %s: %d", endpoint, w.Code) |
| 291 | } |
| 292 | } |
| 293 | } |
| 294 | if len(s.terminals.snapshot()) != 1 || s.workspace() != b { |
| 295 | t.Fatal("rejected requests changed existing sessions") |
| 296 | } |
| 297 | } |