| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "net/http" |
| 8 | "net/http/httptest" |
| 9 | "os" |
| 10 | "os/exec" |
| 11 | "path/filepath" |
| 12 | "strings" |
| 13 | "sync" |
| 14 | "sync/atomic" |
| 15 | "testing" |
| 16 | "time" |
| 17 | |
| 18 | "github.com/google/uuid" |
| 19 | ) |
| 20 | |
| 21 | func TestSessionArchiveContentionInBrowser(t *testing.T) { |
| 22 | if os.Getenv("CAGE_TEST_ARCHIVE_BROWSER") == "" { |
| 23 | t.Skip("set CAGE_TEST_ARCHIVE_BROWSER after building the UI to test with real archive handlers") |
| 24 | } |
| 25 | s, id, project := metadataFixture(t) |
| 26 | record, _ := s.mobileCLI.record(s.profile, id) |
| 27 | record.Title = "软件宣传视频制作" |
| 28 | if err := writePrivate(mobileRecordPath(s.profile, id), record); err != nil { |
| 29 | t.Fatal(err) |
| 30 | } |
| 31 | s.op.Lock() |
| 32 | var releaseOnce sync.Once |
| 33 | release := func() { releaseOnce.Do(s.op.Unlock) } |
| 34 | defer release() |
| 35 | var archives atomic.Int32 |
| 36 | handler := s.handler() |
| 37 | host := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 38 | if r.URL.Path == "/fixture/release-operation" { |
| 39 | release() |
| 40 | jsonReply(w, map[string]bool{"ok": true}) |
| 41 | return |
| 42 | } |
| 43 | if r.URL.Path == "/api/cli/sessions/"+id+"/archive" { |
| 44 | archives.Add(1) |
| 45 | } |
| 46 | handler.ServeHTTP(w, r) |
| 47 | })) |
| 48 | defer host.Close() |
| 49 | |
| 50 | defer release() |
| 51 | s.origin = host.URL |
| 52 | input, _ := json.Marshal(map[string]string{ |
| 53 | "origin": host.URL, "cookie": s.cookieName() + "=" + s.session, |
| 54 | "id": id, "workspace": project, "title": record.Title, |
| 55 | }) |
| 56 | ctx, cancel := context.WithTimeout(context.Background(), time.Minute) |
| 57 | defer cancel() |
| 58 | driver := exec.CommandContext(ctx, "node", "../../ui/scripts/archive-contention-smoke.mjs") |
| 59 | driver.Env = append(os.Environ(), "CAGE_TEST_BROWSER="+os.Getenv("CAGE_TEST_ARCHIVE_BROWSER")) |
| 60 | driver.Stdin = strings.NewReader(string(input)) |
| 61 | if output, err := driver.CombinedOutput(); err != nil { |
| 62 | t.Fatalf("browser: %v\n%s", err, output) |
| 63 | } else { |
| 64 | t.Log(string(output)) |
| 65 | } |
| 66 | if archives.Load() != 1 { |
| 67 | t.Fatalf("archive submissions: %d", archives.Load()) |
| 68 | } |
| 69 | s.mobileCLI = mobileCLIStore{} |
| 70 | restored, err := s.mobileCLI.record(s.profile, id) |
| 71 | if err != nil || !restored.Archived || restored.Deleted { |
| 72 | t.Fatal("UI archive was not durable", restored, err) |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | func TestSessionArchiveWaitsForEnvironmentOperation(t *testing.T) { |
| 77 | for _, route := range []string{"/api/cli/sessions/", "/api/mobile/cli/sessions/"} { |
| 78 | t.Run(route, func(t *testing.T) { |
| 79 | s, id, project := metadataFixture(t) |
| 80 | |
| 81 | s.op.Lock() |
| 82 | locked := true |
| 83 | defer func() { |
| 84 | if locked { |
| 85 | s.op.Unlock() |
| 86 | } |
| 87 | }() |
| 88 | done := make(chan *httptest.ResponseRecorder, 1) |
| 89 | go func() { done <- request(s, "POST", route+id+"/archive", s.origin, `{}`, true) }() |
| 90 | select { |
| 91 | case response := <-done: |
| 92 | t.Fatalf("archive rejected during background operation: %d %s", response.Code, response.Body.String()) |
| 93 | case <-time.After(100 * time.Millisecond): |
| 94 | } |
| 95 | s.op.Unlock() |
| 96 | locked = false |
| 97 | select { |
| 98 | case response := <-done: |
| 99 | if response.Code != http.StatusOK { |
| 100 | t.Fatal(response.Code, response.Body.String()) |
| 101 | } |
| 102 | case <-time.After(3 * time.Second): |
| 103 | t.Fatal("archive did not finish after background operation released the lock") |
| 104 | } |
| 105 | if len(s.terminals.snapshot()) != 0 { |
| 106 | t.Fatal("archive left its terminal visible") |
| 107 | } |
| 108 | s.mobileCLI = mobileCLIStore{} |
| 109 | active, err := s.mobileCLI.summaries(s.profile, map[string]bool{project: true}, false) |
| 110 | if err != nil || len(active) != 0 { |
| 111 | t.Fatal("archived session remained active after reload", active, err) |
| 112 | } |
| 113 | archived, err := s.mobileCLI.summaries(s.profile, map[string]bool{project: true}, true) |
| 114 | if err != nil || len(archived) != 1 || archived[0].ID != id { |
| 115 | t.Fatal("archived history was not retained", archived, err) |
| 116 | } |
| 117 | }) |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | func TestSessionArchiveDoesNotApplyCancelledRequest(t *testing.T) { |
| 122 | s, id, _ := metadataFixture(t) |
| 123 | ctx, cancel := context.WithCancel(context.Background()) |
| 124 | defer cancel() |
| 125 | s.op.Lock() |
| 126 | done := make(chan error, 1) |
| 127 | go func() { done <- s.setSessionArchived(id, true, ctx) }() |
| 128 | select { |
| 129 | case err := <-done: |
| 130 | s.op.Unlock() |
| 131 | t.Fatalf("archive did not wait for the operation: %v", err) |
| 132 | case <-time.After(100 * time.Millisecond): |
| 133 | } |
| 134 | cancel() |
| 135 | s.op.Unlock() |
| 136 | if err := <-done; !errors.Is(err, context.Canceled) { |
| 137 | t.Fatalf("cancelled archive: %v", err) |
| 138 | } |
| 139 | record, err := s.mobileCLI.record(s.profile, id) |
| 140 | if err != nil || record.Archived || len(s.terminals.snapshot()) != 1 { |
| 141 | t.Fatal("cancelled archive changed the session", record, err) |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | func metadataFixture(t *testing.T) (*Server, string, string) { |
| 146 | t.Helper() |
| 147 | s := testServer(t) |
| 148 | project, _ := filepath.EvalSymlinks(t.TempDir()) |
| 149 | s.preferences.Workspace = project |
| 150 | id := uuid.NewString() |
| 151 | if _, err := s.mobileCLI.create(s.profile, project, id); err != nil { |
| 152 | t.Fatal(err) |
| 153 | } |
| 154 | record, err := s.mobileCLI.record(s.profile, id) |
| 155 | if err != nil { |
| 156 | t.Fatal(err) |
| 157 | } |
| 158 | record.Terminal, record.TerminalID = true, "fixture-terminal" |
| 159 | if err := writePrivate(mobileRecordPath(s.profile, id), record); err != nil { |
| 160 | t.Fatal(err) |
| 161 | } |
| 162 | terminal := newTerminalSession(nil) |
| 163 | terminal.id, terminal.sharedID, terminal.workspace, terminal.kind = record.TerminalID, id, project, "claude" |
| 164 | terminal.closed = true |
| 165 | close(terminal.done) |
| 166 | s.terminals.sessions = map[string]*terminalSession{terminal.id: terminal} |
| 167 | return s, id, project |
| 168 | } |
| 169 | |
| 170 | func TestSessionMetadataBidirectionalAndDurable(t *testing.T) { |
| 171 | s, id, project := metadataFixture(t) |
| 172 | path := "/api/mobile/cli/sessions/" + id |
| 173 | if w := request(s, "POST", path+"/metadata", s.origin, `{"title":"手机命名","pinned":true}`, true); w.Code != 200 { |
| 174 | t.Fatalf("mobile metadata: %d %s", w.Code, w.Body.String()) |
| 175 | } |
| 176 | w := request(s, "GET", "/api/terminals", "", "", true) |
| 177 | var terminals []map[string]any |
| 178 | if err := json.Unmarshal(w.Body.Bytes(), &terminals); err != nil { |
| 179 | t.Fatal(err) |
| 180 | } |
| 181 | if len(terminals) != 1 || terminals[0]["title"] != "手机命名" || terminals[0]["pinned"] != true { |
| 182 | t.Fatalf("desktop did not reflect mobile: %s", w.Body.String()) |
| 183 | } |
| 184 | if w := request(s, "POST", "/api/terminals/fixture-terminal/metadata", s.origin, `{"title":"电脑命名","pinned":false}`, true); w.Code != 200 { |
| 185 | t.Fatal(w.Code, w.Body.String()) |
| 186 | } |
| 187 | |
| 188 | record, _ := s.mobileCLI.record(s.profile, id) |
| 189 | record.Title = "CLI 自动摘要" |
| 190 | if err := writePrivate(mobileRecordPath(s.profile, id), record); err != nil { |
| 191 | t.Fatal(err) |
| 192 | } |
| 193 | s.mobileCLI = mobileCLIStore{} |
| 194 | summaries, err := s.mobileCLI.summaries(s.profile, map[string]bool{project: true}, false) |
| 195 | if err != nil || len(summaries) != 1 || summaries[0].Title != "电脑命名" || summaries[0].Pinned { |
| 196 | t.Fatalf("mobile metadata after restart: %#v %v", summaries, err) |
| 197 | } |
| 198 | for _, body := range []string{`{"title":" "}`, `{"title":"` + strings.Repeat("名", 101) + `"}`, `{}`} { |
| 199 | if w := request(s, "POST", path+"/metadata", s.origin, body, true); w.Code == 200 { |
| 200 | t.Fatal("invalid metadata accepted", body) |
| 201 | } |
| 202 | } |
| 203 | if w := request(s, "POST", path+"/metadata", "https://other.invalid", `{"pinned":true}`, true); w.Code != http.StatusForbidden { |
| 204 | t.Fatal("cross-origin write", w.Code) |
| 205 | } |
| 206 | s.account.lock() |
| 207 | for _, action := range []string{"metadata", "delete"} { |
| 208 | if w := request(s, "POST", path+"/"+action, s.origin, `{}`, true); w.Code != http.StatusLocked { |
| 209 | t.Fatal("locked mutation", w.Code) |
| 210 | } |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | func TestSessionArchiveClosesBothListsAndRestores(t *testing.T) { |
| 215 | for _, fromPhone := range []bool{false, true} { |
| 216 | t.Run(map[bool]string{true: "phone", false: "desktop"}[fromPhone], func(t *testing.T) { |
| 217 | s, id, project := metadataFixture(t) |
| 218 | method, path, body := "DELETE", "/api/terminals/fixture-terminal", "" |
| 219 | if fromPhone { |
| 220 | method, path, body = "POST", "/api/mobile/cli/sessions/"+id+"/delete", `{}` |
| 221 | } |
| 222 | if w := request(s, method, path, s.origin, body, true); w.Code != 200 { |
| 223 | t.Fatal(w.Code, w.Body.String()) |
| 224 | } |
| 225 | if len(s.terminals.snapshot()) != 0 { |
| 226 | t.Fatal("desktop terminal survived removal") |
| 227 | } |
| 228 | s.mobileCLI = mobileCLIStore{} |
| 229 | list, err := s.mobileCLI.summaries(s.profile, map[string]bool{project: true}, false) |
| 230 | if err != nil || len(list) != 0 { |
| 231 | t.Fatal("deleted entry reappeared after restart", list, err) |
| 232 | } |
| 233 | record, err := s.mobileCLI.record(s.profile, id) |
| 234 | if err != nil || !record.Archived || record.Deleted || record.CLIID == "" { |
| 235 | t.Fatal("history identity tombstone lost", err) |
| 236 | } |
| 237 | if w := request(s, "GET", "/api/mobile/cli/sessions/"+id, "", "", true); w.Code != 410 { |
| 238 | t.Fatal("removed entry accessible", w.Code) |
| 239 | } |
| 240 | if _, err := s.mobileCLI.create(s.profile, project, id); err == nil { |
| 241 | t.Fatal("stale create resurrected deleted entry") |
| 242 | } |
| 243 | archived, err := s.mobileCLI.summaries(s.profile, map[string]bool{project: true}, true) |
| 244 | if err != nil || len(archived) != 1 || archived[0].ID != id { |
| 245 | t.Fatal("archive lost its history entry", archived, err) |
| 246 | } |
| 247 | if w := request(s, "POST", "/api/cli/sessions/"+id+"/restore", s.origin, `{}`, true); w.Code != 200 { |
| 248 | t.Fatal(w.Code, w.Body.String()) |
| 249 | } |
| 250 | for _, route := range []string{"/api/cli/sessions", "/api/mobile/cli/sessions"} { |
| 251 | w := request(s, "GET", route, "", "", true) |
| 252 | if w.Code != 200 || !strings.Contains(w.Body.String(), id) { |
| 253 | t.Fatal("restored history missing from a client", route, w.Body.String()) |
| 254 | } |
| 255 | } |
| 256 | }) |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | func TestLegacyDeletedSessionMigratesToArchive(t *testing.T) { |
| 261 | s, id, project := metadataFixture(t) |
| 262 | record, _ := s.mobileCLI.record(s.profile, id) |
| 263 | record.Deleted = true |
| 264 | record.Turns = []mobileTurn{{ID: uuid.NewString(), Prompt: "retained prompt", Text: "retained reply", Status: "completed"}} |
| 265 | if err := writePrivate(mobileRecordPath(s.profile, id), record); err != nil { |
| 266 | t.Fatal(err) |
| 267 | } |
| 268 | s.mobileCLI = mobileCLIStore{} |
| 269 | list, err := s.mobileCLI.summaries(s.profile, map[string]bool{project: true}, true) |
| 270 | if err != nil || len(list) != 1 { |
| 271 | t.Fatal(list, err) |
| 272 | } |
| 273 | migrated, err := s.mobileCLI.record(s.profile, id) |
| 274 | if err != nil || migrated.Deleted || !migrated.Archived || migrated.Turns[0].Text != "retained reply" { |
| 275 | t.Fatal("legacy history lost", err) |
| 276 | } |
| 277 | data, _ := os.ReadFile(mobileRecordPath(s.profile, id)) |
| 278 | var persisted mobileRecord |
| 279 | if json.Unmarshal(data, &persisted) != nil || !persisted.Archived || persisted.Deleted { |
| 280 | t.Fatal("archive migration not persisted") |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | func TestPurgeFailureKeepsDurablePendingDeletion(t *testing.T) { |
| 285 | s, id, project := metadataFixture(t) |
| 286 | path := "/api/cli/sessions/" + id |
| 287 | if w := request(s, "POST", path+"/purge", s.origin, `{}`, true); w.Code != 400 { |
| 288 | t.Fatal("purge skipped confirmation", w.Code) |
| 289 | } |
| 290 | if w := request(s, "POST", path+"/purge", s.origin, `{"confirm":true}`, true); w.Code == 200 { |
| 291 | t.Fatal("unarchived purge accepted") |
| 292 | } |
| 293 | if w := request(s, "POST", path+"/archive", s.origin, `{}`, true); w.Code != 200 { |
| 294 | t.Fatal(w.Code, w.Body.String()) |
| 295 | } |
| 296 | if w := request(s, "POST", path+"/purge", s.origin, `{"confirm":true}`, true); w.Code == 200 { |
| 297 | t.Fatal("offline guest claimed deletion") |
| 298 | } |
| 299 | s.mobileCLI = mobileCLIStore{} |
| 300 | list, err := s.mobileCLI.summaries(s.profile, map[string]bool{project: true}, true) |
| 301 | if err != nil || len(list) != 1 || !list[0].Deleting { |
| 302 | t.Fatal("deletion intent was lost", list, err) |
| 303 | } |
| 304 | if w := request(s, "POST", path+"/restore", s.origin, `{}`, true); w.Code == 200 { |
| 305 | t.Fatal("partly deleted history restored") |
| 306 | } |
| 307 | } |