oficina / equipo Public

Connections slice 1: headless C1 to C6, Review failover

Headless scenarios with the fake Claude and fake Codex in bubblewrap:
C1 Claude to Claude failover with the switched line, C2 the Codex
coordinator end to end with tools and a cold resume, C3 Codex added by
device code (refused and already connected too), C4 a second Claude at
the machine (loopback) and by the terminal card, C5 Engineering and
Review moving connection after a quota refusal, C6 a held turn answered
once a Codex account is added.

Review now runs again on the next connection after a quota refusal, and
a step's line names the limited provider.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 914413a97b730f96f3e4cddd9adb13aedabd4a56 parent a480eaf
6 files changed, +490 −14
  • internal/equipo/work_pages.go +4 −0
  • internal/fakeclaude/fake.go +28 −10
  • internal/fakecodex/fake.go +4 −1
  • internal/headless/connections_test.go +411 −0
  • internal/headless/env_test.go +12 −3
  • internal/runner/thin/judge.go +31 −0
diff --git a/internal/equipo/work_pages.go b/internal/equipo/work_pages.go
index 38bf9927..6970027c 100644
--- a/internal/equipo/work_pages.go
+++ b/internal/equipo/work_pages.go
@@ -95,6 +95,10 @@ func taskLineOf(t wire.Task, viewer string) taskLine {
if s.Rebase {
l.Line += " (" + copyText("work.rebase") + ")"
}
+ if s.Switched != nil {
+ // "Engineering on Codex (Claude was limited)": what ran it, and why.
+ l.Line += " (" + fmt.Sprintf(copyText("work.switched"), providerName(s.Switched.From)) + ")"
+ }
if s.State == wire.StepDone {
switch s.Specialist {
case wire.SpecialistChecks:
diff --git a/internal/fakeclaude/fake.go b/internal/fakeclaude/fake.go
index e4b82c50..0e34724b 100644
--- a/internal/fakeclaude/fake.go
+++ b/internal/fakeclaude/fake.go
@@ -648,6 +648,27 @@ func (f *fake) serve(stdin io.Reader, stdout, stderr io.Writer) int {
if strings.Contains(prompt, "=== Your notebook") {
reply += " (notebook in context)"
}
+ // limit:<email> refuses the turn on quota when this home's account
+ // is that email (steplimit:<email> does so for an Engineering step):
+ // a rejected rate_limit_event with its reset, then an error result,
+ // as the CLI reports a spent weekly limit.
+ refuse := func() {
+ reset := time.Now().Add(46 * time.Hour).Truncate(time.Hour).Unix()
+ emit(map[string]any{"type": "rate_limit_event", "rate_limit_info": map[string]any{"status": "rejected", "resetsAt": reset, "rateLimitType": "seven_day", "utilization": 1.0, "unifiedWindows": map[string]any{"seven_day": map[string]any{"utilization": 1.0, "resetsAt": reset, "status": "rejected"}}}, "uuid": fmt.Sprintf("limit-%d", turn), "session_id": f.session})
+ emit(map[string]any{"type": "result", "subtype": "success", "is_error": true, "result": "You've hit your weekly limit", "session_id": session, "num_turns": 1, "usage": map[string]int{"input_tokens": 0, "output_tokens": 0}, "terminal_reason": "completed", "result_index": turn - 1, "uuid": fmt.Sprintf("result-%d", turn)})
+ }
+ if m := limitWord.FindStringSubmatch(newest); m != nil && m[1] == accountEmail() {
+ refuse()
+ continue
+ }
+ if m := stepLimitWord.FindStringSubmatch(prompt); m != nil && m[1] == accountEmail() && strings.HasPrefix(prompt, "[Equipo: engineering]") {
+ refuse()
+ continue
+ }
+ if m := reviewLimitWord.FindStringSubmatch(prompt); m != nil && m[1] == accountEmail() && strings.HasPrefix(prompt, "[Equipo: review]") {
+ refuse()
+ continue
+ }
if strings.HasPrefix(prompt, "[Equipo: engineering]") {
newest = ""
reply = f.engineer(prompt, turn, emit)
@@ -744,15 +765,6 @@ func (f *fake) serve(stdin io.Reader, stdout, stderr io.Writer) int {
}
f.record(prompt, reply)
emit(map[string]any{"type": "assistant", "session_id": f.session, "parent_tool_use_id": nil, "message": map[string]any{"model": f.model, "id": fmt.Sprintf("msg_fake_%d", turn), "type": "message", "role": "assistant", "content": []any{map[string]string{"type": "text", "text": reply}}, "usage": map[string]int{"input_tokens": len(prompt) / 4, "output_tokens": len(reply) / 4}}, "uuid": fmt.Sprintf("assistant-%d", turn)})
- // limit:<email> refuses the turn on quota when this home's account
- // is that email: a rejected rate_limit_event with its reset, then an
- // error result, as the CLI reports a spent weekly limit.
- if m := limitWord.FindStringSubmatch(newest); m != nil && m[1] == accountEmail() {
- reset := time.Now().Add(46 * time.Hour).Truncate(time.Hour).Unix()
- emit(map[string]any{"type": "rate_limit_event", "rate_limit_info": map[string]any{"status": "rejected", "resetsAt": reset, "rateLimitType": "seven_day", "utilization": 1.0, "unifiedWindows": map[string]any{"seven_day": map[string]any{"utilization": 1.0, "resetsAt": reset, "status": "rejected"}}}, "uuid": fmt.Sprintf("limit-%d", turn), "session_id": f.session})
- emit(map[string]any{"type": "result", "subtype": "success", "is_error": true, "result": "You've hit your weekly limit", "session_id": session, "num_turns": 1, "usage": map[string]int{"input_tokens": 0, "output_tokens": 0}, "terminal_reason": "completed", "result_index": turn - 1, "uuid": fmt.Sprintf("result-%d", turn)})
- continue
- }
emit(map[string]any{"type": "rate_limit_event", "rate_limit_info": map[string]any{"status": "allowed", "resetsAt": time.Now().Add(100 * time.Hour).Truncate(time.Hour).Unix(), "rateLimitType": "seven_day", "utilization": 0.25}, "uuid": fmt.Sprintf("limit-%d", turn), "session_id": f.session})
failed := strings.Contains(newest, "fail")
subtype := "success"
@@ -767,7 +779,13 @@ func (f *fake) serve(stdin io.Reader, stdout, stderr io.Writer) int {
var moveInPause = regexp.MustCompile(`movein-pause:([0-9]+)`)
// limitWord is limit:<email>.
-var limitWord = regexp.MustCompile(`limit:([^\s]+@[^\s]+[a-z])`)
+var limitWord = regexp.MustCompile(`\blimit:([^\s|]+@[^\s|]+[a-z])`)
+
+// reviewLimitWord is reviewlimit:<email>, for a Review step only.
+var reviewLimitWord = regexp.MustCompile(`\breviewlimit:([^\s|]+@[^\s|]+[a-z])`)
+
+// stepLimitWord is steplimit:<email>, for an Engineering step only.
+var stepLimitWord = regexp.MustCompile(`\bsteplimit:([^\s|]+@[^\s|]+[a-z])`)
// accountEmail is the signed-in account of the home the fake runs in.
func accountEmail() string {
diff --git a/internal/fakecodex/fake.go b/internal/fakecodex/fake.go
index 54ea9051..114786f0 100644
--- a/internal/fakecodex/fake.go
+++ b/internal/fakecodex/fake.go
@@ -48,6 +48,9 @@ func Main(args []string, stdin io.Reader, stdout, stderr io.Writer) int {
fmt.Fprintln(stdout, "codex-cli "+Version)
return 0
}
+ if len(args) > 0 && args[len(args)-1] == "--help" {
+ return 0
+ }
if len(args) == 0 || args[0] != "app-server" {
fmt.Fprintln(stderr, "fakecodex: only app-server is faked")
return 2
@@ -350,7 +353,7 @@ func (s *server) record(thread, prompt, reply string) int {
var (
toolWord = regexp.MustCompile(`tool:([a-z_]+)(?::([^\n]*))?`)
- limitWord = regexp.MustCompile(`limit:([^\s]+@[^\s]+[a-z])`)
+ limitWord = regexp.MustCompile(`\blimit:([^\s|]+@[^\s|]+[a-z])`)
sleepWord = regexp.MustCompile(`\bsleep:([0-9]+)`)
)
diff --git a/internal/headless/connections_test.go b/internal/headless/connections_test.go
new file mode 100644
index 00000000..a9b208f9
--- /dev/null
+++ b/internal/headless/connections_test.go
@@ -0,0 +1,411 @@
+package headless
+
+import (
+ "context"
+ "crypto/rand"
+ "encoding/json"
+ "net/http"
+ "net/url"
+ "os"
+ "os/exec"
+ "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/thintest"
+ "amadan.net/oficina/equipo/internal/runner/thin"
+ "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", turn, n)
+ }
+ 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)
+ }{
+ {"C1_claude_failover", connClaudeFailover},
+ {"C2_codex_coordinator", connCodexCoordinator},
+ {"C3_codex_device_code", connCodexDeviceCode},
+ {"C4_claude_sign_in", connClaudeSignIn},
+ {"C5_engineering_failover", connEngineeringFailover},
+ {"C5_review_failover", connReviewFailover},
+ {"C6_no_connection", connNoConnection},
+ } {
+ t.Run(sc.name, func(t *testing.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&#39;s limit 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)
+ 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/connections")
+ if !strings.Contains(page, "data-device-code") || !strings.Contains(page, code.Prompt.Code) || !strings.Contains(page, `http-equiv="refresh"`) {
+ t.Fatal("device code not on the page")
+ }
+ 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. At the runner's machine: the card links to
+// Anthropic's sign-in page, whose redirect is the CLI's own loopback
+// listener (simulated here by the browser's callback); nothing is pasted
+// anywhere. Elsewhere: the honest terminal card, which turns healthy when
+// `equipo-runner login claude` finishes there.
+func connClaudeSignIn(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) {
+ r.start(t)
+ s := open(t, env)
+ c, err := env.Client.Connect(s.ctx, wire.Connect{Provider: "claude", SameMachine: true})
+ 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.PromptLink
+ })
+ u, err := url.Parse(link.Prompt.URL)
+ if err != nil || u.Host != "claude.com" || !strings.HasSuffix(u.Path, "/oauth/authorize") {
+ t.Fatalf("link %q", link.Prompt.URL)
+ }
+ // The person's browser on this machine signs in; claude.ai redirects
+ // to the CLI's listener.
+ cb, _ := url.Parse(u.Query().Get("redirect_uri"))
+ q := cb.Query()
+ q.Set("code", "fake-code")
+ q.Set("state", u.Query().Get("state"))
+ q.Set("email", second)
+ cb.RawQuery = q.Encode()
+ res, err := http.Get(cb.String())
+ if err != nil || res.StatusCode != 200 {
+ t.Fatalf("callback %v %v", res, err)
+ }
+ res.Body.Close()
+ s.wait(t, "claude-2 healthy", time.Minute, func(cv *thintest.Conversation) bool {
+ v := cv.Connections[c.ID]
+ return v.State == wire.ConnHealthy && v.LocalID == "claude-2" && v.Label == second
+ })
+ // Browser elsewhere: the terminal card.
+ c2, err := env.Client.Connect(s.ctx, wire.Connect{Provider: "claude"})
+ if err != nil || c2.Prompt == nil || c2.Prompt.Kind != wire.PromptTerminal {
+ t.Fatalf("terminal card %+v %v", c2, err)
+ }
+ page := inst.Get(t, "/conversation/connections")
+ if !strings.Contains(page, "data-finish-on") || !strings.Contains(page, "equipo-runner login claude") || !strings.Contains(page, "data-same-machine") {
+ t.Fatal("terminal card not on the page")
+ }
+ // `equipo-runner login claude` in a terminal on the runner's machine.
+ err = thin.Login(context.Background(), r.cfg, "claude", thin.LoginOptions{Root: filepath.Join(r.root, "accounts"), Output: &strings.Builder{}, Command: func(ctx context.Context, binary string, args []string, dir string, env []string) error {
+ cmd := exec.CommandContext(ctx, binary, args...)
+ cmd.Dir, cmd.Env = dir, append(env, "FAKE_LOGIN_EMAIL=third@example.com")
+ return cmd.Run()
+ }})
+ if err != nil {
+ t.Fatal(err)
+ }
+ s.wait(t, "terminal sign-in seen", time.Minute, func(cv *thintest.Conversation) bool {
+ v := cv.Connections[c2.ID]
+ return v.State == wire.ConnHealthy && v.Label == "third@example.com"
+ })
+ 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)
+ if step.State != wire.StepDone || !step.Pushed || step.Account != "claude-2" || step.Attempt != 1 {
+ 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")
+ }
+ var rows int
+ _ = inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_usage WHERE step_id = ? AND role = 'engineering' AND connection = 'claude-2'", step.ID).Scan(&rows)
+ if rows != 1 {
+ t.Fatalf("step usage rows %d", rows)
+ }
+}
+
+// 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)
+ 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.TurnRunning && 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 {
+ t.Fatalf("review %+v", review)
+ }
+ if review.Switched == nil || review.Switched.From != "claude" {
+ t.Fatalf("review switched %+v", review.Switched)
+ }
+}
diff --git a/internal/headless/env_test.go b/internal/headless/env_test.go
index fe5875e3..ff0855fa 100644
--- a/internal/headless/env_test.go
+++ b/internal/headless/env_test.go
@@ -20,6 +20,7 @@ import (
"time"
"amadan.net/oficina/equipo/internal/fakeclaude"
+ "amadan.net/oficina/equipo/internal/fakecodex"
"amadan.net/oficina/equipo/internal/runner"
"amadan.net/oficina/equipo/internal/runner/containment"
"amadan.net/oficina/equipo/internal/runner/thin"
@@ -35,6 +36,10 @@ func TestMain(m *testing.M) {
switch filepath.Base(os.Args[0]) {
case "claude":
os.Exit(fakeclaude.Main(os.Args[1:], os.Stdin, os.Stdout, os.Stderr))
+ case "codex":
+ os.Exit(fakecodex.Main(os.Args[1:], os.Stdin, os.Stdout, os.Stderr))
+ case "codex-code-mode-host":
+ os.Exit(0)
case "equipo-tool-proxy":
if len(os.Args) != 3 || os.Args[1] != "--socket" {
os.Exit(2)
@@ -245,6 +250,8 @@ func localEnv(t *testing.T) (*Env, *thintest.Instance, *localRunner) {
private(t, root)
bin := private(t, filepath.Join(root, "bin"))
digest := copyExecutable(t, filepath.Join(bin, "claude"))
+ codexDigest := copyExecutable(t, filepath.Join(bin, "codex"))
+ hostDigest := copyExecutable(t, filepath.Join(bin, "codex-code-mode-host"))
copyExecutable(t, filepath.Join(bin, "equipo-tool-proxy"))
state := private(t, filepath.Join(root, "state"))
if err = thintest.WriteRunnerCredential(state, cred); err != nil {
@@ -261,14 +268,14 @@ func localEnv(t *testing.T) (*Env, *thintest.Instance, *localRunner) {
bindings := filepath.Join(config, "bindings.json")
writeJSON(t, bindings, []map[string]any{{"id": "claude-1", "local_id": "claude-1", "label": "claude-1", "person_id": thintest.Owner, "provider": "claude", "family": "claude", "model": "claude-opus-5-5", "account_id": thintest.Owner, "provider_home": home, "kind": "subscription", "expected_identity": identity}})
self, _ := os.Executable()
- cfg := runner.Config{Origin: inst.URL, InstanceID: inst.TeamID, StateDir: state, AccountBindingsPath: bindings, AmadanCredentialPath: filepath.Join(config, "amadan.json"), ClaudePath: filepath.Join(bin, "claude"), CodexPath: filepath.Join(bin, "claude"), CodexCodeModeHostPath: filepath.Join(bin, "claude"), BwrapPath: "/usr/bin/bwrap", GoRoot: filepath.Join(root, "go"), GoBinary: filepath.Join(root, "go", "bin", "go"), WorkspaceRoot: filepath.Join(root, "work"), ScratchRoot: filepath.Join(root, "scratch"), GitPath: "/usr/bin/git", AmadanPath: filepath.Join(bin, "claude"), ToolProxyPath: filepath.Join(bin, "equipo-tool-proxy"), Executable: self}
+ cfg := runner.Config{Origin: inst.URL, InstanceID: inst.TeamID, StateDir: state, AccountBindingsPath: bindings, AmadanCredentialPath: filepath.Join(config, "amadan.json"), ClaudePath: filepath.Join(bin, "claude"), CodexPath: filepath.Join(bin, "codex"), CodexCodeModeHostPath: filepath.Join(bin, "codex-code-mode-host"), BwrapPath: "/usr/bin/bwrap", GoRoot: filepath.Join(root, "go"), GoBinary: filepath.Join(root, "go", "bin", "go"), WorkspaceRoot: filepath.Join(root, "work"), ScratchRoot: filepath.Join(root, "scratch"), GitPath: "/usr/bin/git", AmadanPath: filepath.Join(bin, "claude"), ToolProxyPath: filepath.Join(bin, "equipo-tool-proxy"), Executable: self}
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
if testing.Verbose() {
logger = slog.New(slog.NewTextHandler(os.Stderr, nil))
}
forge := newLocalForge(t, root)
// Moving in is on only for the scenarios about it (2b_*).
- r := &localRunner{inst: inst, root: root, cfg: cfg, opts: thin.Options{Version: "test", Logger: logger, Forge: forge, NoMoveIn: true, MergeEvery: time.Second, Claude: thin.ClaudeOptions{Digest: digest, Idle: time.Minute, LockWait: 5 * time.Second}}}
+ r := &localRunner{inst: inst, root: root, cfg: cfg, opts: thin.Options{Version: "test", Logger: logger, Forge: forge, NoMoveIn: true, MergeEvery: time.Second, Claude: thin.ClaudeOptions{Digest: digest, Idle: time.Minute, LockWait: 5 * time.Second}, Codex: thin.CodexOptions{Digest: codexDigest, HostDigest: hostDigest}, AccountsRoot: filepath.Join(root, "accounts")}}
t.Cleanup(func() { r.stop(t) })
turns := 0
env := &Env{
@@ -374,6 +381,7 @@ type processConfig struct {
ClaudePath, CodexPath, CodexCodeModeHostPath, BwrapPath, GoRoot string
GoBinary, WorkspaceRoot, ScratchRoot, GitPath, AmadanPath, ToolProxy string
Digest, MoveInNote string
+ CodexDigest, CodexHostDigest, AccountsRoot string
NoMoveIn bool
Idle, LockWait, MaxTurn, Margin time.Duration
// Forge is the local forge's state, so a runner process works on the
@@ -396,6 +404,7 @@ func runnerProcess(path string) int {
opts.Forge = p.Forge.forge()
}
opts.Claude = thin.ClaudeOptions{Digest: p.Digest, Idle: p.Idle, LockWait: p.LockWait, MaxTurn: p.MaxTurn, Margin: p.Margin, MoveInNote: p.MoveInNote}
+ opts.Codex, opts.AccountsRoot = thin.CodexOptions{Digest: p.CodexDigest, HostDigest: p.CodexHostDigest}, p.AccountsRoot
err = thin.Run(ctx, cfg, opts)
if err != nil && ctx.Err() == nil {
return 1
@@ -416,7 +425,7 @@ func (r *localRunner) startProcess(t *testing.T) {
if lf, ok := r.opts.Forge.(*localForge); ok {
fs = lf.state()
}
- raw, _ := json.Marshal(processConfig{Forge: fs, Origin: c.Origin, InstanceID: c.InstanceID, StateDir: c.StateDir, AccountBindingsPath: c.AccountBindingsPath, AmadanCredentialPath: c.AmadanCredentialPath, ClaudePath: c.ClaudePath, CodexPath: c.CodexPath, CodexCodeModeHostPath: c.CodexCodeModeHostPath, BwrapPath: c.BwrapPath, GoRoot: c.GoRoot, GoBinary: c.GoBinary, WorkspaceRoot: c.WorkspaceRoot, ScratchRoot: c.ScratchRoot, GitPath: c.GitPath, AmadanPath: c.AmadanPath, ToolProxy: c.ToolProxyPath, Digest: o.Digest, MoveInNote: o.MoveInNote, NoMoveIn: r.opts.NoMoveIn, Idle: o.Idle, LockWait: o.LockWait, MaxTurn: o.MaxTurn, Margin: o.Margin})
+ raw, _ := json.Marshal(processConfig{Forge: fs, Origin: c.Origin, InstanceID: c.InstanceID, StateDir: c.StateDir, AccountBindingsPath: c.AccountBindingsPath, AmadanCredentialPath: c.AmadanCredentialPath, ClaudePath: c.ClaudePath, CodexPath: c.CodexPath, CodexCodeModeHostPath: c.CodexCodeModeHostPath, BwrapPath: c.BwrapPath, GoRoot: c.GoRoot, GoBinary: c.GoBinary, WorkspaceRoot: c.WorkspaceRoot, ScratchRoot: c.ScratchRoot, GitPath: c.GitPath, AmadanPath: c.AmadanPath, ToolProxy: c.ToolProxyPath, Digest: o.Digest, MoveInNote: o.MoveInNote, CodexDigest: r.opts.Codex.Digest, CodexHostDigest: r.opts.Codex.HostDigest, AccountsRoot: r.opts.AccountsRoot, NoMoveIn: r.opts.NoMoveIn, Idle: o.Idle, LockWait: o.LockWait, MaxTurn: o.MaxTurn, Margin: o.Margin})
path := filepath.Join(r.root, "runner.json")
if err := os.WriteFile(path, raw, 0600); err != nil {
t.Fatal(err)
diff --git a/internal/runner/thin/judge.go b/internal/runner/thin/judge.go
index 6d669fa9..66aa0f46 100644
--- a/internal/runner/thin/judge.go
+++ b/internal/runner/thin/judge.go
@@ -677,6 +677,9 @@ func (e *Engineer) review(ctx context.Context, r stepRow, progress func(wire.Ste
b, label, err := e.reviewer(ctx, r.Person, r.AvoidAccount)
if err != nil {
rep.State, rep.Reason, rep.Termination = wire.StepFailed, "account_unavailable", true
+ if errors.Is(err, ErrNoConnection) {
+ rep.Reason = wire.ReasonNoConnection
+ }
return rep
}
rep.Family, rep.Account = b.Family, b.LocalID
@@ -702,6 +705,27 @@ func (e *Engineer) review(ctx context.Context, r stepRow, progress func(wire.Ste
return "Recorded. End with your summary.", false
}
res := e.run(ctx, r, tree, specialistRun{action: "inspect", binding: b, tools: reviewTools, names: []string{"submit_review", "ask_person"}, permission: claude.ReadPermission, call: call, prompt: e.reviewPrompt(r, diff), keep: e.keepDir(r)})
+ e.observe(b.ID, res)
+ // Refused on quota before a verdict: once the exit is proven, Review
+ // runs again on the next connection the choice gives (the refused one
+ // is limited now), with its own independence label.
+ for res.limit != nil && res.terminated && ctx.Err() == nil && e.Conns != nil && verdictUnset(&mu, &verdict) {
+ e.Conns.Limit(b.ID, *res.limit)
+ if rep.Switched == nil {
+ rep.Switched = e.Conns.LimitedFrom(b.ID)
+ }
+ next, nextLabel, err := e.reviewer(ctx, r.Person, r.AvoidAccount)
+ if err != nil {
+ break
+ }
+ b, label = next, nextLabel
+ rep.Family, rep.Account = b.Family, b.LocalID
+ rep.Switched.To = b.Provider
+ progress(rep)
+ res = e.run(ctx, r, tree, specialistRun{action: "inspect", binding: b, tools: reviewTools, names: []string{"submit_review", "ask_person"}, permission: claude.ReadPermission, call: call, prompt: e.reviewPrompt(r, diff), keep: e.keepDir(r)})
+ e.observe(b.ID, res)
+ }
+ rep.Usage = res.usage(b)
rep.LogTail = res.tail
kept := e.recordKept(ctx, r, b.LocalID, res, r.CandidateSHA)
mu.Lock()
@@ -727,6 +751,13 @@ func (e *Engineer) review(ctx context.Context, r stepRow, progress func(wire.Ste
return rep
}
+// verdictUnset reports whether no verdict was recorded yet.
+func verdictUnset(mu *sync.Mutex, verdict *string) bool {
+ mu.Lock()
+ defer mu.Unlock()
+ return *verdict == ""
+}
+
// reviewPrompt is the Review specialist's one user frame.
func (e *Engineer) reviewPrompt(r stepRow, diff string) string {
var b strings.Builder