| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "strings" |
| 7 | "testing" |
| 8 | "time" |
| 9 | |
| 10 | "amadan.net/oficina/equipo/internal/wire" |
| 11 | ) |
| 12 | |
| 13 | // pausedRig is a task whose Engineering step is held on RUNNER1, with the |
| 14 | // creator's connections as given. Its clock is Paul's: Tuesday 24 |
| 15 | // November 2026, noon in Dublin. |
| 16 | func pausedRig(t *testing.T, hold wire.StepHold, conns ...connectionRecord) (*meteredRig, time.Time) { |
| 17 | return pausedRigAt(t, wire.ProtocolPinnedRelease, wire.SpecialistEngineering, hold, conns...) |
| 18 | } |
| 19 | |
| 20 | // pausedRigAt is pausedRig with the runner at protocol, holding a step of |
| 21 | // specialist. |
| 22 | func pausedRigAt(t *testing.T, protocol int, specialist string, hold wire.StepHold, conns ...connectionRecord) (*meteredRig, time.Time) { |
| 23 | t.Helper() |
| 24 | r := newMeteredRig(t) |
| 25 | now := time.Date(2026, 11, 24, 12, 0, 0, 0, time.UTC) |
| 26 | r.s.now = func() time.Time { return now } |
| 27 | g := r.s.db.G |
| 28 | // The rig's own connections are not this test's. |
| 29 | if err := g.Where("1 = 1").Delete(&connectionRecord{}).Error; err != nil { |
| 30 | t.Fatal(err) |
| 31 | } |
| 32 | for _, c := range conns { |
| 33 | c.Person, c.RunnerID, c.Revision, c.CreatedAt, c.UpdatedAt = "owner@example.com", "RUNNER1", 1, now, now |
| 34 | if err := g.Create(&c).Error; err != nil { |
| 35 | t.Fatal(err) |
| 36 | } |
| 37 | } |
| 38 | if err := g.Create(&projectRecord{ID: "p_1", Repo: "amadan.net/oficina/sample", State: wire.ProjectActive, CreatedAt: now, UpdatedAt: now}).Error; err != nil { |
| 39 | t.Fatal(err) |
| 40 | } |
| 41 | if err := g.Create(&taskRecord{ID: "tk1", ProjectID: "p_1", Title: "Swipe down to dismiss the keyboard on iOS", Stage: wire.StageInProgress, Creator: "owner@example.com", Revision: 3, CreatedAt: now, UpdatedAt: now}).Error; err != nil { |
| 42 | t.Fatal(err) |
| 43 | } |
| 44 | held := now.Add(-3 * time.Hour) |
| 45 | if err := g.Create(&stepRecord{ID: "s1", TaskID: "tk1", Idx: 1, Specialist: specialist, Person: "owner@example.com", RunnerID: "RUNNER1", State: wire.StepRunning, Attempt: 1, Hold: asJSON(hold), HeldAt: &held, Revision: 1, CreatedAt: now, UpdatedAt: now}).Error; err != nil { |
| 46 | t.Fatal(err) |
| 47 | } |
| 48 | if err := g.Exec("CREATE TABLE IF NOT EXISTS runners (id text PRIMARY KEY, person text, role text, label text, removing_at datetime, tainted_at datetime, revoked_at datetime)").Error; err != nil { |
| 49 | t.Fatal(err) |
| 50 | } |
| 51 | if err := g.Exec("INSERT INTO runners(id, person, role, label) VALUES ('RUNNER1', 'owner@example.com', 'primary', 'Paul’s Mac mini')").Error; err != nil { |
| 52 | t.Fatal(err) |
| 53 | } |
| 54 | if err := g.Create(&runnerSessionRecord{RunnerID: "RUNNER1", Connected: true, SeenAt: now, Protocol: protocol}).Error; err != nil { |
| 55 | t.Fatal(err) |
| 56 | } |
| 57 | return r, now |
| 58 | } |
| 59 | |
| 60 | func headroom(used float64, resets time.Time) string { |
| 61 | return asJSON(wire.Headroom{ResetsAt: &resets, Windows: []wire.Window{{Name: "five_hour", UsedPercent: used, Minutes: 300, ResetsAt: &resets}}}) |
| 62 | } |
| 63 | |
| 64 | func pausedOf(t *testing.T, r *meteredRig) *wire.StepPaused { |
| 65 | t.Helper() |
| 66 | task, err := r.s.Task(context.Background(), "owner@example.com", "tk1") |
| 67 | if err != nil { |
| 68 | t.Fatal(err) |
| 69 | } |
| 70 | for _, s := range task.Steps { |
| 71 | if s.ID == "s1" { |
| 72 | return s.Paused |
| 73 | } |
| 74 | } |
| 75 | t.Fatal("no step s1") |
| 76 | return nil |
| 77 | } |
| 78 | |
| 79 | // Paul's case: the Claude allowance ran out and resets at 21:00 UTC; |
| 80 | // Codex has room. Run now would take Codex, and says so. |
| 81 | func TestRunNowPredictsCodexWhenClaudeIsOut(t *testing.T) { |
| 82 | reset := time.Date(2026, 11, 24, 21, 0, 0, 0, time.UTC) |
| 83 | r, now := pausedRig(t, wire.StepHold{Reason: wire.HoldHeadroom, Connection: "claude-1", Provider: wire.ProviderClaude, ResetsAt: &reset, WakeAt: &reset, StepRevision: 1}, |
| 84 | connectionRecord{ID: "cn_claude", LocalID: "claude-1", Provider: wire.ProviderClaude, Kind: wire.KindToken, State: wire.ConnLimited, Headroom: headroom(100, reset)}, |
| 85 | connectionRecord{ID: "cn_codex", LocalID: "codex-1", Provider: wire.ProviderCodex, Kind: wire.KindToken, State: wire.ConnHealthy, Headroom: headroom(12, reset.Add(48*time.Hour))}, |
| 86 | ) |
| 87 | p := pausedOf(t, r) |
| 88 | if p == nil || p.RunNow == nil { |
| 89 | t.Fatalf("no offer: %+v", p) |
| 90 | } |
| 91 | if o := *p.RunNow; o.Connection != "cn_codex" || o.Name != "Codex" || o.Billing != wire.BillingSubscription || o.Same { |
| 92 | t.Fatalf("offer %+v", o) |
| 93 | } |
| 94 | if p.UsedPercent == nil || *p.UsedPercent != 100 { |
| 95 | t.Fatalf("used %v", p.UsedPercent) |
| 96 | } |
| 97 | if p.Since == nil || !p.Since.Equal(now.Add(-3*time.Hour)) || p.Offline { |
| 98 | t.Fatalf("since %v offline %v", p.Since, p.Offline) |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | // Claude is 85% used (Equipo keeps the rest for urgent work) and Codex |
| 103 | // is fuller: Run now would use Claude's last share. |
| 104 | func TestRunNowPredictsTheLastShare(t *testing.T) { |
| 105 | reset := time.Date(2026, 11, 24, 21, 0, 0, 0, time.UTC) |
| 106 | r, _ := pausedRig(t, wire.StepHold{Reason: wire.HoldHeadroom, Connection: "claude-1", Provider: wire.ProviderClaude, ResetsAt: &reset, WakeAt: &reset, StepRevision: 1}, |
| 107 | connectionRecord{ID: "cn_claude", LocalID: "claude-1", Provider: wire.ProviderClaude, Kind: wire.KindToken, State: wire.ConnHealthy, Headroom: headroom(85, reset)}, |
| 108 | connectionRecord{ID: "cn_codex", LocalID: "codex-1", Provider: wire.ProviderCodex, Kind: wire.KindToken, State: wire.ConnHealthy, Headroom: headroom(96, reset)}, |
| 109 | ) |
| 110 | p := pausedOf(t, r) |
| 111 | if p == nil || p.RunNow == nil || p.RunNow.Connection != "cn_claude" || !p.RunNow.Same || p.RunNow.LeftPercent != 15 { |
| 112 | t.Fatalf("offer %+v", p) |
| 113 | } |
| 114 | if *p.UsedPercent != 85 { |
| 115 | t.Fatalf("used %d", *p.UsedPercent) |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | // Nothing else can run it: no offer, and none for a spending bar. |
| 120 | func TestRunNowOffersNothingItCannotDo(t *testing.T) { |
| 121 | reset := time.Date(2026, 11, 24, 21, 0, 0, 0, time.UTC) |
| 122 | r, _ := pausedRig(t, wire.StepHold{Reason: wire.HoldHeadroom, Connection: "claude-1", Provider: wire.ProviderClaude, ResetsAt: &reset, WakeAt: &reset, StepRevision: 1}, |
| 123 | connectionRecord{ID: "cn_claude", LocalID: "claude-1", Provider: wire.ProviderClaude, Kind: wire.KindToken, State: wire.ConnLimited, Headroom: headroom(100, reset)}, |
| 124 | ) |
| 125 | if p := pausedOf(t, r); p == nil || p.RunNow != nil { |
| 126 | t.Fatalf("offer with nothing to run on: %+v", p) |
| 127 | } |
| 128 | r2, _ := pausedRig(t, wire.StepHold{Reason: wire.HoldBudget, Connection: "tensorx-1", Provider: wire.ProviderTensorX, WakeAt: &reset, StepRevision: 1}, |
| 129 | connectionRecord{ID: "cn_codex", LocalID: "codex-1", Provider: wire.ProviderCodex, Kind: wire.KindToken, State: wire.ConnHealthy, Headroom: headroom(10, reset)}, |
| 130 | ) |
| 131 | if p := pausedOf(t, r2); p == nil || p.RunNow != nil { |
| 132 | t.Fatalf("offer past a spending bar: %+v", p) |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | // A metered connection with room is what Run now would use when no |
| 137 | // subscription can: it bills per use, and says so. |
| 138 | func TestRunNowPredictsMetered(t *testing.T) { |
| 139 | reset := time.Date(2026, 11, 24, 21, 0, 0, 0, time.UTC) |
| 140 | r, _ := pausedRig(t, wire.StepHold{Reason: wire.HoldNoConnection, NeedsPerson: wire.HoldNeedsNoConnection, StepRevision: 1}, |
| 141 | connectionRecord{ID: "cn_claude", LocalID: "claude-1", Provider: wire.ProviderClaude, Kind: wire.KindToken, State: wire.ConnLimited, Headroom: headroom(100, reset)}, |
| 142 | connectionRecord{ID: "cn_tx", LocalID: "tensorx-1", Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, Harness: "pi", State: wire.ConnHealthy, Billing: wire.BillingMetered, |
| 143 | Budget: `{"day":1000000,"month":10000000,"currency":"USD","revision":1}`, BudgetApplied: 1, Spend: `{"day":0,"month":0,"currency":"USD","unknown":false,"running":false}`, |
| 144 | Models: `["z-ai/glm-5.3"]`, ModelsListed: `[{"id":"z-ai/glm-5.3","eligible":true,"family":"glm","tier":"strong"}]`}, |
| 145 | ) |
| 146 | p := pausedOf(t, r) |
| 147 | if p == nil || p.RunNow == nil || p.RunNow.Connection != "cn_tx" || p.RunNow.Billing != wire.BillingMetered || p.RunNow.Name != "TensorX" { |
| 148 | t.Fatalf("offer %+v", p) |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | // The step waits for its runner, which is offline: paused since it was |
| 153 | // last seen, with no Run now. |
| 154 | func TestPausedWhileTheRunnerIsOffline(t *testing.T) { |
| 155 | r, now := pausedRig(t, wire.StepHold{}) |
| 156 | g := r.s.db.G |
| 157 | seen := now.Add(-40 * time.Minute) |
| 158 | if err := g.Exec("UPDATE runner_sessions SET connected = ?, seen_at = ?", false, seen).Error; err != nil { |
| 159 | t.Fatal(err) |
| 160 | } |
| 161 | if err := g.Exec("UPDATE chat_steps SET hold = '', held_at = NULL, state = ?, placement = ?", wire.StepQueued, wire.PlacementWaiting).Error; err != nil { |
| 162 | t.Fatal(err) |
| 163 | } |
| 164 | p := pausedOf(t, r) |
| 165 | if p == nil || !p.Offline || p.Since == nil || !p.Since.Equal(seen) || p.RunNow != nil { |
| 166 | t.Fatalf("offline %+v", p) |
| 167 | } |
| 168 | // Back online: nothing waits. |
| 169 | if err := g.Exec("UPDATE runner_sessions SET connected = ?, seen_at = ?", true, now).Error; err != nil { |
| 170 | t.Fatal(err) |
| 171 | } |
| 172 | if p := pausedOf(t, r); p != nil { |
| 173 | t.Fatalf("online %+v", p) |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | func tensorxConn() connectionRecord { |
| 178 | return connectionRecord{ID: "cn_tx", LocalID: "tensorx-1", Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, Harness: "pi", State: wire.ConnHealthy, Billing: wire.BillingMetered, |
| 179 | Budget: `{"day":1000000,"month":10000000,"currency":"USD","revision":1}`, BudgetApplied: 1, Spend: `{"day":0,"month":0,"currency":"USD","unknown":false,"running":false}`, |
| 180 | Models: `["z-ai/glm-5.3"]`, ModelsListed: `[{"id":"z-ai/glm-5.3","eligible":true,"family":"glm","tier":"strong"}]`} |
| 181 | } |
| 182 | |
| 183 | // Fable's scenario (review B1): Engineering ran on Claude; Review is held; |
| 184 | // Codex is at its limit, Claude is 85% used, TensorX has budget. The |
| 185 | // family rule with leave puts TensorX first, so the instance says so |
| 186 | // (bills per use, no carry_on), never "Claude has room now". |
| 187 | func TestRunNowPredictsReviewsFamilyRule(t *testing.T) { |
| 188 | reset := time.Date(2026, 11, 24, 18, 0, 0, 0, time.UTC) |
| 189 | r, _ := pausedRigAt(t, wire.ProtocolPinnedRelease, wire.SpecialistReview, wire.StepHold{Reason: wire.HoldHeadroom, Connection: "codex-1", Provider: wire.ProviderCodex, ResetsAt: &reset, StepRevision: 1}, |
| 190 | connectionRecord{ID: "cn_claude", LocalID: "claude-1", Provider: wire.ProviderClaude, Kind: wire.KindToken, State: wire.ConnHealthy, Headroom: headroom(85, reset)}, |
| 191 | connectionRecord{ID: "cn_codex", LocalID: "codex-1", Provider: wire.ProviderCodex, Kind: wire.KindToken, State: wire.ConnLimited, Headroom: headroom(100, reset)}, |
| 192 | tensorxConn(), |
| 193 | ) |
| 194 | if err := r.s.db.G.Exec("UPDATE chat_steps SET account = 'claude-1' WHERE id = 's1'").Error; err != nil { |
| 195 | t.Fatal(err) |
| 196 | } |
| 197 | if err := r.s.db.G.Create(&stepRecord{ID: "s0", TaskID: "tk1", Idx: 0, Specialist: wire.SpecialistEngineering, Person: "owner@example.com", RunnerID: "RUNNER1", State: wire.StepDone, Attempt: 1, Account: "claude-1", Family: "claude", Pushed: true, Revision: 1, CreatedAt: reset, UpdatedAt: reset}).Error; err != nil { |
| 198 | t.Fatal(err) |
| 199 | } |
| 200 | p := pausedOf(t, r) |
| 201 | if p == nil || p.RunNow == nil || p.RunNow.Connection != "cn_tx" || p.RunNow.Billing != wire.BillingMetered { |
| 202 | t.Fatalf("Review's prediction: %+v", p.RunNow) |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | // A fix round resumes its kept metered session with leave: the |
| 207 | // prediction says TensorX, as the runner would, not Codex. |
| 208 | func TestRunNowPredictsAKeptSession(t *testing.T) { |
| 209 | reset := time.Date(2026, 11, 24, 18, 0, 0, 0, time.UTC) |
| 210 | r, _ := pausedRig(t, wire.StepHold{Reason: wire.HoldHeadroom, Connection: "claude-1", Provider: wire.ProviderClaude, ResetsAt: &reset, StepRevision: 1}, |
| 211 | connectionRecord{ID: "cn_codex", LocalID: "codex-1", Provider: wire.ProviderCodex, Kind: wire.KindToken, State: wire.ConnHealthy, Headroom: headroom(10, reset)}, |
| 212 | tensorxConn(), |
| 213 | ) |
| 214 | if err := r.s.db.G.Exec("UPDATE chat_steps SET round = 1, idx = 2 WHERE id = 's1'").Error; err != nil { |
| 215 | t.Fatal(err) |
| 216 | } |
| 217 | if err := r.s.db.G.Create(&stepRecord{ID: "s0", TaskID: "tk1", Idx: 1, Specialist: wire.SpecialistEngineering, Person: "owner@example.com", RunnerID: "RUNNER1", State: wire.StepDone, Attempt: 1, Account: "tensorx-1", Model: "z-ai/glm-5.3", Revision: 1, CreatedAt: reset, UpdatedAt: reset}).Error; err != nil { |
| 218 | t.Fatal(err) |
| 219 | } |
| 220 | if p := pausedOf(t, r); p == nil || p.RunNow == nil || p.RunNow.Connection != "cn_tx" { |
| 221 | t.Fatalf("a kept session's prediction: %+v", p.RunNow) |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | // A runner below protocol 29 cannot be held to one connection: Run now |
| 226 | // promises nothing (plain), and names no model. |
| 227 | func TestRunNowIsPlainForAnOlderRunner(t *testing.T) { |
| 228 | reset := time.Date(2026, 11, 24, 21, 0, 0, 0, time.UTC) |
| 229 | r, _ := pausedRigAt(t, wire.Protocol28, wire.SpecialistEngineering, wire.StepHold{Reason: wire.HoldHeadroom, Connection: "claude-1", Provider: wire.ProviderClaude, ResetsAt: &reset, StepRevision: 1}, |
| 230 | connectionRecord{ID: "cn_codex", LocalID: "codex-1", Provider: wire.ProviderCodex, Kind: wire.KindToken, State: wire.ConnHealthy, Headroom: headroom(10, reset)}, |
| 231 | ) |
| 232 | p := pausedOf(t, r) |
| 233 | if p == nil || p.RunNow == nil || !p.RunNow.Plain || p.RunNow.Name != "" || p.RunNow.Connection != "" { |
| 234 | t.Fatalf("an older runner's offer: %+v", p.RunNow) |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | // S2: once Run now is written for the hold, it is not offered again, and |
| 239 | // a second tap says it is already on its way. The release is pinned to |
| 240 | // the connection the person was shown. |
| 241 | func TestRunNowOnceAndPinned(t *testing.T) { |
| 242 | reset := time.Date(2026, 11, 24, 21, 0, 0, 0, time.UTC) |
| 243 | r, _ := pausedRig(t, wire.StepHold{Reason: wire.HoldHeadroom, Connection: "claude-1", Provider: wire.ProviderClaude, ResetsAt: &reset, StepRevision: 1}, |
| 244 | connectionRecord{ID: "cn_claude", LocalID: "claude-1", Provider: wire.ProviderClaude, Kind: wire.KindToken, State: wire.ConnLimited, Headroom: headroom(100, reset)}, |
| 245 | connectionRecord{ID: "cn_codex", LocalID: "codex-1", Provider: wire.ProviderCodex, Kind: wire.KindToken, State: wire.ConnHealthy, Headroom: headroom(10, reset)}, |
| 246 | ) |
| 247 | ctx := context.Background() |
| 248 | if _, err := r.s.RunNow(ctx, "owner@example.com", "tk1", wire.RunNow{Step: "s1", StepRevision: 1, Offer: "cn_codex"}); err != nil { |
| 249 | t.Fatal(err) |
| 250 | } |
| 251 | var rel releaseRecord |
| 252 | if err := r.s.db.G.Where("step_id = 's1'").First(&rel).Error; err != nil || rel.Connection != "codex-1" { |
| 253 | t.Fatalf("release %+v %v", rel, err) |
| 254 | } |
| 255 | var body string |
| 256 | r.s.db.G.Raw("SELECT body FROM runner_commands WHERE kind = ?", wire.FrameRelease).Scan(&body) |
| 257 | if !strings.Contains(body, `"connection":"codex-1"`) { |
| 258 | t.Fatalf("the release frame is not pinned: %s", body) |
| 259 | } |
| 260 | if p := pausedOf(t, r); p == nil || p.RunNow != nil { |
| 261 | t.Fatalf("offered again after the release: %+v", p) |
| 262 | } |
| 263 | if _, err := r.s.RunNow(ctx, "owner@example.com", "tk1", wire.RunNow{Step: "s1", StepRevision: 1, Offer: "cn_codex"}); !errors.Is(err, ErrAlreadyReleased) { |
| 264 | t.Fatalf("a second tap: %v", err) |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | // S1: one job card that cannot be projected never stops the minute's |
| 269 | // sweep: it is logged and skipped, and the next card is brought up to |
| 270 | // date in its own transaction. |
| 271 | func TestRefreshJobsSkipsAFailingCard(t *testing.T) { |
| 272 | r := newMeteredRig(t) |
| 273 | now := r.s.now() |
| 274 | g := r.s.db.G |
| 275 | for i, id := range []string{"h_bad", "h_good"} { |
| 276 | if err := g.Create(&handoffRecord{ID: id, Person: "owner@example.com", LedgerKey: id, State: handoffOpen, Lane: wire.JobLane(id), CreatedAt: now, UpdatedAt: now}).Error; err != nil { |
| 277 | t.Fatal(err) |
| 278 | } |
| 279 | if err := g.Create(&cardRecord{ID: "c_" + id, Person: "owner@example.com", Kind: wire.CardJob, State: wire.JobWorking, Lane: wire.LaneAssistant, HandoffID: id, Options: "[]", Links: "[]", Result: "stale words", Revision: 1, CreatedAt: now.Add(time.Duration(i) * time.Second), UpdatedAt: now}).Error; err != nil { |
| 280 | t.Fatal(err) |
| 281 | } |
| 282 | } |
| 283 | r.s.projectJobHook = func(t *txn, h handoffRecord) error { |
| 284 | if h.ID == "h_bad" { |
| 285 | return errors.New("a card that cannot be projected") |
| 286 | } |
| 287 | return t.projectJob(h) |
| 288 | } |
| 289 | r.s.refreshJobs(context.Background()) |
| 290 | var good cardRecord |
| 291 | if err := g.Where("id = 'c_h_good'").First(&good).Error; err != nil || good.Result == "stale words" { |
| 292 | t.Fatalf("the card after a failing one was not refreshed: %+v %v", good, err) |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | // pausedJob follows the rig's task with a hand-off and projects its job |
| 297 | // card, as Base would read it. |
| 298 | func pausedJob(t *testing.T, r *meteredRig) wire.AssistantCard { |
| 299 | t.Helper() |
| 300 | now := r.s.now() |
| 301 | g := r.s.db.G |
| 302 | h := handoffRecord{ID: "h_job1", Person: "owner@example.com", LedgerKey: "h_job1", State: handoffOpen, Lane: wire.JobLane("h_job1"), Title: "Bakery website", CreatedAt: now, UpdatedAt: now} |
| 303 | if err := g.Create(&h).Error; err != nil { |
| 304 | t.Fatal(err) |
| 305 | } |
| 306 | if err := g.Create(&handoffTaskRecord{HandoffID: h.ID, TaskID: "tk1"}).Error; err != nil { |
| 307 | t.Fatal(err) |
| 308 | } |
| 309 | r.s.refreshJobs(context.Background()) |
| 310 | var out wire.AssistantCard |
| 311 | if err := r.s.tx(context.Background(), func(tx *txn) error { |
| 312 | if err := tx.projectJob(h); err != nil { |
| 313 | return err |
| 314 | } |
| 315 | c, ok, err := tx.jobCard(h) |
| 316 | if err != nil || !ok { |
| 317 | return errors.Join(err, errors.New("no job card")) |
| 318 | } |
| 319 | out, err = tx.assistantCardView(c) |
| 320 | return err |
| 321 | }); err != nil { |
| 322 | t.Fatal(err) |
| 323 | } |
| 324 | return out |
| 325 | } |
| 326 | |
| 327 | // Carry on now's edges (review N12): another person's job card is not |
| 328 | // found; a prediction on a metered connection offers no Carry on now (it |
| 329 | // is not "at no extra cost"); and once Run now was written, two minutes |
| 330 | // on the card is paused again without it. |
| 331 | func TestCarryOnEdges(t *testing.T) { |
| 332 | reset := time.Date(2026, 11, 24, 21, 0, 0, 0, time.UTC) |
| 333 | ctx := context.Background() |
| 334 | r, now := pausedRig(t, wire.StepHold{Reason: wire.HoldHeadroom, Connection: "claude-1", Provider: wire.ProviderClaude, ResetsAt: &reset, WakeAt: &reset, StepRevision: 1}, |
| 335 | connectionRecord{ID: "cn_claude", LocalID: "claude-1", Provider: wire.ProviderClaude, Kind: wire.KindToken, State: wire.ConnLimited, Headroom: headroom(100, reset)}, |
| 336 | connectionRecord{ID: "cn_codex", LocalID: "codex-1", Provider: wire.ProviderCodex, Kind: wire.KindToken, State: wire.ConnHealthy, Headroom: headroom(10, reset)}, |
| 337 | ) |
| 338 | card := pausedJob(t, r) |
| 339 | if card.State != wire.JobPaused || !card.CarryOn { |
| 340 | t.Fatalf("the job card %+v", card) |
| 341 | } |
| 342 | if _, err := r.s.CarryOn(ctx, "other@example.com", card.ID, wire.CarryOn{Revision: card.Revision, IdempotencyKey: "k"}); !errors.Is(err, ErrNotFound) { |
| 343 | t.Fatalf("another person's card: %v", err) |
| 344 | } |
| 345 | // Run now was written three minutes ago and the runner still holds |
| 346 | // the step: paused again, with no Carry on now. |
| 347 | if err := r.s.db.G.Create(&releaseRecord{ID: "rl_old", TaskID: "tk1", StepID: "s1", StepRevision: 1, Person: "owner@example.com", RunnerID: "RUNNER1", Connection: "codex-1", CreatedAt: now.Add(-3 * time.Minute)}).Error; err != nil { |
| 348 | t.Fatal(err) |
| 349 | } |
| 350 | r.s.refreshJobs(ctx) |
| 351 | after := pausedJob2(t, r, card.ID) |
| 352 | if after.State != wire.JobPaused || after.CarryOn { |
| 353 | t.Fatalf("after an old release: %+v", after) |
| 354 | } |
| 355 | if _, err := r.s.CarryOn(ctx, "owner@example.com", card.ID, wire.CarryOn{Revision: after.Revision, IdempotencyKey: "k2"}); !errors.Is(err, ErrCarryOnUnavailable) { |
| 356 | t.Fatalf("carry on after an old release: %v", err) |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | // pausedJob2 reads one job card as Base would. |
| 361 | func pausedJob2(t *testing.T, r *meteredRig, id string) (out wire.AssistantCard) { |
| 362 | t.Helper() |
| 363 | if err := r.s.tx(context.Background(), func(tx *txn) error { |
| 364 | var err error |
| 365 | out, err = tx.assistantCardOf(id) |
| 366 | return err |
| 367 | }); err != nil { |
| 368 | t.Fatal(err) |
| 369 | } |
| 370 | return out |
| 371 | } |
| 372 | |
| 373 | // A metered prediction is no Carry on now: it bills. |
| 374 | func TestCarryOnNeverForMetered(t *testing.T) { |
| 375 | reset := time.Date(2026, 11, 24, 21, 0, 0, 0, time.UTC) |
| 376 | r, _ := pausedRig(t, wire.StepHold{Reason: wire.HoldHeadroom, Connection: "claude-1", Provider: wire.ProviderClaude, ResetsAt: &reset, WakeAt: &reset, StepRevision: 1}, |
| 377 | connectionRecord{ID: "cn_claude", LocalID: "claude-1", Provider: wire.ProviderClaude, Kind: wire.KindToken, State: wire.ConnLimited, Headroom: headroom(100, reset)}, |
| 378 | tensorxConn(), |
| 379 | ) |
| 380 | card := pausedJob(t, r) |
| 381 | if card.State != wire.JobPaused || card.CarryOn { |
| 382 | t.Fatalf("a metered prediction offered Carry on now: %+v", card) |
| 383 | } |
| 384 | } |
| 385 | |
| 386 | // Review R2: the family rule compares the runner's families, and Codex's |
| 387 | // is gpt. Engineering ran on Codex; Review is held; Claude is at its |
| 388 | // limit, Codex is 85% used and TensorX has budget. With leave the runner |
| 389 | // tries another family than gpt first, so TensorX, and the instance says |
| 390 | // so, not "Codex has room now". |
| 391 | func TestRunNowPredictsReviewAfterCodex(t *testing.T) { |
| 392 | reset := time.Date(2026, 11, 24, 18, 0, 0, 0, time.UTC) |
| 393 | r, _ := pausedRigAt(t, wire.ProtocolPinnedRelease, wire.SpecialistReview, wire.StepHold{Reason: wire.HoldHeadroom, Connection: "claude-1", Provider: wire.ProviderClaude, ResetsAt: &reset, StepRevision: 1}, |
| 394 | connectionRecord{ID: "cn_claude", LocalID: "claude-1", Provider: wire.ProviderClaude, Kind: wire.KindToken, State: wire.ConnLimited, Headroom: headroom(100, reset)}, |
| 395 | connectionRecord{ID: "cn_codex", LocalID: "codex-1", Provider: wire.ProviderCodex, Kind: wire.KindToken, State: wire.ConnHealthy, Headroom: headroom(85, reset)}, |
| 396 | tensorxConn(), |
| 397 | ) |
| 398 | if err := r.s.db.G.Exec("UPDATE chat_steps SET account = 'codex-1' WHERE id = 's1'").Error; err != nil { |
| 399 | t.Fatal(err) |
| 400 | } |
| 401 | if err := r.s.db.G.Create(&stepRecord{ID: "s0", TaskID: "tk1", Idx: 0, Specialist: wire.SpecialistEngineering, Person: "owner@example.com", RunnerID: "RUNNER1", State: wire.StepDone, Attempt: 1, Account: "codex-1", Family: "gpt", Pushed: true, Revision: 1, CreatedAt: reset, UpdatedAt: reset}).Error; err != nil { |
| 402 | t.Fatal(err) |
| 403 | } |
| 404 | if p := pausedOf(t, r); p == nil || p.RunNow == nil || p.RunNow.Connection != "cn_tx" { |
| 405 | t.Fatalf("Review after Codex: %+v", p.RunNow) |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | // Review R1: the tap carries what the page showed. Claude is at its |
| 410 | // limit; the page showed "Run it now with Codex"; Codex then filled, so |
| 411 | // Run now now would use TensorX, which bills. The tap naming Codex is |
| 412 | // refused (offer_changed), and so is one naming nothing or plain; no |
| 413 | // release is written. A tap naming what is offered now is pinned there. |
| 414 | func TestRunNowRefusesAChangedOffer(t *testing.T) { |
| 415 | reset := time.Date(2026, 11, 24, 21, 0, 0, 0, time.UTC) |
| 416 | r, _ := pausedRig(t, wire.StepHold{Reason: wire.HoldHeadroom, Connection: "claude-1", Provider: wire.ProviderClaude, ResetsAt: &reset, StepRevision: 1}, |
| 417 | connectionRecord{ID: "cn_claude", LocalID: "claude-1", Provider: wire.ProviderClaude, Kind: wire.KindToken, State: wire.ConnLimited, Headroom: headroom(100, reset)}, |
| 418 | connectionRecord{ID: "cn_codex", LocalID: "codex-1", Provider: wire.ProviderCodex, Kind: wire.KindToken, State: wire.ConnHealthy, Headroom: headroom(10, reset)}, |
| 419 | tensorxConn(), |
| 420 | ) |
| 421 | ctx := context.Background() |
| 422 | if p := pausedOf(t, r); p == nil || p.RunNow == nil || p.RunNow.Connection != "cn_codex" { |
| 423 | t.Fatalf("the page shows %+v", p) |
| 424 | } |
| 425 | if err := r.s.db.G.Exec("UPDATE chat_connections SET state = ?, headroom = ? WHERE id = 'cn_codex'", wire.ConnLimited, headroom(100, reset)).Error; err != nil { |
| 426 | t.Fatal(err) |
| 427 | } |
| 428 | for _, shown := range []string{"cn_codex", wire.RunNowPlain, ""} { |
| 429 | if _, err := r.s.RunNow(ctx, "owner@example.com", "tk1", wire.RunNow{Step: "s1", StepRevision: 1, Offer: shown}); !errors.Is(err, ErrOfferChanged) { |
| 430 | t.Fatalf("a tap showing %q: %v", shown, err) |
| 431 | } |
| 432 | } |
| 433 | var n int64 |
| 434 | r.s.db.G.Model(&releaseRecord{}).Count(&n) |
| 435 | if n != 0 { |
| 436 | t.Fatalf("%d releases written for a changed offer", n) |
| 437 | } |
| 438 | if p := pausedOf(t, r); p == nil || p.RunNow == nil || p.RunNow.Connection != "cn_tx" || p.RunNow.Billing != wire.BillingMetered { |
| 439 | t.Fatalf("the page now shows %+v", p.RunNow) |
| 440 | } |
| 441 | if _, err := r.s.RunNow(ctx, "owner@example.com", "tk1", wire.RunNow{Step: "s1", StepRevision: 1, Offer: "cn_tx"}); err != nil { |
| 442 | t.Fatal(err) |
| 443 | } |
| 444 | var rel releaseRecord |
| 445 | if err := r.s.db.G.Where("step_id = 's1'").First(&rel).Error; err != nil || rel.Connection != "tensorx-1" { |
| 446 | t.Fatalf("release %+v %v", rel, err) |
| 447 | } |
| 448 | } |
| 449 | |
| 450 | // An older runner's plain Run now: only when the page showed it, and the |
| 451 | // offer says when it may bill per use. |
| 452 | func TestPlainRunNowOnlyWhenShown(t *testing.T) { |
| 453 | reset := time.Date(2026, 11, 24, 21, 0, 0, 0, time.UTC) |
| 454 | r, _ := pausedRigAt(t, wire.Protocol28, wire.SpecialistEngineering, wire.StepHold{Reason: wire.HoldHeadroom, Connection: "claude-1", Provider: wire.ProviderClaude, ResetsAt: &reset, StepRevision: 1}, |
| 455 | connectionRecord{ID: "cn_codex", LocalID: "codex-1", Provider: wire.ProviderCodex, Kind: wire.KindToken, State: wire.ConnHealthy, Headroom: headroom(10, reset)}, |
| 456 | tensorxConn(), |
| 457 | ) |
| 458 | if p := pausedOf(t, r); p == nil || p.RunNow == nil || !p.RunNow.Plain || !p.RunNow.MayBill { |
| 459 | t.Fatalf("an older runner's offer: %+v", p.RunNow) |
| 460 | } |
| 461 | ctx := context.Background() |
| 462 | if _, err := r.s.RunNow(ctx, "owner@example.com", "tk1", wire.RunNow{Step: "s1", StepRevision: 1, Offer: "cn_codex"}); !errors.Is(err, ErrOfferChanged) { |
| 463 | t.Fatalf("a named tap to an older runner: %v", err) |
| 464 | } |
| 465 | if _, err := r.s.RunNow(ctx, "owner@example.com", "tk1", wire.RunNow{Step: "s1", StepRevision: 1, Offer: wire.RunNowPlain}); err != nil { |
| 466 | t.Fatal(err) |
| 467 | } |
| 468 | var rel releaseRecord |
| 469 | if err := r.s.db.G.Where("step_id = 's1'").First(&rel).Error; err != nil || rel.Connection != "" { |
| 470 | t.Fatalf("plain release %+v %v", rel, err) |
| 471 | } |
| 472 | } |
| 473 | |
| 474 | // Base's carry_on pins the connection behind it: when the prediction |
| 475 | // moves to another plan, the card's revision moves, and a tap on the old |
| 476 | // revision is stale; on the new one the release is pinned to the new plan. |
| 477 | func TestCarryOnPinsItsConnection(t *testing.T) { |
| 478 | reset := time.Date(2026, 11, 24, 21, 0, 0, 0, time.UTC) |
| 479 | ctx := context.Background() |
| 480 | r, _ := pausedRig(t, wire.StepHold{Reason: wire.HoldHeadroom, Connection: "claude-1", Provider: wire.ProviderClaude, ResetsAt: &reset, WakeAt: &reset, StepRevision: 1}, |
| 481 | connectionRecord{ID: "cn_claude", LocalID: "claude-1", Provider: wire.ProviderClaude, Kind: wire.KindToken, State: wire.ConnLimited, Headroom: headroom(100, reset)}, |
| 482 | connectionRecord{ID: "cn_codex", LocalID: "codex-1", Provider: wire.ProviderCodex, Kind: wire.KindToken, State: wire.ConnHealthy, Headroom: headroom(10, reset)}, |
| 483 | connectionRecord{ID: "cn_claude2", LocalID: "claude-2", Provider: wire.ProviderClaude, Kind: wire.KindToken, State: wire.ConnHealthy, Headroom: headroom(50, reset)}, |
| 484 | ) |
| 485 | card := pausedJob(t, r) |
| 486 | if !card.CarryOn { |
| 487 | t.Fatalf("no carry on: %+v", card) |
| 488 | } |
| 489 | if err := r.s.db.G.Exec("UPDATE chat_connections SET state = ?, headroom = ? WHERE id = 'cn_codex'", wire.ConnLimited, headroom(100, reset)).Error; err != nil { |
| 490 | t.Fatal(err) |
| 491 | } |
| 492 | if _, err := r.s.CarryOn(ctx, "owner@example.com", card.ID, wire.CarryOn{Revision: card.Revision, IdempotencyKey: "k1"}); !errors.Is(err, ErrCardConflict) { |
| 493 | t.Fatalf("carry on after the plan changed: %v", err) |
| 494 | } |
| 495 | now := pausedJob2(t, r, card.ID) |
| 496 | if !now.CarryOn || now.Revision == card.Revision { |
| 497 | t.Fatalf("the card after the change: %+v", now) |
| 498 | } |
| 499 | if _, err := r.s.CarryOn(ctx, "owner@example.com", card.ID, wire.CarryOn{Revision: now.Revision, IdempotencyKey: "k2"}); err != nil { |
| 500 | t.Fatal(err) |
| 501 | } |
| 502 | var rel releaseRecord |
| 503 | if err := r.s.db.G.Where("step_id = 's1'").First(&rel).Error; err != nil || rel.Connection != "claude-2" { |
| 504 | t.Fatalf("release %+v %v", rel, err) |
| 505 | } |
| 506 | } |
| 507 | |