| 1 | package headless |
| 2 | |
| 3 | import ( |
| 4 | "crypto/rand" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "net/url" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | "time" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/fakeclaude" |
| 15 | "amadan.net/oficina/equipo/internal/fakecodex" |
| 16 | "amadan.net/oficina/equipo/internal/runner" |
| 17 | "amadan.net/oficina/equipo/internal/testci" |
| 18 | "amadan.net/oficina/equipo/internal/thintest" |
| 19 | "amadan.net/oficina/equipo/internal/wire" |
| 20 | ) |
| 21 | |
| 22 | // Equipo Connections slice 1, headless: real instance, runner and |
| 23 | // bubblewrap with the fake Claude and fake Codex CLIs. |
| 24 | |
| 25 | const second = "second@example.com" |
| 26 | |
| 27 | // binding is one entry of the runner's bindings file. |
| 28 | func (r *localRunner) bindings(t *testing.T) []map[string]any { |
| 29 | t.Helper() |
| 30 | raw, err := os.ReadFile(r.cfg.AccountBindingsPath) |
| 31 | if err != nil { |
| 32 | t.Fatal(err) |
| 33 | } |
| 34 | var out []map[string]any |
| 35 | if err = json.Unmarshal(raw, &out); err != nil { |
| 36 | t.Fatal(err) |
| 37 | } |
| 38 | return out |
| 39 | } |
| 40 | |
| 41 | // addAccount gives the owner another signed-in connection: a dedicated |
| 42 | // home with the provider's fake credentials, appended to the bindings. |
| 43 | func (r *localRunner) addAccount(t *testing.T, provider, id, email string) { |
| 44 | t.Helper() |
| 45 | home := private(t, filepath.Join(r.root, "accounts", id)) |
| 46 | version, model := fakeclaude.Version, "claude-opus-5-5" |
| 47 | if provider == "codex" { |
| 48 | version, model = fakecodex.Version, "gpt-6-astra" |
| 49 | if err := fakecodex.WriteAuth(home, email, "pro"); err != nil { |
| 50 | t.Fatal(err) |
| 51 | } |
| 52 | } else { |
| 53 | writeJSON(t, filepath.Join(home, ".claude.json"), map[string]any{"oauthAccount": map[string]string{"emailAddress": email}}) |
| 54 | if err := fakeclaude.WriteCredentials(home, time.Now().Add(8*time.Hour)); err != nil { |
| 55 | t.Fatal(err) |
| 56 | } |
| 57 | } |
| 58 | identity := map[string]string{"account_id": email, "home_id": rand.Text(), "provider_version": version} |
| 59 | writeJSON(t, filepath.Join(home, "equipo-identity.json"), identity) |
| 60 | bs := append(r.bindings(t), map[string]any{"id": id, "local_id": id, "label": id, "person_id": thintest.Owner, "provider": provider, "family": map[string]string{"claude": "claude", "codex": "gpt"}[provider], "model": model, "account_id": email, "provider_home": home, "kind": "subscription", "expected_identity": identity}) |
| 61 | writeJSON(t, r.cfg.AccountBindingsPath, bs) |
| 62 | } |
| 63 | |
| 64 | // only keeps the bindings with these ids. |
| 65 | func (r *localRunner) only(t *testing.T, ids ...string) { |
| 66 | t.Helper() |
| 67 | var keep []map[string]any |
| 68 | for _, b := range r.bindings(t) { |
| 69 | for _, id := range ids { |
| 70 | if b["id"] == id { |
| 71 | keep = append(keep, b) |
| 72 | } |
| 73 | } |
| 74 | } |
| 75 | writeJSON(t, r.cfg.AccountBindingsPath, keep) |
| 76 | } |
| 77 | |
| 78 | func replyOf(t *testing.T, s *session, turn string) wire.Message { |
| 79 | t.Helper() |
| 80 | s.waitTurn(t, turn, wire.TurnReplied, wire.TurnFailed, wire.TurnCancelled) |
| 81 | var out wire.Message |
| 82 | n := 0 |
| 83 | s.conv.Locked(func(c *thintest.Conversation) { |
| 84 | for _, m := range c.Replies() { |
| 85 | if m.TurnID == turn { |
| 86 | out, n = m, n+1 |
| 87 | } |
| 88 | } |
| 89 | }) |
| 90 | if n != 1 { |
| 91 | t.Fatalf("turn %s has %d replies: %+v", turn, n, s.conv.Turns[turn]) |
| 92 | } |
| 93 | return out |
| 94 | } |
| 95 | |
| 96 | func TestHeadlessConnections(t *testing.T) { |
| 97 | for _, sc := range []struct { |
| 98 | name string |
| 99 | run func(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) |
| 100 | }{ |
| 101 | {"U_usage_rows", connUsageRows}, |
| 102 | {"C1_claude_failover", connClaudeFailover}, |
| 103 | {"A6_A7_failure_kinds", connFailureKinds}, |
| 104 | {"A5_cancel_and_sign_out", connCancelAndSignOut}, |
| 105 | {"F2_quota_after_writes", connQuotaAfterWrites}, |
| 106 | {"C2_codex_coordinator", connCodexCoordinator}, |
| 107 | {"C3_codex_device_code", connCodexDeviceCode}, |
| 108 | {"C4_claude_sign_in", connClaudeSignIn}, |
| 109 | {"C5_engineering_failover", connEngineeringFailover}, |
| 110 | {"C5_engineering_to_codex", connEngineeringToCodex}, |
| 111 | {"C5_review_on_codex", connReviewOnCodex}, |
| 112 | {"C5_review_failover", connReviewFailover}, |
| 113 | {"C5_engineering_waits", connEngineeringWaits}, |
| 114 | {"C5_review_auth", connReviewAuth}, |
| 115 | {"P1_preference", connPreference}, |
| 116 | {"C5_review_other_family_first", connReviewOtherFamilyFirst}, |
| 117 | {"C6_no_connection", connNoConnection}, |
| 118 | } { |
| 119 | t.Run(sc.name, func(t *testing.T) { |
| 120 | testci.Quarantine(t) |
| 121 | env, inst, r := localEnv(t) |
| 122 | r.opts.ConnectLimit = time.Minute |
| 123 | sc.run(t, env, inst, r) |
| 124 | }) |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | // C1: two Claude accounts; the first hits its weekly limit mid-turn. The |
| 129 | // reply arrives once, from the second, with the switched line and the |
| 130 | // first's reset; the next turn stays on the second. |
| 131 | func connClaudeFailover(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { |
| 132 | r.addAccount(t, "claude", "claude-2", second) |
| 133 | r.start(t) |
| 134 | s := open(t, env) |
| 135 | sent := s.send(t, "Hello there. limit:"+thintest.Owner) |
| 136 | m := replyOf(t, s, sent.Turn.ID) |
| 137 | turn := s.conv.Turns[sent.Turn.ID] |
| 138 | if turn.State != wire.TurnReplied || turn.Attempt != 2 || turn.Connection != "claude-2" { |
| 139 | t.Fatalf("turn %+v", turn) |
| 140 | } |
| 141 | if m.Switched == nil || m.Switched.From != "claude" || m.Switched.To != "claude" || m.Switched.Window != "seven_day" || m.Switched.ResetsAt == nil || time.Until(*m.Switched.ResetsAt) < 40*time.Hour { |
| 142 | t.Fatalf("switched %+v", m.Switched) |
| 143 | } |
| 144 | if !strings.Contains(m.Text, "fresh session") || !strings.Contains(m.Text, "I see the earlier conversation") && !strings.Contains(m.Text, "Turn 1") { |
| 145 | t.Fatalf("not a fresh session on the second account: %q", m.Text) |
| 146 | } |
| 147 | page := inst.Get(t, "/conversation") |
| 148 | if !strings.Contains(page, "data-switched") || !strings.Contains(page, "Switched to Claude; Claude resets") { |
| 149 | t.Fatal("no switched line on the page") |
| 150 | } |
| 151 | next := s.send(t, "And now?") |
| 152 | n := replyOf(t, s, next.Turn.ID) |
| 153 | if v := s.conv.Turns[next.Turn.ID]; v.Connection != "claude-2" || v.Attempt != 1 || n.Switched != nil || !strings.Contains(n.Text, "resumed session") { |
| 154 | t.Fatalf("second turn %+v %q %+v", v, n.Text, n.Switched) |
| 155 | } |
| 156 | conns, err := env.Client.Connections(s.ctx) |
| 157 | if err != nil { |
| 158 | t.Fatal(err) |
| 159 | } |
| 160 | limited := false |
| 161 | for _, c := range conns.Items { |
| 162 | limited = limited || c.LocalID == "claude-1" && c.State == wire.ConnLimited && c.Headroom != nil && c.Headroom.ResetsAt != nil |
| 163 | } |
| 164 | if !limited { |
| 165 | t.Fatalf("claude-1 not shown limited: %+v", conns.Items) |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | // C2: Codex as the coordinator, end to end: the pinned app-server in the |
| 170 | // converse containment, its Equipo tools through the approval and the |
| 171 | // MCP proxy (a task recorded), usage recorded, and a cold resume of the |
| 172 | // same thread after the runner restarts. |
| 173 | func connCodexCoordinator(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { |
| 174 | r.addAccount(t, "codex", "codex-1", thintest.Owner) |
| 175 | r.only(t, "codex-1") |
| 176 | r.start(t) |
| 177 | s := open(t, env) |
| 178 | sent := s.send(t, "There is a typo in the sample README.\ntool:status\ntool:record_task:oficina/sample|Fix the README typo|The README says teh panes.") |
| 179 | m := replyOf(t, s, sent.Turn.ID) |
| 180 | if !strings.Contains(m.Text, "fake Codex coordinator. Turn 1, fresh thread") || !strings.Contains(m.Text, "[status: {") || !strings.Contains(m.Text, `[record_task: {`) || !strings.Contains(m.Text, `"task":"tk`) { |
| 181 | t.Fatalf("reply %q", m.Text) |
| 182 | } |
| 183 | if id := s.taskOf(t, sent.Turn.ID); id == "" { |
| 184 | t.Fatal("no task") |
| 185 | } |
| 186 | if v := s.conv.Turns[sent.Turn.ID]; v.Connection != "codex-1" { |
| 187 | t.Fatalf("turn %+v", v) |
| 188 | } |
| 189 | var rows int |
| 190 | var model, provider string |
| 191 | _ = inst.DB.Writer().QueryRow("SELECT count(*), max(model), max(provider) FROM chat_usage WHERE turn_id = ? AND output_tokens > 0 AND reasoning_output_tokens = 7", sent.Turn.ID).Scan(&rows, &model, &provider) |
| 192 | if rows != 1 || model != "gpt-6-astra" || provider != "codex" { |
| 193 | t.Fatalf("usage %d %s %s", rows, model, provider) |
| 194 | } |
| 195 | r.stop(t) |
| 196 | r.start(t) |
| 197 | again := s.send(t, "Thanks.") |
| 198 | n := replyOf(t, s, again.Turn.ID) |
| 199 | if !strings.Contains(n.Text, "Turn 2, resumed thread") { |
| 200 | t.Fatalf("after a restart %q", n.Text) |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | // C3: a Codex account added in the app by device code: the card shows |
| 205 | // OpenAI's page and code, the person approves there (the fake reads a |
| 206 | // file), and the connection turns healthy with the account's email; a |
| 207 | // refused device login ends provider_refused; the same account twice is |
| 208 | // already_connected. |
| 209 | func connCodexDeviceCode(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { |
| 210 | r.start(t) |
| 211 | s := open(t, env) |
| 212 | // Claude answers first: the conversation is on Claude. |
| 213 | replyOf(t, s, s.send(t, "Hello first.").Turn.ID) |
| 214 | approve := filepath.Join(r.root, "accounts", ".fake-device.json") |
| 215 | os.Remove(approve) |
| 216 | c, err := env.Client.Connect(s.ctx, wire.Connect{Provider: "codex"}) |
| 217 | if err != nil { |
| 218 | t.Fatal(err) |
| 219 | } |
| 220 | var code wire.Connection |
| 221 | s.wait(t, "device code", time.Minute, func(cv *thintest.Conversation) bool { |
| 222 | code = cv.Connections[c.ID] |
| 223 | return code.Prompt != nil && code.Prompt.Kind == wire.PromptDeviceCode |
| 224 | }) |
| 225 | if code.Prompt.URL != "https://auth.openai.com/codex/device" || !strings.HasPrefix(code.Prompt.Code, "FAKE-") { |
| 226 | t.Fatalf("prompt %+v", code.Prompt) |
| 227 | } |
| 228 | page := inst.Get(t, "/conversation/settings/connections/add") |
| 229 | if !strings.Contains(page, "data-device-code") || strings.Count(page, ">"+code.Prompt.Code+"<") != 1 || !strings.Contains(page, `href="`+code.Prompt.URL+`"`) { |
| 230 | t.Fatal("the device code is not on the page once, or OpenAI's page is not its link") |
| 231 | } |
| 232 | // The page never reloads itself: it follows the event stream. |
| 233 | if strings.Contains(page, `http-equiv="refresh"`) || strings.Contains(page, ">"+code.Prompt.URL+"<") { |
| 234 | t.Fatal("the page refreshes itself, or shows OpenAI's address as text") |
| 235 | } |
| 236 | writeJSON(t, approve, map[string]any{"email": second, "plan": "pro"}) |
| 237 | s.wait(t, "codex healthy", time.Minute, func(cv *thintest.Conversation) bool { |
| 238 | v := cv.Connections[c.ID] |
| 239 | return v.State == wire.ConnHealthy && v.LocalID == "codex-1" && v.Label == second && v.Plan == "pro" |
| 240 | }) |
| 241 | found := false |
| 242 | for _, b := range r.bindings(t) { |
| 243 | found = found || b["id"] == "codex-1" && b["provider"] == "codex" && b["person_id"] == thintest.Owner |
| 244 | } |
| 245 | if !found { |
| 246 | t.Fatal("no codex binding") |
| 247 | } |
| 248 | // The same account again. |
| 249 | c2, err := env.Client.Connect(s.ctx, wire.Connect{Provider: "codex"}) |
| 250 | if err != nil { |
| 251 | t.Fatal(err) |
| 252 | } |
| 253 | s.wait(t, "already connected", time.Minute, func(cv *thintest.Conversation) bool { |
| 254 | v := cv.Connections[c2.ID] |
| 255 | return v.State == wire.ConnError && v.Reason == "already_connected" |
| 256 | }) |
| 257 | if _, err := os.Stat(filepath.Join(r.root, "accounts", "codex-2")); !os.IsNotExist(err) { |
| 258 | t.Fatalf("the duplicate home stayed: %v", err) |
| 259 | } |
| 260 | // Device login not enabled: refused. |
| 261 | writeJSON(t, approve, map[string]any{"refuse": true}) |
| 262 | c3, err := env.Client.Connect(s.ctx, wire.Connect{Provider: "codex"}) |
| 263 | if err != nil { |
| 264 | t.Fatal(err) |
| 265 | } |
| 266 | s.wait(t, "refused", time.Minute, func(cv *thintest.Conversation) bool { |
| 267 | v := cv.Connections[c3.ID] |
| 268 | return v.State == wire.ConnError && v.Reason == "provider_refused" |
| 269 | }) |
| 270 | // The new connection answers: Claude is limited, Codex takes over. |
| 271 | sent := s.send(t, "Hello. limit:"+thintest.Owner) |
| 272 | m := replyOf(t, s, sent.Turn.ID) |
| 273 | if !strings.Contains(m.Text, "fake Codex coordinator") || m.Switched == nil || m.Switched.To != "codex" { |
| 274 | t.Fatalf("reply %q %+v", m.Text, m.Switched) |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | // C4: a second Claude account. "I am at this machine" is gone and |
| 279 | // refused; Claude is the sign-in by a link, started on the real runner |
| 280 | // (its own setup-token, the fake), whose card shows the link; cancelled, |
| 281 | // the CLI goes and so does the home. (The code and the token: |
| 282 | // TestHeadlessClaudeSignIn.) |
| 283 | func connClaudeSignIn(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { |
| 284 | r.start(t) |
| 285 | s := open(t, env) |
| 286 | if _, err := env.Client.Connect(s.ctx, wire.Connect{Provider: "claude", SameMachine: true}); thintest.Status(err) != 422 { |
| 287 | t.Fatalf("at this machine: %v", err) |
| 288 | } |
| 289 | c, err := env.Client.Connect(s.ctx, wire.Connect{Provider: "claude"}) |
| 290 | if err != nil { |
| 291 | t.Fatal(err) |
| 292 | } |
| 293 | var link wire.Connection |
| 294 | s.wait(t, "sign-in link", time.Minute, func(cv *thintest.Conversation) bool { |
| 295 | link = cv.Connections[c.ID] |
| 296 | return link.Prompt != nil && link.Prompt.Kind == wire.PromptAuthorize && link.Prompt.URL != "" |
| 297 | }) |
| 298 | u, err := url.Parse(link.Prompt.URL) |
| 299 | if err != nil || u.Host != "claude.com" || u.Query().Get("redirect_uri") != wire.EndpointClaudeCode { |
| 300 | t.Fatalf("link %q", link.Prompt.URL) |
| 301 | } |
| 302 | if _, err = env.Client.CancelConnection(s.ctx, c.ID); err != nil { |
| 303 | t.Fatal(err) |
| 304 | } |
| 305 | until(t, "the attempt's home gone", func() bool { |
| 306 | _, err := os.Stat(filepath.Join(r.root, "accounts", "claude-2")) |
| 307 | return os.IsNotExist(err) |
| 308 | }) |
| 309 | var _ runner.Config |
| 310 | } |
| 311 | |
| 312 | // C5: an Engineering step whose account hits its limit: the namespace's |
| 313 | // exit is proven, the refused attempt's tree is discarded, and the step |
| 314 | // runs again on the other account; the step shows both. |
| 315 | func connEngineeringFailover(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { |
| 316 | r.addAccount(t, "claude", "claude-2", second) |
| 317 | r.start(t) |
| 318 | s := open(t, env) |
| 319 | s.keep() |
| 320 | text := "tool:record_task:oficina/sample|Fix the README typo|teh\ntool:start_task:$task|Fix it. reviewsleep:20000 steplimit:" + thintest.Owner + " edit:README.md|teh panes|the panes" |
| 321 | sent := s.send(t, text) |
| 322 | id := s.taskOf(t, sent.Turn.ID) |
| 323 | step := s.step(t, id, 5*time.Minute, wire.StepDone, wire.StepFailed) |
| 324 | // The refused attempt and the one that ran are two attempts. |
| 325 | if step.State != wire.StepDone || !step.Pushed || step.Account != "claude-2" || step.Attempt != 2 { |
| 326 | t.Fatalf("step %+v", step) |
| 327 | } |
| 328 | if step.Switched == nil || step.Switched.From != "claude" || step.Switched.ResetsAt == nil { |
| 329 | t.Fatalf("step switched %+v", step.Switched) |
| 330 | } |
| 331 | page := inst.Get(t, "/tasks/"+id) |
| 332 | if !strings.Contains(page, "Claude was limited") { |
| 333 | t.Fatal("the task page does not show the switch") |
| 334 | } |
| 335 | if got := stepUsage(t, inst, step.ID); got != "1/failed/claude-1 2/replied/claude-2" { |
| 336 | t.Fatalf("step usage rows %q", got) |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | // C5 across families (F6): the owner's Claude refuses an Engineering |
| 341 | // step on quota; once its exit is proven the step's second attempt runs |
| 342 | // on Codex, pushes, and the card shows both. |
| 343 | func connEngineeringToCodex(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { |
| 344 | r.addAccount(t, "codex", "codex-1", second) |
| 345 | r.start(t) |
| 346 | s := open(t, env) |
| 347 | s.keep() |
| 348 | text := "tool:record_task:oficina/sample|Fix the README typo|teh\ntool:start_task:$task|Fix it. steplimit:" + thintest.Owner + " edit:README.md|teh panes|the panes" |
| 349 | sent := s.send(t, text) |
| 350 | id := s.taskOf(t, sent.Turn.ID) |
| 351 | step := s.step(t, id, 5*time.Minute, wire.StepDone, wire.StepFailed) |
| 352 | if step.State != wire.StepDone || !step.Pushed || step.Account != "codex-1" || step.Attempt != 2 || step.Headline != "Made the change the task asks for." { |
| 353 | t.Fatalf("step %+v", step) |
| 354 | } |
| 355 | // The card shows both: the step on Codex, and Claude limited. |
| 356 | if step.Family != "gpt" || step.Switched == nil || step.Switched.From != "claude" || step.Switched.To != "codex" || step.Switched.ResetsAt == nil { |
| 357 | t.Fatalf("step switched %+v", step.Switched) |
| 358 | } |
| 359 | if step.Askable { |
| 360 | t.Fatal("a Codex step keeps no session to ask") |
| 361 | } |
| 362 | if page := inst.Get(t, "/tasks/"+id); !strings.Contains(page, "Claude was limited") { |
| 363 | t.Fatal("the task page does not show the switch") |
| 364 | } |
| 365 | if got := stepUsage(t, inst, step.ID); got != "1/failed/claude-1 2/replied/codex-1" { |
| 366 | t.Fatalf("step usage rows %q", got) |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | // C5, Review on another family: Engineering runs on the owner's Claude, |
| 371 | // and Review on their Codex connection approves, labelled other_family. |
| 372 | func connReviewOnCodex(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { |
| 373 | r.addAccount(t, "codex", "codex-1", second) |
| 374 | r.start(t) |
| 375 | s := open(t, env) |
| 376 | s.keep() |
| 377 | text := "tool:record_task:oficina/sample|Fix the README typo|teh\ntool:start_task:$task|Fix it. edit:README.md|teh panes|the panes" |
| 378 | sent := s.send(t, text) |
| 379 | id := s.taskOf(t, sent.Turn.ID) |
| 380 | var review wire.Step |
| 381 | s.wait(t, "review done", 5*time.Minute, func(c *thintest.Conversation) bool { |
| 382 | for _, st := range c.Tasks[id].Steps { |
| 383 | if st.Specialist == wire.SpecialistReview && wire.StepTerminal(c.Steps[st.ID].State) { |
| 384 | review = c.Steps[st.ID] |
| 385 | return true |
| 386 | } |
| 387 | } |
| 388 | return false |
| 389 | }) |
| 390 | if review.State != wire.StepDone || review.Verdict != wire.VerdictApprove || review.Account != "codex-1" || review.ReviewLabel != wire.ReviewOtherFamily || !strings.Contains(review.Summary, "(from Codex)") || review.Askable { |
| 391 | t.Fatalf("review %+v", review) |
| 392 | } |
| 393 | if got := stepUsage(t, inst, review.ID); got != "1/replied/codex-1" { |
| 394 | t.Fatalf("review usage rows %q", got) |
| 395 | } |
| 396 | } |
| 397 | |
| 398 | // Astra round 2: Engineering on Claude-A, with Claude-B and Codex-C |
| 399 | // healthy and Claude preferred: Review goes to Codex-C, the other family, |
| 400 | // before preference and headroom are looked at. |
| 401 | func connReviewOtherFamilyFirst(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { |
| 402 | r.addAccount(t, "claude", "claude-2", "claude-b@example.com") |
| 403 | r.addAccount(t, "codex", "codex-1", second) |
| 404 | r.start(t) |
| 405 | s := open(t, env) |
| 406 | s.keep() |
| 407 | if _, err := env.Client.SetPreferences(s.ctx, wire.Preferences{Provider: "claude"}); err != nil { |
| 408 | t.Fatal(err) |
| 409 | } |
| 410 | time.Sleep(2 * time.Second) |
| 411 | text := "tool:record_task:oficina/sample|Fix the README typo|teh\ntool:start_task:$task|Fix it. edit:README.md|teh panes|the panes" |
| 412 | sent := s.send(t, text) |
| 413 | id := s.taskOf(t, sent.Turn.ID) |
| 414 | var eng, review wire.Step |
| 415 | s.wait(t, "review done", 5*time.Minute, func(c *thintest.Conversation) bool { |
| 416 | for _, st := range c.Tasks[id].Steps { |
| 417 | switch { |
| 418 | case st.Specialist == wire.SpecialistEngineering: |
| 419 | eng = c.Steps[st.ID] |
| 420 | case st.Specialist == wire.SpecialistReview && wire.StepTerminal(c.Steps[st.ID].State): |
| 421 | review = c.Steps[st.ID] |
| 422 | return true |
| 423 | } |
| 424 | } |
| 425 | return false |
| 426 | }) |
| 427 | if eng.Account != "claude-1" || review.State != wire.StepDone || review.Account != "codex-1" || review.ReviewLabel != wire.ReviewOtherFamily { |
| 428 | t.Fatalf("engineering on %s, review %+v", eng.Account, review) |
| 429 | } |
| 430 | } |
| 431 | |
| 432 | // stepUsage is a step's usage rows as attempt/outcome/connection. |
| 433 | func stepUsage(t *testing.T, inst *thintest.Instance, step string) string { |
| 434 | t.Helper() |
| 435 | rows, err := inst.DB.Writer().Query("SELECT attempt, outcome, connection FROM chat_usage WHERE step_id = ? ORDER BY attempt", step) |
| 436 | if err != nil { |
| 437 | t.Fatal(err) |
| 438 | } |
| 439 | defer rows.Close() |
| 440 | var out []string |
| 441 | for rows.Next() { |
| 442 | var attempt int64 |
| 443 | var outcome, conn string |
| 444 | if err := rows.Scan(&attempt, &outcome, &conn); err != nil { |
| 445 | t.Fatal(err) |
| 446 | } |
| 447 | out = append(out, fmt.Sprintf("%d/%s/%s", attempt, outcome, conn)) |
| 448 | } |
| 449 | return strings.Join(out, " ") |
| 450 | } |
| 451 | |
| 452 | // C5, nothing left: the only connection refuses an Engineering step on |
| 453 | // quota. The step does not fail: its next attempt waits, and runs on its |
| 454 | // own once a connection is added. |
| 455 | func connEngineeringWaits(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { |
| 456 | r.start(t) |
| 457 | s := open(t, env) |
| 458 | s.keep() |
| 459 | text := "tool:record_task:oficina/sample|Fix the README typo|teh\ntool:start_task:$task|Fix it. steplimit:" + thintest.Owner + " edit:README.md|teh panes|the panes" |
| 460 | sent := s.send(t, text) |
| 461 | id := s.taskOf(t, sent.Turn.ID) |
| 462 | var eng wire.Step |
| 463 | s.wait(t, "second attempt", 2*time.Minute, func(c *thintest.Conversation) bool { |
| 464 | for _, st := range c.Tasks[id].Steps { |
| 465 | if st.Specialist == wire.SpecialistEngineering { |
| 466 | eng = c.Steps[st.ID] |
| 467 | } |
| 468 | } |
| 469 | return eng.Attempt == 2 |
| 470 | }) |
| 471 | time.Sleep(3 * time.Second) |
| 472 | if v := s.conv.Steps[eng.ID]; wire.StepTerminal(v.State) { |
| 473 | t.Fatalf("the step ended with nothing to run it: %+v", v) |
| 474 | } |
| 475 | r.addAccount(t, "claude", "claude-2", second) |
| 476 | step := s.step(t, id, 3*time.Minute, wire.StepDone, wire.StepFailed) |
| 477 | if step.State != wire.StepDone || step.Account != "claude-2" || step.Attempt != 2 { |
| 478 | t.Fatalf("step %+v", step) |
| 479 | } |
| 480 | } |
| 481 | |
| 482 | // C5, Review's credential refused: the review moves to another |
| 483 | // connection as a new attempt, and the refused one needs signing in again. |
| 484 | func connReviewAuth(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { |
| 485 | r.addAccount(t, "claude", "claude-2", second) |
| 486 | r.start(t) |
| 487 | s := open(t, env) |
| 488 | s.keep() |
| 489 | text := "tool:record_task:oficina/sample|Fix the README typo|teh\ntool:start_task:$task|Fix it. reviewauth:" + second + " edit:README.md|teh panes|the panes" |
| 490 | sent := s.send(t, text) |
| 491 | id := s.taskOf(t, sent.Turn.ID) |
| 492 | var review wire.Step |
| 493 | s.wait(t, "review done", 5*time.Minute, func(c *thintest.Conversation) bool { |
| 494 | for _, st := range c.Tasks[id].Steps { |
| 495 | if st.Specialist == wire.SpecialistReview && wire.StepTerminal(c.Steps[st.ID].State) { |
| 496 | review = c.Steps[st.ID] |
| 497 | return true |
| 498 | } |
| 499 | } |
| 500 | return false |
| 501 | }) |
| 502 | if review.State != wire.StepDone || review.Account != "claude-1" || review.Attempt != 2 || review.Switched == nil { |
| 503 | t.Fatalf("review %+v", review) |
| 504 | } |
| 505 | s.wait(t, "sign in again", time.Minute, func(c *thintest.Conversation) bool { |
| 506 | for _, v := range c.Connections { |
| 507 | if v.LocalID == "claude-2" { |
| 508 | return v.State == wire.ConnSignInAgain |
| 509 | } |
| 510 | } |
| 511 | return false |
| 512 | }) |
| 513 | } |
| 514 | |
| 515 | // C6: nothing can answer: the turn is held with the no_connection card |
| 516 | // (no "send again"), the message waits; a Codex account added in the app |
| 517 | // answers it, once, with the switched line. |
| 518 | func connNoConnection(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { |
| 519 | r.start(t) |
| 520 | s := open(t, env) |
| 521 | replyOf(t, s, s.send(t, "Hello first.").Turn.ID) |
| 522 | // F5: a cancel while the turn waits ends it, cancelled. |
| 523 | first := s.send(t, "Hello. limit:"+thintest.Owner) |
| 524 | s.wait(t, "first waits", time.Minute, func(cv *thintest.Conversation) bool { return cv.Turns[first.Turn.ID].State == wire.TurnWaiting }) |
| 525 | if _, err := env.Client.Cancel(s.ctx, first.Turn.ID); err != nil { |
| 526 | t.Fatal(err) |
| 527 | } |
| 528 | s.waitTurn(t, first.Turn.ID, wire.TurnCancelled) |
| 529 | sent := s.send(t, "Hello. limit:"+thintest.Owner) |
| 530 | s.wait(t, "held", time.Minute, func(cv *thintest.Conversation) bool { |
| 531 | v := cv.Turns[sent.Turn.ID] |
| 532 | return v.State == wire.TurnWaiting && v.Reason == wire.ReasonNoConnection |
| 533 | }) |
| 534 | page := inst.Get(t, "/conversation") |
| 535 | if !strings.Contains(page, "data-no-connection") || !strings.Contains(page, "Nothing can answer right now. Claude resets") || strings.Contains(page, "Send your message again") { |
| 536 | t.Fatal("no connection card") |
| 537 | } |
| 538 | writeJSON(t, filepath.Join(r.root, "accounts", ".fake-device.json"), map[string]any{"email": second, "plan": "plus"}) |
| 539 | c, err := env.Client.Connect(s.ctx, wire.Connect{Provider: "codex"}) |
| 540 | if err != nil { |
| 541 | t.Fatal(err) |
| 542 | } |
| 543 | s.wait(t, "codex healthy", time.Minute, func(cv *thintest.Conversation) bool { return cv.Connections[c.ID].State == wire.ConnHealthy }) |
| 544 | m := replyOf(t, s, sent.Turn.ID) |
| 545 | v := s.conv.Turns[sent.Turn.ID] |
| 546 | if v.State != wire.TurnReplied || v.Connection != "codex-1" || !strings.Contains(m.Text, "fake Codex coordinator") || m.Switched == nil || m.Switched.To != "codex" { |
| 547 | t.Fatalf("turn %+v reply %q %+v", v, m.Text, m.Switched) |
| 548 | } |
| 549 | } |
| 550 | |
| 551 | // C5, Review: Review runs away from Engineering's account; that account |
| 552 | // hits its limit before a verdict; once its exit is proven Review runs |
| 553 | // again on what is left (Engineering's own account, a fresh session) and |
| 554 | // approves, and the step shows the switch. |
| 555 | func connReviewFailover(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { |
| 556 | r.addAccount(t, "claude", "claude-2", second) |
| 557 | r.start(t) |
| 558 | s := open(t, env) |
| 559 | s.keep() |
| 560 | text := "tool:record_task:oficina/sample|Fix the README typo|teh\ntool:start_task:$task|Fix it. reviewlimit:" + second + " edit:README.md|teh panes|the panes" |
| 561 | sent := s.send(t, text) |
| 562 | id := s.taskOf(t, sent.Turn.ID) |
| 563 | var review wire.Step |
| 564 | s.wait(t, "review done", 5*time.Minute, func(c *thintest.Conversation) bool { |
| 565 | for _, st := range c.Tasks[id].Steps { |
| 566 | if st.Specialist == wire.SpecialistReview && wire.StepTerminal(c.Steps[st.ID].State) { |
| 567 | review = c.Steps[st.ID] |
| 568 | return true |
| 569 | } |
| 570 | } |
| 571 | return false |
| 572 | }) |
| 573 | if review.State != wire.StepDone || review.Verdict != wire.VerdictApprove || review.Account != "claude-1" || review.ReviewLabel != wire.ReviewSameAccount || review.Attempt != 2 { |
| 574 | t.Fatalf("review %+v", review) |
| 575 | } |
| 576 | if review.Switched == nil || review.Switched.From != "claude" { |
| 577 | t.Fatalf("review switched %+v", review.Switched) |
| 578 | } |
| 579 | } |
| 580 | |
| 581 | // usageRow is one recorded usage row. |
| 582 | type usageRow struct { |
| 583 | Attempt int64 |
| 584 | Outcome, Model, Conn string |
| 585 | Complete bool |
| 586 | Input, Output, Reasoning *int64 |
| 587 | } |
| 588 | |
| 589 | func usageRows(t *testing.T, inst *thintest.Instance, turn string) []usageRow { |
| 590 | t.Helper() |
| 591 | rows, err := inst.DB.Writer().Query("SELECT attempt, outcome, model, connection, complete, input_tokens, output_tokens, reasoning_output_tokens FROM chat_usage WHERE turn_id = ? ORDER BY attempt, model", turn) |
| 592 | if err != nil { |
| 593 | t.Fatal(err) |
| 594 | } |
| 595 | defer rows.Close() |
| 596 | var out []usageRow |
| 597 | for rows.Next() { |
| 598 | var r usageRow |
| 599 | if err := rows.Scan(&r.Attempt, &r.Outcome, &r.Model, &r.Conn, &r.Complete, &r.Input, &r.Output, &r.Reasoning); err != nil { |
| 600 | t.Fatal(err) |
| 601 | } |
| 602 | out = append(out, r) |
| 603 | } |
| 604 | return out |
| 605 | } |
| 606 | |
| 607 | // U1 and U2: a Claude turn and a Codex turn each record one complete |
| 608 | // row (Claude's reasoning null, Codex's aggregated from several notices |
| 609 | // and a resent one); a cancelled turn records its attempt as cancelled. |
| 610 | func connUsageRows(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { |
| 611 | r.addAccount(t, "codex", "codex-1", second) |
| 612 | r.start(t) |
| 613 | s := open(t, env) |
| 614 | first := s.send(t, "Hello.") |
| 615 | replyOf(t, s, first.Turn.ID) |
| 616 | rows := usageRows(t, inst, first.Turn.ID) |
| 617 | if len(rows) != 1 || rows[0].Outcome != wire.OutcomeReplied || !rows[0].Complete || rows[0].Conn != "claude-1" || rows[0].Input == nil || rows[0].Reasoning != nil { |
| 618 | t.Fatalf("claude rows %+v", rows) |
| 619 | } |
| 620 | // Claude limited: the turn moves to Codex; the refused attempt is |
| 621 | // recorded as failed, the reply's as replied. |
| 622 | moved := s.send(t, "Again. limit:"+thintest.Owner) |
| 623 | replyOf(t, s, moved.Turn.ID) |
| 624 | rows = usageRows(t, inst, moved.Turn.ID) |
| 625 | if len(rows) != 2 || rows[0].Attempt != 1 || rows[0].Outcome != wire.OutcomeFailed || rows[0].Conn != "claude-1" || rows[1].Attempt != 2 || rows[1].Outcome != wire.OutcomeReplied || rows[1].Conn != "codex-1" || !rows[1].Complete || rows[1].Reasoning == nil || *rows[1].Reasoning != 7 { |
| 626 | t.Fatalf("failover rows %+v", rows) |
| 627 | } |
| 628 | cancelled := s.send(t, "Take your time. sleep:4000") |
| 629 | s.wait(t, "draft", time.Minute, func(c *thintest.Conversation) bool { return c.Drafts[cancelled.Turn.ID] != "" }) |
| 630 | if _, err := env.Client.Cancel(s.ctx, cancelled.Turn.ID); err != nil { |
| 631 | t.Fatal(err) |
| 632 | } |
| 633 | s.waitTurn(t, cancelled.Turn.ID, wire.TurnCancelled) |
| 634 | var got []usageRow |
| 635 | s.wait(t, "cancelled row", time.Minute, func(*thintest.Conversation) bool { |
| 636 | got = usageRows(t, inst, cancelled.Turn.ID) |
| 637 | return len(got) > 0 |
| 638 | }) |
| 639 | // What the cancelled turn used before the cancel is kept, not complete. |
| 640 | if len(got) != 1 || got[0].Outcome != wire.OutcomeCancelled || got[0].Complete || got[0].Input == nil || *got[0].Input == 0 { |
| 641 | t.Fatalf("cancelled rows %+v", got) |
| 642 | } |
| 643 | } |
| 644 | |
| 645 | // A6, A7: a refusal with no reset time reported marks the connection |
| 646 | // limited with no reset shown anywhere; the provider refusing the |
| 647 | // credential marks it sign_in_again, never limited; both move the turn. |
| 648 | func connFailureKinds(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { |
| 649 | r.addAccount(t, "claude", "claude-2", second) |
| 650 | r.addAccount(t, "claude", "claude-3", "third@example.com") |
| 651 | r.start(t) |
| 652 | s := open(t, env) |
| 653 | sent := s.send(t, "Hello. limitnoreset:"+thintest.Owner) |
| 654 | m := replyOf(t, s, sent.Turn.ID) |
| 655 | if m.Switched == nil || m.Switched.ResetsAt != nil || s.conv.Turns[sent.Turn.ID].Connection != "claude-2" { |
| 656 | t.Fatalf("no-reset switch %+v %+v", m.Switched, s.conv.Turns[sent.Turn.ID]) |
| 657 | } |
| 658 | page := inst.Get(t, "/conversation") |
| 659 | if !strings.Contains(page, ">Switched to Claude</p>") { |
| 660 | t.Fatal("the switched line names a reset that was not reported") |
| 661 | } |
| 662 | auth := s.send(t, "Hello again. authrefused:"+second) |
| 663 | a := replyOf(t, s, auth.Turn.ID) |
| 664 | if a.Switched == nil || a.Switched.ResetsAt != nil || s.conv.Turns[auth.Turn.ID].Connection != "claude-3" { |
| 665 | t.Fatalf("auth switch %+v %+v", a.Switched, s.conv.Turns[auth.Turn.ID]) |
| 666 | } |
| 667 | state := map[string]wire.Connection{} |
| 668 | s.wait(t, "states", time.Minute, func(c *thintest.Conversation) bool { |
| 669 | for _, v := range c.Connections { |
| 670 | state[v.LocalID] = v |
| 671 | } |
| 672 | return state["claude-1"].State == wire.ConnLimited && state["claude-2"].State == wire.ConnSignInAgain |
| 673 | }) |
| 674 | if h := state["claude-1"].Headroom; h != nil && h.ResetsAt != nil { |
| 675 | t.Fatalf("a reset time was invented: %+v", h) |
| 676 | } |
| 677 | page = inst.Get(t, "/conversation/connections") |
| 678 | if !strings.Contains(page, "Limited, no reset time reported") || !strings.Contains(page, "Needs signing in again") { |
| 679 | t.Fatal("connection states not on the page") |
| 680 | } |
| 681 | } |
| 682 | |
| 683 | // codexHomes lists the codex-* homes under the accounts root. |
| 684 | func (r *localRunner) codexHomes() []string { |
| 685 | m, _ := filepath.Glob(filepath.Join(r.root, "accounts", "codex-*")) |
| 686 | return m |
| 687 | } |
| 688 | |
| 689 | func (r *localRunner) hasBinding(t *testing.T, provider string) bool { |
| 690 | for _, b := range r.bindings(t) { |
| 691 | if b["provider"] == provider { |
| 692 | return true |
| 693 | } |
| 694 | } |
| 695 | return false |
| 696 | } |
| 697 | |
| 698 | // A5 and sign-out: a cancel while the person approves at the same moment |
| 699 | // leaves no connection, binding or home behind, whichever came first; a |
| 700 | // connection signed out from the app is gone from the runner and shown |
| 701 | // signed out. |
| 702 | func connCancelAndSignOut(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { |
| 703 | r.start(t) |
| 704 | s := open(t, env) |
| 705 | approve := filepath.Join(r.root, "accounts", ".fake-device.json") |
| 706 | c, err := env.Client.Connect(s.ctx, wire.Connect{Provider: "codex"}) |
| 707 | if err != nil { |
| 708 | t.Fatal(err) |
| 709 | } |
| 710 | s.wait(t, "device code", time.Minute, func(cv *thintest.Conversation) bool { return cv.Connections[c.ID].Prompt != nil }) |
| 711 | writeJSON(t, approve, map[string]any{"email": second, "plan": "pro"}) |
| 712 | if _, err = env.Client.CancelConnection(s.ctx, c.ID); err != nil { |
| 713 | t.Fatal(err) |
| 714 | } |
| 715 | deadline := time.Now().Add(30 * time.Second) |
| 716 | for (r.hasBinding(t, "codex") || len(r.codexHomes()) > 0) && time.Now().Before(deadline) { |
| 717 | time.Sleep(200 * time.Millisecond) |
| 718 | } |
| 719 | if r.hasBinding(t, "codex") || len(r.codexHomes()) > 0 { |
| 720 | t.Fatalf("a cancelled attempt left a connection: %v", r.codexHomes()) |
| 721 | } |
| 722 | time.Sleep(time.Second) |
| 723 | if v, _ := env.Client.Connection(s.ctx, c.ID); v.State != wire.ConnError || v.Reason != "cancelled" { |
| 724 | t.Fatalf("cancelled attempt %+v", v) |
| 725 | } |
| 726 | list, _ := env.Client.Connections(s.ctx) |
| 727 | for _, v := range list.Items { |
| 728 | if v.Provider == "codex" && v.State == wire.ConnHealthy { |
| 729 | t.Fatalf("a cancelled Codex connection appeared: %+v", v) |
| 730 | } |
| 731 | } |
| 732 | // Connected, then signed out from the app. |
| 733 | c2, err := env.Client.Connect(s.ctx, wire.Connect{Provider: "codex"}) |
| 734 | if err != nil { |
| 735 | t.Fatal(err) |
| 736 | } |
| 737 | s.wait(t, "healthy", time.Minute, func(cv *thintest.Conversation) bool { return cv.Connections[c2.ID].State == wire.ConnHealthy }) |
| 738 | if _, err = env.Client.SignOut(s.ctx, c2.ID); err != nil { |
| 739 | t.Fatal(err) |
| 740 | } |
| 741 | s.wait(t, "signed out", time.Minute, func(cv *thintest.Conversation) bool { return cv.Connections[c2.ID].State == wire.ConnSignedOut }) |
| 742 | // The instance shows signed out as soon as a hello no longer holds the |
| 743 | // connection, which the runner sends once the binding is dropped and |
| 744 | // a moment before the home is deleted; on a loaded machine that |
| 745 | // moment is visible, so wait for the home as for the cancel above. |
| 746 | deadline = time.Now().Add(30 * time.Second) |
| 747 | for (r.hasBinding(t, "codex") || len(r.codexHomes()) > 0) && time.Now().Before(deadline) { |
| 748 | time.Sleep(200 * time.Millisecond) |
| 749 | } |
| 750 | if r.hasBinding(t, "codex") || len(r.codexHomes()) > 0 { |
| 751 | t.Fatal("signed out, but the binding or home stayed") |
| 752 | } |
| 753 | } |
| 754 | |
| 755 | // F2: the limit hits straight after the turn's writes (add_project, |
| 756 | // record_task, start_task, ask_person, set_project_home). The new attempt |
| 757 | // on the other account is told what was done, its repeats are answered |
| 758 | // from the record, and there is one project, one task, one step and one |
| 759 | // question card. |
| 760 | func connQuotaAfterWrites(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { |
| 761 | r.addAccount(t, "claude", "claude-2", second) |
| 762 | r.start(t) |
| 763 | s := open(t, env) |
| 764 | // reword: the new attempt words every write differently; status runs |
| 765 | // first and last (F2b: the second attempt's status is fresh). |
| 766 | text := "Please fix the typo. reword\nlimitafter:" + thintest.Owner + "\ntool:status\ntool:add_project:oficina/sample\ntool:record_task:oficina/sample|Fix the README typo|teh\ntool:start_task:$task|Fix it. reviewsleep:60000 edit:README.md|teh panes|the panes\ntool:ask_person:Which colour?|Red|Blue\ntool:set_project_home:oficina\ntool:status" |
| 767 | sent := s.send(t, text) |
| 768 | m := replyOf(t, s, sent.Turn.ID) |
| 769 | turn := s.conv.Turns[sent.Turn.ID] |
| 770 | if turn.Attempt != 2 || turn.Connection != "claude-2" || m.Switched == nil { |
| 771 | t.Fatalf("turn %+v switched %+v", turn, m.Switched) |
| 772 | } |
| 773 | if !strings.Contains(m.Text, "(earlier effects in context)") { |
| 774 | t.Fatalf("the new attempt was not told what was done: %q", m.Text) |
| 775 | } |
| 776 | // F2b: the new attempt's first status is fresh: the project added in |
| 777 | // the first attempt is in it. |
| 778 | if _, after, ok := strings.Cut(m.Text, "[status: "); !ok || !strings.Contains(strings.SplitN(after, "[add_project", 2)[0], `"projects":[{`) { |
| 779 | t.Fatalf("status was not fresh: %q", m.Text) |
| 780 | } |
| 781 | time.Sleep(2 * time.Second) |
| 782 | snap, err := env.Client.Snapshot(s.ctx) |
| 783 | if err != nil { |
| 784 | t.Fatal(err) |
| 785 | } |
| 786 | tasks, steps, questions, projects := 0, 0, 0, 0 |
| 787 | for _, k := range snap.Tasks { |
| 788 | if strings.HasPrefix(k.Title, "Fix the README typo") { |
| 789 | tasks++ |
| 790 | for _, st := range k.Steps { |
| 791 | if st.Specialist == wire.SpecialistEngineering { |
| 792 | steps++ |
| 793 | } |
| 794 | } |
| 795 | } |
| 796 | } |
| 797 | for _, c := range snap.Cards { |
| 798 | if c.Kind == wire.CardQuestion { |
| 799 | questions++ |
| 800 | } |
| 801 | } |
| 802 | for _, p := range snap.Projects { |
| 803 | if strings.HasSuffix(p.Repo, "oficina/sample") { |
| 804 | projects++ |
| 805 | } |
| 806 | } |
| 807 | if tasks != 1 || steps != 1 || questions != 1 || projects != 1 { |
| 808 | t.Fatalf("effects ran again: %d tasks, %d steps, %d question cards, %d projects", tasks, steps, questions, projects) |
| 809 | } |
| 810 | // Every write of attempt 2 reached the instance, the one ledger, and |
| 811 | // was folded there: the reworded ones (record_task, start_task, |
| 812 | // ask_person) by kind, the identical ones (add_project, |
| 813 | // set_project_home) too. |
| 814 | var replayed int |
| 815 | _ = inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_tool_calls WHERE turn_id = ? AND attempt = 2 AND result LIKE '%\"replayed\":true%'", sent.Turn.ID).Scan(&replayed) |
| 816 | if replayed != 5 { |
| 817 | t.Fatalf("%d reworded writes were folded by the ledger", replayed) |
| 818 | } |
| 819 | } |
| 820 | |
| 821 | // scenarioConnWitness is Connections slice 1's live witness (staging |
| 822 | // only): the person's messages in EQUIPO_STAGING_CONN_WITNESS, separated |
| 823 | // by a line "---", each answered by whichever connection the runner |
| 824 | // chooses. It records, per turn, the connection that answered, the |
| 825 | // attempt, the switched line and the time to the reply. |
| 826 | func scenarioConnWitness(t *testing.T, env *Env) { |
| 827 | text := os.Getenv("EQUIPO_STAGING_CONN_WITNESS") |
| 828 | if !env.Live || text == "" { |
| 829 | t.Skip("staging only, with EQUIPO_STAGING_CONN_WITNESS") |
| 830 | } |
| 831 | s := open(t, env) |
| 832 | s.keep() |
| 833 | s.wait(t, "runner online", time.Minute, func(c *thintest.Conversation) bool { return c.Runner.Online }) |
| 834 | conns, err := env.Client.Connections(s.ctx) |
| 835 | if err != nil { |
| 836 | t.Fatal(err) |
| 837 | } |
| 838 | var held []map[string]any |
| 839 | for _, c := range conns.Items { |
| 840 | h := map[string]any{"local_id": c.LocalID, "provider": c.Provider, "state": c.State, "plan": c.Plan} |
| 841 | if c.Headroom != nil { |
| 842 | h["resets_at"], h["utilization"] = c.Headroom.ResetsAt, c.Headroom.Utilization |
| 843 | } |
| 844 | held = append(held, h) |
| 845 | } |
| 846 | var turns []map[string]any |
| 847 | for _, msg := range strings.Split(text, "\n---\n") { |
| 848 | start := time.Now() |
| 849 | sent := s.send(t, strings.TrimSpace(msg)) |
| 850 | turn := s.waitTurn(t, sent.Turn.ID, wire.TurnReplied, wire.TurnFailed, wire.TurnCancelled) |
| 851 | row := map[string]any{"turn": turn.ID, "state": turn.State, "reason": turn.Reason, "attempt": turn.Attempt, "connection": turn.Connection, "seconds": time.Since(start).Seconds()} |
| 852 | s.conv.Locked(func(c *thintest.Conversation) { |
| 853 | for _, m := range c.Replies() { |
| 854 | if m.TurnID == turn.ID { |
| 855 | row["reply"], row["switched"] = clipText(m.Text, 300), m.Switched |
| 856 | } |
| 857 | } |
| 858 | }) |
| 859 | t.Logf("turn %+v", row) |
| 860 | turns = append(turns, row) |
| 861 | if turn.State != wire.TurnReplied { |
| 862 | break |
| 863 | } |
| 864 | } |
| 865 | Witness[t.Name()] = map[string]any{"connections": held, "turns": turns} |
| 866 | } |
| 867 | |
| 868 | func clipText(s string, n int) string { |
| 869 | if len(s) <= n { |
| 870 | return s |
| 871 | } |
| 872 | return s[:n] + "…" |
| 873 | } |
| 874 | |
| 875 | // P1: the person prefers Codex. The coordinator, on Claude, moves to |
| 876 | // Codex at the next turn (a boundary), with the switched line; Automatic |
| 877 | // again keeps it where it is (stickiness). A stale revision is refused, |
| 878 | // and a preference never overrides health: Codex limited, the turn runs |
| 879 | // on Claude. A signed-out record can be forgotten. |
| 880 | func connPreference(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { |
| 881 | r.addAccount(t, "codex", "codex-1", second) |
| 882 | r.start(t) |
| 883 | s := open(t, env) |
| 884 | first := s.send(t, "Hello.") |
| 885 | replyOf(t, s, first.Turn.ID) |
| 886 | if c := s.conv.Turns[first.Turn.ID].Connection; c != "claude-1" { |
| 887 | t.Fatalf("first turn on %s", c) |
| 888 | } |
| 889 | p, err := env.Client.Preferences(s.ctx) |
| 890 | if err != nil || p.Provider != "" || p.Revision != 0 { |
| 891 | t.Fatalf("preferences %+v %v", p, err) |
| 892 | } |
| 893 | if p, err = env.Client.SetPreferences(s.ctx, wire.Preferences{Provider: "codex"}); err != nil || p.Revision != 1 { |
| 894 | t.Fatalf("set %+v %v", p, err) |
| 895 | } |
| 896 | if _, err = env.Client.SetPreferences(s.ctx, wire.Preferences{Provider: "claude"}); err == nil { |
| 897 | t.Fatal("a stale revision was taken") |
| 898 | } |
| 899 | // The runner has it once the frame lands; the next turn moves. |
| 900 | deadline := time.Now().Add(30 * time.Second) |
| 901 | var moved wire.Message |
| 902 | var turn wire.Turn |
| 903 | for { |
| 904 | sent := s.send(t, "Next.") |
| 905 | moved = replyOf(t, s, sent.Turn.ID) |
| 906 | turn = s.conv.Turns[sent.Turn.ID] |
| 907 | if turn.Connection == "codex-1" || time.Now().After(deadline) { |
| 908 | break |
| 909 | } |
| 910 | } |
| 911 | if turn.Connection != "codex-1" || turn.Attempt != 1 || moved.Switched == nil || moved.Switched.To != "codex" { |
| 912 | t.Fatalf("preferred turn %+v %+v", turn, moved.Switched) |
| 913 | } |
| 914 | if _, err = env.Client.SetPreferences(s.ctx, wire.Preferences{Provider: "", Revision: 1}); err != nil { |
| 915 | t.Fatal(err) |
| 916 | } |
| 917 | time.Sleep(2 * time.Second) |
| 918 | stay := s.send(t, "Again.") |
| 919 | replyOf(t, s, stay.Turn.ID) |
| 920 | if c := s.conv.Turns[stay.Turn.ID].Connection; c != "codex-1" { |
| 921 | t.Fatalf("Automatic moved the session to %s", c) |
| 922 | } |
| 923 | // Preferred but limited: Claude answers. |
| 924 | if _, err = env.Client.SetPreferences(s.ctx, wire.Preferences{Provider: "codex", Revision: 2}); err != nil { |
| 925 | t.Fatal(err) |
| 926 | } |
| 927 | time.Sleep(2 * time.Second) |
| 928 | held := s.send(t, "Limited now. limit:"+second) |
| 929 | replyOf(t, s, held.Turn.ID) |
| 930 | if c := s.conv.Turns[held.Turn.ID].Connection; c != "claude-1" { |
| 931 | t.Fatalf("a limited preferred connection answered: %s", c) |
| 932 | } |
| 933 | // Signed out, then forgotten. |
| 934 | var codex wire.Connection |
| 935 | for _, v := range s.conv.Connections { |
| 936 | if v.LocalID == "codex-1" { |
| 937 | codex = v |
| 938 | } |
| 939 | } |
| 940 | if _, err = env.Client.SignOut(s.ctx, codex.ID); err != nil { |
| 941 | t.Fatal(err) |
| 942 | } |
| 943 | s.wait(t, "signed out", time.Minute, func(cv *thintest.Conversation) bool { return cv.Connections[codex.ID].State == wire.ConnSignedOut }) |
| 944 | if err = env.Client.Forget(s.ctx, codex.ID); err != nil { |
| 945 | t.Fatal(err) |
| 946 | } |
| 947 | list, _ := env.Client.Connections(s.ctx) |
| 948 | for _, v := range list.Items { |
| 949 | if v.ID == codex.ID { |
| 950 | t.Fatal("the forgotten record stayed") |
| 951 | } |
| 952 | } |
| 953 | s.wait(t, "forgotten in the stream", time.Minute, func(cv *thintest.Conversation) bool { |
| 954 | _, ok := cv.Connections[codex.ID] |
| 955 | return !ok |
| 956 | }) |
| 957 | } |
| 958 | |