1package subagents
2
3import (
4 "context"
5 "fmt"
6 "testing"
7 "time"
8)
9
10func TestResidentManagerSnapshotPageAndLookupAreBounded(t *testing.T) {
11 manager := NewResidentManager(t.TempDir(), func(ResidentChildSpec, *ResidentJournal) (ResidentRuntime, error) {
12 return ResidentTurnRunner(func(context.Context, string) error { return nil }), nil
13 })
14 t.Cleanup(func() { _ = manager.Close(context.Background()) })
15 for i := 0; i < 5; i++ {
16 spec := ResidentChildSpec{ID: fmt.Sprintf("child-%d", i), SessionID: fmt.Sprintf("session-%d", i), Provider: "openai", Model: "gpt-5"}
17 if _, err := manager.Spawn(context.Background(), spec, "task"); err != nil {
18 t.Fatal(err)
19 }
20 }
21 page, total := manager.SnapshotPage(2, 2)
22 if total != 5 || len(page) != 2 || page[0].ID != "child-2" || page[1].ID != "child-3" {
23 t.Fatalf("page/total = %#v/%d", page, total)
24 }
25 snapshot, ok := manager.SnapshotFor("child-4")
26 if !ok || snapshot.ID != "child-4" {
27 t.Fatalf("single snapshot = %#v, %t", snapshot, ok)
28 }
29}
30
31func TestResidentManagerRecentSnapshotPageOrdersLatestTransitionFirst(t *testing.T) {
32 now := time.Date(2026, time.August, 13, 12, 0, 0, 0, time.UTC)
33 manager := &ResidentManager{children: map[string]*ResidentChild{}, recovered: map[string]ResidentSnapshot{
34 "older": {ID: "older", State: ResidentIdle, UpdatedAt: now.Add(-time.Hour)},
35 "newer": {ID: "newer", State: ResidentRunning, UpdatedAt: now.Add(-time.Minute)},
36 }, recoveredSpec: map[string]ResidentChildSpec{}, pending: map[string]struct{}{}}
37 page, total := manager.RecentSnapshotPage(0, 1)
38 if total != 2 || len(page) != 1 || page[0].ID != "newer" {
39 t.Fatalf("recent page = %#v/%d", page, total)
40 }
41}
42
43func TestResidentManagerActiveSnapshotPageSkipsForeignActiveChildren(t *testing.T) {
44 now := time.Date(2026, time.August, 13, 12, 0, 0, 0, time.UTC)
45 manager := &ResidentManager{children: map[string]*ResidentChild{}, recovered: map[string]ResidentSnapshot{
46 "foreign": {ID: "foreign", State: ResidentRunning, OwnedElsewhere: true, UpdatedAt: now},
47 "local-newer": {ID: "local-newer", State: ResidentRunning, UpdatedAt: now.Add(-time.Minute)},
48 "local-older": {ID: "local-older", State: ResidentQueued, UpdatedAt: now.Add(-time.Hour)},
49 "idle": {ID: "idle", State: ResidentIdle, UpdatedAt: now.Add(time.Minute)},
50 }, recoveredSpec: map[string]ResidentChildSpec{}, pending: map[string]struct{}{}}
51 page, total := manager.ActiveSnapshotPage(1)
52 if total != 2 || len(page) != 1 || page[0].ID != "local-newer" {
53 t.Fatalf("active page = %#v/%d, want bounded same-host active children", page, total)
54 }
55}