| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "path/filepath" |
| 6 | "testing" |
| 7 | |
| 8 | "reasonix/internal/agent" |
| 9 | "reasonix/internal/control" |
| 10 | "reasonix/internal/event" |
| 11 | "reasonix/internal/provider" |
| 12 | ) |
| 13 | |
| 14 | func TestDesktopBranchTransitionMovesLeaseAndTabAtomically(t *testing.T) { |
| 15 | dir := schemaOneTempDir(t) |
| 16 | originalPath := filepath.Join(dir, "session.jsonl") |
| 17 | sess := agent.NewSession("sys") |
| 18 | sess.Add(provider.Message{Role: provider.RoleUser, Content: "hello"}) |
| 19 | if err := sess.SaveIfAbsent(originalPath); err != nil { |
| 20 | t.Fatal(err) |
| 21 | } |
| 22 | ag := agent.New(nil, nil, sess, agent.Options{}, event.Discard) |
| 23 | app := &App{ |
| 24 | ctx: context.Background(), |
| 25 | tabs: map[string]*WorkspaceTab{}, |
| 26 | detachedSessions: map[string]*WorkspaceTab{}, |
| 27 | } |
| 28 | tab := &WorkspaceTab{ID: "tab", SessionPath: originalPath, Ready: true} |
| 29 | ctrl := newFixtureController(t, control.Options{ |
| 30 | Runner: ag, |
| 31 | Executor: ag, |
| 32 | SessionDir: dir, |
| 33 | SessionPath: originalPath, |
| 34 | Sink: event.Discard, |
| 35 | OnSessionTransition: app.handleTabSessionTransition(tab), |
| 36 | }) |
| 37 | tab.Ctrl = ctrl |
| 38 | app.tabs[tab.ID] = tab |
| 39 | app.tabOrder = []string{tab.ID} |
| 40 | app.mu.Lock() |
| 41 | app.newSessionRuntimeLocked(tab, sessionRuntimeKey(originalPath)) |
| 42 | app.mu.Unlock() |
| 43 | if err := tab.ensureSessionLease(originalPath); err != nil { |
| 44 | t.Fatal(err) |
| 45 | } |
| 46 | defer tab.releaseSessionLease() |
| 47 | if err := bindTabWriteAuthority(tab, ctrl); err != nil { |
| 48 | t.Fatal(err) |
| 49 | } |
| 50 | |
| 51 | branchPath, err := ctrl.Branch("child") |
| 52 | if err != nil { |
| 53 | t.Fatalf("Branch: %v", err) |
| 54 | } |
| 55 | if tab.SessionPath != branchPath || ctrl.SessionPath() != branchPath { |
| 56 | t.Fatalf("tab/controller paths = %q/%q, want %q", tab.SessionPath, ctrl.SessionPath(), branchPath) |
| 57 | } |
| 58 | tab.sessionLeaseMu.Lock() |
| 59 | lease := tab.sessionLease |
| 60 | tab.sessionLeaseMu.Unlock() |
| 61 | if lease == nil || lease.Path() != agent.CanonicalSessionPath(branchPath) { |
| 62 | t.Fatalf("tab lease = %v, want branch path", lease) |
| 63 | } |
| 64 | if auth := ag.Session().WriteAuthority(); auth == nil || !auth.Covers(branchPath) { |
| 65 | t.Fatal("branch Session was published without target authority") |
| 66 | } |
| 67 | old, err := agent.TryAcquireSessionLease(originalPath) |
| 68 | if err != nil { |
| 69 | t.Fatalf("source lease remained held: %v", err) |
| 70 | } |
| 71 | old.Release() |
| 72 | app.mu.Lock() |
| 73 | runtime := app.runtimeBySessionKey[sessionRuntimeKey(branchPath)] |
| 74 | app.mu.Unlock() |
| 75 | if runtime == nil || runtime.Owner != tab { |
| 76 | t.Fatal("runtime registry did not move to branch path") |
| 77 | } |
| 78 | } |
| 79 |