| 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'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) |
| + } |
| +} |