| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "os" |
| 5 | "path/filepath" |
| 6 | "strings" |
| 7 | "testing" |
| 8 | "time" |
| 9 | |
| 10 | "reasonix/internal/agent" |
| 11 | "reasonix/internal/provider" |
| 12 | ) |
| 13 | |
| 14 | func TestRecoveryGCStartupWaitIsCancellationAware(t *testing.T) { |
| 15 | done := make(chan struct{}) |
| 16 | elapsed := make(chan time.Time, 1) |
| 17 | elapsed <- time.Now() |
| 18 | if !waitRecoveryGCStartup(done, elapsed) { |
| 19 | t.Fatal("elapsed startup grace should allow the first sweep") |
| 20 | } |
| 21 | done = make(chan struct{}) |
| 22 | close(done) |
| 23 | if waitRecoveryGCStartup(done, make(chan time.Time)) { |
| 24 | t.Fatal("cancelled startup must skip the first sweep") |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | // forkCoveredRecoveryBranch builds the reclaimable shape in dir: a conflict |
| 29 | // fork whose parent went on to contain everything the fork preserved. |
| 30 | func forkCoveredRecoveryBranch(t *testing.T, dir, name string) (parentPath, branchPath string) { |
| 31 | t.Helper() |
| 32 | parentPath = filepath.Join(dir, name+".jsonl") |
| 33 | disk := agent.NewSession("sys") |
| 34 | disk.Add(provider.Message{Role: provider.RoleUser, Content: "first"}) |
| 35 | disk.Add(provider.Message{Role: provider.RoleAssistant, Content: "one"}) |
| 36 | disk.Add(provider.Message{Role: provider.RoleUser, Content: "disk " + name}) |
| 37 | if err := disk.Save(parentPath); err != nil { |
| 38 | t.Fatalf("Save parent: %v", err) |
| 39 | } |
| 40 | stale := agent.NewSession("sys") |
| 41 | stale.Add(provider.Message{Role: provider.RoleUser, Content: "first"}) |
| 42 | stale.Add(provider.Message{Role: provider.RoleAssistant, Content: "one"}) |
| 43 | stale.Add(provider.Message{Role: provider.RoleUser, Content: "local " + name}) |
| 44 | info, err := stale.SaveRecoveryBranch(agent.RecoveryBranchOptions{OriginalPath: parentPath}) |
| 45 | if err != nil { |
| 46 | t.Fatalf("SaveRecoveryBranch: %v", err) |
| 47 | } |
| 48 | covering, err := agent.LoadSession(parentPath) |
| 49 | if err != nil { |
| 50 | t.Fatalf("Load covering parent: %v", err) |
| 51 | } |
| 52 | covering.Replace(append([]provider.Message(nil), stale.Snapshot()...)) |
| 53 | covering.Add(provider.Message{Role: provider.RoleAssistant, Content: "answered after recovery"}) |
| 54 | if err := covering.SaveRewrite(parentPath); err != nil { |
| 55 | t.Fatalf("Save covering parent: %v", err) |
| 56 | } |
| 57 | return parentPath, info.Path |
| 58 | } |
| 59 | |
| 60 | func TestRecoveryGCTrashesCoveredForkAndKeepsParent(t *testing.T) { |
| 61 | isolateDesktopUserDirs(t) |
| 62 | root := globalTabWorkspaceRoot() |
| 63 | dir := desktopSessionDir(root) |
| 64 | if err := os.MkdirAll(dir, 0o755); err != nil { |
| 65 | t.Fatalf("mkdir sessions: %v", err) |
| 66 | } |
| 67 | parentPath, branchPath := forkCoveredRecoveryBranch(t, dir, "session") |
| 68 | |
| 69 | app := &App{tabs: map[string]*WorkspaceTab{}, detachedSessions: map[string]*WorkspaceTab{}} |
| 70 | if got := app.reclaimRecoveryBranchesIn([]string{dir}, time.Now().Add(48*time.Hour), agent.RecoveryGCGracePeriod); got != 1 { |
| 71 | t.Fatalf("reclaimed = %d, want 1", got) |
| 72 | } |
| 73 | |
| 74 | if _, err := os.Stat(branchPath); !os.IsNotExist(err) { |
| 75 | t.Fatalf("reclaimed branch still present at %s (err=%v)", branchPath, err) |
| 76 | } |
| 77 | key := filepath.Base(branchPath) |
| 78 | trashPath := filepath.Join(dir, sessionTrashDir, key, key) |
| 79 | if _, err := os.Stat(trashPath); err != nil { |
| 80 | t.Fatalf("reclaimed branch should be in trash: %v", err) |
| 81 | } |
| 82 | if _, err := os.Stat(parentPath); err != nil { |
| 83 | t.Fatalf("parent session must be untouched: %v", err) |
| 84 | } |
| 85 | |
| 86 | // A second sweep is a no-op: nothing left to reclaim. |
| 87 | if got := app.reclaimRecoveryBranchesIn([]string{dir}, time.Now().Add(48*time.Hour), agent.RecoveryGCGracePeriod); got != 0 { |
| 88 | t.Fatalf("second sweep reclaimed = %d, want 0", got) |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | func TestRecoveryGCSkipsBranchOpenInTab(t *testing.T) { |
| 93 | isolateDesktopUserDirs(t) |
| 94 | root := globalTabWorkspaceRoot() |
| 95 | dir := desktopSessionDir(root) |
| 96 | if err := os.MkdirAll(dir, 0o755); err != nil { |
| 97 | t.Fatalf("mkdir sessions: %v", err) |
| 98 | } |
| 99 | _, branchPath := forkCoveredRecoveryBranch(t, dir, "open") |
| 100 | |
| 101 | tab := &WorkspaceTab{ID: "tab", Scope: "global", SessionPath: branchPath, Ready: true} |
| 102 | app := &App{tabs: map[string]*WorkspaceTab{"tab": tab}} |
| 103 | if got := app.reclaimRecoveryBranchesIn([]string{dir}, time.Now().Add(48*time.Hour), agent.RecoveryGCGracePeriod); got != 0 { |
| 104 | t.Fatalf("reclaimed = %d, want 0 while the branch is open in a tab", got) |
| 105 | } |
| 106 | if _, err := os.Stat(branchPath); err != nil { |
| 107 | t.Fatalf("open branch must be untouched: %v", err) |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | // TestRecoveryGCFirstSweepWaitsForTabRestore forces the startup race the |
| 112 | // review caught: a saved recovery tab exists in desktop-tabs.json but a.tabs |
| 113 | // has not been populated yet. The GC's first sweep must wait for the restore |
| 114 | // gate — sweeping early would judge the branch "not open in any tab" and |
| 115 | // DeleteSession would persist the pre-restore (empty) tab list over the |
| 116 | // user's saved one. |
| 117 | func TestRecoveryGCFirstSweepWaitsForTabRestore(t *testing.T) { |
| 118 | isolateDesktopUserDirs(t) |
| 119 | root := globalTabWorkspaceRoot() |
| 120 | dir := desktopSessionDir(root) |
| 121 | if err := os.MkdirAll(dir, 0o755); err != nil { |
| 122 | t.Fatalf("mkdir sessions: %v", err) |
| 123 | } |
| 124 | _, branchPath := forkCoveredRecoveryBranch(t, dir, "startup") |
| 125 | |
| 126 | ctx := t.Context() |
| 127 | app := &App{ |
| 128 | ctx: ctx, |
| 129 | tabs: map[string]*WorkspaceTab{}, |
| 130 | tabsRestored: make(chan struct{}), |
| 131 | } |
| 132 | |
| 133 | swept := make(chan int, 1) |
| 134 | go func() { |
| 135 | select { |
| 136 | case <-app.tabsRestoredSignal(): |
| 137 | case <-ctx.Done(): |
| 138 | swept <- -1 |
| 139 | return |
| 140 | } |
| 141 | swept <- app.reclaimRecoveryBranchesIn([]string{dir}, time.Now().Add(48*time.Hour), agent.RecoveryGCGracePeriod) |
| 142 | }() |
| 143 | |
| 144 | // Gate still closed: the sweep must not have run — the branch is intact. |
| 145 | select { |
| 146 | case n := <-swept: |
| 147 | t.Fatalf("sweep ran before tab restore completed (reclaimed=%d)", n) |
| 148 | case <-time.After(100 * time.Millisecond): |
| 149 | } |
| 150 | if _, err := os.Stat(branchPath); err != nil { |
| 151 | t.Fatalf("branch touched before restore completed: %v", err) |
| 152 | } |
| 153 | |
| 154 | // Restore lands the saved tab holding the branch, then opens the gate: |
| 155 | // the sweep runs and must skip the now-open branch. |
| 156 | tab := &WorkspaceTab{ID: "tab", Scope: "global", SessionPath: branchPath, Ready: true} |
| 157 | app.mu.Lock() |
| 158 | app.tabs["tab"] = tab |
| 159 | app.mu.Unlock() |
| 160 | app.markTabsRestored() |
| 161 | |
| 162 | if n := <-swept; n != 0 { |
| 163 | t.Fatalf("post-restore sweep reclaimed = %d, want 0 (branch is open in a restored tab)", n) |
| 164 | } |
| 165 | if _, err := os.Stat(branchPath); err != nil { |
| 166 | t.Fatalf("restored tab's branch must be untouched: %v", err) |
| 167 | } |
| 168 | |
| 169 | // markTabsRestored is idempotent (restore + recover paths may both fire). |
| 170 | app.markTabsRestored() |
| 171 | } |
| 172 | |
| 173 | func TestRecoveryGCRunsDespiteSafeModeEnv(t *testing.T) { |
| 174 | // v1.20+: GC is no longer suppressed by REASONIX_SAFE_MODE. |
| 175 | isolateDesktopUserDirs(t) |
| 176 | t.Setenv("REASONIX_SAFE_MODE", "1") |
| 177 | root := globalTabWorkspaceRoot() |
| 178 | dir := desktopSessionDir(root) |
| 179 | if err := os.MkdirAll(dir, 0o755); err != nil { |
| 180 | t.Fatalf("mkdir sessions: %v", err) |
| 181 | } |
| 182 | _, branchPath := forkCoveredRecoveryBranch(t, dir, "safe") |
| 183 | |
| 184 | app := &App{tabs: map[string]*WorkspaceTab{}, detachedSessions: map[string]*WorkspaceTab{}} |
| 185 | _ = app.reclaimRecoveryBranchesIn([]string{dir}, time.Now().Add(48*time.Hour), agent.RecoveryGCGracePeriod) |
| 186 | // Branch may or may not be reclaimed depending on age/coverage; the |
| 187 | // important contract is that Safe Mode env does not force a no-op panic-free path. |
| 188 | _ = branchPath |
| 189 | } |
| 190 | |
| 191 | func TestRecoveryGCSkipsWhenBranchContinuesAfterScan(t *testing.T) { |
| 192 | // Scan marks the branch reclaimable, then a concurrent continue-edit must |
| 193 | // make DeleteRecoveryCopy refuse so unique content is never trashed. |
| 194 | isolateDesktopUserDirs(t) |
| 195 | root := globalTabWorkspaceRoot() |
| 196 | dir := desktopSessionDir(root) |
| 197 | if err := os.MkdirAll(dir, 0o755); err != nil { |
| 198 | t.Fatalf("mkdir sessions: %v", err) |
| 199 | } |
| 200 | _, branchPath := forkCoveredRecoveryBranch(t, dir, "race-edit") |
| 201 | later := time.Now().Add(48 * time.Hour) |
| 202 | reclaimable, err := agent.ReclaimableRecoveryBranches(dir, later, agent.RecoveryGCGracePeriod) |
| 203 | if err != nil { |
| 204 | t.Fatalf("ReclaimableRecoveryBranches: %v", err) |
| 205 | } |
| 206 | if len(reclaimable) != 1 || reclaimable[0] != branchPath { |
| 207 | t.Fatalf("reclaimable = %v, want only %s", reclaimable, branchPath) |
| 208 | } |
| 209 | branch, err := agent.LoadSession(branchPath) |
| 210 | if err != nil { |
| 211 | t.Fatalf("LoadSession: %v", err) |
| 212 | } |
| 213 | branch.Add(provider.Message{Role: provider.RoleAssistant, Content: "continued after scan"}) |
| 214 | if err := branch.Save(branchPath); err != nil { |
| 215 | t.Fatalf("Save continued branch: %v", err) |
| 216 | } |
| 217 | app := NewApp() |
| 218 | if got := app.reclaimRecoveryBranchesIn([]string{dir}, later, agent.RecoveryGCGracePeriod); got != 0 { |
| 219 | t.Fatalf("reclaimed = %d, want 0 after post-scan continue", got) |
| 220 | } |
| 221 | if _, err := os.Stat(branchPath); err != nil { |
| 222 | t.Fatalf("continued branch must remain: %v", err) |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | func TestRecoveryGCSkipsWhenLeaseAcquiredAfterScan(t *testing.T) { |
| 227 | isolateDesktopUserDirs(t) |
| 228 | root := globalTabWorkspaceRoot() |
| 229 | dir := desktopSessionDir(root) |
| 230 | if err := os.MkdirAll(dir, 0o755); err != nil { |
| 231 | t.Fatalf("mkdir sessions: %v", err) |
| 232 | } |
| 233 | _, branchPath := forkCoveredRecoveryBranch(t, dir, "race-lease") |
| 234 | later := time.Now().Add(48 * time.Hour) |
| 235 | reclaimable, err := agent.ReclaimableRecoveryBranches(dir, later, agent.RecoveryGCGracePeriod) |
| 236 | if err != nil { |
| 237 | t.Fatalf("ReclaimableRecoveryBranches: %v", err) |
| 238 | } |
| 239 | if len(reclaimable) != 1 { |
| 240 | t.Fatalf("reclaimable = %v, want one path", reclaimable) |
| 241 | } |
| 242 | lease, err := agent.TryAcquireSessionLease(branchPath) |
| 243 | if err != nil { |
| 244 | t.Fatalf("TryAcquireSessionLease: %v", err) |
| 245 | } |
| 246 | defer lease.Release() |
| 247 | app := NewApp() |
| 248 | if got := app.reclaimRecoveryBranchesIn([]string{dir}, later, agent.RecoveryGCGracePeriod); got != 0 { |
| 249 | t.Fatalf("reclaimed = %d, want 0 while lease held", got) |
| 250 | } |
| 251 | if _, err := os.Stat(branchPath); err != nil { |
| 252 | t.Fatalf("leased branch must remain: %v", err) |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | func TestRecoveryGCUsesDeleteRecoveryCopyNotDeleteSession(t *testing.T) { |
| 257 | source, err := os.ReadFile("recovery_gc.go") |
| 258 | if err != nil { |
| 259 | t.Fatal(err) |
| 260 | } |
| 261 | text := string(source) |
| 262 | if !strings.Contains(text, "DeleteRecoveryCopy(path)") { |
| 263 | t.Fatal("background recovery GC must call DeleteRecoveryCopy") |
| 264 | } |
| 265 | if strings.Contains(text, "DeleteSession(path)") { |
| 266 | t.Fatal("background recovery GC must not use unguarded DeleteSession") |
| 267 | } |
| 268 | } |
| 269 |