package headless import ( "crypto/rand" "encoding/json" "fmt" "net/url" "os" "path/filepath" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/fakeclaude" "amadan.net/oficina/equipo/internal/fakecodex" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/testci" "amadan.net/oficina/equipo/internal/thintest" "amadan.net/oficina/equipo/internal/wire" ) // Equipo Connections slice 1, headless: real instance, runner and // bubblewrap with the fake Claude and fake Codex CLIs. const second = "second@example.com" // binding is one entry of the runner's bindings file. func (r *localRunner) bindings(t *testing.T) []map[string]any { t.Helper() raw, err := os.ReadFile(r.cfg.AccountBindingsPath) if err != nil { t.Fatal(err) } var out []map[string]any if err = json.Unmarshal(raw, &out); err != nil { t.Fatal(err) } return out } // addAccount gives the owner another signed-in connection: a dedicated // home with the provider's fake credentials, appended to the bindings. func (r *localRunner) addAccount(t *testing.T, provider, id, email string) { t.Helper() home := private(t, filepath.Join(r.root, "accounts", id)) version, model := fakeclaude.Version, "claude-opus-5-5" if provider == "codex" { version, model = fakecodex.Version, "gpt-6-astra" if err := fakecodex.WriteAuth(home, email, "pro"); err != nil { t.Fatal(err) } } else { writeJSON(t, filepath.Join(home, ".claude.json"), map[string]any{"oauthAccount": map[string]string{"emailAddress": email}}) if err := fakeclaude.WriteCredentials(home, time.Now().Add(8*time.Hour)); err != nil { t.Fatal(err) } } identity := map[string]string{"account_id": email, "home_id": rand.Text(), "provider_version": version} writeJSON(t, filepath.Join(home, "equipo-identity.json"), identity) 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}) writeJSON(t, r.cfg.AccountBindingsPath, bs) } // only keeps the bindings with these ids. func (r *localRunner) only(t *testing.T, ids ...string) { t.Helper() var keep []map[string]any for _, b := range r.bindings(t) { for _, id := range ids { if b["id"] == id { keep = append(keep, b) } } } writeJSON(t, r.cfg.AccountBindingsPath, keep) } func replyOf(t *testing.T, s *session, turn string) wire.Message { t.Helper() s.waitTurn(t, turn, wire.TurnReplied, wire.TurnFailed, wire.TurnCancelled) var out wire.Message n := 0 s.conv.Locked(func(c *thintest.Conversation) { for _, m := range c.Replies() { if m.TurnID == turn { out, n = m, n+1 } } }) if n != 1 { t.Fatalf("turn %s has %d replies: %+v", turn, n, s.conv.Turns[turn]) } return out } func TestHeadlessConnections(t *testing.T) { for _, sc := range []struct { name string run func(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) }{ {"U_usage_rows", connUsageRows}, {"C1_claude_failover", connClaudeFailover}, {"A6_A7_failure_kinds", connFailureKinds}, {"A5_cancel_and_sign_out", connCancelAndSignOut}, {"F2_quota_after_writes", connQuotaAfterWrites}, {"C2_codex_coordinator", connCodexCoordinator}, {"C3_codex_device_code", connCodexDeviceCode}, {"C4_claude_sign_in", connClaudeSignIn}, {"C5_engineering_failover", connEngineeringFailover}, {"C5_engineering_to_codex", connEngineeringToCodex}, {"C5_review_on_codex", connReviewOnCodex}, {"C5_review_failover", connReviewFailover}, {"C5_engineering_waits", connEngineeringWaits}, {"C5_review_auth", connReviewAuth}, {"P1_preference", connPreference}, {"C5_review_other_family_first", connReviewOtherFamilyFirst}, {"C6_no_connection", connNoConnection}, } { t.Run(sc.name, func(t *testing.T) { testci.Quarantine(t) env, inst, r := localEnv(t) r.opts.ConnectLimit = time.Minute sc.run(t, env, inst, r) }) } } // C1: two Claude accounts; the first hits its weekly limit mid-turn. The // reply arrives once, from the second, with the switched line and the // first's reset; the next turn stays on the second. func connClaudeFailover(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { r.addAccount(t, "claude", "claude-2", second) r.start(t) s := open(t, env) sent := s.send(t, "Hello there. limit:"+thintest.Owner) m := replyOf(t, s, sent.Turn.ID) turn := s.conv.Turns[sent.Turn.ID] if turn.State != wire.TurnReplied || turn.Attempt != 2 || turn.Connection != "claude-2" { t.Fatalf("turn %+v", turn) } 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 { t.Fatalf("switched %+v", m.Switched) } if !strings.Contains(m.Text, "fresh session") || !strings.Contains(m.Text, "I see the earlier conversation") && !strings.Contains(m.Text, "Turn 1") { t.Fatalf("not a fresh session on the second account: %q", m.Text) } page := inst.Get(t, "/conversation") if !strings.Contains(page, "data-switched") || !strings.Contains(page, "Switched to Claude; Claude resets") { t.Fatal("no switched line on the page") } next := s.send(t, "And now?") n := replyOf(t, s, next.Turn.ID) if v := s.conv.Turns[next.Turn.ID]; v.Connection != "claude-2" || v.Attempt != 1 || n.Switched != nil || !strings.Contains(n.Text, "resumed session") { t.Fatalf("second turn %+v %q %+v", v, n.Text, n.Switched) } conns, err := env.Client.Connections(s.ctx) if err != nil { t.Fatal(err) } limited := false for _, c := range conns.Items { limited = limited || c.LocalID == "claude-1" && c.State == wire.ConnLimited && c.Headroom != nil && c.Headroom.ResetsAt != nil } if !limited { t.Fatalf("claude-1 not shown limited: %+v", conns.Items) } } // C2: Codex as the coordinator, end to end: the pinned app-server in the // converse containment, its Equipo tools through the approval and the // MCP proxy (a task recorded), usage recorded, and a cold resume of the // same thread after the runner restarts. func connCodexCoordinator(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { r.addAccount(t, "codex", "codex-1", thintest.Owner) r.only(t, "codex-1") r.start(t) s := open(t, env) 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.") m := replyOf(t, s, sent.Turn.ID) 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`) { t.Fatalf("reply %q", m.Text) } if id := s.taskOf(t, sent.Turn.ID); id == "" { t.Fatal("no task") } if v := s.conv.Turns[sent.Turn.ID]; v.Connection != "codex-1" { t.Fatalf("turn %+v", v) } var rows int var model, provider string _ = 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) if rows != 1 || model != "gpt-6-astra" || provider != "codex" { t.Fatalf("usage %d %s %s", rows, model, provider) } r.stop(t) r.start(t) again := s.send(t, "Thanks.") n := replyOf(t, s, again.Turn.ID) if !strings.Contains(n.Text, "Turn 2, resumed thread") { t.Fatalf("after a restart %q", n.Text) } } // C3: a Codex account added in the app by device code: the card shows // OpenAI's page and code, the person approves there (the fake reads a // file), and the connection turns healthy with the account's email; a // refused device login ends provider_refused; the same account twice is // already_connected. func connCodexDeviceCode(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { r.start(t) s := open(t, env) // Claude answers first: the conversation is on Claude. replyOf(t, s, s.send(t, "Hello first.").Turn.ID) approve := filepath.Join(r.root, "accounts", ".fake-device.json") os.Remove(approve) c, err := env.Client.Connect(s.ctx, wire.Connect{Provider: "codex"}) if err != nil { t.Fatal(err) } var code wire.Connection s.wait(t, "device code", time.Minute, func(cv *thintest.Conversation) bool { code = cv.Connections[c.ID] return code.Prompt != nil && code.Prompt.Kind == wire.PromptDeviceCode }) if code.Prompt.URL != "https://auth.openai.com/codex/device" || !strings.HasPrefix(code.Prompt.Code, "FAKE-") { t.Fatalf("prompt %+v", code.Prompt) } page := inst.Get(t, "/conversation/settings/connections/add") if !strings.Contains(page, "data-device-code") || strings.Count(page, ">"+code.Prompt.Code+"<") != 1 || !strings.Contains(page, `href="`+code.Prompt.URL+`"`) { t.Fatal("the device code is not on the page once, or OpenAI's page is not its link") } // The page never reloads itself: it follows the event stream. if strings.Contains(page, `http-equiv="refresh"`) || strings.Contains(page, ">"+code.Prompt.URL+"<") { t.Fatal("the page refreshes itself, or shows OpenAI's address as text") } writeJSON(t, approve, map[string]any{"email": second, "plan": "pro"}) s.wait(t, "codex healthy", time.Minute, func(cv *thintest.Conversation) bool { v := cv.Connections[c.ID] return v.State == wire.ConnHealthy && v.LocalID == "codex-1" && v.Label == second && v.Plan == "pro" }) found := false for _, b := range r.bindings(t) { found = found || b["id"] == "codex-1" && b["provider"] == "codex" && b["person_id"] == thintest.Owner } if !found { t.Fatal("no codex binding") } // The same account again. c2, err := env.Client.Connect(s.ctx, wire.Connect{Provider: "codex"}) if err != nil { t.Fatal(err) } s.wait(t, "already connected", time.Minute, func(cv *thintest.Conversation) bool { v := cv.Connections[c2.ID] return v.State == wire.ConnError && v.Reason == "already_connected" }) if _, err := os.Stat(filepath.Join(r.root, "accounts", "codex-2")); !os.IsNotExist(err) { t.Fatalf("the duplicate home stayed: %v", err) } // Device login not enabled: refused. writeJSON(t, approve, map[string]any{"refuse": true}) c3, err := env.Client.Connect(s.ctx, wire.Connect{Provider: "codex"}) if err != nil { t.Fatal(err) } s.wait(t, "refused", time.Minute, func(cv *thintest.Conversation) bool { v := cv.Connections[c3.ID] return v.State == wire.ConnError && v.Reason == "provider_refused" }) // The new connection answers: Claude is limited, Codex takes over. sent := s.send(t, "Hello. limit:"+thintest.Owner) m := replyOf(t, s, sent.Turn.ID) if !strings.Contains(m.Text, "fake Codex coordinator") || m.Switched == nil || m.Switched.To != "codex" { t.Fatalf("reply %q %+v", m.Text, m.Switched) } } // C4: a second Claude account. "I am at this machine" is gone and // refused; Claude is the sign-in by a link, started on the real runner // (its own setup-token, the fake), whose card shows the link; cancelled, // the CLI goes and so does the home. (The code and the token: // TestHeadlessClaudeSignIn.) func connClaudeSignIn(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { r.start(t) s := open(t, env) if _, err := env.Client.Connect(s.ctx, wire.Connect{Provider: "claude", SameMachine: true}); thintest.Status(err) != 422 { t.Fatalf("at this machine: %v", err) } c, err := env.Client.Connect(s.ctx, wire.Connect{Provider: "claude"}) if err != nil { t.Fatal(err) } var link wire.Connection s.wait(t, "sign-in link", time.Minute, func(cv *thintest.Conversation) bool { link = cv.Connections[c.ID] return link.Prompt != nil && link.Prompt.Kind == wire.PromptAuthorize && link.Prompt.URL != "" }) u, err := url.Parse(link.Prompt.URL) if err != nil || u.Host != "claude.com" || u.Query().Get("redirect_uri") != wire.EndpointClaudeCode { t.Fatalf("link %q", link.Prompt.URL) } if _, err = env.Client.CancelConnection(s.ctx, c.ID); err != nil { t.Fatal(err) } until(t, "the attempt's home gone", func() bool { _, err := os.Stat(filepath.Join(r.root, "accounts", "claude-2")) return os.IsNotExist(err) }) var _ runner.Config } // C5: an Engineering step whose account hits its limit: the namespace's // exit is proven, the refused attempt's tree is discarded, and the step // runs again on the other account; the step shows both. func connEngineeringFailover(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { r.addAccount(t, "claude", "claude-2", second) r.start(t) s := open(t, env) s.keep() 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" sent := s.send(t, text) id := s.taskOf(t, sent.Turn.ID) step := s.step(t, id, 5*time.Minute, wire.StepDone, wire.StepFailed) // The refused attempt and the one that ran are two attempts. if step.State != wire.StepDone || !step.Pushed || step.Account != "claude-2" || step.Attempt != 2 { t.Fatalf("step %+v", step) } if step.Switched == nil || step.Switched.From != "claude" || step.Switched.ResetsAt == nil { t.Fatalf("step switched %+v", step.Switched) } page := inst.Get(t, "/tasks/"+id) if !strings.Contains(page, "Claude was limited") { t.Fatal("the task page does not show the switch") } if got := stepUsage(t, inst, step.ID); got != "1/failed/claude-1 2/replied/claude-2" { t.Fatalf("step usage rows %q", got) } } // C5 across families (F6): the owner's Claude refuses an Engineering // step on quota; once its exit is proven the step's second attempt runs // on Codex, pushes, and the card shows both. func connEngineeringToCodex(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { r.addAccount(t, "codex", "codex-1", second) r.start(t) s := open(t, env) s.keep() 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" sent := s.send(t, text) id := s.taskOf(t, sent.Turn.ID) step := s.step(t, id, 5*time.Minute, wire.StepDone, wire.StepFailed) if step.State != wire.StepDone || !step.Pushed || step.Account != "codex-1" || step.Attempt != 2 || step.Headline != "Made the change the task asks for." { t.Fatalf("step %+v", step) } // The card shows both: the step on Codex, and Claude limited. if step.Family != "gpt" || step.Switched == nil || step.Switched.From != "claude" || step.Switched.To != "codex" || step.Switched.ResetsAt == nil { t.Fatalf("step switched %+v", step.Switched) } if step.Askable { t.Fatal("a Codex step keeps no session to ask") } if page := inst.Get(t, "/tasks/"+id); !strings.Contains(page, "Claude was limited") { t.Fatal("the task page does not show the switch") } if got := stepUsage(t, inst, step.ID); got != "1/failed/claude-1 2/replied/codex-1" { t.Fatalf("step usage rows %q", got) } } // C5, Review on another family: Engineering runs on the owner's Claude, // and Review on their Codex connection approves, labelled other_family. func connReviewOnCodex(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { r.addAccount(t, "codex", "codex-1", second) r.start(t) s := open(t, env) s.keep() text := "tool:record_task:oficina/sample|Fix the README typo|teh\ntool:start_task:$task|Fix it. edit:README.md|teh panes|the panes" sent := s.send(t, text) id := s.taskOf(t, sent.Turn.ID) var review wire.Step s.wait(t, "review done", 5*time.Minute, func(c *thintest.Conversation) bool { for _, st := range c.Tasks[id].Steps { if st.Specialist == wire.SpecialistReview && wire.StepTerminal(c.Steps[st.ID].State) { review = c.Steps[st.ID] return true } } return false }) 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 { t.Fatalf("review %+v", review) } if got := stepUsage(t, inst, review.ID); got != "1/replied/codex-1" { t.Fatalf("review usage rows %q", got) } } // Astra round 2: Engineering on Claude-A, with Claude-B and Codex-C // healthy and Claude preferred: Review goes to Codex-C, the other family, // before preference and headroom are looked at. func connReviewOtherFamilyFirst(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { r.addAccount(t, "claude", "claude-2", "claude-b@example.com") r.addAccount(t, "codex", "codex-1", second) r.start(t) s := open(t, env) s.keep() if _, err := env.Client.SetPreferences(s.ctx, wire.Preferences{Provider: "claude"}); err != nil { t.Fatal(err) } time.Sleep(2 * time.Second) text := "tool:record_task:oficina/sample|Fix the README typo|teh\ntool:start_task:$task|Fix it. edit:README.md|teh panes|the panes" sent := s.send(t, text) id := s.taskOf(t, sent.Turn.ID) var eng, review wire.Step s.wait(t, "review done", 5*time.Minute, func(c *thintest.Conversation) bool { for _, st := range c.Tasks[id].Steps { switch { case st.Specialist == wire.SpecialistEngineering: eng = c.Steps[st.ID] case st.Specialist == wire.SpecialistReview && wire.StepTerminal(c.Steps[st.ID].State): review = c.Steps[st.ID] return true } } return false }) if eng.Account != "claude-1" || review.State != wire.StepDone || review.Account != "codex-1" || review.ReviewLabel != wire.ReviewOtherFamily { t.Fatalf("engineering on %s, review %+v", eng.Account, review) } } // stepUsage is a step's usage rows as attempt/outcome/connection. func stepUsage(t *testing.T, inst *thintest.Instance, step string) string { t.Helper() rows, err := inst.DB.Writer().Query("SELECT attempt, outcome, connection FROM chat_usage WHERE step_id = ? ORDER BY attempt", step) if err != nil { t.Fatal(err) } defer rows.Close() var out []string for rows.Next() { var attempt int64 var outcome, conn string if err := rows.Scan(&attempt, &outcome, &conn); err != nil { t.Fatal(err) } out = append(out, fmt.Sprintf("%d/%s/%s", attempt, outcome, conn)) } return strings.Join(out, " ") } // C5, nothing left: the only connection refuses an Engineering step on // quota. The step does not fail: its next attempt waits, and runs on its // own once a connection is added. func connEngineeringWaits(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { r.start(t) s := open(t, env) s.keep() 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" sent := s.send(t, text) id := s.taskOf(t, sent.Turn.ID) var eng wire.Step s.wait(t, "second attempt", 2*time.Minute, func(c *thintest.Conversation) bool { for _, st := range c.Tasks[id].Steps { if st.Specialist == wire.SpecialistEngineering { eng = c.Steps[st.ID] } } return eng.Attempt == 2 }) time.Sleep(3 * time.Second) if v := s.conv.Steps[eng.ID]; wire.StepTerminal(v.State) { t.Fatalf("the step ended with nothing to run it: %+v", v) } r.addAccount(t, "claude", "claude-2", second) step := s.step(t, id, 3*time.Minute, wire.StepDone, wire.StepFailed) if step.State != wire.StepDone || step.Account != "claude-2" || step.Attempt != 2 { t.Fatalf("step %+v", step) } } // C5, Review's credential refused: the review moves to another // connection as a new attempt, and the refused one needs signing in again. func connReviewAuth(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { r.addAccount(t, "claude", "claude-2", second) r.start(t) s := open(t, env) s.keep() 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" sent := s.send(t, text) id := s.taskOf(t, sent.Turn.ID) var review wire.Step s.wait(t, "review done", 5*time.Minute, func(c *thintest.Conversation) bool { for _, st := range c.Tasks[id].Steps { if st.Specialist == wire.SpecialistReview && wire.StepTerminal(c.Steps[st.ID].State) { review = c.Steps[st.ID] return true } } return false }) if review.State != wire.StepDone || review.Account != "claude-1" || review.Attempt != 2 || review.Switched == nil { t.Fatalf("review %+v", review) } s.wait(t, "sign in again", time.Minute, func(c *thintest.Conversation) bool { for _, v := range c.Connections { if v.LocalID == "claude-2" { return v.State == wire.ConnSignInAgain } } return false }) } // C6: nothing can answer: the turn is held with the no_connection card // (no "send again"), the message waits; a Codex account added in the app // answers it, once, with the switched line. func connNoConnection(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { r.start(t) s := open(t, env) replyOf(t, s, s.send(t, "Hello first.").Turn.ID) // F5: a cancel while the turn waits ends it, cancelled. first := s.send(t, "Hello. limit:"+thintest.Owner) s.wait(t, "first waits", time.Minute, func(cv *thintest.Conversation) bool { return cv.Turns[first.Turn.ID].State == wire.TurnWaiting }) if _, err := env.Client.Cancel(s.ctx, first.Turn.ID); err != nil { t.Fatal(err) } s.waitTurn(t, first.Turn.ID, wire.TurnCancelled) sent := s.send(t, "Hello. limit:"+thintest.Owner) s.wait(t, "held", time.Minute, func(cv *thintest.Conversation) bool { v := cv.Turns[sent.Turn.ID] return v.State == wire.TurnWaiting && v.Reason == wire.ReasonNoConnection }) page := inst.Get(t, "/conversation") if !strings.Contains(page, "data-no-connection") || !strings.Contains(page, "Nothing can answer right now. Claude resets") || strings.Contains(page, "Send your message again") { t.Fatal("no connection card") } writeJSON(t, filepath.Join(r.root, "accounts", ".fake-device.json"), map[string]any{"email": second, "plan": "plus"}) c, err := env.Client.Connect(s.ctx, wire.Connect{Provider: "codex"}) if err != nil { t.Fatal(err) } s.wait(t, "codex healthy", time.Minute, func(cv *thintest.Conversation) bool { return cv.Connections[c.ID].State == wire.ConnHealthy }) m := replyOf(t, s, sent.Turn.ID) v := s.conv.Turns[sent.Turn.ID] if v.State != wire.TurnReplied || v.Connection != "codex-1" || !strings.Contains(m.Text, "fake Codex coordinator") || m.Switched == nil || m.Switched.To != "codex" { t.Fatalf("turn %+v reply %q %+v", v, m.Text, m.Switched) } } // C5, Review: Review runs away from Engineering's account; that account // hits its limit before a verdict; once its exit is proven Review runs // again on what is left (Engineering's own account, a fresh session) and // approves, and the step shows the switch. func connReviewFailover(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { r.addAccount(t, "claude", "claude-2", second) r.start(t) s := open(t, env) s.keep() 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" sent := s.send(t, text) id := s.taskOf(t, sent.Turn.ID) var review wire.Step s.wait(t, "review done", 5*time.Minute, func(c *thintest.Conversation) bool { for _, st := range c.Tasks[id].Steps { if st.Specialist == wire.SpecialistReview && wire.StepTerminal(c.Steps[st.ID].State) { review = c.Steps[st.ID] return true } } return false }) if review.State != wire.StepDone || review.Verdict != wire.VerdictApprove || review.Account != "claude-1" || review.ReviewLabel != wire.ReviewSameAccount || review.Attempt != 2 { t.Fatalf("review %+v", review) } if review.Switched == nil || review.Switched.From != "claude" { t.Fatalf("review switched %+v", review.Switched) } } // usageRow is one recorded usage row. type usageRow struct { Attempt int64 Outcome, Model, Conn string Complete bool Input, Output, Reasoning *int64 } func usageRows(t *testing.T, inst *thintest.Instance, turn string) []usageRow { t.Helper() 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) if err != nil { t.Fatal(err) } defer rows.Close() var out []usageRow for rows.Next() { var r usageRow if err := rows.Scan(&r.Attempt, &r.Outcome, &r.Model, &r.Conn, &r.Complete, &r.Input, &r.Output, &r.Reasoning); err != nil { t.Fatal(err) } out = append(out, r) } return out } // U1 and U2: a Claude turn and a Codex turn each record one complete // row (Claude's reasoning null, Codex's aggregated from several notices // and a resent one); a cancelled turn records its attempt as cancelled. func connUsageRows(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { r.addAccount(t, "codex", "codex-1", second) r.start(t) s := open(t, env) first := s.send(t, "Hello.") replyOf(t, s, first.Turn.ID) rows := usageRows(t, inst, first.Turn.ID) 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 { t.Fatalf("claude rows %+v", rows) } // Claude limited: the turn moves to Codex; the refused attempt is // recorded as failed, the reply's as replied. moved := s.send(t, "Again. limit:"+thintest.Owner) replyOf(t, s, moved.Turn.ID) rows = usageRows(t, inst, moved.Turn.ID) 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 { t.Fatalf("failover rows %+v", rows) } cancelled := s.send(t, "Take your time. sleep:4000") s.wait(t, "draft", time.Minute, func(c *thintest.Conversation) bool { return c.Drafts[cancelled.Turn.ID] != "" }) if _, err := env.Client.Cancel(s.ctx, cancelled.Turn.ID); err != nil { t.Fatal(err) } s.waitTurn(t, cancelled.Turn.ID, wire.TurnCancelled) var got []usageRow s.wait(t, "cancelled row", time.Minute, func(*thintest.Conversation) bool { got = usageRows(t, inst, cancelled.Turn.ID) return len(got) > 0 }) // What the cancelled turn used before the cancel is kept, not complete. if len(got) != 1 || got[0].Outcome != wire.OutcomeCancelled || got[0].Complete || got[0].Input == nil || *got[0].Input == 0 { t.Fatalf("cancelled rows %+v", got) } } // A6, A7: a refusal with no reset time reported marks the connection // limited with no reset shown anywhere; the provider refusing the // credential marks it sign_in_again, never limited; both move the turn. func connFailureKinds(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { r.addAccount(t, "claude", "claude-2", second) r.addAccount(t, "claude", "claude-3", "third@example.com") r.start(t) s := open(t, env) sent := s.send(t, "Hello. limitnoreset:"+thintest.Owner) m := replyOf(t, s, sent.Turn.ID) if m.Switched == nil || m.Switched.ResetsAt != nil || s.conv.Turns[sent.Turn.ID].Connection != "claude-2" { t.Fatalf("no-reset switch %+v %+v", m.Switched, s.conv.Turns[sent.Turn.ID]) } page := inst.Get(t, "/conversation") if !strings.Contains(page, ">Switched to Claude

") { t.Fatal("the switched line names a reset that was not reported") } auth := s.send(t, "Hello again. authrefused:"+second) a := replyOf(t, s, auth.Turn.ID) if a.Switched == nil || a.Switched.ResetsAt != nil || s.conv.Turns[auth.Turn.ID].Connection != "claude-3" { t.Fatalf("auth switch %+v %+v", a.Switched, s.conv.Turns[auth.Turn.ID]) } state := map[string]wire.Connection{} s.wait(t, "states", time.Minute, func(c *thintest.Conversation) bool { for _, v := range c.Connections { state[v.LocalID] = v } return state["claude-1"].State == wire.ConnLimited && state["claude-2"].State == wire.ConnSignInAgain }) if h := state["claude-1"].Headroom; h != nil && h.ResetsAt != nil { t.Fatalf("a reset time was invented: %+v", h) } page = inst.Get(t, "/conversation/connections") if !strings.Contains(page, "Limited, no reset time reported") || !strings.Contains(page, "Needs signing in again") { t.Fatal("connection states not on the page") } } // codexHomes lists the codex-* homes under the accounts root. func (r *localRunner) codexHomes() []string { m, _ := filepath.Glob(filepath.Join(r.root, "accounts", "codex-*")) return m } func (r *localRunner) hasBinding(t *testing.T, provider string) bool { for _, b := range r.bindings(t) { if b["provider"] == provider { return true } } return false } // A5 and sign-out: a cancel while the person approves at the same moment // leaves no connection, binding or home behind, whichever came first; a // connection signed out from the app is gone from the runner and shown // signed out. func connCancelAndSignOut(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { r.start(t) s := open(t, env) approve := filepath.Join(r.root, "accounts", ".fake-device.json") c, err := env.Client.Connect(s.ctx, wire.Connect{Provider: "codex"}) if err != nil { t.Fatal(err) } s.wait(t, "device code", time.Minute, func(cv *thintest.Conversation) bool { return cv.Connections[c.ID].Prompt != nil }) writeJSON(t, approve, map[string]any{"email": second, "plan": "pro"}) if _, err = env.Client.CancelConnection(s.ctx, c.ID); err != nil { t.Fatal(err) } deadline := time.Now().Add(30 * time.Second) for (r.hasBinding(t, "codex") || len(r.codexHomes()) > 0) && time.Now().Before(deadline) { time.Sleep(200 * time.Millisecond) } if r.hasBinding(t, "codex") || len(r.codexHomes()) > 0 { t.Fatalf("a cancelled attempt left a connection: %v", r.codexHomes()) } time.Sleep(time.Second) if v, _ := env.Client.Connection(s.ctx, c.ID); v.State != wire.ConnError || v.Reason != "cancelled" { t.Fatalf("cancelled attempt %+v", v) } list, _ := env.Client.Connections(s.ctx) for _, v := range list.Items { if v.Provider == "codex" && v.State == wire.ConnHealthy { t.Fatalf("a cancelled Codex connection appeared: %+v", v) } } // Connected, then signed out from the app. c2, err := env.Client.Connect(s.ctx, wire.Connect{Provider: "codex"}) if err != nil { t.Fatal(err) } s.wait(t, "healthy", time.Minute, func(cv *thintest.Conversation) bool { return cv.Connections[c2.ID].State == wire.ConnHealthy }) if _, err = env.Client.SignOut(s.ctx, c2.ID); err != nil { t.Fatal(err) } s.wait(t, "signed out", time.Minute, func(cv *thintest.Conversation) bool { return cv.Connections[c2.ID].State == wire.ConnSignedOut }) // The instance shows signed out as soon as a hello no longer holds the // connection, which the runner sends once the binding is dropped and // a moment before the home is deleted; on a loaded machine that // moment is visible, so wait for the home as for the cancel above. deadline = time.Now().Add(30 * time.Second) for (r.hasBinding(t, "codex") || len(r.codexHomes()) > 0) && time.Now().Before(deadline) { time.Sleep(200 * time.Millisecond) } if r.hasBinding(t, "codex") || len(r.codexHomes()) > 0 { t.Fatal("signed out, but the binding or home stayed") } } // F2: the limit hits straight after the turn's writes (add_project, // record_task, start_task, ask_person, set_project_home). The new attempt // on the other account is told what was done, its repeats are answered // from the record, and there is one project, one task, one step and one // question card. func connQuotaAfterWrites(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { r.addAccount(t, "claude", "claude-2", second) r.start(t) s := open(t, env) // reword: the new attempt words every write differently; status runs // first and last (F2b: the second attempt's status is fresh). 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" sent := s.send(t, text) m := replyOf(t, s, sent.Turn.ID) turn := s.conv.Turns[sent.Turn.ID] if turn.Attempt != 2 || turn.Connection != "claude-2" || m.Switched == nil { t.Fatalf("turn %+v switched %+v", turn, m.Switched) } if !strings.Contains(m.Text, "(earlier effects in context)") { t.Fatalf("the new attempt was not told what was done: %q", m.Text) } // F2b: the new attempt's first status is fresh: the project added in // the first attempt is in it. if _, after, ok := strings.Cut(m.Text, "[status: "); !ok || !strings.Contains(strings.SplitN(after, "[add_project", 2)[0], `"projects":[{`) { t.Fatalf("status was not fresh: %q", m.Text) } time.Sleep(2 * time.Second) snap, err := env.Client.Snapshot(s.ctx) if err != nil { t.Fatal(err) } tasks, steps, questions, projects := 0, 0, 0, 0 for _, k := range snap.Tasks { if strings.HasPrefix(k.Title, "Fix the README typo") { tasks++ for _, st := range k.Steps { if st.Specialist == wire.SpecialistEngineering { steps++ } } } } for _, c := range snap.Cards { if c.Kind == wire.CardQuestion { questions++ } } for _, p := range snap.Projects { if strings.HasSuffix(p.Repo, "oficina/sample") { projects++ } } if tasks != 1 || steps != 1 || questions != 1 || projects != 1 { t.Fatalf("effects ran again: %d tasks, %d steps, %d question cards, %d projects", tasks, steps, questions, projects) } // Every write of attempt 2 reached the instance, the one ledger, and // was folded there: the reworded ones (record_task, start_task, // ask_person) by kind, the identical ones (add_project, // set_project_home) too. var replayed int _ = 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) if replayed != 5 { t.Fatalf("%d reworded writes were folded by the ledger", replayed) } } // scenarioConnWitness is Connections slice 1's live witness (staging // only): the person's messages in EQUIPO_STAGING_CONN_WITNESS, separated // by a line "---", each answered by whichever connection the runner // chooses. It records, per turn, the connection that answered, the // attempt, the switched line and the time to the reply. func scenarioConnWitness(t *testing.T, env *Env) { text := os.Getenv("EQUIPO_STAGING_CONN_WITNESS") if !env.Live || text == "" { t.Skip("staging only, with EQUIPO_STAGING_CONN_WITNESS") } s := open(t, env) s.keep() s.wait(t, "runner online", time.Minute, func(c *thintest.Conversation) bool { return c.Runner.Online }) conns, err := env.Client.Connections(s.ctx) if err != nil { t.Fatal(err) } var held []map[string]any for _, c := range conns.Items { h := map[string]any{"local_id": c.LocalID, "provider": c.Provider, "state": c.State, "plan": c.Plan} if c.Headroom != nil { h["resets_at"], h["utilization"] = c.Headroom.ResetsAt, c.Headroom.Utilization } held = append(held, h) } var turns []map[string]any for _, msg := range strings.Split(text, "\n---\n") { start := time.Now() sent := s.send(t, strings.TrimSpace(msg)) turn := s.waitTurn(t, sent.Turn.ID, wire.TurnReplied, wire.TurnFailed, wire.TurnCancelled) row := map[string]any{"turn": turn.ID, "state": turn.State, "reason": turn.Reason, "attempt": turn.Attempt, "connection": turn.Connection, "seconds": time.Since(start).Seconds()} s.conv.Locked(func(c *thintest.Conversation) { for _, m := range c.Replies() { if m.TurnID == turn.ID { row["reply"], row["switched"] = clipText(m.Text, 300), m.Switched } } }) t.Logf("turn %+v", row) turns = append(turns, row) if turn.State != wire.TurnReplied { break } } Witness[t.Name()] = map[string]any{"connections": held, "turns": turns} } func clipText(s string, n int) string { if len(s) <= n { return s } return s[:n] + "…" } // P1: the person prefers Codex. The coordinator, on Claude, moves to // Codex at the next turn (a boundary), with the switched line; Automatic // again keeps it where it is (stickiness). A stale revision is refused, // and a preference never overrides health: Codex limited, the turn runs // on Claude. A signed-out record can be forgotten. func connPreference(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { r.addAccount(t, "codex", "codex-1", second) r.start(t) s := open(t, env) first := s.send(t, "Hello.") replyOf(t, s, first.Turn.ID) if c := s.conv.Turns[first.Turn.ID].Connection; c != "claude-1" { t.Fatalf("first turn on %s", c) } p, err := env.Client.Preferences(s.ctx) if err != nil || p.Provider != "" || p.Revision != 0 { t.Fatalf("preferences %+v %v", p, err) } if p, err = env.Client.SetPreferences(s.ctx, wire.Preferences{Provider: "codex"}); err != nil || p.Revision != 1 { t.Fatalf("set %+v %v", p, err) } if _, err = env.Client.SetPreferences(s.ctx, wire.Preferences{Provider: "claude"}); err == nil { t.Fatal("a stale revision was taken") } // The runner has it once the frame lands; the next turn moves. deadline := time.Now().Add(30 * time.Second) var moved wire.Message var turn wire.Turn for { sent := s.send(t, "Next.") moved = replyOf(t, s, sent.Turn.ID) turn = s.conv.Turns[sent.Turn.ID] if turn.Connection == "codex-1" || time.Now().After(deadline) { break } } if turn.Connection != "codex-1" || turn.Attempt != 1 || moved.Switched == nil || moved.Switched.To != "codex" { t.Fatalf("preferred turn %+v %+v", turn, moved.Switched) } if _, err = env.Client.SetPreferences(s.ctx, wire.Preferences{Provider: "", Revision: 1}); err != nil { t.Fatal(err) } time.Sleep(2 * time.Second) stay := s.send(t, "Again.") replyOf(t, s, stay.Turn.ID) if c := s.conv.Turns[stay.Turn.ID].Connection; c != "codex-1" { t.Fatalf("Automatic moved the session to %s", c) } // Preferred but limited: Claude answers. if _, err = env.Client.SetPreferences(s.ctx, wire.Preferences{Provider: "codex", Revision: 2}); err != nil { t.Fatal(err) } time.Sleep(2 * time.Second) held := s.send(t, "Limited now. limit:"+second) replyOf(t, s, held.Turn.ID) if c := s.conv.Turns[held.Turn.ID].Connection; c != "claude-1" { t.Fatalf("a limited preferred connection answered: %s", c) } // Signed out, then forgotten. var codex wire.Connection for _, v := range s.conv.Connections { if v.LocalID == "codex-1" { codex = v } } if _, err = env.Client.SignOut(s.ctx, codex.ID); err != nil { t.Fatal(err) } s.wait(t, "signed out", time.Minute, func(cv *thintest.Conversation) bool { return cv.Connections[codex.ID].State == wire.ConnSignedOut }) if err = env.Client.Forget(s.ctx, codex.ID); err != nil { t.Fatal(err) } list, _ := env.Client.Connections(s.ctx) for _, v := range list.Items { if v.ID == codex.ID { t.Fatal("the forgotten record stayed") } } s.wait(t, "forgotten in the stream", time.Minute, func(cv *thintest.Conversation) bool { _, ok := cv.Connections[codex.ID] return !ok }) }