oficina / equipo Public

Connections slice 1: in-app sign-in, fake Codex, instance records and cards

Runner: a connector runs each connection attempt the app starts. Codex
signs in by device code through the pinned app-server in a new home
(account/login/start, chatgptDeviceCode); Claude at the runner's machine
runs the unmodified claude auth login on a pty with BROWSER recording the
loopback authorize URL; Claude elsewhere shows the terminal step and
watches for the new binding. Nothing typed in the app reaches the runner.

Instance: chat_connections and chat_usage (migration 0048), connections
from hello and connection frames, the connect and cancel_connect
mailbox, GET/POST /api/v1/connections, the switched line on replies and
steps, the held turn (no_connection) and its card, usage rows for turns,
steps and answers, and a Connections page under /conversation.

fakecodex reproduces the app-server for CI: device-code sign-in, rate
limits, token usage, MCP approvals, usageLimitExceeded. fakeclaude gains
a loopback sign-in and limit:<email>.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev d74e500d60a8856917b4b0726b255f6710dd87eb parent baadd5d
32 files changed, +2,590 −207
  • internal/equipo/app.go +3 −0
  • internal/equipo/chat/connections.go +386 −0
  • internal/equipo/chat/http.go +51 −0
  • internal/equipo/chat/models.go +8 −4
  • internal/equipo/chat/questions.go +3 −0
  • internal/equipo/chat/runner.go +24 −4
  • internal/equipo/chat/store.go +26 −5
  • internal/equipo/chat/stream.go +1 −1
  • internal/equipo/chat/tasks.go +25 −3
  • internal/equipo/chat_connections.go +180 −0
  • internal/equipo/chat_page.go +16 −1
  • internal/equipo/copy.go +196 −161
  • internal/equipo/handlers.go +1 −0
  • internal/equipo/migrations/0048_thin_connections.sql +7 −0
  • internal/equipo/migrations/schema.sql +7 −3
  • internal/equipo/render.go +1 −1
  • internal/equipo/static/chat-stream.js +14 −3
  • internal/equipo/templates/chat.html +3 −1
  • internal/equipo/templates/models.html +20 −0
  • internal/fakeclaude/fake.go +68 −0
  • internal/fakecodex/fake.go +606 −0
  • internal/runner/connect/limits.go +4 −4
  • internal/runner/connect/login.go +269 −0
  • internal/runner/thin/connector.go +361 −0
  • internal/runner/thin/link.go +16 −0
  • internal/runner/thin/login.go +21 −12
  • internal/runner/thin/run.go +14 −1
  • internal/runner/thin/state.go +1 −1
  • internal/thintest/client.go +37 −1
  • internal/thintest/connections_contract_test.go +203 −0
  • internal/thintest/instance.go +17 −0
  • internal/wire/wiretest/testdata/api/connections.json +1 −1
diff --git a/internal/equipo/app.go b/internal/equipo/app.go
index d18ecbc5..ec979543 100644
--- a/internal/equipo/app.go
+++ b/internal/equipo/app.go
@@ -211,6 +211,9 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg
r.Post("/conversation/projects/{id}/remove", a.chatProjectRemove)
r.Get("/conversation/notebook", a.chatNotebook)
r.Post("/conversation/notebook/reset", a.chatNotebookReset)
+ r.Get("/conversation/connections", a.connectionsView)
+ r.Post("/conversation/connections", a.connectionsStart)
+ r.Post("/conversation/connections/{id}/cancel", a.connectionsCancel)
a.conversationHandler().Routes(r)
a.planHandler().Routes(r)
r.Post("/tasks/{id}/steps/{key}/selection", a.confirmPlanSelection)
diff --git a/internal/equipo/chat/connections.go b/internal/equipo/chat/connections.go
new file mode 100644
index 00000000..cb529649
--- /dev/null
+++ b/internal/equipo/chat/connections.go
@@ -0,0 +1,386 @@
+package chat
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "slices"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+ "gorm.io/gorm"
+)
+
+// Connections (Equipo Connections spec §§2, 7, slice 1): the instance
+// keeps a record of each of a person's connections and never a secret.
+// A record comes from the runner's hello (what it holds) or from a
+// connection attempt the person started here.
+
+// ErrRunnerOffline: a connection attempt needs the person's runner.
+var ErrRunnerOffline = errors.New("runner offline")
+
+// connectionAttemptLimit ends an attempt that made no progress (the
+// device code itself expires after fifteen minutes).
+const connectionAttemptLimit = 15 * time.Minute
+
+// headroomEvery throttles events for headroom-only changes.
+const headroomEvery = time.Minute
+
+type connectionRecord struct {
+ ID string `gorm:"primaryKey"`
+ Person string `gorm:"index:chat_connection_person"`
+ RunnerID string
+ LocalID string
+ Provider string
+ Kind string
+ Label string
+ State string
+ Reason string
+ Plan string
+ Headroom string
+ Prompt string
+ Revision int64
+ CreatedAt time.Time
+ UpdatedAt time.Time
+}
+
+func (connectionRecord) TableName() string { return "chat_connections" }
+
+// usageRecord is one turn's, step attempt's or answer's token use, as the
+// runner reported it from the harness (spec §6, recorded from day one).
+type usageRecord struct {
+ ID int64 `gorm:"primaryKey"`
+ Person string `gorm:"index:chat_usage_person,priority:1"`
+ Connection string
+ Provider string
+ Model string
+ Role string
+ TaskID string
+ StepID string
+ TurnID string
+ Attempt int64
+ InputTokens int64
+ CachedInputTokens int64
+ CacheWriteTokens int64
+ OutputTokens int64
+ ReasoningOutputTokens int64
+ RecordedAt time.Time `gorm:"index:chat_usage_person,priority:2"`
+}
+
+func (usageRecord) TableName() string { return "chat_usage" }
+
+func connectionView(r connectionRecord) wire.Connection {
+ v := wire.Connection{ID: r.ID, Revision: r.Revision, RunnerID: r.RunnerID, LocalID: r.LocalID, Provider: r.Provider, Kind: r.Kind, Label: r.Label, State: r.State, Reason: r.Reason, Plan: r.Plan, CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt}
+ if r.Headroom != "" {
+ v.Headroom = &wire.Headroom{}
+ if json.Unmarshal([]byte(r.Headroom), v.Headroom) != nil {
+ v.Headroom = nil
+ }
+ }
+ if r.Prompt != "" && r.State == wire.ConnConnecting {
+ v.Prompt = &wire.ConnectPrompt{}
+ if json.Unmarshal([]byte(r.Prompt), v.Prompt) != nil {
+ v.Prompt = nil
+ }
+ }
+ return v
+}
+
+func asJSON(v any) string {
+ if v == nil {
+ return ""
+ }
+ raw, _ := json.Marshal(v)
+ if string(raw) == "null" {
+ return ""
+ }
+ return string(raw)
+}
+
+// saveConnection writes a connection and its event in the transaction.
+func (t *txn) saveConnection(r *connectionRecord, fresh bool) error {
+ r.Revision++
+ r.UpdatedAt = t.now()
+ var err error
+ if fresh {
+ r.CreatedAt = r.UpdatedAt
+ err = t.db.Create(r).Error
+ } else {
+ err = t.db.Model(&connectionRecord{}).Where("id = ?", r.ID).Select("local_id", "label", "state", "reason", "plan", "headroom", "prompt", "revision", "updated_at").Updates(r).Error
+ }
+ if err != nil {
+ return err
+ }
+ return t.event(r.Person, wire.EventConnection, "connection", r.ID, r.Revision, "", "", 0, connectionView(*r))
+}
+
+func (t *txn) connections(person string) ([]connectionRecord, error) {
+ var rows []connectionRecord
+ err := t.db.Where("person = ?", person).Order("created_at, id").Find(&rows).Error
+ return rows, err
+}
+
+// helloConnections records what the person's runner holds: new
+// connections appear, changed ones update (headroom at most once a
+// minute), and one the runner no longer holds is signed out. A
+// teammate's connection in the same hello is never recorded for this
+// person: only the runner's own person's.
+func (t *txn) helloConnections(l Lease, held []wire.HeldConnection) error {
+ person, runner := l.Runner.Person, l.Runner.RunnerID
+ rows, err := t.connections(person)
+ if err != nil {
+ return err
+ }
+ byLocal := map[string]int{}
+ for i, r := range rows {
+ if r.RunnerID == runner && r.LocalID != "" {
+ byLocal[r.LocalID] = i
+ }
+ }
+ seen := map[string]bool{}
+ for _, h := range held {
+ if h.Person != person || h.LocalID == "" || !slices.Contains([]string{wire.ConnHealthy, wire.ConnLimited, wire.ConnSignInAgain, wire.ConnError}, h.State) {
+ continue
+ }
+ seen[h.LocalID] = true
+ headroom := asJSON(h.Headroom)
+ i, ok := byLocal[h.LocalID]
+ if !ok {
+ // An attempt that just finished reports this connection itself.
+ if slices.ContainsFunc(rows, func(r connectionRecord) bool {
+ return r.RunnerID == runner && r.State == wire.ConnConnecting && r.Provider == h.Provider
+ }) {
+ continue
+ }
+ r := connectionRecord{ID: newID("cn_"), Person: person, RunnerID: runner, LocalID: h.LocalID, Provider: h.Provider, Kind: h.Kind, Label: h.Label, State: h.State, Plan: h.Plan, Headroom: headroom}
+ if err := t.saveConnection(&r, true); err != nil {
+ return err
+ }
+ continue
+ }
+ r := rows[i]
+ changed := r.State != h.State || r.Label != h.Label || r.Plan != h.Plan || r.Reason != ""
+ if !changed && r.Headroom == headroom {
+ continue
+ }
+ if !changed && t.now().Sub(r.UpdatedAt) < headroomEvery {
+ continue
+ }
+ r.State, r.Label, r.Plan, r.Headroom, r.Reason, r.Prompt = h.State, h.Label, h.Plan, headroom, "", ""
+ if err := t.saveConnection(&r, false); err != nil {
+ return err
+ }
+ }
+ for _, r := range rows {
+ if r.RunnerID == runner && r.LocalID != "" && !seen[r.LocalID] && r.State != wire.ConnSignedOut && r.State != wire.ConnConnecting {
+ r.State, r.Headroom = wire.ConnSignedOut, ""
+ if err := t.saveConnection(&r, false); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
+
+// connectionReport applies the runner's word on one of its person's
+// connection attempts.
+func (t *txn) connectionReport(l Lease, v *wire.ConnectionReport) error {
+ if !wire.ConnectReasons[v.Reason] || !slices.Contains([]string{wire.ConnConnecting, wire.ConnHealthy, wire.ConnError, wire.ConnLimited}, v.State) {
+ return ErrInvalid
+ }
+ var r connectionRecord
+ err := t.db.Where("id = ? AND person = ? AND runner_id = ?", v.Connection, l.Runner.Person, l.Runner.RunnerID).First(&r).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ // An attempt that ended stays ended: a late frame changes nothing.
+ if r.State != wire.ConnConnecting {
+ return nil
+ }
+ r.State, r.Reason = v.State, v.Reason
+ if v.Label != "" {
+ r.Label = v.Label
+ }
+ if v.Plan != "" {
+ r.Plan = v.Plan
+ }
+ if v.Headroom != nil {
+ r.Headroom = asJSON(v.Headroom)
+ }
+ if v.Prompt != nil {
+ r.Prompt = asJSON(v.Prompt)
+ }
+ if v.State != wire.ConnConnecting {
+ r.Prompt = ""
+ }
+ if v.LocalID != "" && v.State != wire.ConnError {
+ // The hello may have recorded the new connection first.
+ if err := t.db.Where("person = ? AND runner_id = ? AND local_id = ? AND id <> ?", r.Person, r.RunnerID, v.LocalID, r.ID).Delete(&connectionRecord{}).Error; err != nil {
+ return err
+ }
+ r.LocalID = v.LocalID
+ }
+ return t.saveConnection(&r, false)
+}
+
+// Connections lists the person's own connections, every runner.
+func (s *Store) Connections(ctx context.Context, person string) (out []wire.Connection, err error) {
+ out = []wire.Connection{}
+ err = s.read(ctx, func(tx *gorm.DB) error {
+ if err := s.authority.CurrentPerson(ctx, tx); err != nil {
+ return err
+ }
+ rows, err := (&txn{s: s, db: tx}).connections(person)
+ for _, r := range rows {
+ out = append(out, connectionView(r))
+ }
+ return err
+ })
+ return out, err
+}
+
+// Connection reads one of the person's connections.
+func (s *Store) Connection(ctx context.Context, person, id string) (out wire.Connection, err error) {
+ err = s.read(ctx, func(tx *gorm.DB) error {
+ if err := s.authority.CurrentPerson(ctx, tx); err != nil {
+ return err
+ }
+ var r connectionRecord
+ if err := tx.Where("id = ? AND person = ?", id, person).First(&r).Error; errors.Is(err, gorm.ErrRecordNotFound) {
+ return ErrNotFound
+ } else if err != nil {
+ return err
+ }
+ out = connectionView(r)
+ return nil
+ })
+ return out, err
+}
+
+// StartConnection starts a connection attempt on the person's runner (spec §2.1):
+// a Codex account by device code; a Claude account by the CLI's own
+// sign-in, finished at the runner's machine (loopback, no paste) or, when
+// the person's browser is elsewhere, by `equipo-runner login claude` in
+// a terminal there. Nothing secret passes through the instance either way.
+// A second attempt for the same provider while one is connecting returns
+// that one.
+func (s *Store) StartConnection(ctx context.Context, person string, in wire.Connect) (out wire.Connection, err error) {
+ if in.Provider != wire.ProviderClaude && in.Provider != wire.ProviderCodex || in.Kind != "" && in.Kind != wire.KindSubscription {
+ return out, ErrInvalid
+ }
+ err = s.tx(ctx, func(t *txn) error {
+ if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
+ return err
+ }
+ runner, err := s.runnerView(t.db, person)
+ if err != nil {
+ return err
+ }
+ if runner.ID == "" || in.RunnerID != "" && in.RunnerID != runner.ID {
+ return ErrNotFound
+ }
+ rows, err := t.connections(person)
+ if err != nil {
+ return err
+ }
+ for _, r := range rows {
+ if r.State == wire.ConnConnecting && r.Provider == in.Provider && r.RunnerID == runner.ID {
+ out = connectionView(r)
+ return nil
+ }
+ }
+ if !runner.Online {
+ return ErrRunnerOffline
+ }
+ r := connectionRecord{ID: newID("cn_"), Person: person, RunnerID: runner.ID, Provider: in.Provider, Kind: wire.KindSubscription, State: wire.ConnConnecting}
+ if in.Provider == wire.ProviderClaude && !in.SameMachine {
+ // The honest card: Claude's sign-in finishes on the runner's
+ // machine. The runner watches for the terminal login.
+ r.Prompt = asJSON(wire.ConnectPrompt{Kind: wire.PromptTerminal, Code: "equipo-runner login claude"})
+ }
+ if err := t.saveConnection(&r, true); err != nil {
+ return err
+ }
+ out = connectionView(r)
+ return t.command(person, wire.FrameConnect, wire.ConnectCommand{Connection: r.ID, Person: person, Provider: r.Provider, Kind: r.Kind, SameMachine: in.SameMachine})
+ })
+ return out, err
+}
+
+// CancelConnection ends the person's connection attempt.
+func (s *Store) CancelConnection(ctx context.Context, person, id string) (out wire.Connection, err error) {
+ err = s.tx(ctx, func(t *txn) error {
+ if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
+ return err
+ }
+ var r connectionRecord
+ if err := t.db.Where("id = ? AND person = ?", id, person).First(&r).Error; errors.Is(err, gorm.ErrRecordNotFound) {
+ return ErrNotFound
+ } else if err != nil {
+ return err
+ }
+ if r.State != wire.ConnConnecting {
+ out = connectionView(r)
+ return nil
+ }
+ r.State, r.Reason, r.Prompt = wire.ConnError, "cancelled", ""
+ if err := t.saveConnection(&r, false); err != nil {
+ return err
+ }
+ out = connectionView(r)
+ return t.command(person, wire.FrameCancelConnect, wire.CancelConnectCommand{Connection: r.ID, Person: person})
+ })
+ return out, err
+}
+
+// expireAttempts ends attempts that made no progress (a runner that went
+// away mid-attempt reports nothing).
+func (t *txn) expireAttempts() error {
+ var rows []connectionRecord
+ if err := t.db.Where("state = ? AND updated_at < ?", wire.ConnConnecting, t.now().Add(-connectionAttemptLimit)).Find(&rows).Error; err != nil {
+ return err
+ }
+ for i := range rows {
+ rows[i].State, rows[i].Reason, rows[i].Prompt = wire.ConnError, "timed_out", ""
+ if err := t.saveConnection(&rows[i], false); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// recordUsage keeps one usage row; a usage with no tokens is not one.
+func (t *txn) recordUsage(person, role, task, step, turn string, attempt int64, u *wire.Usage) error {
+ if u == nil || u.InputTokens+u.OutputTokens+u.CachedInputTokens+u.CacheWriteTokens+u.ReasoningOutputTokens == 0 {
+ return nil
+ }
+ return t.db.Create(&usageRecord{Person: person, Connection: u.Connection, Provider: u.Provider, Model: u.Model, Role: role, TaskID: task, StepID: step, TurnID: turn, Attempt: attempt, InputTokens: u.InputTokens, CachedInputTokens: u.CachedInputTokens, CacheWriteTokens: u.CacheWriteTokens, OutputTokens: u.OutputTokens, ReasoningOutputTokens: u.ReasoningOutputTokens, RecordedAt: t.now()}).Error
+}
+
+// NoConnectionLine is what the person's connections say about why
+// nothing can answer: each connection's provider with its state and, for
+// a limited one, the reset the provider reported. The page renders it.
+type NoConnectionLine struct {
+ Provider string
+ State string
+ ResetsAt *time.Time
+}
+
+// NoConnection reads the person's connections for the no_connection card.
+func (s *Store) NoConnection(ctx context.Context, person string) (out []NoConnectionLine, err error) {
+ conns, err := s.Connections(ctx, person)
+ for _, c := range conns {
+ if c.State == wire.ConnConnecting || c.State == wire.ConnError && c.LocalID == "" {
+ continue
+ }
+ line := NoConnectionLine{Provider: c.Provider, State: c.State}
+ if c.Headroom != nil && c.State == wire.ConnLimited {
+ line.ResetsAt = c.Headroom.ResetsAt
+ }
+ out = append(out, line)
+ }
+ return out, err
+}
diff --git a/internal/equipo/chat/http.go b/internal/equipo/chat/http.go
index dacd9a16..7c95c70f 100644
--- a/internal/equipo/chat/http.go
+++ b/internal/equipo/chat/http.go
@@ -81,9 +81,58 @@ func (h *HTTP) Mount(r chi.Router) {
r.Get("/questions/{id}", h.thinOr("GET /questions/{id}", thinQuestion, h.bearer(h.question)))
r.Post("/questions/{id}/cancel", h.bearer(h.cancelQuestion))
r.Get("/needs-you", h.thinOr("GET /needs-you", deviceClient, h.bearer(h.needsYou)))
+ r.Get("/connections", h.thinOr("GET /connections", deviceClient, h.bearer(h.connections)))
+ r.Post("/connections", h.bearer(h.connect))
+ r.Get("/connections/{id}", h.thinOr("GET /connections/{id}", thinConnection, h.bearer(h.connection)))
+ r.Post("/connections/{id}/cancel", h.bearer(h.cancelConnection))
r.Get("/events", h.events)
}
+// thinConnection: thin connection ids start "cn_".
+func thinConnection(r *http.Request) bool { return strings.HasPrefix(chi.URLParam(r, "id"), "cn_") }
+
+func (h *HTTP) connections(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
+ out, err := h.Store.Connections(r.Context(), p.Address)
+ if err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ writeJSON(w, 200, wire.ConnectionList{Items: out})
+}
+
+func (h *HTTP) connection(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
+ out, err := h.Store.Connection(r.Context(), p.Address, chi.URLParam(r, "id"))
+ if err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ writeJSON(w, 200, out)
+}
+
+// connect is POST /api/v1/connections: 202 with the attempt connecting.
+func (h *HTTP) connect(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
+ var in wire.Connect
+ if err := readJSON(r, &in); err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ out, err := h.Store.StartConnection(r.Context(), p.Address, in)
+ if err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ writeJSON(w, http.StatusAccepted, out)
+}
+
+func (h *HTTP) cancelConnection(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
+ out, err := h.Store.CancelConnection(r.Context(), p.Address, chi.URLParam(r, "id"))
+ if err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ writeJSON(w, 200, out)
+}
+
type handler func(http.ResponseWriter, *http.Request, personapi.PersonPrincipal)
// bearer admits device bearers only; web pages call the store server side.
@@ -133,6 +182,8 @@ func (h *HTTP) fail(w http.ResponseWriter, r *http.Request, err error) {
personapi.WriteError(w, r, 409, "task_merging", nil)
case errors.Is(err, ErrNotAskable):
personapi.WriteError(w, r, 409, "not_askable", nil)
+ case errors.Is(err, ErrRunnerOffline):
+ personapi.WriteError(w, r, 409, "runner_offline", nil)
default:
h.Failure(w, r, err)
}
diff --git a/internal/equipo/chat/models.go b/internal/equipo/chat/models.go
index 4f410749..8b9632fb 100644
--- a/internal/equipo/chat/models.go
+++ b/internal/equipo/chat/models.go
@@ -7,7 +7,7 @@ package chat
import "time"
// Models are the tables this package owns, for the migration check.
-var Models = []any{&turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, &notebookRecord{}, &taskRecord{}, &stepRecord{}, &entryRecord{}, &attachmentRecord{}, &questionRecord{}}
+var Models = []any{&turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, &notebookRecord{}, &taskRecord{}, &stepRecord{}, &entryRecord{}, &attachmentRecord{}, &questionRecord{}, &connectionRecord{}, &usageRecord{}}
type turnRecord struct {
ID string `gorm:"primaryKey"`
@@ -25,9 +25,11 @@ type turnRecord struct {
// move-in or explore turn asked to give way to the person.
Kind string
Yield bool
- Revision int64
- CreatedAt time.Time
- UpdatedAt time.Time
+ // Connection is the runner's connection that answered (its LocalID).
+ Connection string
+ Revision int64
+ CreatedAt time.Time
+ UpdatedAt time.Time
}
func (turnRecord) TableName() string { return "chat_turns" }
@@ -45,6 +47,8 @@ type messageRecord struct {
TurnID string `gorm:"index:chat_message_turn"`
Revision int64
CreatedAt time.Time
+ // Switched is the reply's wire.Switched JSON, or empty.
+ Switched string
}
func (messageRecord) TableName() string { return "chat_messages" }
diff --git a/internal/equipo/chat/questions.go b/internal/equipo/chat/questions.go
index 1b464cd0..52802b2b 100644
--- a/internal/equipo/chat/questions.go
+++ b/internal/equipo/chat/questions.go
@@ -422,6 +422,9 @@ func (t *txn) answer(l Lease, v *wire.AnswerReport) error {
break
}
q.State, q.Reason, q.Answer = wire.QuestionAnswered, "", clipText(answer, wire.MaxAnswerText)
+ if err := t.recordUsage(q.Asker, "ask", q.TaskID, q.StepID, q.ID, q.Attempt, v.Usage); err != nil {
+ return err
+ }
if v.Timing != nil {
raw, _ := json.Marshal(v.Timing)
q.Timing = string(raw)
diff --git a/internal/equipo/chat/runner.go b/internal/equipo/chat/runner.go
index 1fc4e479..53ce95da 100644
--- a/internal/equipo/chat/runner.go
+++ b/internal/equipo/chat/runner.go
@@ -53,6 +53,13 @@ func (s *Store) Connect(ctx context.Context, p RunnerPrincipal, process string,
if err != nil {
return err
}
+ if primary, err := t.s.authority.PrimaryRunner(t.db, p.Person); err != nil {
+ return err
+ } else if primary == p.RunnerID {
+ if err := t.helloConnections(lease, hello.Connections); err != nil {
+ return err
+ }
+ }
return t.runnerEvent(p.Person, r)
})
return lease, err
@@ -111,6 +118,9 @@ func (s *Store) Heartbeat(ctx context.Context, l Lease, hello wire.Hello) error
if err := t.resolveAccess(l.Runner.Person, hello); err != nil {
return err
}
+ if err := t.helloConnections(l, hello.Connections); err != nil {
+ return err
+ }
}
if !online {
return t.runnerEvent(l.Runner.Person, r)
@@ -220,6 +230,8 @@ func (s *Store) Apply(ctx context.Context, l Lease, f wire.Frame, body any) erro
return t.answer(l, v)
case *wire.BranchReport:
return t.branchMoved(l, v)
+ case *wire.ConnectionReport:
+ return t.connectionReport(l, v)
}
return ErrInvalid
})
@@ -309,10 +321,13 @@ func (t *txn) reply(l Lease, v *wire.Reply) error {
if len(v.Text) > 4*wire.MaxMessageBytes {
v.Text = v.Text[:4*wire.MaxMessageBytes]
}
- r.State, r.Reason, r.Attempt = wire.TurnReplied, "", v.Attempt
+ r.State, r.Reason, r.Attempt, r.Connection = wire.TurnReplied, "", v.Attempt, v.Usage.Connection
+ if err := t.recordUsage(r.Person, "coordinator", "", "", r.ID, v.Attempt, &v.Usage); err != nil {
+ return err
+ }
// A move-in or explore turn with nothing to say posts nothing.
if !quietReply(r, v.Text) {
- m := messageRecord{ID: newID("m_"), Person: r.Person, IdempotencyKey: "reply:" + r.ID, Role: wire.RoleCoordinator, Text: v.Text, TurnID: r.ID, Revision: 1, CreatedAt: t.now()}
+ m := messageRecord{ID: newID("m_"), Person: r.Person, IdempotencyKey: "reply:" + r.ID, Role: wire.RoleCoordinator, Text: v.Text, TurnID: r.ID, Revision: 1, CreatedAt: t.now(), Switched: asJSON(v.Switched)}
if err = t.db.Create(&m).Error; err != nil {
return err
}
@@ -351,10 +366,15 @@ func (t *txn) report(l Lease, v *wire.TurnReport) error {
}
switch v.State {
case wire.TurnRunning:
- if v.Attempt == r.Attempt && r.State == wire.TurnRunning {
+ // Running again on a new attempt (recovery, a failover), or held
+ // for a connection (no_connection) and going again ("").
+ if v.Reason != "" && v.Reason != wire.ReasonNoConnection {
+ return ErrInvalid
+ }
+ if v.Attempt == r.Attempt && r.State == wire.TurnRunning && r.Reason == v.Reason {
return nil
}
- r.State, r.Attempt = wire.TurnRunning, v.Attempt
+ r.State, r.Attempt, r.Reason = wire.TurnRunning, v.Attempt, v.Reason
return t.saveTurn(&r)
case wire.TurnFailed, wire.TurnCancelled:
r.State, r.Reason, r.Attempt = v.State, v.Reason, v.Attempt
diff --git a/internal/equipo/chat/store.go b/internal/equipo/chat/store.go
index 187334e4..ee04f16f 100644
--- a/internal/equipo/chat/store.go
+++ b/internal/equipo/chat/store.go
@@ -131,7 +131,14 @@ func (t *txn) turnEvent(r turnRecord) error {
}
func messageView(m messageRecord) wire.Message {
- return wire.Message{ID: m.ID, Revision: m.Revision, Role: m.Role, Text: m.Text, TurnID: m.TurnID, CreatedAt: m.CreatedAt}
+ v := wire.Message{ID: m.ID, Revision: m.Revision, Role: m.Role, Text: m.Text, TurnID: m.TurnID, CreatedAt: m.CreatedAt}
+ if m.Switched != "" {
+ v.Switched = &wire.Switched{}
+ if json.Unmarshal([]byte(m.Switched), v.Switched) != nil {
+ v.Switched = nil
+ }
+ }
+ return v
}
func (t *txn) messageEvent(m messageRecord) error {
@@ -143,7 +150,7 @@ func (t *txn) turnView(r turnRecord) (wire.Turn, error) {
if err := t.db.Model(&messageRecord{}).Where("turn_id = ? AND role = ?", r.ID, wire.RolePerson).Order("seq").Pluck("id", &ids).Error; err != nil {
return wire.Turn{}, err
}
- v := wire.Turn{ID: r.ID, Revision: r.Revision, Kind: r.Kind, State: r.State, Reason: r.Reason, Attempt: r.Attempt, MessageIDs: ids, ReplyID: r.ReplyID, CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt}
+ v := wire.Turn{ID: r.ID, Revision: r.Revision, Kind: r.Kind, State: r.State, Reason: r.Reason, Attempt: r.Attempt, MessageIDs: ids, ReplyID: r.ReplyID, Connection: r.Connection, CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt}
if r.Timing != "" && r.State == wire.TurnReplied {
v.Timing = &wire.TurnTiming{}
if err := json.Unmarshal([]byte(r.Timing), v.Timing); err != nil {
@@ -156,7 +163,7 @@ func (t *txn) turnView(r turnRecord) (wire.Turn, error) {
func (t *txn) saveTurn(r *turnRecord) error {
r.Revision++
r.UpdatedAt = t.now()
- if err := t.db.Model(&turnRecord{}).Where("id = ?", r.ID).Select("state", "reason", "attempt", "dispatched", "dispatched_at", "timing", "reply_id", "revision", "updated_at", "yield").Updates(r).Error; err != nil {
+ if err := t.db.Model(&turnRecord{}).Where("id = ?", r.ID).Select("state", "reason", "attempt", "dispatched", "dispatched_at", "timing", "reply_id", "revision", "updated_at", "yield", "connection").Updates(r).Error; err != nil {
return err
}
return t.turnEvent(*r)
@@ -483,7 +490,14 @@ func (s *Store) Snapshot(ctx context.Context, person string) (out wire.Snapshot,
if out.Cards, e = full.snapshotCards(person); e != nil {
return e
}
- out.Tasks, e = full.recentTasks(wire.MaxProjectCards)
+ if out.Tasks, e = full.recentTasks(wire.MaxProjectCards); e != nil {
+ return e
+ }
+ conns, e := full.connections(person)
+ out.Connections = make([]wire.Connection, 0, len(conns))
+ for _, r := range conns {
+ out.Connections = append(out.Connections, connectionView(r))
+ }
return e
})
return out, err
@@ -572,6 +586,13 @@ func (s *Store) Sweep(ctx context.Context) error {
if err := tx.Exec("DELETE FROM runner_commands WHERE acked_at IS NOT NULL AND acked_at < ? AND seq < (SELECT max(seq) FROM runner_commands)", cut).Error; err != nil {
return err
}
- return tx.Exec("DELETE FROM runner_inbox WHERE seen_at < ?", s.now().Add(-7*24*time.Hour)).Error
+ if err := tx.Exec("DELETE FROM runner_inbox WHERE seen_at < ?", s.now().Add(-7*24*time.Hour)).Error; err != nil {
+ return err
+ }
+ // Raw usage rows are kept 90 days (spec §6).
+ if err := tx.Exec("DELETE FROM chat_usage WHERE recorded_at < ?", s.now().Add(-90*24*time.Hour)).Error; err != nil {
+ return err
+ }
+ return (&txn{s: s, ctx: ctx, db: tx, touched: map[string]bool{}}).expireAttempts()
})
}
diff --git a/internal/equipo/chat/stream.go b/internal/equipo/chat/stream.go
index 75532b0c..320fc347 100644
--- a/internal/equipo/chat/stream.go
+++ b/internal/equipo/chat/stream.go
@@ -153,7 +153,7 @@ func (rc *runnerConn) read(ctx context.Context) websocket.StatusCode {
switch v := body.(type) {
case *wire.Hello:
err = store.Heartbeat(ctx, rc.lease, *v)
- case *wire.Sync, *wire.Ack, *wire.DeltaReport, *wire.Reply, *wire.TurnReport, *wire.ToolCall, *wire.ActivityReport, *wire.MoveIn, *wire.NotebookReport, *wire.StepReport, *wire.MergedReport, *wire.AnswerReport, *wire.BranchReport:
+ case *wire.Sync, *wire.Ack, *wire.DeltaReport, *wire.Reply, *wire.TurnReport, *wire.ToolCall, *wire.ActivityReport, *wire.MoveIn, *wire.NotebookReport, *wire.StepReport, *wire.MergedReport, *wire.AnswerReport, *wire.BranchReport, *wire.ConnectionReport:
err = store.Apply(ctx, rc.lease, f, body)
case *wire.LeaseCheck:
// Answered only while this connection holds the lease.
diff --git a/internal/equipo/chat/tasks.go b/internal/equipo/chat/tasks.go
index b596951f..30422e2d 100644
--- a/internal/equipo/chat/tasks.go
+++ b/internal/equipo/chat/tasks.go
@@ -124,6 +124,8 @@ type stepRecord struct {
MergeInto string
MergeStrategy string
WithoutChecks bool
+ // Switched is the wire.Switched JSON when the step moved connection.
+ Switched string
}
func (stepRecord) TableName() string { return "chat_steps" }
@@ -287,6 +289,18 @@ func stepView(s stepRecord) wire.Step {
Rebase: s.Rebase, MergeSHA: s.MergeSHA, Into: s.MergeInto, Strategy: s.MergeStrategy, WithoutChecks: s.WithoutChecks}
}
+// stepViewSwitched adds the switched line, when the step moved.
+func stepViewSwitched(s stepRecord) wire.Step {
+ v := stepView(s)
+ if s.Switched != "" {
+ v.Switched = &wire.Switched{}
+ if json.Unmarshal([]byte(s.Switched), v.Switched) != nil {
+ v.Switched = nil
+ }
+ }
+ return v
+}
+
// taskView is the task with its project, findings, steps and thread.
func (t *txn) taskView(k taskRecord) (wire.Task, error) {
v := wire.Task{ID: k.ID, Revision: k.Revision, ProjectID: k.ProjectID, Title: k.Title, Brief: k.Brief, Stage: k.Stage, Branch: k.Branch, BaseSHA: k.BaseSHA, Creator: k.Creator, TurnID: k.TurnID, Findings: []wire.Finding{}, Steps: []wire.Step{}, Thread: []wire.ThreadEntry{}, CreatedAt: k.CreatedAt, UpdatedAt: k.UpdatedAt}
@@ -314,7 +328,7 @@ func (t *txn) taskView(k taskRecord) (wire.Task, error) {
return v, err
}
for _, s := range steps {
- v.Steps = append(v.Steps, stepView(s))
+ v.Steps = append(v.Steps, stepViewSwitched(s))
if s.Pushed {
v.URL = BranchURL(p.Repo, k.Branch)
}
@@ -396,7 +410,7 @@ func (t *txn) taskEvent(k taskRecord) error {
func (t *txn) saveStep(s *stepRecord, k *taskRecord) error {
s.Revision++
s.UpdatedAt = t.now()
- if err := t.db.Model(&stepRecord{}).Where("id = ?", s.ID).Select("state", "reason", "attempt", "base_sha", "candidate_sha", "pushed", "terminated", "summary", "log_tail", "started_at", "finished_at", "revision", "updated_at", "family", "account", "verdict", "review_label", "findings", "checks", "gate", "exit_code", "output", "republish", "from_attempt", "askable", "rebase", "from_base", "from_candidate", "merge_sha", "merge_into", "merge_strategy", "without_checks").Updates(s).Error; err != nil {
+ if err := t.db.Model(&stepRecord{}).Where("id = ?", s.ID).Select("state", "reason", "attempt", "base_sha", "candidate_sha", "pushed", "terminated", "summary", "log_tail", "started_at", "finished_at", "revision", "updated_at", "family", "account", "verdict", "review_label", "findings", "checks", "gate", "exit_code", "output", "republish", "from_attempt", "askable", "rebase", "from_base", "from_candidate", "merge_sha", "merge_into", "merge_strategy", "without_checks", "switched").Updates(s).Error; err != nil {
return err
}
members, err := t.members()
@@ -404,7 +418,7 @@ func (t *txn) saveStep(s *stepRecord, k *taskRecord) error {
return err
}
for _, m := range members {
- if err := t.event(m, wire.EventStep, "step", s.ID, s.Revision, "", "", s.Attempt, stepView(*s)); err != nil {
+ if err := t.event(m, wire.EventStep, "step", s.ID, s.Revision, "", "", s.Attempt, stepViewSwitched(*s)); err != nil {
return err
}
}
@@ -752,6 +766,14 @@ func (t *txn) stepReport(l Lease, v *wire.StepReport) error {
s.Terminated, changed = true, true
}
} else {
+ if wire.StepTerminal(v.State) {
+ if err := t.recordUsage(s.Person, s.Specialist, s.TaskID, s.ID, "", s.Attempt, v.Usage); err != nil {
+ return err
+ }
+ }
+ if v.Switched != nil && s.Switched == "" {
+ s.Switched, changed = asJSON(v.Switched), true
+ }
if s.BaseSHA == "" && v.BaseSHA != "" {
s.BaseSHA, changed = v.BaseSHA, true
if k.BaseSHA == "" {
diff --git a/internal/equipo/chat_connections.go b/internal/equipo/chat_connections.go
new file mode 100644
index 00000000..4ba07dc1
--- /dev/null
+++ b/internal/equipo/chat_connections.go
@@ -0,0 +1,180 @@
+package equipo
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "strings"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/chat"
+ "amadan.net/oficina/equipo/internal/wire"
+ "github.com/go-chi/chi/v5"
+ "gorm.io/gorm"
+)
+
+// The person's connections page (Equipo Connections slice 1): the
+// accounts their coordinator and specialists run on, how each stands,
+// and adding one from the app. Scriptless: a connecting attempt reloads
+// the page every few seconds until it ends.
+
+type modelLine struct {
+ ID, Name, Label, State string
+ Connecting bool
+ Prompt *wire.ConnectPrompt
+ Note string
+}
+
+type modelsView struct {
+ Items []modelLine
+ Runner string
+ Offline bool
+ Refresh bool
+}
+
+// providerName is how a provider is named to a person.
+func providerName(p string) string {
+ switch p {
+ case wire.ProviderClaude:
+ return "Claude"
+ case wire.ProviderCodex:
+ return "Codex"
+ }
+ return p
+}
+
+// resetText renders a provider's reset time in UTC, the instance's only
+// zone until a person's zone is known.
+func resetText(t time.Time) string { return t.UTC().Format("Mon 15:04") + " UTC" }
+
+func connectionState(c wire.Connection) string {
+ switch c.State {
+ case wire.ConnHealthy:
+ return copyText("chat.connections.healthy")
+ case wire.ConnLimited:
+ if c.Headroom != nil && c.Headroom.ResetsAt != nil {
+ return fmt.Sprintf(copyText("chat.connections.limited_until"), resetText(*c.Headroom.ResetsAt))
+ }
+ return copyText("chat.connections.limited")
+ case wire.ConnSignedOut:
+ return copyText("chat.connections.signed_out")
+ case wire.ConnSignInAgain:
+ return copyText("chat.connections.sign_in_again")
+ case wire.ConnConnecting:
+ return fmt.Sprintf(copyText("chat.connections.connecting"), providerName(c.Provider))
+ }
+ return copyText("chat.connections.error")
+}
+
+// switchedText is the quiet line under a reply that moved connection.
+func switchedText(s *wire.Switched) string {
+ if s == nil {
+ return ""
+ }
+ to := providerName(s.To)
+ if s.ResetsAt == nil {
+ return fmt.Sprintf(copyText("chat.switched"), to)
+ }
+ return fmt.Sprintf(copyText("chat.switched_reset"), to, providerName(s.From), resetText(*s.ResetsAt))
+}
+
+// noConnectionText says why nothing can answer, from the connections.
+func noConnectionText(lines []chat.NoConnectionLine) string {
+ var parts []string
+ for _, l := range lines {
+ name := providerName(l.Provider)
+ switch {
+ case l.State == wire.ConnLimited && l.ResetsAt != nil:
+ parts = append(parts, fmt.Sprintf(copyText("chat.no_connection.resets"), name, resetText(*l.ResetsAt)))
+ case l.State == wire.ConnLimited:
+ parts = append(parts, fmt.Sprintf(copyText("chat.no_connection.limited"), name))
+ case l.State == wire.ConnSignedOut || l.State == wire.ConnSignInAgain || l.State == wire.ConnError:
+ parts = append(parts, fmt.Sprintf(copyText("chat.no_connection.signed_out"), name))
+ }
+ }
+ why := strings.Join(parts, "; ") + "."
+ if len(parts) == 0 {
+ why = copyText("chat.no_connection.none")
+ }
+ return fmt.Sprintf(copyText("chat.no_connection"), why)
+}
+
+func (a *application) runnerLabel(ctx context.Context, address, id string) string {
+ label := ""
+ _ = a.store.readTeam(ctx, Actor{Address: address}, func(tx *gorm.DB, _ Team) error {
+ return tx.Raw("SELECT coalesce(label, '') FROM runners WHERE id = ?", id).Scan(&label).Error
+ })
+ return label
+}
+
+func (a *application) connectionsView(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store")
+ ctx, address, ok := sessionContext(r)
+ if !ok {
+ a.failure(w, r, ErrForbidden)
+ return
+ }
+ snap, err := a.store.Chat().Snapshot(ctx, address)
+ if err != nil {
+ a.failure(w, r, chatError(err))
+ return
+ }
+ data, err := a.page(r, "conversation")
+ if err != nil {
+ a.failure(w, r, err)
+ return
+ }
+ data.Title = "chat.connections.title"
+ v := modelsView{Offline: !snap.Runner.Online, Runner: a.runnerLabel(ctx, address, snap.Runner.ID)}
+ if v.Runner == "" {
+ v.Runner = copyText("chat.connections.title")
+ }
+ for _, c := range snap.Connections {
+ line := modelLine{ID: c.ID, Name: providerName(c.Provider), Label: c.Label, State: connectionState(c), Connecting: c.State == wire.ConnConnecting, Prompt: c.Prompt}
+ if c.State == wire.ConnError && c.LocalID == "" {
+ // An attempt that ended says why once, then the page moves on.
+ if time.Since(c.UpdatedAt) > 10*time.Minute {
+ continue
+ }
+ line.State, line.Note = "", copyText("chat.connections.reason."+c.Reason)
+ }
+ v.Refresh = v.Refresh || line.Connecting
+ v.Items = append(v.Items, line)
+ }
+ data.Models = v
+ render(w, "models", data)
+}
+
+// connectionsStart is Add Codex, Add Claude and "I am at this machine".
+func (a *application) connectionsStart(w http.ResponseWriter, r *http.Request) {
+ a.chatActionTo(w, r, "/conversation/connections", func(ctx context.Context, address string) error {
+ provider, same := r.PostFormValue("provider"), r.PostFormValue("same_machine") == "1"
+ if same {
+ // The terminal card gives way to the sign-in at this machine.
+ conns, err := a.store.Chat().Connections(ctx, address)
+ if err != nil {
+ return err
+ }
+ for _, c := range conns {
+ if c.State == wire.ConnConnecting && c.Provider == provider {
+ if _, err := a.store.Chat().CancelConnection(ctx, address, c.ID); err != nil {
+ return err
+ }
+ }
+ }
+ }
+ _, err := a.store.Chat().StartConnection(ctx, address, wire.Connect{Provider: provider, Kind: wire.KindSubscription, SameMachine: same})
+ if errors.Is(err, chat.ErrRunnerOffline) {
+ return nil
+ }
+ return err
+ })
+}
+
+func (a *application) connectionsCancel(w http.ResponseWriter, r *http.Request) {
+ a.chatActionTo(w, r, "/conversation/connections", func(ctx context.Context, address string) error {
+ _, err := a.store.Chat().CancelConnection(ctx, address, chi.URLParam(r, "id"))
+ return err
+ })
+}
diff --git a/internal/equipo/chat_page.go b/internal/equipo/chat_page.go
index b9bd0bdc..151b8089 100644
--- a/internal/equipo/chat_page.go
+++ b/internal/equipo/chat_page.go
@@ -26,11 +26,18 @@ type chatView struct {
Messages []chatLine
Waiting []wire.Turn
Ended *chatEnded
+ // NoConnection is the card for a turn held because nothing the person
+ // connected can answer; the message waits and goes on its own.
+ NoConnection *noConnectionCard
Offline bool
Cursor int64
}
+type noConnectionCard struct{ TurnID, Line string }
+
type chatLine struct {
+ // Switched is the quiet line under a reply that moved connection.
+ Switched string
ID, Text, TurnID string
Own bool
CreatedAt time.Time
@@ -151,7 +158,7 @@ func (a *application) chatPage(w http.ResponseWriter, r *http.Request) {
view := chatView{Offline: !snap.Runner.Online, Cursor: snap.Cursor}
last := map[string]int{}
for i, m := range snap.Messages {
- view.Messages = append(view.Messages, chatLine{ID: m.ID, Text: m.Text, TurnID: m.TurnID, Own: m.Role == wire.RolePerson, CreatedAt: m.CreatedAt})
+ view.Messages = append(view.Messages, chatLine{ID: m.ID, Text: m.Text, TurnID: m.TurnID, Own: m.Role == wire.RolePerson, CreatedAt: m.CreatedAt, Switched: switchedText(m.Switched)})
last[m.TurnID] = i
}
choices, err := a.store.Chat().ProjectChoices(ctx, address)
@@ -198,6 +205,14 @@ func (a *application) chatPage(w http.ResponseWriter, r *http.Request) {
for i, t := range snap.Turns {
if !wire.Terminal(t.State) {
view.Waiting = append(view.Waiting, t)
+ if t.Reason == wire.ReasonNoConnection && view.NoConnection == nil {
+ lines, err := a.store.Chat().NoConnection(ctx, address)
+ if err != nil {
+ a.failure(w, r, chatError(err))
+ return
+ }
+ view.NoConnection = &noConnectionCard{TurnID: t.ID, Line: noConnectionText(lines)}
+ }
}
// Turns the coordinator takes on its own never end in a note.
if t.Kind == wire.TurnPerson && (latest == nil || t.CreatedAt.After(latest.CreatedAt)) {
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index dca918d0..3d00264f 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -467,167 +467,202 @@ var pageCopy = map[string]string{
"plan.action.scope": "Define scope",
// COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context): conversation.title
// COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "conversation.thinking": "Thinking",
- "chat.offline": "Your runner is offline. Messages wait here until it is back.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.failed": "The coordinator could not answer. Send your message again to retry.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.cancelled": "Stopped.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.activity.thinking": "Thinking", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.activity.status": "Checking your projects…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.activity.add_project": "Adding a project…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.activity.ask_person": "Writing you a question…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.activity.other": "Working…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.activity.find": "Looking for it…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.activity.search_code": "Searching the code…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.activity.read_file": "Reading the code…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.activity.create_project": "Creating a repository…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.activity.set_project_home": "Updating where new projects go…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.activity.write_note": "Writing notes…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.activity.read_notes": "Reading notes…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.activity.read_file_repo": "Reading %s…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.activity.search_code_repo": "Searching %s…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.activity.move_in": "Moving in… %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.activity.explore": "Looking at new access… %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.activity.record_task": "Noting the task…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.activity.add_finding": "Noting what I found…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.activity.start_task": "Handing it to Engineering…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.activity.read_task": "Checking the task…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.activity.cancel_task": "Cancelling the task…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "nav.tasks": "Tasks", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.access_resolved": "%s is reachable now.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.grant_check": "Check now", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.stage.noted": "Noted", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.stage.investigated": "Looking into it", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.stage.in_progress": "In progress", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.stage.in_review": "In review", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.stage.ready_to_merge": "Ready to merge", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.stage.done": "Done", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.stage.cancelled": "Cancelled", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.stopped": "Stopped: %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.reason.runner_restarted": "the runner restarted", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.reason.no_changes": "nothing needed changing", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.reason.push_failed": "the push to Amadan failed", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.reason.push_conflict": "the branch changed on Amadan", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.reason.step_timeout": "it ran out of time", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.reason.interrupted": "the runner lost track of it", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.reason.other": "something went wrong", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.pushed": "Pushed %s at %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.open": "Open on Amadan", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.retry": "Retry", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.cancel": "Cancel", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.step": "%s, attempt %d: %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.step.queued": "waiting", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.step.running": "working", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.step.done": "done", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.step.failed": "stopped", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.step.cancelled": "cancelled", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.findings": "Findings", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.steps": "Steps", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.notes": "Notes", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.note_add": "Add a note", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.notes_empty": "No notes yet.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.noted_by": "Noted by %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.tasks_empty": "No tasks yet. Tell the coordinator what needs doing.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.all_tasks": "All tasks", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.projects_empty": "No projects yet. They appear here when the coordinator adds them.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "nav.working": "working", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "nav.more": "+%d more", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.specialist.engineering": "Engineering", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.specialist.checks": "Checks", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.specialist.review": "Review", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.round": "fix round %d", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.checks.passed": "Checks passed (%s)", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.checks.failed": "Checks failed (%s, exit %d)", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.checks.none": "No checks found", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.checks.needs_macos": "Checks can't run here (needs macOS)", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.checks.needs_network": "Checks can't run here (they need the network)", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.checks.checks_timeout": "Checks didn't finish in time", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.checks.checks_unavailable": "Checks can't run on this runner", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.checks.running": "Running checks…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.review.approve": "Approved (%s)", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.review.changes_requested": "Changes requested (%s)", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.review.running": "Reviewing…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.review.other_family": "another model family", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.review.same_family": "same family", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.review.same_account": "same family, same account", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.needs.fix_rounds": "Needs you: still not approved after two fix rounds", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.needs.branch_moved": "Needs you: the branch moved on Amadan after it was checked", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.needs.review_blocked": "Needs you: the review ended without a verdict", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.reason.no_verdict": "the review gave no verdict", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.reason.candidate_unavailable": "the commit was not on Amadan", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.reason.account_unavailable": "no model account was ready", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.review_findings": "Review found", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.needs_empty": "Nothing needs you right now.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.thread": "Questions and notes", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.thread_empty": "No questions or notes yet.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.ask.target": "Asking %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.ask.change": "change", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.ask.placeholder": "Ask %s about this work", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.ask.queued": "Waiting for its turn…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.ask.failed": "%s couldn't answer: %s.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.ask.cancelled": "Question cancelled.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.ask.reason.session_gone": "its session for this work is no longer kept", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.ask.reason.task_ended": "the task has ended", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.stage.merging": "Merging…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.merged": "Merged into %s at %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.merged_without_checks": "Merged into %s at %s, without checks", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.specialist.merge": "Merge", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.rebase": "rebase", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.needs.merge_conflict": "Needs you: it still conflicts with the default branch after a rebase", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.reason.merge_conflict": "it conflicts with the default branch", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.reason.branch_moved": "the branch moved on Amadan", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.reason.amadan_ci_pending": "Amadan's own CI had not finished", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.reason.amadan_ci_failed": "Amadan's own CI did not pass", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.reason.merge_forbidden": "Equipo may not merge in this repository", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.reason.merge_failed": "Amadan did not merge it", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.merge_question": "Merge %s without checks?", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.merge": "Merge", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.wait": "Wait for checks", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.merge_chose_merge": "Merging without checks.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.merge_chose_wait": "Waiting for checks.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.merge_resolved": "Nothing to decide any more.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.merge_adopt": "Merge %s?", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.not_now": "Not now", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.merge_chose_not_now": "Not now.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.merged": "Merged [%s](%s) into %s.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.merged_without_checks": "Merged [%s](%s) into %s without checks.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.activity.add_report": "Adding to the task…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.activity.read_change": "Looking at the change…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "work.task_count": "Tasks: %d", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.moving_in": "Moving in…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.exploring": "Looking at new access…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.added": "Added %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.working": "Working in %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.created": "Created %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.removed": "Removed %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.changed": "Moved to %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.change": "Change", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.move": "Move", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.remove": "Remove", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.use": "Use this", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.answer": "Answer", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.answered": "You answered: %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.access": "Equipo can't reach %s yet. Its agent reaches %s.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.grant": "Grant access", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.grant_how": "The namespace owner runs this once:", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.home": "New projects go to %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.home_cleared": "New projects go to the best-fitting existing repository", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.undo": "Undo", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.undone": "Undone", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.home_ask": "Use %s for new projects?", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.home_ask_clear": "Stop using %s for new projects?", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.confirm": "Yes", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.card.more": "More", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.notebook.link": "Notebook", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.notebook.title": "Notebook", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.notebook.lede": "What your coordinator keeps in mind, and where each note came from. Notes are reference for it, never instructions.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.notebook.empty": "Your coordinator has no notes yet.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.notebook.person": "You said", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.notebook.repo": "From %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.notebook.own": "Coordinator's note", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.notebook.reset": "Reset", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.notebook.reset_help": "Reset clears these notes and starts your coordinator afresh. It moves in again and introduces itself.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "chat.elapsed": "{n}s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "conversation.title": "Conversation",
+ "conversation.thinking": "Thinking",
+ "chat.offline": "Your runner is offline. Messages wait here until it is back.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.failed": "The coordinator could not answer this message.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.cancelled": "Stopped.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.activity.thinking": "Thinking", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.activity.status": "Checking your projects…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.activity.add_project": "Adding a project…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.activity.ask_person": "Writing you a question…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.activity.other": "Working…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.activity.find": "Looking for it…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.activity.search_code": "Searching the code…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.activity.read_file": "Reading the code…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.activity.create_project": "Creating a repository…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.activity.set_project_home": "Updating where new projects go…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.activity.write_note": "Writing notes…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.activity.read_notes": "Reading notes…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.activity.read_file_repo": "Reading %s…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.activity.search_code_repo": "Searching %s…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.activity.move_in": "Moving in… %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.activity.explore": "Looking at new access… %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.activity.record_task": "Noting the task…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.activity.add_finding": "Noting what I found…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.activity.start_task": "Handing it to Engineering…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.activity.read_task": "Checking the task…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.activity.cancel_task": "Cancelling the task…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "nav.tasks": "Tasks", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.access_resolved": "%s is reachable now.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.grant_check": "Check now", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.stage.noted": "Noted", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.stage.investigated": "Looking into it", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.stage.in_progress": "In progress", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.stage.in_review": "In review", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.stage.ready_to_merge": "Ready to merge", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.stage.done": "Done", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.stage.cancelled": "Cancelled", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.stopped": "Stopped: %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.reason.runner_restarted": "the runner restarted", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.reason.no_changes": "nothing needed changing", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.reason.push_failed": "the push to Amadan failed", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.reason.push_conflict": "the branch changed on Amadan", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.reason.step_timeout": "it ran out of time", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.reason.interrupted": "the runner lost track of it", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.reason.other": "something went wrong", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.pushed": "Pushed %s at %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.open": "Open on Amadan", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.retry": "Retry", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.cancel": "Cancel", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.step": "%s, attempt %d: %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.step.queued": "waiting", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.step.running": "working", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.step.done": "done", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.step.failed": "stopped", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.step.cancelled": "cancelled", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.findings": "Findings", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.steps": "Steps", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.notes": "Notes", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.note_add": "Add a note", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.notes_empty": "No notes yet.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.noted_by": "Noted by %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.tasks_empty": "No tasks yet. Tell the coordinator what needs doing.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.all_tasks": "All tasks", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.projects_empty": "No projects yet. They appear here when the coordinator adds them.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "nav.working": "working", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "nav.more": "+%d more", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.specialist.engineering": "Engineering", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.specialist.checks": "Checks", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.specialist.review": "Review", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.round": "fix round %d", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.checks.passed": "Checks passed (%s)", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.checks.failed": "Checks failed (%s, exit %d)", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.checks.none": "No checks found", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.checks.needs_macos": "Checks can't run here (needs macOS)", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.checks.needs_network": "Checks can't run here (they need the network)", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.checks.checks_timeout": "Checks didn't finish in time", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.checks.checks_unavailable": "Checks can't run on this runner", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.checks.running": "Running checks…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.review.approve": "Approved (%s)", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.review.changes_requested": "Changes requested (%s)", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.review.running": "Reviewing…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.review.other_family": "another model family", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.review.same_family": "same family", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.review.same_account": "same family, same account", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.needs.fix_rounds": "Needs you: still not approved after two fix rounds", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.needs.branch_moved": "Needs you: the branch moved on Amadan after it was checked", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.needs.review_blocked": "Needs you: the review ended without a verdict", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.reason.no_verdict": "the review gave no verdict", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.reason.candidate_unavailable": "the commit was not on Amadan", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.reason.account_unavailable": "no model account was ready", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.review_findings": "Review found", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.needs_empty": "Nothing needs you right now.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.thread": "Questions and notes", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.thread_empty": "No questions or notes yet.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.ask.target": "Asking %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.ask.change": "change", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.ask.placeholder": "Ask %s about this work", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.ask.queued": "Waiting for its turn…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.ask.failed": "%s couldn't answer: %s.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.ask.cancelled": "Question cancelled.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.ask.reason.session_gone": "its session for this work is no longer kept", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.ask.reason.task_ended": "the task has ended", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.stage.merging": "Merging…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.merged": "Merged into %s at %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.merged_without_checks": "Merged into %s at %s, without checks", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.specialist.merge": "Merge", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.rebase": "rebase", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.needs.merge_conflict": "Needs you: it still conflicts with the default branch after a rebase", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.reason.merge_conflict": "it conflicts with the default branch", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.reason.branch_moved": "the branch moved on Amadan", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.reason.amadan_ci_pending": "Amadan's own CI had not finished", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.reason.amadan_ci_failed": "Amadan's own CI did not pass", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.reason.merge_forbidden": "Equipo may not merge in this repository", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.reason.merge_failed": "Amadan did not merge it", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.merge_question": "Merge %s without checks?", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.merge": "Merge", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.wait": "Wait for checks", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.merge_chose_merge": "Merging without checks.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.merge_chose_wait": "Waiting for checks.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.merge_resolved": "Nothing to decide any more.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.merge_adopt": "Merge %s?", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.not_now": "Not now", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.merge_chose_not_now": "Not now.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.title": "Connections", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.empty": "Nothing is connected yet.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.add_codex": "Add Codex", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.add_claude": "Add Claude", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.connecting": "Connecting %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.device": "Go to %s and enter %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.sign_in_claude": "Sign in to Claude", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.finish_on": "Finish signing in on %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.finish_how": "Claude sign-in finishes on the machine that runs your runner. In a terminal there, run:", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.same_machine": "I am at this machine", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.cancel": "Cancel", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.healthy": "Healthy", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.limited": "Limited", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.limited_until": "Limited until %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.signed_out": "Signed out", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.sign_in_again": "Needs signing in again", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.error": "Not working", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.reason.timed_out": "The sign-in was not finished in time.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.reason.cancelled": "Cancelled.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.reason.provider_refused": "The provider did not complete the sign-in.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.reason.runner_offline": "Your runner went offline during the sign-in.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.reason.identity_mismatch": "The sign-in did not match an account.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.reason.already_connected": "That account is already connected.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.connections.offline": "Your runner is offline. Start it to add a connection.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.switched": "Switched to %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.switched_reset": "Switched to %s; %s's limit resets %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.no_connection": "Nothing can answer right now. %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.no_connection.resets": "%s resets %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.no_connection.limited": "%s is limited", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.no_connection.signed_out": "%s is signed out", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.no_connection.none": "Nothing is connected.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.no_connection.add": "Add a connection", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.reason.limited": "its model account reached its limit", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.reason.no_connection": "nothing connected can run it", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.switched": "%s was limited", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.merged": "Merged [%s](%s) into %s.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.merged_without_checks": "Merged [%s](%s) into %s without checks.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.activity.add_report": "Adding to the task…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.activity.read_change": "Looking at the change…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "work.task_count": "Tasks: %d", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.moving_in": "Moving in…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.exploring": "Looking at new access…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.added": "Added %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.working": "Working in %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.created": "Created %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.removed": "Removed %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.changed": "Moved to %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.change": "Change", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.move": "Move", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.remove": "Remove", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.use": "Use this", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.answer": "Answer", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.answered": "You answered: %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.access": "Equipo can't reach %s yet. Its agent reaches %s.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.grant": "Grant access", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.grant_how": "The namespace owner runs this once:", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.home": "New projects go to %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.home_cleared": "New projects go to the best-fitting existing repository", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.undo": "Undo", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.undone": "Undone", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.home_ask": "Use %s for new projects?", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.home_ask_clear": "Stop using %s for new projects?", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.confirm": "Yes", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.card.more": "More", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.notebook.link": "Notebook", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.notebook.title": "Notebook", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.notebook.lede": "What your coordinator keeps in mind, and where each note came from. Notes are reference for it, never instructions.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.notebook.empty": "Your coordinator has no notes yet.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.notebook.person": "You said", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.notebook.repo": "From %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.notebook.own": "Coordinator's note", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.notebook.reset": "Reset", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.notebook.reset_help": "Reset clears these notes and starts your coordinator afresh. It moves in again and introduces itself.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.elapsed": "{n}s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "conversation.title": "Conversation",
// COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context): conversation.empty
"conversation.empty": "Say what you want done. Your coordinator picks the project and tells you, and you can change it.",
"conversation.age_minutes": "%d min", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
diff --git a/internal/equipo/handlers.go b/internal/equipo/handlers.go
index ae804950..0eb7b53f 100644
--- a/internal/equipo/handlers.go
+++ b/internal/equipo/handlers.go
@@ -41,6 +41,7 @@ type pageData struct {
Chat chatView
Thin workView
Notebook []notebookLine
+ Models modelsView
ChatStream bool
Coordinator conversation.CoordinatorPage
Plan planning.Page
diff --git a/internal/equipo/migrations/0048_thin_connections.sql b/internal/equipo/migrations/0048_thin_connections.sql
new file mode 100644
index 00000000..95cd666b
--- /dev/null
+++ b/internal/equipo/migrations/0048_thin_connections.sql
@@ -0,0 +1,7 @@
+CREATE TABLE chat_connections (id text PRIMARY KEY, person text, runner_id text, local_id text, provider text, kind text, label text, state text, reason text, plan text, headroom text, prompt text, revision integer, created_at datetime, updated_at datetime);
+CREATE INDEX chat_connection_person ON chat_connections(person);
+CREATE TABLE chat_usage (id integer PRIMARY KEY, person text, connection text, provider text, model text, role text, task_id text, step_id text, turn_id text, attempt integer, input_tokens integer, cached_input_tokens integer, cache_write_tokens integer, output_tokens integer, reasoning_output_tokens integer, recorded_at datetime);
+CREATE INDEX chat_usage_person ON chat_usage(person, recorded_at);
+ALTER TABLE chat_messages ADD COLUMN switched text;
+ALTER TABLE chat_turns ADD COLUMN connection text;
+ALTER TABLE chat_steps ADD COLUMN switched text;
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index 42ef65f3..1b33fba6 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -567,9 +567,9 @@ ALTER TABLE coordinator_turns ADD COLUMN partial_at integer;
ALTER TABLE coordinator_turns ADD COLUMN reply_message_id text;
ALTER TABLE coordinator_turns ADD COLUMN superseded_by text;
-CREATE TABLE chat_turns (id text PRIMARY KEY, person text, state text, reason text, attempt integer, dispatched numeric, reply_id text, revision integer, created_at datetime, updated_at datetime, dispatched_at datetime, timing text, kind text, yield numeric);
+CREATE TABLE chat_turns (id text PRIMARY KEY, person text, state text, reason text, attempt integer, dispatched numeric, reply_id text, revision integer, created_at datetime, updated_at datetime, dispatched_at datetime, timing text, kind text, yield numeric, connection text);
CREATE INDEX chat_turn_person ON chat_turns(person,state);
-CREATE TABLE chat_messages (seq integer PRIMARY KEY, id text, person text, idempotency_key text, body_hash text, role text, text text, turn_id text, revision integer, created_at datetime);
+CREATE TABLE chat_messages (seq integer PRIMARY KEY, id text, person text, idempotency_key text, body_hash text, role text, text text, turn_id text, revision integer, created_at datetime, switched text);
CREATE UNIQUE INDEX chat_message_id ON chat_messages(id);
CREATE INDEX chat_message_person ON chat_messages(person);
CREATE UNIQUE INDEX chat_message_key ON chat_messages(person,idempotency_key);
@@ -594,7 +594,7 @@ CREATE INDEX chat_card_task ON chat_cards(task_id);
CREATE TABLE chat_project_attachments (project_id text, kind text, ref text, name text, created_at datetime, PRIMARY KEY (project_id, kind, ref));
CREATE TABLE chat_tasks (id text PRIMARY KEY, project_id text, title text, brief text, stage text, branch text, base_sha text, creator text, turn_id text, cancel_requested numeric, revision integer, created_at datetime, updated_at datetime, watching text, moved_from text, branch_head text, merge_asked text, merged_sha text, merged_into text, merge_strategy text, merged_without_checks numeric, merged_at datetime, ready_sha text, merge_eligible text, done_at datetime);
CREATE INDEX chat_task_project ON chat_tasks(project_id);
-CREATE TABLE chat_steps (id text PRIMARY KEY, task_id text, idx integer, specialist text, person text, state text, reason text, attempt integer, base_sha text, candidate_sha text, pushed numeric, terminated numeric, summary text, log_tail text, started_at datetime, finished_at datetime, revision integer, created_at datetime, updated_at datetime, round integer, family text, account text, verdict text, review_label text, findings text, checks text, gate text, exit_code integer, output text, republish numeric, from_attempt integer, askable numeric, rebase numeric, from_base text, from_candidate text, merge_sha text, merge_into text, merge_strategy text, without_checks numeric);
+CREATE TABLE chat_steps (id text PRIMARY KEY, task_id text, idx integer, specialist text, person text, state text, reason text, attempt integer, base_sha text, candidate_sha text, pushed numeric, terminated numeric, summary text, log_tail text, started_at datetime, finished_at datetime, revision integer, created_at datetime, updated_at datetime, round integer, family text, account text, verdict text, review_label text, findings text, checks text, gate text, exit_code integer, output text, republish numeric, from_attempt integer, askable numeric, rebase numeric, from_base text, from_candidate text, merge_sha text, merge_into text, merge_strategy text, without_checks numeric, switched text);
CREATE INDEX chat_step_task ON chat_steps(task_id);
CREATE TABLE chat_task_entries (id text PRIMARY KEY, task_id text, idempotency_key text, kind text, author text, text text, repo text, path text, line integer, created_at datetime);
CREATE INDEX chat_entry_task ON chat_task_entries(task_id);
@@ -602,3 +602,7 @@ CREATE UNIQUE INDEX chat_entry_key ON chat_task_entries(task_id, idempotency_key
CREATE TABLE chat_questions (id text PRIMARY KEY, task_id text, asker text, idempotency_key text, step_id text, specialist text, chosen text, text text, state text, reason text, attempt integer, dispatched numeric, answer text, timing text, revision integer, created_at datetime, updated_at datetime);
CREATE INDEX chat_question_task ON chat_questions(task_id);
CREATE UNIQUE INDEX chat_question_key ON chat_questions(task_id, asker, idempotency_key);
+CREATE TABLE chat_connections (id text PRIMARY KEY, person text, runner_id text, local_id text, provider text, kind text, label text, state text, reason text, plan text, headroom text, prompt text, revision integer, created_at datetime, updated_at datetime);
+CREATE INDEX chat_connection_person ON chat_connections(person);
+CREATE TABLE chat_usage (id integer PRIMARY KEY, person text, connection text, provider text, model text, role text, task_id text, step_id text, turn_id text, attempt integer, input_tokens integer, cached_input_tokens integer, cache_write_tokens integer, output_tokens integer, reasoning_output_tokens integer, recorded_at datetime);
+CREATE INDEX chat_usage_person ON chat_usage(person, recorded_at);
diff --git a/internal/equipo/render.go b/internal/equipo/render.go
index c750b97e..5b5f5626 100644
--- a/internal/equipo/render.go
+++ b/internal/equipo/render.go
@@ -28,7 +28,7 @@ var assets = rastrillo.NewAssets(appFS)
var pages = map[string]*template.Template{}
func init() {
- for _, name := range []string{"person_devices", "person_device", "teams", "onboarding", "invite", "playbooks", "playbook_form", "playbook_diff", "specialist_form", "template_library", "template_diff", "conversation", "chat", "thread", "plan", "coordinator", "preferences", "index", "empty", "projects", "project", "project_form", "people", "settings", "specialist", "errors", "signin_page", "form_error", "runners", "tasks", "task", "task_form", "question", "merge", "connections", "recovery", "recovery_form", "rendered_approval", "notebook", "work_tasks", "work_task", "work_projects", "work_project"} {
+ for _, name := range []string{"person_devices", "person_device", "teams", "onboarding", "invite", "playbooks", "playbook_form", "playbook_diff", "specialist_form", "template_library", "template_diff", "conversation", "chat", "thread", "plan", "coordinator", "preferences", "index", "empty", "projects", "project", "project_form", "people", "settings", "specialist", "errors", "signin_page", "form_error", "runners", "tasks", "task", "task_form", "question", "merge", "connections", "recovery", "recovery_form", "rendered_approval", "notebook", "work_tasks", "work_task", "work_projects", "work_project", "models"} {
page := template.Must(template.New("layout").
Funcs(ui.Funcs(ui.WithIcons(icons.Icon, icons.Assets))).
Funcs(template.FuncMap{"chatMarkdown": chatmarkdown.Render, "projectAllows": library.ProjectAllowed, "asset": assets.Path, "copy": copyText, "taskGroups": func() []string { return []string{"needs-person", "running", "queued", "finished"} },
diff --git a/internal/equipo/static/chat-stream.js b/internal/equipo/static/chat-stream.js
index 037a26d1..f49d472c 100644
--- a/internal/equipo/static/chat-stream.js
+++ b/internal/equipo/static/chat-stream.js
@@ -412,9 +412,11 @@
return;
}
if (type === "delta") {
- var d = drafts[v.turn_id] || { text: "", bytes: 0 };
+ var d = drafts[v.turn_id];
+ // A new attempt (a failover, a recovery) starts its draft afresh.
+ if (!d || d.attempt !== e.attempt) d = { text: "", bytes: 0, attempt: e.attempt };
if (v.offset !== d.bytes) return;
- drafts[v.turn_id] = { text: d.text + v.text, bytes: d.bytes + utf8.encode(v.text).length };
+ drafts[v.turn_id] = { text: d.text + v.text, bytes: d.bytes + utf8.encode(v.text).length, attempt: d.attempt };
showDraft(v.turn_id);
} else if (type === "message") {
if (feed.querySelector('[data-message="' + CSS.escape(v.id) + '"]')) return;
@@ -433,7 +435,16 @@
scroll();
} else if (type === "turn") {
if (v.state === "queued" || v.state === "running") {
- bubble(v.id, v.kind);
+ var shownDraft = bubble(v.id, v.kind);
+ if (drafts[v.id] && drafts[v.id].attempt !== v.attempt) {
+ // The refused attempt's words go; the next attempt's follow.
+ delete drafts[v.id];
+ var body = shownDraft && shownDraft.querySelector("[data-stream-text]");
+ if (body) body.textContent = "";
+ }
+ // Held for a connection, or going again: the card is the server's.
+ var held = !!feed.querySelector('[data-no-connection="' + CSS.escape(v.id) + '"]');
+ if ((v.reason === "no_connection") !== held) refresh().catch(function () { location.reload(); });
} else if (v.state === "replied" && !v.reply_id) {
// A turn that ended with nothing to say (an empty explore).
delete drafts[v.id];
diff --git a/internal/equipo/templates/chat.html b/internal/equipo/templates/chat.html
index 44e7bbd5..b224bcd0 100644
--- a/internal/equipo/templates/chat.html
+++ b/internal/equipo/templates/chat.html
@@ -11,7 +11,7 @@
{{define "work-task-receipt"}}{{with .Task}}<p equipo-card-line>{{icon "check-circle"}}<span><a href="/tasks/{{.ID}}">{{.Title}}</a></span><span equipo-stage data-stage="{{.Stage}}" data-needs="{{.NeedsYou}}">{{.StageLine}}</span></p>{{if and .Pushed (not .MergedLine)}}<p equipo-card-note data-pushed><span>{{.Pushed}}</span><a href="{{.URL}}" rel="noopener" target="_blank" data-open-amadan>{{copy "work.open"}}</a></p>{{end}}{{if or .ChecksLine .ReviewLine}}<p equipo-card-note data-judged>{{with .ChecksLine}}<span data-checks>{{.}}</span>{{end}}{{with .ReviewLine}}<span data-verdict>{{.}}</span>{{end}}</p>{{end}}{{if .MergedLine}}<p equipo-card-note data-merged><span>{{.MergedLine}}</span><a href="{{.RepoURL}}" rel="noopener" target="_blank" data-open-amadan>{{copy "work.open"}}</a></p>{{end}}{{end}}{{if .Open}}<button type="button" equipo-receipt-more aria-expanded="false" aria-controls="acts-{{.ID}}" aria-label="{{copy "chat.card.more"}}">⋯</button><span equipo-receipt-actions id="acts-{{.ID}}">{{template "work-task-actions" .Task}}</span>{{end}}{{end}}
{{define "content"}}
<div equipo-conversation data-chat-stream data-cursor="{{.Chat.Cursor}}" data-person="{{.Address}}" data-elapsed="{{copy "chat.elapsed"}}" data-moving-in="{{copy "chat.moving_in"}}" data-exploring="{{copy "chat.exploring"}}">
-<header equipo-chat-header><h1>{{copy "conversation.title"}}</h1><a href="/conversation/notebook" equipo-header-button aria-label="{{copy "chat.notebook.link"}}" title="{{copy "chat.notebook.link"}}">{{icon "notebook"}}</a></header>
+<header equipo-chat-header><h1>{{copy "conversation.title"}}</h1><a href="/conversation/notebook" equipo-header-button aria-label="{{copy "chat.notebook.link"}}" title="{{copy "chat.notebook.link"}}">{{icon "notebook"}}</a><a href="/conversation/connections" equipo-header-button aria-label="{{copy "chat.connections.title"}}" title="{{copy "chat.connections.title"}}" data-connections-link>{{icon "plug"}}</a></header>
<p equipo-offline role="status"{{if not .Chat.Offline}} hidden{{end}}>{{copy "chat.offline"}}</p>
<div equipo-scroll tabindex="0" role="region" aria-label="{{copy "conversation.title"}}">
<section id="conversation-feed">
@@ -26,10 +26,12 @@
<li equipo-message="{{if .Own}}own{{else}}incoming{{end}}" data-message="{{.ID}}" data-turn-id="{{.TurnID}}">
<div equipo-message-meta><strong{{if .Own}} equipo-visually-hidden{{end}}>{{if .Own}}{{$.Address}}{{else}}{{icon "message-circle"}}{{copy "conversation.coordinator"}}{{end}}</strong><time datetime="{{.CreatedAt.Format "2006-01-02T15:04:05Z07:00"}}">{{.CreatedAt.Format "15:04"}}</time></div>
<div equipo-bubble>{{if .Own}}<p equipo-message-body>{{.Text}}</p>{{else}}<div equipo-message-body equipo-markdown>{{chatMarkdown .Text}}</div>{{end}}</div>
+{{with .Switched}}<p equipo-card-note data-switched>{{.}}</p>{{end}}
</li>
{{range .Cards}}{{template "chat-card" .}}{{end}}{{end}}
{{else}}<li data-empty-state="conversation.empty">{{copy "conversation.empty"}}</li>{{end}}
{{range .Chat.Waiting}}<li equipo-message="incoming" equipo-thinking data-turn="{{.ID}}"{{with .Kind}} data-kind="{{.}}"{{end}} data-started="{{.CreatedAt.UnixMilli}}" aria-busy="true"><div equipo-message-meta><strong>{{icon "message-circle"}}{{copy "conversation.coordinator"}}</strong><time></time></div><div equipo-bubble><div equipo-message-body equipo-markdown data-stream-text></div><p equipo-activity-line><span equipo-activity>{{if eq .Kind "move_in"}}{{copy "chat.moving_in"}}{{else if eq .Kind "explore"}}{{copy "chat.exploring"}}{{else}}{{copy "chat.activity.thinking"}}{{end}}</span><span equipo-activity-sep aria-hidden="true">·</span><span equipo-elapsed></span></p></div></li>{{end}}
+{{with .Chat.NoConnection}}<li equipo-card="no_connection" data-no-connection="{{.TurnID}}"><p equipo-card-line>{{.Line}}</p><p equipo-actions><a rst-btn="primary" href="/conversation/connections" data-add-connection>{{copy "chat.no_connection.add"}}</a></p></li>{{end}}
{{with .Chat.Ended}}<li equipo-system-note data-ended="{{.ID}}"><p>{{copy .Key}}</p></li>{{end}}
</ol>
</section>
diff --git a/internal/equipo/templates/models.html b/internal/equipo/templates/models.html
new file mode 100644
index 00000000..3ab1f175
--- /dev/null
+++ b/internal/equipo/templates/models.html
@@ -0,0 +1,20 @@
+{{define "up-label"}}{{copy "conversation.title"}}{{end}}
+{{define "up"}}/conversation{{end}}
+{{define "title"}}{{copy "chat.connections.title"}}{{end}}
+{{define "content"}}
+{{if .Models.Refresh}}<meta http-equiv="refresh" content="3">{{end}}
+<section equipo-notebook data-connections>
+<header equipo-notebook-head><h1>{{copy "chat.connections.title"}}</h1></header>
+{{if .Models.Offline}}<p equipo-offline role="status">{{copy "chat.connections.offline"}}</p>{{end}}
+{{if .Models.Items}}<ul equipo-notes role="list">{{range .Models.Items}}<li equipo-note data-connection="{{.ID}}"{{if .Connecting}} data-connecting{{end}}>
+<p><strong>{{.Name}}</strong>{{with .Label}} {{.}}{{end}}</p>
+{{with .State}}<p equipo-note-caption data-connection-state><span>{{.}}</span></p>{{end}}
+{{with .Note}}<p equipo-note-caption data-connection-note><span>{{.}}</span></p>{{end}}
+{{if .Connecting}}{{with .Prompt}}{{if eq .Kind "device_code"}}<p data-device-code>{{printf (copy "chat.connections.device") .URL .Code}}</p><p><a rst-btn="primary" href="{{.URL}}" rel="noopener" target="_blank">{{.URL}}</a> <code>{{.Code}}</code></p>
+{{else if eq .Kind "link"}}<p><a rst-btn="primary" href="{{.URL}}" rel="noopener" target="_blank" data-sign-in>{{copy "chat.connections.sign_in_claude"}}</a></p>
+{{else if eq .Kind "terminal"}}<p data-finish-on>{{printf (copy "chat.connections.finish_on") $.Models.Runner}}</p><p>{{copy "chat.connections.finish_how"}}</p><p><code>{{.Code}}</code></p><form method="post" action="/conversation/connections"><input type="hidden" name="provider" value="claude"><input type="hidden" name="same_machine" value="1"><button equipo-link type="submit" data-same-machine>{{copy "chat.connections.same_machine"}}</button></form>{{end}}{{end}}
+<form method="post" action="/conversation/connections/{{.ID}}/cancel"><button equipo-link type="submit" data-connection-cancel>{{copy "chat.connections.cancel"}}</button></form>{{end}}
+</li>{{end}}</ul>{{else}}<p data-empty-state="chat.connections.empty">{{copy "chat.connections.empty"}}</p>{{end}}
+<footer equipo-notebook-foot><form method="post" action="/conversation/connections" equipo-actions><input type="hidden" name="provider" value="codex"><button rst-btn type="submit" data-add="codex">{{copy "chat.connections.add_codex"}}</button></form><form method="post" action="/conversation/connections" equipo-actions><input type="hidden" name="provider" value="claude"><button rst-btn type="submit" data-add="claude">{{copy "chat.connections.add_claude"}}</button></form></footer>
+</section>
+{{end}}
diff --git a/internal/fakeclaude/fake.go b/internal/fakeclaude/fake.go
index 32e902ed..e4b82c50 100644
--- a/internal/fakeclaude/fake.go
+++ b/internal/fakeclaude/fake.go
@@ -68,6 +68,9 @@ import (
"encoding/json"
"fmt"
"io"
+ "net"
+ "net/http"
+ "net/url"
"os"
"os/exec"
"path/filepath"
@@ -138,6 +141,43 @@ func authStatus(stdout io.Writer) int {
func authLogin() int {
email := os.Getenv("FAKE_LOGIN_EMAIL")
+ if b := os.Getenv("BROWSER"); b != "" && email == "" {
+ // The loopback sign-in: open the browser at the authorize page with
+ // a redirect to this process, and finish on the callback. The
+ // callback carries the email the "browser" signed in as.
+ l, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ return 1
+ }
+ port := l.Addr().(*net.TCPAddr).Port
+ state := "fake-state"
+ u := "https://claude.com/cai/oauth/authorize?code=true&client_id=fake&response_type=code&redirect_uri=" + url.QueryEscape(fmt.Sprintf("http://127.0.0.1:%d/callback", port)) + "&state=" + state
+ fmt.Println("Opening browser to sign in…")
+ _ = exec.Command(b, u).Run()
+ fmt.Println("If the browser didn't open, visit: https://claude.com/cai/oauth/authorize?code=true&client_id=fake&redirect_uri=https%3A%2F%2Fplatform.claude.com%2Foauth%2Fcode%2Fcallback")
+ got := make(chan string, 1)
+ srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/callback" || r.URL.Query().Get("state") != state || r.URL.Query().Get("code") == "" {
+ http.Error(w, "bad callback", 400)
+ return
+ }
+ fmt.Fprintln(w, "Signed in. You can close this tab.")
+ select {
+ case got <- r.URL.Query().Get("email"):
+ default:
+ }
+ })}
+ go srv.Serve(l)
+ select {
+ case email = <-got:
+ case <-time.After(2 * time.Minute):
+ return 1
+ }
+ srv.Close()
+ if email == "" {
+ return 1
+ }
+ }
if email == "" {
return 1
}
@@ -236,6 +276,9 @@ var pauseWord = regexp.MustCompile(`pause:([0-9]+)`)
// the end of the line.
var toolWord = regexp.MustCompile(`tool:([a-z_]+)(?::([^\n]*))?`)
+// ToolInput is the input the fakes send for tool:<name>:<arg>.
+func ToolInput(name, arg string) map[string]any { return toolInput(name, arg) }
+
func toolInput(name, arg string) map[string]any {
arg = strings.TrimSpace(arg)
switch name {
@@ -701,6 +744,16 @@ 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"
if failed {
@@ -713,6 +766,21 @@ 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])`)
+
+// accountEmail is the signed-in account of the home the fake runs in.
+func accountEmail() string {
+ var v struct {
+ Account struct {
+ Email string `json:"emailAddress"`
+ } `json:"oauthAccount"`
+ }
+ raw, _ := os.ReadFile(filepath.Join(home(), ".claude.json"))
+ _ = json.Unmarshal(raw, &v)
+ return v.Account.Email
+}
+
var noteID = regexp.MustCompile(`\[(n[0-9]+)\]`)
// keepAll reads the notebook and keeps every entry before the new ones.
diff --git a/internal/fakecodex/fake.go b/internal/fakecodex/fake.go
new file mode 100644
index 00000000..54ea9051
--- /dev/null
+++ b/internal/fakecodex/fake.go
@@ -0,0 +1,606 @@
+// Package fakecodex is a stand-in for the pinned Codex 0.165.0 CLI's
+// app-server, reproducing what Equipo relies on from its JSON-RPC
+// protocol (the schemas under internal/runner/provider/codex/testdata and
+// `codex app-server generate-json-schema`): initialize; account/read with
+// and without a refresh; config/read echoing the -c session flags as the
+// effective configuration; the device-code sign-in (account/login/start
+// with chatgptDeviceCode, account/login/completed); account/rateLimits;
+// thread/start and thread/resume with a rollout under
+// $CODEX_HOME/sessions; turn/start with agentMessage deltas, items,
+// thread/tokenUsage/updated and turn/completed; turn/interrupt; and MCP
+// tool calls through the configured stdio server after an
+// mcpServer/elicitation/request approval.
+//
+// Test binaries call Main when they are started as "codex". The device
+// sign-in completes when <dirname $CODEX_HOME>/.fake-device.json appears:
+// {"email": ..., "plan": ...} approves, {"refuse": true} is OpenAI
+// refusing (device login not enabled). Prompt words in the newest
+// message steer a turn: "tool:<name>[:<arg>]" as in fakeclaude,
+// "limit:<email>" (the account at that email has spent its limit: both
+// windows at 100% and the turn fails usageLimitExceeded), "sleep:<ms>"
+// pauses mid-reply, "fail" fails the turn.
+package fakecodex
+
+import (
+ "bufio"
+ "crypto/rand"
+ "encoding/json"
+ "fmt"
+ "io"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "regexp"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/fakeclaude"
+)
+
+// Version is the pinned CLI version the fake reports.
+const Version = "0.165.0"
+
+// Main runs the fake with argv after the program name.
+func Main(args []string, stdin io.Reader, stdout, stderr io.Writer) int {
+ if len(args) == 1 && args[0] == "--version" {
+ fmt.Fprintln(stdout, "codex-cli "+Version)
+ return 0
+ }
+ if len(args) == 0 || args[0] != "app-server" {
+ fmt.Fprintln(stderr, "fakecodex: only app-server is faked")
+ return 2
+ }
+ settings := map[string]any{}
+ for i := 1; i < len(args); i++ {
+ if args[i] == "-c" && i+1 < len(args) {
+ i++
+ k, v, ok := strings.Cut(args[i], "=")
+ if !ok {
+ return 2
+ }
+ val, rest, err := parseTOML(v)
+ if err != nil || strings.TrimSpace(rest) != "" {
+ fmt.Fprintln(stderr, "fakecodex: bad -c value for", k)
+ return 2
+ }
+ settings[k] = val
+ }
+ }
+ s := &server{out: json.NewEncoder(stdout), settings: settings, home: os.Getenv("CODEX_HOME"), answers: map[string]chan json.RawMessage{}}
+ return s.serve(stdin)
+}
+
+type server struct {
+ wmu sync.Mutex
+ out *json.Encoder
+ settings map[string]any
+ home string
+
+ mu sync.Mutex
+ thread string
+ turn string
+ interrupt chan struct{}
+ answers map[string]chan json.RawMessage
+ reqID int
+
+ mcpIn io.Writer
+ mcpOut *bufio.Reader
+ callID int
+}
+
+func (s *server) send(v any) {
+ s.wmu.Lock()
+ defer s.wmu.Unlock()
+ _ = s.out.Encode(v)
+}
+
+func (s *server) notify(method string, params any) {
+ s.send(map[string]any{"method": method, "params": params})
+}
+
+func (s *server) reply(id json.RawMessage, result any) {
+ s.send(map[string]any{"id": id, "result": result})
+}
+
+func (s *server) fail(id json.RawMessage, message string) {
+ s.send(map[string]any{"id": id, "error": map[string]any{"code": -32600, "message": message}})
+}
+
+// request asks the client something and waits for its answer.
+func (s *server) request(method string, params any) json.RawMessage {
+ s.mu.Lock()
+ s.reqID++
+ id := strconv.Quote("s" + strconv.Itoa(s.reqID))
+ ch := make(chan json.RawMessage, 1)
+ s.answers[id] = ch
+ s.mu.Unlock()
+ s.send(map[string]any{"id": json.RawMessage(id), "method": method, "params": params})
+ select {
+ case raw := <-ch:
+ return raw
+ case <-time.After(30 * time.Second):
+ return nil
+ }
+}
+
+func uuid() string {
+ var b [16]byte
+ _, _ = rand.Read(b[:])
+ b[6] = (b[6] & 15) | 112
+ b[8] = (b[8] & 63) | 128
+ return fmt.Sprintf("%x-%x-%x-%x-%x", b[:4], b[4:6], b[6:8], b[8:10], b[10:])
+}
+
+type authFile struct {
+ Email string `json:"email"`
+ Plan string `json:"plan"`
+}
+
+func (s *server) auth() (authFile, bool) {
+ var a authFile
+ raw, err := os.ReadFile(filepath.Join(s.home, "auth.json"))
+ return a, err == nil && json.Unmarshal(raw, &a) == nil && a.Email != ""
+}
+
+// WriteAuth signs a fake home in, as `codex login` leaves auth.json.
+func WriteAuth(home, email, plan string) error {
+ raw, _ := json.Marshal(map[string]any{"email": email, "plan": plan, "tokens": map[string]string{"id_token": "fake", "access_token": "fake", "refresh_token": "fake"}})
+ tmp := filepath.Join(home, ".auth.json.fake")
+ if err := os.WriteFile(tmp, raw, 0600); err != nil {
+ return err
+ }
+ return os.Rename(tmp, filepath.Join(home, "auth.json"))
+}
+
+func (s *server) serve(stdin io.Reader) int {
+ scan := bufio.NewScanner(stdin)
+ scan.Buffer(make([]byte, 0, 64<<10), 4<<20)
+ for scan.Scan() {
+ var m struct {
+ ID json.RawMessage `json:"id"`
+ Method string `json:"method"`
+ Params json.RawMessage `json:"params"`
+ Result json.RawMessage `json:"result"`
+ Error json.RawMessage `json:"error"`
+ }
+ if json.Unmarshal(scan.Bytes(), &m) != nil {
+ return 1
+ }
+ if m.Method == "" {
+ s.mu.Lock()
+ ch := s.answers[string(m.ID)]
+ delete(s.answers, string(m.ID))
+ s.mu.Unlock()
+ if ch != nil {
+ if len(m.Error) > 0 {
+ ch <- json.RawMessage(`{"refused":true}`)
+ } else {
+ ch <- m.Result
+ }
+ }
+ continue
+ }
+ if len(m.ID) == 0 {
+ continue
+ }
+ s.handle(m.ID, m.Method, m.Params)
+ }
+ return 0
+}
+
+func (s *server) handle(id json.RawMessage, method string, params json.RawMessage) {
+ switch method {
+ case "initialize":
+ s.reply(id, map[string]any{"userAgent": "equipo/" + Version + " (fake; linux)", "codexHome": s.home, "platformFamily": "unix", "platformOs": "linux"})
+ case "account/read":
+ var p struct {
+ Refresh bool `json:"refreshToken"`
+ }
+ _ = json.Unmarshal(params, &p)
+ if _, err := os.Stat(filepath.Join(s.home, ".fake-revoked")); err == nil && p.Refresh {
+ s.fail(id, "refresh_token_invalidated")
+ return
+ }
+ a, ok := s.auth()
+ if !ok {
+ s.reply(id, map[string]any{"account": nil, "requiresOpenaiAuth": true})
+ return
+ }
+ s.reply(id, map[string]any{"account": map[string]any{"type": "chatgpt", "email": a.Email, "planType": a.Plan}, "requiresOpenaiAuth": true})
+ case "config/read":
+ origins := map[string]any{}
+ for k := range s.settings {
+ origins[k] = map[string]any{"name": map[string]string{"type": "sessionFlags"}, "version": "fake-1"}
+ }
+ s.reply(id, map[string]any{"config": s.settings, "layers": []any{map[string]any{"name": map[string]string{"type": "sessionFlags"}, "version": "fake-1", "config": s.settings, "disabledReason": nil}}, "origins": origins})
+ case "account/login/start":
+ var p struct {
+ Type string `json:"type"`
+ }
+ if json.Unmarshal(params, &p) != nil || p.Type != "chatgptDeviceCode" {
+ s.fail(id, "unsupported login type")
+ return
+ }
+ login := uuid()
+ s.reply(id, map[string]any{"type": "chatgptDeviceCode", "loginId": login, "verificationUrl": "https://auth.openai.com/codex/device", "userCode": "FAKE-" + strings.ToUpper(login[:4])})
+ go s.deviceLogin(login)
+ case "account/login/cancel":
+ s.reply(id, map[string]any{"status": "canceled"})
+ case "account/rateLimits/read":
+ s.reply(id, map[string]any{"rateLimits": s.limits(false)})
+ case "thread/start", "thread/resume":
+ var p struct {
+ ThreadID string `json:"threadId"`
+ }
+ _ = json.Unmarshal(params, &p)
+ thread := uuid()
+ if method == "thread/resume" {
+ if s.rollout(p.ThreadID) == "" {
+ s.fail(id, "no rollout found for thread id "+p.ThreadID)
+ return
+ }
+ thread = p.ThreadID
+ }
+ s.mu.Lock()
+ s.thread = thread
+ s.mu.Unlock()
+ model, _ := s.settings["model"].(string)
+ s.reply(id, map[string]any{"thread": map[string]any{"id": thread}, "model": model, "modelProvider": "openai", "cwd": "/workspace", "approvalPolicy": "on-request", "approvalsReviewer": "user", "activePermissionProfile": map[string]any{"id": "equipo", "extends": nil}, "runtimeWorkspaceRoots": []string{"/workspace"}})
+ case "turn/start":
+ var p struct {
+ ThreadID string `json:"threadId"`
+ Input []struct {
+ Text string `json:"text"`
+ } `json:"input"`
+ }
+ s.mu.Lock()
+ thread := s.thread
+ s.mu.Unlock()
+ if json.Unmarshal(params, &p) != nil || p.ThreadID != thread || len(p.Input) != 1 {
+ s.fail(id, "bad turn")
+ return
+ }
+ turn := uuid()
+ stop := make(chan struct{})
+ s.mu.Lock()
+ s.turn, s.interrupt = turn, stop
+ s.mu.Unlock()
+ s.reply(id, map[string]any{"turn": map[string]any{"id": turn, "status": "inProgress", "items": []any{}}})
+ go s.runTurn(thread, turn, p.Input[0].Text, stop)
+ case "turn/interrupt":
+ s.mu.Lock()
+ if s.interrupt != nil {
+ close(s.interrupt)
+ s.interrupt = nil
+ }
+ s.mu.Unlock()
+ s.reply(id, map[string]any{})
+ default:
+ s.fail(id, "method not faked: "+method)
+ }
+}
+
+// deviceLogin waits for the person's approval (a file the test writes
+// beside the new home) and completes the sign-in.
+func (s *server) deviceLogin(login string) {
+ path := filepath.Join(filepath.Dir(s.home), ".fake-device.json")
+ for deadline := time.Now().Add(2 * time.Minute); time.Now().Before(deadline); time.Sleep(100 * time.Millisecond) {
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ continue
+ }
+ var v struct {
+ Email, Plan string
+ Refuse bool
+ }
+ if json.Unmarshal(raw, &v) != nil {
+ continue
+ }
+ if v.Refuse {
+ s.notify("account/login/completed", map[string]any{"loginId": login, "success": false, "error": "Enable device code authorization for Codex in ChatGPT Security Settings"})
+ return
+ }
+ if WriteAuth(s.home, v.Email, v.Plan) != nil {
+ return
+ }
+ s.notify("account/login/completed", map[string]any{"loginId": login, "success": true, "error": nil})
+ s.notify("account/updated", map[string]any{"authMode": "chatgpt", "planType": v.Plan})
+ return
+ }
+}
+
+func (s *server) limits(spent bool) map[string]any {
+ used := 10
+ if spent {
+ used = 100
+ }
+ a, _ := s.auth()
+ return map[string]any{"primary": map[string]any{"usedPercent": used, "windowDurationMins": 300, "resetsAt": time.Now().Add(3 * time.Hour).Truncate(time.Hour).Unix()}, "secondary": map[string]any{"usedPercent": used, "windowDurationMins": 10080, "resetsAt": time.Now().Add(70 * time.Hour).Truncate(time.Hour).Unix()}, "planType": a.Plan, "limitId": nil, "limitName": nil, "rateLimitReachedType": nil}
+}
+
+// rollout is the thread's rollout file, or "".
+func (s *server) rollout(thread string) string {
+ matches, _ := filepath.Glob(filepath.Join(s.home, "sessions", "*", "*", "*", "rollout-*-"+thread+".jsonl"))
+ if len(matches) == 1 {
+ return matches[0]
+ }
+ return ""
+}
+
+func (s *server) record(thread, prompt, reply string) int {
+ path := s.rollout(thread)
+ if path == "" {
+ now := time.Now().UTC()
+ path = filepath.Join(s.home, "sessions", now.Format("2006"), now.Format("01"), now.Format("02"), "rollout-"+now.Format("2006-01-02T15-04-05")+"-"+thread+".jsonl")
+ _ = os.MkdirAll(filepath.Dir(path), 0700)
+ }
+ f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
+ if err == nil {
+ for _, line := range []map[string]string{{"type": "user", "text": prompt}, {"type": "agent", "text": reply}} {
+ raw, _ := json.Marshal(line)
+ f.Write(append(raw, '\n'))
+ }
+ f.Close()
+ }
+ raw, _ := os.ReadFile(path)
+ return strings.Count(string(raw), `"type":"agent"`)
+}
+
+var (
+ toolWord = regexp.MustCompile(`tool:([a-z_]+)(?::([^\n]*))?`)
+ limitWord = regexp.MustCompile(`limit:([^\s]+@[^\s]+[a-z])`)
+ sleepWord = regexp.MustCompile(`\bsleep:([0-9]+)`)
+)
+
+func (s *server) runTurn(thread, turn, prompt string, stop chan struct{}) {
+ newest := prompt
+ if _, after, ok := strings.Cut(prompt, "Newest message:\n"); ok {
+ newest = after
+ }
+ done := func(status string, turnErr any) {
+ s.notify("turn/completed", map[string]any{"threadId": thread, "turn": map[string]any{"id": turn, "status": status, "items": []any{}, "error": turnErr}})
+ }
+ interrupted := func() bool {
+ select {
+ case <-stop:
+ done("interrupted", nil)
+ return true
+ default:
+ return false
+ }
+ }
+ s.notify("turn/started", map[string]any{"threadId": thread, "turn": map[string]any{"id": turn, "status": "inProgress", "items": []any{}}})
+ a, _ := s.auth()
+ if m := limitWord.FindStringSubmatch(newest); m != nil && m[1] == a.Email {
+ s.notify("account/rateLimits/updated", map[string]any{"rateLimits": s.limits(true)})
+ e := map[string]any{"message": "You've hit your usage limit.", "codexErrorInfo": "usageLimitExceeded", "additionalDetails": nil}
+ s.notify("error", map[string]any{"threadId": thread, "turnId": turn, "willRetry": false, "error": e})
+ done("failed", e)
+ return
+ }
+ reply := ""
+ for i, m := range toolWord.FindAllStringSubmatch(newest, -1) {
+ item := fmt.Sprintf("mcp_%s_%d", turn[:8], i)
+ input := fakeclaude.ToolInput(m[1], m[2])
+ args, _ := json.Marshal(input)
+ started := map[string]any{"id": item, "type": "mcpToolCall", "server": "equipo", "tool": m[1], "arguments": json.RawMessage(args), "status": "inProgress"}
+ s.notify("item/started", map[string]any{"threadId": thread, "turnId": turn, "item": started})
+ answer := s.request("mcpServer/elicitation/request", map[string]any{"threadId": thread, "turnId": turn, "serverName": "equipo", "mode": "form", "message": "Allow the equipo MCP server to run tool " + m[1] + "?", "_meta": map[string]any{"codex_approval_kind": "mcp_tool_call", "tool_params": json.RawMessage(args)}, "requestedSchema": map[string]any{"type": "object", "properties": map[string]any{}}})
+ var v struct {
+ Action string `json:"action"`
+ }
+ _ = json.Unmarshal(answer, &v)
+ text, isError := "user declined the tool call", true
+ if v.Action == "accept" {
+ text, isError = s.callTool(m[1], input)
+ }
+ status := "completed"
+ if isError {
+ status = "failed"
+ }
+ s.notify("item/completed", map[string]any{"threadId": thread, "turnId": turn, "item": map[string]any{"id": item, "type": "mcpToolCall", "server": "equipo", "tool": m[1], "arguments": json.RawMessage(args), "status": status, "result": map[string]any{"content": []any{map[string]string{"type": "text", "text": text}}}, "error": nil}})
+ reply += fmt.Sprintf(" [%s: %s]", m[1], text)
+ if interrupted() {
+ return
+ }
+ }
+ turns := 0
+ if path := s.rollout(thread); path != "" {
+ raw, _ := os.ReadFile(path)
+ turns = strings.Count(string(raw), `"type":"agent"`)
+ }
+ context := "fresh"
+ if turns > 0 {
+ context = "resumed"
+ }
+ text := fmt.Sprintf("Hello from the fake Codex coordinator. Turn %d, %s thread.", turns+1, context) + reply
+ if strings.Contains(prompt, "Conversation so far") {
+ text += " I see the earlier conversation."
+ }
+ if strings.Contains(prompt, "=== Your notebook") {
+ text += " (notebook in context)"
+ }
+ pause := time.Duration(0)
+ if m := sleepWord.FindStringSubmatch(newest); m != nil {
+ ms, _ := strconv.Atoi(m[1])
+ pause = time.Duration(ms) * time.Millisecond
+ }
+ msg := "msg_" + turn[:8]
+ s.notify("item/started", map[string]any{"threadId": thread, "turnId": turn, "item": map[string]any{"id": msg, "type": "agentMessage", "text": ""}})
+ words := strings.SplitAfter(text, " ")
+ third := max(len(words)/3, 1)
+ for i := 0; i < len(words); i += third {
+ chunk := strings.Join(words[i:min(i+third, len(words))], "")
+ s.notify("item/agentMessage/delta", map[string]any{"threadId": thread, "turnId": turn, "itemId": msg, "delta": chunk})
+ if pause > 0 && i == 0 {
+ select {
+ case <-stop:
+ case <-time.After(pause):
+ }
+ }
+ if interrupted() {
+ return
+ }
+ }
+ if strings.Contains(newest, "fail") {
+ done("failed", map[string]any{"message": "stream disconnected", "codexErrorInfo": "other"})
+ return
+ }
+ s.notify("item/completed", map[string]any{"threadId": thread, "turnId": turn, "item": map[string]any{"id": msg, "type": "agentMessage", "text": text}})
+ s.record(thread, prompt, text)
+ usage := map[string]any{"inputTokens": len(prompt) / 4, "cachedInputTokens": len(prompt) / 8, "cacheWriteInputTokens": 0, "outputTokens": len(text) / 4, "reasoningOutputTokens": 7, "totalTokens": len(prompt)/4 + len(text)/4 + 7}
+ s.notify("thread/tokenUsage/updated", map[string]any{"threadId": thread, "turnId": turn, "tokenUsage": map[string]any{"last": usage, "total": usage, "modelContextWindow": 272000}})
+ s.notify("account/rateLimits/updated", map[string]any{"rateLimits": s.limits(false)})
+ done("completed", nil)
+}
+
+// callTool calls an Equipo tool through the configured MCP server,
+// starting it on first use.
+func (s *server) callTool(name string, input map[string]any) (string, bool) {
+ if s.mcpIn == nil {
+ if msg := s.connectMCP(); msg != "" {
+ return msg, true
+ }
+ }
+ s.callID++
+ raw, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 100 + s.callID, "method": "tools/call", "params": map[string]any{"name": name, "arguments": input}})
+ if _, err := s.mcpIn.Write(append(raw, '\n')); err != nil {
+ return "MCP write failed", true
+ }
+ line, err := s.mcpOut.ReadBytes('\n')
+ var reply struct {
+ Result struct {
+ Content []struct {
+ Text string `json:"text"`
+ } `json:"content"`
+ IsError bool `json:"isError"`
+ } `json:"result"`
+ Error *struct{} `json:"error"`
+ }
+ if err != nil || json.Unmarshal(line, &reply) != nil || reply.Error != nil || len(reply.Result.Content) == 0 {
+ return "MCP call failed", true
+ }
+ return reply.Result.Content[0].Text, reply.Result.IsError
+}
+
+// connectMCP starts the equipo server from the session flags and checks
+// its tool list against enabled_tools, as Codex filters it.
+func (s *server) connectMCP() string {
+ servers, _ := s.settings["mcp_servers"].(map[string]any)
+ eq, _ := servers["equipo"].(map[string]any)
+ command, _ := eq["command"].(string)
+ var args []string
+ if list, ok := eq["args"].([]any); ok {
+ for _, a := range list {
+ if v, ok := a.(string); ok {
+ args = append(args, v)
+ }
+ }
+ }
+ if command == "" {
+ return "no MCP server configured"
+ }
+ cmd := exec.Command(command, args...)
+ in, _ := cmd.StdinPipe()
+ out, _ := cmd.StdoutPipe()
+ if cmd.Start() != nil {
+ return "MCP server did not start"
+ }
+ r := bufio.NewReader(out)
+ call := func(id int, method string, params any) json.RawMessage {
+ raw, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": id, "method": method, "params": params})
+ if _, err := in.Write(append(raw, '\n')); err != nil {
+ return nil
+ }
+ line, err := r.ReadBytes('\n')
+ var reply struct {
+ Result json.RawMessage `json:"result"`
+ }
+ if err != nil || json.Unmarshal(line, &reply) != nil {
+ return nil
+ }
+ return reply.Result
+ }
+ if call(1, "initialize", map[string]any{"protocolVersion": "2025-06-18", "capabilities": map[string]any{}, "clientInfo": map[string]string{"name": "fake-codex", "version": Version}}) == nil {
+ return "MCP initialize failed"
+ }
+ note, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "method": "notifications/initialized"})
+ in.Write(append(note, '\n'))
+ if call(2, "tools/list", map[string]any{}) == nil {
+ return "MCP tools/list failed"
+ }
+ s.mcpIn, s.mcpOut = in, r
+ return ""
+}
+
+// parseTOML reads one value of the inline TOML the launcher renders:
+// basic strings, integers, booleans, arrays and inline tables with
+// quoted keys. It returns the value and the unread rest.
+func parseTOML(v string) (any, string, error) {
+ v = strings.TrimLeft(v, " ")
+ switch {
+ case v == "":
+ return nil, v, fmt.Errorf("empty")
+ case v[0] == '"':
+ end := 1
+ for ; end < len(v); end++ {
+ if v[end] == '\\' {
+ end++
+ continue
+ }
+ if v[end] == '"' {
+ break
+ }
+ }
+ if end >= len(v) {
+ return nil, v, fmt.Errorf("unterminated string")
+ }
+ s, err := strconv.Unquote(v[:end+1])
+ return s, v[end+1:], err
+ case strings.HasPrefix(v, "true"):
+ return true, v[4:], nil
+ case strings.HasPrefix(v, "false"):
+ return false, v[5:], nil
+ case v[0] == '[':
+ out := []any{}
+ rest := strings.TrimLeft(v[1:], " ")
+ for !strings.HasPrefix(rest, "]") {
+ val, r, err := parseTOML(rest)
+ if err != nil {
+ return nil, v, err
+ }
+ out = append(out, val)
+ rest = strings.TrimLeft(strings.TrimPrefix(strings.TrimLeft(r, " "), ","), " ")
+ }
+ return out, rest[1:], nil
+ case v[0] == '{':
+ out := map[string]any{}
+ rest := strings.TrimLeft(v[1:], " ")
+ for !strings.HasPrefix(rest, "}") {
+ key, r, err := parseTOML(rest)
+ k, ok := key.(string)
+ if err != nil || !ok {
+ return nil, v, fmt.Errorf("bad key")
+ }
+ r = strings.TrimLeft(r, " ")
+ if !strings.HasPrefix(r, "=") {
+ return nil, v, fmt.Errorf("missing =")
+ }
+ val, r2, err := parseTOML(r[1:])
+ if err != nil {
+ return nil, v, err
+ }
+ out[k] = val
+ rest = strings.TrimLeft(strings.TrimPrefix(strings.TrimLeft(r2, " "), ","), " ")
+ }
+ return out, rest[1:], nil
+ }
+ end := strings.IndexAny(v, ",]} ")
+ if end < 0 {
+ end = len(v)
+ }
+ n, err := strconv.ParseInt(v[:end], 10, 64)
+ return n, v[end:], err
+}
diff --git a/internal/runner/connect/limits.go b/internal/runner/connect/limits.go
index 1a639978..25cb6c91 100644
--- a/internal/runner/connect/limits.go
+++ b/internal/runner/connect/limits.go
@@ -19,7 +19,7 @@ type Limit struct {
Headroom *wire.Headroom
}
-func unix(sec int64) *time.Time {
+func fromUnix(sec int64) *time.Time {
if sec <= 0 {
return nil
}
@@ -48,14 +48,14 @@ func ClaudeRateLimit(raw []byte) (Limit, bool) {
if json.Unmarshal(raw, &v) != nil || v.Type != "rate_limit_event" || v.Info == nil {
return Limit{}, false
}
- h := &wire.Headroom{Utilization: v.Info.Utilization, ResetsAt: unix(v.Info.ResetsAt), Windows: []wire.Window{}}
+ h := &wire.Headroom{Utilization: v.Info.Utilization, ResetsAt: fromUnix(v.Info.ResetsAt), Windows: []wire.Window{}}
for _, name := range []string{"five_hour", "seven_day", "seven_day_opus", "seven_day_sonnet"} {
if w, ok := v.Info.Windows[name]; ok {
minutes := int64(300)
if name != "five_hour" {
minutes = 10080
}
- h.Windows = append(h.Windows, wire.Window{Name: name, UsedPercent: w.Utilization * 100, Minutes: minutes, ResetsAt: unix(w.ResetsAt)})
+ h.Windows = append(h.Windows, wire.Window{Name: name, UsedPercent: w.Utilization * 100, Minutes: minutes, ResetsAt: fromUnix(w.ResetsAt)})
}
}
l := Limit{Limited: v.Info.Status == "rejected", Window: v.Info.Type, Headroom: h}
@@ -103,7 +103,7 @@ func CodexRateLimits(raw json.RawMessage) (Limit, string, bool) {
win.Minutes = *w.w.Minutes
}
if w.w.ResetsAt != nil {
- win.ResetsAt = unix(*w.w.ResetsAt)
+ win.ResetsAt = fromUnix(*w.w.ResetsAt)
}
h.Windows = append(h.Windows, win)
if w.w.UsedPercent >= used {
diff --git a/internal/runner/connect/login.go b/internal/runner/connect/login.go
new file mode 100644
index 00000000..86bbca68
--- /dev/null
+++ b/internal/runner/connect/login.go
@@ -0,0 +1,269 @@
+package connect
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/url"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "syscall"
+ "time"
+
+ "golang.org/x/sys/unix"
+)
+
+// Sign-in outcomes a connection attempt reports (wire.ConnectReasons).
+var (
+ ErrRefused = errors.New("provider_refused")
+ ErrTimedOut = errors.New("timed_out")
+ ErrCancelled = errors.New("cancelled")
+)
+
+// Account is who a sign-in signed in, as the provider's CLI reports it.
+type Account struct {
+ Email, Plan string
+ Limits *Limit
+}
+
+// CodexDeviceLogin signs a new Codex home in by device code (spec §2.2):
+// the pinned app-server in that home asks OpenAI for a code
+// (account/login/start, chatgptDeviceCode), prompt shows the person the
+// verification URL and the code, and the app-server polls OpenAI until
+// the person approves (account/login/completed). Nothing is typed back
+// into Equipo; the tokens stay in the home's auth.json.
+func CodexDeviceLogin(ctx context.Context, binary, home string, env []string, prompt func(verifyURL, code string)) (Account, error) {
+ cmd := exec.Command(binary, "app-server", "--strict-config", "--listen", "stdio://")
+ cmd.Dir, cmd.Env = home, env
+ cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
+ in, err := cmd.StdinPipe()
+ if err != nil {
+ return Account{}, err
+ }
+ out, err := cmd.StdoutPipe()
+ if err != nil {
+ return Account{}, err
+ }
+ cmd.Stderr = io.Discard
+ if err = cmd.Start(); err != nil {
+ return Account{}, err
+ }
+ defer func() {
+ in.Close()
+ done := make(chan struct{})
+ go func() { _ = cmd.Wait(); close(done) }()
+ select {
+ case <-done:
+ case <-time.After(5 * time.Second):
+ _ = unix.Kill(-cmd.Process.Pid, unix.SIGKILL)
+ <-done
+ }
+ }()
+ rpc := NewAppServer(out, in)
+ call := func(method string, params any) (json.RawMessage, error) {
+ cctx, cancel := context.WithTimeout(ctx, 30*time.Second)
+ defer cancel()
+ raw, _, err := rpc.Call(cctx, method, params)
+ return raw, err
+ }
+ raw, err := call("initialize", map[string]any{"clientInfo": map[string]any{"name": "equipo", "version": "2"}, "capabilities": map[string]any{"experimentalApi": true}})
+ var init struct{ CodexHome string }
+ if err != nil || json.Unmarshal(raw, &init) != nil || init.CodexHome != home {
+ return Account{}, fmt.Errorf("codex app-server did not start in the new home")
+ }
+ _ = rpc.Notify("initialized", map[string]any{})
+ raw, err = call("account/login/start", map[string]string{"type": "chatgptDeviceCode"})
+ var start struct {
+ Type, LoginID, VerificationURL, UserCode string
+ }
+ if err != nil || json.Unmarshal(raw, &start) != nil || start.Type != "chatgptDeviceCode" || start.LoginID == "" || start.UserCode == "" {
+ return Account{}, ErrRefused
+ }
+ u, err := url.Parse(start.VerificationURL)
+ if err != nil || u.Scheme != "https" || len(start.UserCode) > 32 {
+ return Account{}, ErrRefused
+ }
+ prompt(start.VerificationURL, start.UserCode)
+ for {
+ select {
+ case <-ctx.Done():
+ cctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ _, _, _ = rpc.Call(cctx, "account/login/cancel", map[string]string{"loginId": start.LoginID})
+ cancel()
+ if errors.Is(ctx.Err(), context.DeadlineExceeded) {
+ return Account{}, ErrTimedOut
+ }
+ return Account{}, ErrCancelled
+ case m, ok := <-rpc.Messages:
+ if !ok {
+ return Account{}, ErrRefused
+ }
+ if len(m.ID) > 0 {
+ _ = rpc.Refuse(m.ID)
+ continue
+ }
+ if m.Method != "account/login/completed" {
+ continue
+ }
+ var done struct {
+ LoginID *string `json:"loginId"`
+ Success bool `json:"success"`
+ }
+ if json.Unmarshal(m.Params, &done) != nil || done.LoginID != nil && *done.LoginID != start.LoginID {
+ continue
+ }
+ if !done.Success {
+ return Account{}, ErrRefused
+ }
+ raw, err = call("account/read", map[string]bool{"refreshToken": false})
+ var acct struct {
+ Account *struct{ Type, Email, PlanType string }
+ }
+ if err != nil || json.Unmarshal(raw, &acct) != nil || acct.Account == nil || acct.Account.Type != "chatgpt" || acct.Account.Email == "" {
+ return Account{}, ErrRefused
+ }
+ a := Account{Email: acct.Account.Email, Plan: acct.Account.PlanType}
+ if raw, err = call("account/rateLimits/read", nil); err == nil {
+ var v struct {
+ RateLimits json.RawMessage `json:"rateLimits"`
+ }
+ if json.Unmarshal(raw, &v) == nil {
+ if l, plan, ok := CodexRateLimits(v.RateLimits); ok {
+ a.Limits = &l
+ if a.Plan == "" {
+ a.Plan = plan
+ }
+ }
+ }
+ }
+ return a, nil
+ }
+ }
+}
+
+// signInURL is the authorize URL Claude's CLI hands its browser: the
+// loopback flow, redirecting to http://localhost:<port>/callback.
+var signInURL = regexp.MustCompile(`https://[a-z.]+/[A-Za-z0-9/_.-]*oauth/authorize\?[^\s"'\x1b\x07]+`)
+
+// claudeHosts are the sign-in pages Claude's CLI may send a browser to.
+var claudeHosts = []string{"claude.ai", "claude.com", "platform.claude.com", "console.anthropic.com"}
+
+// LoopbackURL checks a sign-in URL: Anthropic's own authorize page with a
+// redirect to the CLI's loopback listener, nothing else.
+func LoopbackURL(raw string) (string, bool) {
+ u, err := url.Parse(strings.TrimSpace(raw))
+ if err != nil || u.Scheme != "https" || !strings.HasSuffix(u.Path, "/oauth/authorize") {
+ return "", false
+ }
+ host := false
+ for _, h := range claudeHosts {
+ host = host || u.Host == h
+ }
+ redirect, err := url.Parse(u.Query().Get("redirect_uri"))
+ if !host || err != nil || redirect.Scheme != "http" || redirect.Hostname() != "localhost" && redirect.Hostname() != "127.0.0.1" {
+ return "", false
+ }
+ return u.String(), true
+}
+
+// ClaudeLoopbackLogin runs the unmodified `claude auth login` in a new
+// home on a pseudo-terminal, with BROWSER set to a recorder in scratch,
+// so the runner learns the authorize URL the CLI would open (spec §2.3
+// case 1). prompt shows it; the person's browser, on this machine, signs
+// in and claude.ai redirects to the CLI's own loopback listener. Nothing
+// is ever written to the CLI: no code or token passes through Equipo.
+// It returns once the CLI exits; success is its exit status 0.
+func ClaudeLoopbackLogin(ctx context.Context, binary, home, scratch string, env []string, prompt func(signInURL string)) error {
+ recorded := filepath.Join(scratch, "sign-in-url")
+ browser := filepath.Join(scratch, "browser")
+ script := "#!/bin/sh\nprintf '%s\\n' \"$1\" > '" + recorded + "'\n"
+ if strings.ContainsRune(recorded, '\'') {
+ return fmt.Errorf("scratch path")
+ }
+ if err := os.WriteFile(browser, []byte(script), 0700); err != nil {
+ return err
+ }
+ master, tty, err := openPTY()
+ if err != nil {
+ return err
+ }
+ defer master.Close()
+ cmd := exec.Command(binary, "auth", "login", "--claudeai")
+ cmd.Dir = home
+ cmd.Env = append(env, "BROWSER="+browser, "TERM=xterm-256color")
+ cmd.Stdin, cmd.Stdout, cmd.Stderr = tty, tty, tty
+ cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true, Setctty: true}
+ if err = cmd.Start(); err != nil {
+ tty.Close()
+ return err
+ }
+ tty.Close()
+ // The CLI's own output is read and dropped: only the recorded URL is used.
+ go func() { _, _ = io.Copy(io.Discard, master) }()
+ exited := make(chan error, 1)
+ go func() { exited <- cmd.Wait() }()
+ shown := false
+ tick := time.NewTicker(100 * time.Millisecond)
+ defer tick.Stop()
+ for {
+ select {
+ case err := <-exited:
+ if err != nil {
+ return ErrRefused
+ }
+ return nil
+ case <-ctx.Done():
+ _ = unix.Kill(-cmd.Process.Pid, unix.SIGKILL)
+ <-exited
+ if errors.Is(ctx.Err(), context.DeadlineExceeded) {
+ return ErrTimedOut
+ }
+ return ErrCancelled
+ case <-tick.C:
+ if shown {
+ continue
+ }
+ raw, err := os.ReadFile(recorded)
+ if err != nil {
+ continue
+ }
+ if u, ok := LoopbackURL(string(bytes.TrimSpace(raw))); ok {
+ shown = true
+ prompt(u)
+ }
+ }
+ }
+}
+
+// openPTY opens a pseudo-terminal pair, wide enough that the CLI never
+// wraps a line.
+func openPTY() (*os.File, *os.File, error) {
+ master, err := os.OpenFile("/dev/ptmx", os.O_RDWR|unix.O_NOCTTY|unix.O_CLOEXEC, 0)
+ if err != nil {
+ return nil, nil, err
+ }
+ fd := int(master.Fd())
+ if err = unix.IoctlSetPointerInt(fd, unix.TIOCSPTLCK, 0); err != nil {
+ master.Close()
+ return nil, nil, err
+ }
+ n, err := unix.IoctlGetInt(fd, unix.TIOCGPTN)
+ if err != nil {
+ master.Close()
+ return nil, nil, err
+ }
+ tty, err := os.OpenFile(fmt.Sprintf("/dev/pts/%d", n), os.O_RDWR|unix.O_NOCTTY, 0)
+ if err != nil {
+ master.Close()
+ return nil, nil, err
+ }
+ ws := unix.Winsize{Row: 50, Col: 1000}
+ _ = unix.IoctlSetWinsize(int(tty.Fd()), unix.TIOCSWINSZ, &ws)
+ return master, tty, nil
+}
diff --git a/internal/runner/thin/connector.go b/internal/runner/thin/connector.go
new file mode 100644
index 00000000..1f7be2d4
--- /dev/null
+++ b/internal/runner/thin/connector.go
@@ -0,0 +1,361 @@
+package thin
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "log/slog"
+ "os"
+ "path/filepath"
+ "slices"
+ "sync"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner"
+ "amadan.net/oficina/equipo/internal/runner/connect"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/wire"
+ "golang.org/x/sys/unix"
+)
+
+const connectSchema = `
+CREATE TABLE IF NOT EXISTS connect_attempts (id TEXT PRIMARY KEY, person TEXT NOT NULL, provider TEXT NOT NULL, same_machine INTEGER NOT NULL DEFAULT 0, state TEXT NOT NULL, home TEXT NOT NULL DEFAULT '', created_at TEXT NOT NULL);
+`
+
+// ConnectLimit ends an attempt the person did not finish (spec §2.1: ten
+// minutes with no progress; the Codex device code itself lasts fifteen).
+const ConnectLimit = 10 * time.Minute
+
+// Connector adds connections from the app (spec §2): a Codex account by
+// device code, a Claude account by the CLI's own sign-in finished at
+// this machine (loopback, no paste), or, when the person's browser is
+// elsewhere, by `equipo-runner login claude` in a terminal here, which
+// the connector watches for. The provider's own CLI signs in, in a new
+// dedicated home; the instance only ever sees the provider's display
+// code or sign-in page and the account's email. Nothing moves from the
+// app to the runner but the request to begin.
+type Connector struct {
+ Runner runner.Config
+ State *State
+ Conns *Conns
+ // Root holds the dedicated homes (DefaultAccountsRoot).
+ Root string
+ Owners []string
+ Notify func()
+ Logger *slog.Logger
+ // Limit bounds an attempt (default ConnectLimit).
+ Limit time.Duration
+
+ mu sync.Mutex
+ attempts map[string]context.CancelFunc
+ ctx context.Context
+}
+
+func (c *Connector) log(msg string, err error) {
+ if c.Logger != nil && err != nil {
+ c.Logger.Warn(msg, "err", sanitize(err))
+ }
+}
+
+// Start reports attempts a previous process left unfinished (their sign-in
+// process died with it) and removes their unfinished homes.
+func (c *Connector) Start(ctx context.Context) error {
+ c.mu.Lock()
+ c.ctx, c.attempts = ctx, map[string]context.CancelFunc{}
+ c.mu.Unlock()
+ rows, err := c.State.db.QueryContext(ctx, "SELECT id, person, provider, home FROM connect_attempts WHERE state='running'")
+ if err != nil {
+ return err
+ }
+ type left struct{ id, person, provider, home string }
+ var all []left
+ for rows.Next() {
+ var l left
+ if err = rows.Scan(&l.id, &l.person, &l.provider, &l.home); err != nil {
+ rows.Close()
+ return err
+ }
+ all = append(all, l)
+ }
+ rows.Close()
+ for _, l := range all {
+ c.removeHome(l.home)
+ c.finish(l.id, wire.ConnectionReport{Connection: l.id, Person: l.person, Provider: l.provider, State: wire.ConnError, Reason: "runner_offline"})
+ }
+ return nil
+}
+
+// Accept records a connect command exactly once and starts the attempt.
+func (c *Connector) Accept(ctx context.Context, frameID string, cmd wire.ConnectCommand) error {
+ fresh := false
+ err := c.State.tx(ctx, func(t *sql.Tx) error {
+ var err error
+ if fresh, err = seen(t, frameID); err != nil || !fresh {
+ return err
+ }
+ same := 0
+ if cmd.SameMachine {
+ same = 1
+ }
+ _, err = t.Exec("INSERT INTO connect_attempts(id, person, provider, same_machine, state, created_at) VALUES(?,?,?,?,?,?) ON CONFLICT DO NOTHING", cmd.Connection, cmd.Person, cmd.Provider, same, "running", now())
+ return err
+ })
+ if err != nil || !fresh {
+ return err
+ }
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.ctx == nil {
+ return errors.New("connector not started")
+ }
+ limit := c.Limit
+ if limit <= 0 {
+ limit = ConnectLimit
+ }
+ actx, cancel := context.WithTimeout(c.ctx, limit)
+ c.attempts[cmd.Connection] = cancel
+ go c.run(actx, cancel, cmd)
+ return nil
+}
+
+// Cancel ends an attempt the person cancelled.
+func (c *Connector) Cancel(ctx context.Context, frameID string, cmd wire.CancelConnectCommand) error {
+ fresh := false
+ err := c.State.tx(ctx, func(t *sql.Tx) error {
+ var err error
+ fresh, err = seen(t, frameID)
+ return err
+ })
+ if err != nil || !fresh {
+ return err
+ }
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if cancel := c.attempts[cmd.Connection]; cancel != nil {
+ cancel()
+ }
+ return nil
+}
+
+// report sends progress on an attempt (durable).
+func (c *Connector) report(r wire.ConnectionReport) {
+ err := c.State.tx(context.Background(), func(t *sql.Tx) error { return c.State.enqueue(t, wire.FrameConnection, "", r) })
+ c.log("connect report", err)
+ if c.Notify != nil {
+ c.Notify()
+ }
+}
+
+// finish reports an attempt's end and marks it done, in one transaction.
+func (c *Connector) finish(id string, r wire.ConnectionReport) {
+ err := c.State.tx(context.Background(), func(t *sql.Tx) error {
+ if _, err := t.Exec("UPDATE connect_attempts SET state='done' WHERE id=?", id); err != nil {
+ return err
+ }
+ return c.State.enqueue(t, wire.FrameConnection, "", r)
+ })
+ c.log("connect report", err)
+ if c.Notify != nil {
+ c.Notify()
+ }
+}
+
+func reasonOf(err error) string {
+ switch {
+ case errors.Is(err, connect.ErrTimedOut), errors.Is(err, context.DeadlineExceeded):
+ return "timed_out"
+ case errors.Is(err, connect.ErrCancelled), errors.Is(err, context.Canceled):
+ return "cancelled"
+ }
+ return "provider_refused"
+}
+
+func (c *Connector) run(ctx context.Context, cancel context.CancelFunc, cmd wire.ConnectCommand) {
+ defer cancel()
+ defer func() {
+ c.mu.Lock()
+ delete(c.attempts, cmd.Connection)
+ c.mu.Unlock()
+ }()
+ base := wire.ConnectionReport{Connection: cmd.Connection, Person: cmd.Person, Provider: cmd.Provider}
+ fail := func(reason string) {
+ r := base
+ r.State, r.Reason = wire.ConnError, reason
+ c.finish(cmd.Connection, r)
+ }
+ if !slices.Contains(c.Owners, cmd.Person) || cmd.Provider != wire.ProviderClaude && cmd.Provider != wire.ProviderCodex {
+ fail("provider_refused")
+ return
+ }
+ if cmd.Provider == wire.ProviderClaude && !cmd.SameMachine {
+ c.watchTerminal(ctx, cmd, base, fail)
+ return
+ }
+ if err := os.MkdirAll(c.Root, 0700); err != nil {
+ fail("provider_refused")
+ return
+ }
+ id, home, err := nextHome(c.Root, cmd.Provider)
+ if err == nil {
+ err = provider.CheckLoginHome(home)
+ }
+ if err != nil {
+ c.log("connect home", err)
+ if home != "" {
+ os.Remove(home)
+ }
+ fail("provider_refused")
+ return
+ }
+ _, _ = c.State.db.Exec("UPDATE connect_attempts SET home=? WHERE id=?", home, cmd.Connection)
+ lock, err := os.Open(home)
+ if err == nil {
+ err = unix.Flock(int(lock.Fd()), unix.LOCK_EX|unix.LOCK_NB)
+ }
+ if err != nil {
+ if lock != nil {
+ lock.Close()
+ }
+ c.removeHome(home)
+ fail("provider_refused")
+ return
+ }
+ defer lock.Close()
+ env := provider.LoginEnvironment(cmd.Provider, home)
+ var acct connect.Account
+ if cmd.Provider == wire.ProviderCodex {
+ acct, err = connect.CodexDeviceLogin(ctx, c.Runner.CodexPath, home, env, func(u, code string) {
+ r := base
+ r.State, r.Prompt = wire.ConnConnecting, &wire.ConnectPrompt{Kind: wire.PromptDeviceCode, URL: u, Code: code}
+ c.report(r)
+ })
+ } else {
+ scratch, serr := os.MkdirTemp(c.Runner.ScratchRoot, "policy-")
+ if serr != nil {
+ err = serr
+ } else {
+ err = connect.ClaudeLoopbackLogin(ctx, c.Runner.ClaudePath, home, scratch, env, func(u string) {
+ r := base
+ r.State, r.Prompt = wire.ConnConnecting, &wire.ConnectPrompt{Kind: wire.PromptLink, URL: u}
+ c.report(r)
+ })
+ os.RemoveAll(scratch)
+ }
+ }
+ if err != nil {
+ c.log("connect sign-in", err)
+ c.removeHome(home)
+ fail(reasonOf(err))
+ return
+ }
+ // The same account connected twice would only split one limit.
+ observed, err := c.identify(ctx, cmd, id, home)
+ if err != nil {
+ c.removeHome(home)
+ if errors.Is(err, errAlreadyConnected) {
+ fail("already_connected")
+ } else {
+ c.log("connect identity", err)
+ fail("identity_mismatch")
+ }
+ return
+ }
+ if c.Conns != nil {
+ c.Conns.Forget(id)
+ if acct.Limits != nil {
+ c.Conns.Observe(id, *acct.Limits, acct.Plan)
+ }
+ c.Conns.changed()
+ }
+ r := base
+ r.State, r.LocalID, r.Label, r.Plan = wire.ConnHealthy, id, observed.AccountID, acct.Plan
+ if acct.Limits != nil {
+ r.Headroom = acct.Limits.Headroom
+ }
+ c.finish(cmd.Connection, r)
+}
+
+var errAlreadyConnected = errors.New("already connected")
+
+// identify records the signed-in home as a connection of the person's,
+// unless the same account is already one.
+func (c *Connector) identify(ctx context.Context, cmd wire.ConnectCommand, id, home string) (provider.Identity, error) {
+ options := provider.LoginOptions{ClaudePath: c.Runner.ClaudePath, CodexPath: c.Runner.CodexPath}
+ probe, ok := provider.NewLoginDriver(options).(interface {
+ Probe(context.Context, provider.Binding) (provider.Identity, error)
+ })
+ if !ok {
+ return provider.Identity{}, provider.ErrLoginUnavailable
+ }
+ observed, err := probe.Probe(ctx, provider.Binding{ID: id, Home: home, Provider: cmd.Provider})
+ if err != nil {
+ return observed, err
+ }
+ for _, b := range c.mine(cmd.Person) {
+ if b.Provider == cmd.Provider && b.AccountID == observed.AccountID {
+ return observed, errAlreadyConnected
+ }
+ }
+ return finishLogin(ctx, c.Runner, cmd.Person, cmd.Provider, id, home)
+}
+
+func (c *Connector) mine(person string) []runner.AccountBinding {
+ bs, _ := runner.LoadBindings(c.Runner.AccountBindingsPath)
+ var out []runner.AccountBinding
+ for _, b := range bs {
+ if b.PersonID == person {
+ out = append(out, b)
+ }
+ }
+ return out
+}
+
+// watchTerminal is the remote Claude case (spec §2.3 case 2): the
+// sign-in finishes in a terminal on this machine with `equipo-runner
+// login claude`, where any paste goes into the CLI. The attempt shows
+// that and turns healthy when the new connection appears.
+func (c *Connector) watchTerminal(ctx context.Context, cmd wire.ConnectCommand, base wire.ConnectionReport, fail func(string)) {
+ before := map[string]bool{}
+ for _, b := range c.mine(cmd.Person) {
+ before[b.ID] = true
+ }
+ r := base
+ r.State, r.Prompt = wire.ConnConnecting, &wire.ConnectPrompt{Kind: wire.PromptTerminal, Code: "equipo-runner login claude"}
+ c.report(r)
+ tick := time.NewTicker(2 * time.Second)
+ defer tick.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ fail(reasonOf(ctx.Err()))
+ return
+ case <-tick.C:
+ }
+ for _, b := range c.mine(cmd.Person) {
+ if b.Provider == wire.ProviderClaude && !before[b.ID] {
+ if c.Conns != nil {
+ c.Conns.changed()
+ }
+ done := base
+ done.State, done.LocalID, done.Label = wire.ConnHealthy, b.ID, b.AccountID
+ c.finish(cmd.Connection, done)
+ return
+ }
+ }
+ }
+}
+
+// removeHome deletes a home this connector created that never became a
+// connection: never one a binding names.
+func (c *Connector) removeHome(home string) {
+ if home == "" || filepath.Dir(home) != filepath.Clean(c.Root) {
+ return
+ }
+ bs, _ := runner.LoadBindings(c.Runner.AccountBindingsPath)
+ for _, b := range bs {
+ if b.ProviderHome == home {
+ return
+ }
+ }
+ c.log("connect home", os.RemoveAll(home))
+}
diff --git a/internal/runner/thin/link.go b/internal/runner/thin/link.go
index f8d8b399..df055cb2 100644
--- a/internal/runner/thin/link.go
+++ b/internal/runner/thin/link.go
@@ -40,6 +40,8 @@ type Link struct {
// at once).
Synced func()
Hello func() wire.Hello
+ // Connector adds connections the person starts from the app.
+ Connector *Connector
Logger *slog.Logger
// Connected is called with true once a generation is granted and false
// when the socket ends. Tests use it to wait.
@@ -453,6 +455,20 @@ func (l *Link) read(ctx context.Context, c *websocket.Conn) (time.Duration, erro
if fresh {
l.deliverTool(*v)
}
+ case *wire.ConnectCommand:
+ if l.Connector == nil {
+ continue
+ }
+ if err = l.Connector.Accept(ctx, f.ID, *v); err != nil {
+ return 0, err
+ }
+ case *wire.CancelConnectCommand:
+ if l.Connector == nil {
+ continue
+ }
+ if err = l.Connector.Cancel(ctx, f.ID, *v); err != nil {
+ return 0, err
+ }
case *wire.Drain:
return time.Duration(max(v.RetryAfter, 1)) * time.Second, nil
default:
diff --git a/internal/runner/thin/login.go b/internal/runner/thin/login.go
index 00f00cc2..ca07d657 100644
--- a/internal/runner/thin/login.go
+++ b/internal/runner/thin/login.go
@@ -97,34 +97,43 @@ func Login(ctx context.Context, c runner.Config, name string, o LoginOptions) er
if err = o.Command(ctx, binary, args, home, env); err != nil {
return fmt.Errorf("%w: sign-in did not finish", provider.ErrLoginRequired)
}
+ // The probe runs the CLI in the home under its lock.
+ observed, err := finishLogin(ctx, c, person, name, id, home)
+ if err != nil {
+ return err
+ }
+ if err = unix.Flock(int(lock.Fd()), unix.LOCK_UN); err != nil {
+ return err
+ }
+ _, err = fmt.Fprintf(o.Output, "Signed in as %s. Saved as %s.\n", observed.AccountID, id) // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ return err
+}
+
+// finishLogin records a home the provider's own CLI just signed in: the
+// identity the CLI reports (never its login output), the identity file,
+// and the binding for the person. Credentials stay in the home.
+func finishLogin(ctx context.Context, c runner.Config, person, name, id, home string) (provider.Identity, error) {
options := provider.LoginOptions{ClaudePath: c.ClaudePath, CodexPath: c.CodexPath}
probe, ok := provider.NewLoginDriver(options).(interface {
Probe(context.Context, provider.Binding) (provider.Identity, error)
})
if !ok {
- return provider.ErrLoginUnavailable
+ return provider.Identity{}, provider.ErrLoginUnavailable
}
observed, err := probe.Probe(ctx, provider.Binding{ID: id, Home: home, Provider: name})
if err != nil {
- return err
+ return observed, err
}
if observed.AccountID == "" || strings.ContainsAny(observed.AccountID, "\r\n\x1b") {
- return provider.ErrIdentity
+ return observed, provider.ErrIdentity
}
observed.HomeID = rand.Text()
raw, _ := json.Marshal(observed)
if err = os.WriteFile(filepath.Join(home, provider.IdentityFile), raw, 0600); err != nil {
- return err
- }
- if err = unix.Flock(int(lock.Fd()), unix.LOCK_UN); err != nil {
- return err
+ return observed, err
}
b := provider.Binding{ID: id, Home: home, Provider: name, AccountID: observed.AccountID, Expected: observed}
- if err = runnersetup.SaveAccountBinding(ctx, c.AccountBindingsPath, person, DefaultModels[name], runnerproto.AccountSetup{ID: id, Provider: name, Label: id}, b); err != nil {
- return err
- }
- _, err = fmt.Fprintf(o.Output, "Signed in as %s. Saved as %s.\n", observed.AccountID, id) // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- return err
+ return observed, runnersetup.SaveAccountBinding(ctx, c.AccountBindingsPath, person, DefaultModels[name], runnerproto.AccountSetup{ID: id, Provider: name, Label: id}, b)
}
// nextHome creates the first free <provider>-<n> directory.
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go
index 8f7651e8..de9d129f 100644
--- a/internal/runner/thin/run.go
+++ b/internal/runner/thin/run.go
@@ -54,11 +54,16 @@ type Options struct {
// MergeEvery spaces the merge checks of watched task branches
// (default: the minute reach check's pace).
MergeEvery time.Duration
+ // AccountsRoot holds the homes of connections added from the app
+ // (EQUIPO_ACCOUNTS_ROOT; default ~/.local/share/equipo/accounts).
+ AccountsRoot string
+ // ConnectLimit bounds a connection attempt (default ConnectLimit).
+ ConnectLimit time.Duration
}
// OptionsFromEnv reads the runner's optional thin settings.
func OptionsFromEnv(getenv func(string) string) Options {
- return Options{NoCreate: getenv("EQUIPO_RUNNER_CREATE_REPOS") == "0", Home: getenv("EQUIPO_RUNNER_HOME_NAMESPACE"), NoMoveIn: getenv("EQUIPO_RUNNER_MOVE_IN") == "0", IndexPace: 4 * time.Second}
+ return Options{NoCreate: getenv("EQUIPO_RUNNER_CREATE_REPOS") == "0", Home: getenv("EQUIPO_RUNNER_HOME_NAMESPACE"), NoMoveIn: getenv("EQUIPO_RUNNER_MOVE_IN") == "0", IndexPace: 4 * time.Second, AccountsRoot: getenv("EQUIPO_ACCOUNTS_ROOT")}
}
// SessionRoot is where durable coordinator transcripts live by default:
@@ -130,6 +135,14 @@ func Run(ctx context.Context, c runner.Config, o Options) error {
}}
conns.Changed = func() { engine.ConnectionsChanged(); link.HelloSoon() }
link.Engine = engine
+ if o.AccountsRoot == "" {
+ o.AccountsRoot = DefaultAccountsRoot()
+ }
+ connector := &Connector{Runner: c, State: state, Conns: conns, Root: o.AccountsRoot, Owners: coordinatorPersons(c)(), Notify: link.Notify, Logger: o.Logger, Limit: o.ConnectLimit}
+ if err = connector.Start(ctx); err != nil {
+ return err
+ }
+ link.Connector = connector
createIn := &namespaces{}
recheck := make(chan struct{}, 1)
link.Recheck = func() {
diff --git a/internal/runner/thin/state.go b/internal/runner/thin/state.go
index b19c2bb8..d674606b 100644
--- a/internal/runner/thin/state.go
+++ b/internal/runner/thin/state.go
@@ -54,7 +54,7 @@ func OpenState(ctx context.Context, dir string) (*State, error) {
return nil, err
}
d.SetMaxOpenConns(1)
- if _, err = d.ExecContext(ctx, schema+stepSchema+watchSchema+askSchema+connSchema); err != nil {
+ if _, err = d.ExecContext(ctx, schema+stepSchema+watchSchema+askSchema+connSchema+connectSchema); err != nil {
d.Close()
return nil, err
}
diff --git a/internal/thintest/client.go b/internal/thintest/client.go
index 3d44843f..05fe934e 100644
--- a/internal/thintest/client.go
+++ b/internal/thintest/client.go
@@ -163,6 +163,26 @@ func (c *Client) CancelQuestion(ctx context.Context, id string) (out wire.TaskAc
return out, c.do(ctx, "POST", "/api/v1/questions/"+id+"/cancel", nil, &out)
}
+// Connections lists the person's connections.
+func (c *Client) Connections(ctx context.Context) (out wire.ConnectionList, err error) {
+ return out, c.do(ctx, "GET", "/api/v1/connections", nil, &out)
+}
+
+// Connect starts a connection attempt.
+func (c *Client) Connect(ctx context.Context, in wire.Connect) (out wire.Connection, err error) {
+ return out, c.do(ctx, "POST", "/api/v1/connections", in, &out)
+}
+
+// Connection reads one connection.
+func (c *Client) Connection(ctx context.Context, id string) (out wire.Connection, err error) {
+ return out, c.do(ctx, "GET", "/api/v1/connections/"+id, nil, &out)
+}
+
+// CancelConnection ends an attempt.
+func (c *Client) CancelConnection(ctx context.Context, id string) (out wire.Connection, err error) {
+ return out, c.do(ctx, "POST", "/api/v1/connections/"+id+"/cancel", nil, &out)
+}
+
// Stream is one open SSE connection.
type Stream struct {
Events <-chan wire.Event
@@ -238,6 +258,8 @@ type Conversation struct {
Order []string
Turns map[string]wire.Turn
Drafts map[string]string
+ // Connections are the person's connections, by id.
+ Connections map[string]wire.Connection
Runner wire.Runner
Cards map[string]wire.Card
Projects map[string]wire.Project
@@ -277,6 +299,10 @@ func (c *Conversation) Reset(s wire.Snapshot) {
c.Messages, c.Order, c.Turns, c.Drafts = map[string]wire.Message{}, nil, map[string]wire.Turn{}, map[string]string{}
c.Cards, c.Projects = map[string]wire.Card{}, map[string]wire.Project{}
c.Tasks, c.Steps, c.Stages = map[string]wire.Task{}, map[string]wire.Step{}, map[string][]string{}
+ c.Connections = map[string]wire.Connection{}
+ for _, v := range s.Connections {
+ c.Connections[v.ID] = v
+ }
c.Questions, c.DeltaResources = map[string]wire.Question{}, map[string]int{}
for _, k := range s.Tasks {
c.applyTask(k)
@@ -363,12 +389,22 @@ func (c *Conversation) Apply(e wire.Event) bool {
if json.Unmarshal(e.Data, &t) == nil {
if old, ok := c.Turns[t.ID]; !ok || t.Revision > old.Revision {
c.Turns[t.ID] = t
- if t.State == wire.TurnCancelled || t.State == wire.TurnFailed {
+ // A failed or cancelled turn, or a new attempt (a failover,
+ // a recovery), drops the draft: the new attempt streams anew.
+ if t.State == wire.TurnCancelled || t.State == wire.TurnFailed || ok && t.Attempt != old.Attempt {
delete(c.Drafts, t.ID)
}
applied = true
}
}
+ case wire.EventConnection:
+ var v wire.Connection
+ if json.Unmarshal(e.Data, &v) == nil {
+ if old, ok := c.Connections[v.ID]; !ok || v.Revision > old.Revision {
+ c.Connections[v.ID] = v
+ applied = true
+ }
+ }
case wire.EventDelta:
var d wire.Delta
if json.Unmarshal(e.Data, &d) == nil && int64(len(c.Drafts[d.TurnID])) == d.Offset {
diff --git a/internal/thintest/connections_contract_test.go b/internal/thintest/connections_contract_test.go
new file mode 100644
index 00000000..5b3d8b46
--- /dev/null
+++ b/internal/thintest/connections_contract_test.go
@@ -0,0 +1,203 @@
+package thintest
+
+import (
+ "database/sql"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+func held(conns ...wire.HeldConnection) wire.Hello {
+ return wire.Hello{Repos: []string{}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Connections: conns, Versions: map[string]string{"runner": "test"}}
+}
+
+// TestContractConnections: the runner's hello records the person's own
+// connections (never a teammate's); an attempt started in the app goes to
+// the runner as a durable connect frame, shows the provider's device
+// code, turns healthy with the runner's name for it and is not
+// duplicated by the next hello; cancel goes to the runner; a connection
+// the runner no longer holds is signed out. Every document matches the
+// shared fixtures, and no secret-shaped field is ever stored.
+func TestContractConnections(t *testing.T) {
+ r := newRig(t)
+ runner := r.dial(0)
+ r.wait("runner online", func(c *Conversation) bool { return c.Runner.Online })
+ reset := time.Date(2026, 11, 10, 10, 0, 0, 0, time.UTC)
+ one := 1.0
+ hello := held(wire.HeldConnection{LocalID: "claude-a", Person: Owner, Provider: "claude", Kind: "subscription", Label: Owner, State: wire.ConnLimited, Headroom: &wire.Headroom{Utilization: &one, ResetsAt: &reset, Windows: []wire.Window{{Name: "seven_day", UsedPercent: 100, Minutes: 10080, ResetsAt: &reset}}}},
+ wire.HeldConnection{LocalID: "claude-b", Person: "teammate@example.com", Provider: "claude", Kind: "subscription", Label: "teammate@example.com", State: wire.ConnHealthy})
+ hello.Generation = runner.Welcome.Generation
+ if err := runner.Send(r.ctx, "h1", wire.FrameHello, hello); err != nil {
+ t.Fatal(err)
+ }
+ r.wait("claude-a recorded", func(c *Conversation) bool { return len(c.Connections) == 1 })
+ list, err := r.client.Connections(r.ctx)
+ if err != nil || len(list.Items) != 1 || list.Items[0].LocalID != "claude-a" || list.Items[0].State != wire.ConnLimited {
+ t.Fatalf("connections %+v %v", list, err)
+ }
+
+ attempt, err := r.client.Connect(r.ctx, wire.Connect{Provider: "codex", Kind: "subscription"})
+ if err != nil || attempt.State != wire.ConnConnecting || attempt.LocalID != "" {
+ t.Fatalf("connect %+v %v", attempt, err)
+ }
+ f, body, err := runner.Expect(r.ctx, wire.FrameConnect)
+ if err != nil {
+ t.Fatal(err)
+ }
+ shape(t, "frames/connect.json", runner.Received[len(runner.Received)-1])
+ cmd := body.(*wire.ConnectCommand)
+ if cmd.Connection != attempt.ID || cmd.Person != Owner || cmd.Provider != "codex" || cmd.SameMachine {
+ t.Fatalf("connect frame %+v", cmd)
+ }
+ if err = runner.Send(r.ctx, "r-ack-c", wire.FrameAck, wire.Ack{ID: f.ID}); err != nil {
+ t.Fatal(err)
+ }
+ // A second Add while one is connecting is the same attempt.
+ again, err := r.client.Connect(r.ctx, wire.Connect{Provider: "codex"})
+ if err != nil || again.ID != attempt.ID {
+ t.Fatalf("second attempt %+v %v", again, err)
+ }
+ report := wire.ConnectionReport{Connection: attempt.ID, Person: Owner, Provider: "codex", State: wire.ConnConnecting, Prompt: &wire.ConnectPrompt{Kind: wire.PromptDeviceCode, URL: "https://auth.openai.com/codex/device", Code: "ABCD-1234"}}
+ if err = runner.Send(r.ctx, "r-conn-1", wire.FrameConnection, report); err != nil {
+ t.Fatal(err)
+ }
+ r.wait("device code shown", func(c *Conversation) bool {
+ p := c.Connections[attempt.ID].Prompt
+ return p != nil && p.Code == "ABCD-1234"
+ })
+ got, err := r.client.Connection(r.ctx, attempt.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ shape(t, "api/connection-connecting-codex.json", got)
+
+ done := wire.ConnectionReport{Connection: attempt.ID, Person: Owner, LocalID: "codex-1", Provider: "codex", State: wire.ConnHealthy, Label: Owner, Plan: "pro", Headroom: &wire.Headroom{Windows: []wire.Window{}}}
+ // The hello can arrive before the attempt's report: it is not a second
+ // connection.
+ hello.Connections = append(hello.Connections, wire.HeldConnection{LocalID: "codex-1", Person: Owner, Provider: "codex", Kind: "subscription", Label: Owner, State: wire.ConnHealthy, Plan: "pro"})
+ if err = runner.Send(r.ctx, "h2", wire.FrameHello, hello); err != nil {
+ t.Fatal(err)
+ }
+ if err = runner.Send(r.ctx, "r-conn-2", wire.FrameConnection, done); err != nil {
+ t.Fatal(err)
+ }
+ shape(t, "frames/connection.json", runner.Sent[len(runner.Sent)-1])
+ r.wait("codex healthy", func(c *Conversation) bool {
+ v := c.Connections[attempt.ID]
+ return v.State == wire.ConnHealthy && v.LocalID == "codex-1" && v.Prompt == nil
+ })
+ if err = runner.Send(r.ctx, "h3", wire.FrameHello, hello); err != nil {
+ t.Fatal(err)
+ }
+ time.Sleep(200 * time.Millisecond)
+ list, _ = r.client.Connections(r.ctx)
+ if len(list.Items) != 2 {
+ t.Fatalf("after the hello: %+v", list.Items)
+ }
+ shape(t, "api/connections.json", list)
+ // A late frame for an ended attempt changes nothing.
+ if err = runner.Send(r.ctx, "r-conn-3", wire.FrameConnection, report); err != nil {
+ t.Fatal(err)
+ }
+ if v, _ := r.client.Connection(r.ctx, attempt.ID); v.State != wire.ConnHealthy {
+ t.Fatalf("late frame reopened the attempt: %+v", v)
+ }
+
+ // Claude, browser elsewhere: the honest card, and the runner watches.
+ claude, err := r.client.Connect(r.ctx, wire.Connect{Provider: "claude"})
+ if err != nil || claude.Prompt == nil || claude.Prompt.Kind != wire.PromptTerminal || claude.Prompt.Code != "equipo-runner login claude" {
+ t.Fatalf("claude attempt %+v %v", claude, err)
+ }
+ if _, body, err = runner.Expect(r.ctx, wire.FrameConnect); err != nil || body.(*wire.ConnectCommand).SameMachine {
+ t.Fatalf("claude connect %+v %v", body, err)
+ }
+ cancelled, err := r.client.CancelConnection(r.ctx, claude.ID)
+ if err != nil || cancelled.State != wire.ConnError || cancelled.Reason != "cancelled" {
+ t.Fatalf("cancel %+v %v", cancelled, err)
+ }
+ if _, body, err = runner.Expect(r.ctx, wire.FrameCancelConnect); err != nil || body.(*wire.CancelConnectCommand).Connection != claude.ID {
+ t.Fatalf("cancel frame %+v %v", body, err)
+ }
+
+ // A connection the runner no longer holds is signed out.
+ hello.Connections = hello.Connections[:1]
+ if err = runner.Send(r.ctx, "h4", wire.FrameHello, hello); err != nil {
+ t.Fatal(err)
+ }
+ r.wait("codex signed out", func(c *Conversation) bool { return c.Connections[attempt.ID].State == wire.ConnSignedOut })
+ snap, err := r.client.Snapshot(r.ctx)
+ if err != nil || len(snap.Connections) != 3 {
+ t.Fatalf("snapshot connections %+v %v", snap.Connections, err)
+ }
+ // Nothing secret-shaped was stored.
+ var dump string
+ _ = r.inst.DB.Writer().QueryRow("SELECT group_concat(coalesce(headroom,'') || coalesce(prompt,'') || label || plan, '|') FROM chat_connections").Scan(&dump)
+ for _, bad := range []string{"token", "secret", "password", "/home/"} {
+ if strings.Contains(strings.ToLower(dump), bad) {
+ t.Fatalf("stored %q: %s", bad, dump)
+ }
+ }
+ var _ = sql.ErrNoRows
+}
+
+// TestContractHeldTurnAndSwitch: a turn held for a connection carries the
+// reason no_connection while it waits and drops it when it goes on; a
+// failover's new attempt drops the first attempt's draft; the reply
+// carries the switched line and its usage is recorded.
+func TestContractHeldTurnAndSwitch(t *testing.T) {
+ r := newRig(t)
+ runner := r.dial(0)
+ r.wait("runner online", func(c *Conversation) bool { return c.Runner.Online })
+ sent, err := r.client.Send(r.ctx, "hello", "k-held")
+ if err != nil {
+ t.Fatal(err)
+ }
+ f, _, err := runner.Expect(r.ctx, wire.FrameMessage)
+ if err != nil {
+ t.Fatal(err)
+ }
+ runner.Send(r.ctx, "a-1", wire.FrameAck, wire.Ack{ID: f.ID})
+ turn := sent.Turn.ID
+ runner.Send(r.ctx, "r-hold", wire.FrameTurn, wire.TurnReport{TurnID: turn, Attempt: 1, State: wire.TurnRunning, Reason: wire.ReasonNoConnection})
+ r.wait("held", func(c *Conversation) bool {
+ v := c.Turns[turn]
+ return v.State == wire.TurnRunning && v.Reason == wire.ReasonNoConnection
+ })
+ page := r.inst.Get(t, "/conversation")
+ if !strings.Contains(page, "data-no-connection") || !strings.Contains(page, "Nothing can answer right now.") || strings.Contains(page, "Send your message again") {
+ t.Fatalf("held card missing from the page")
+ }
+ runner.Send(r.ctx, "r-go", wire.FrameTurn, wire.TurnReport{TurnID: turn, Attempt: 1, State: wire.TurnRunning})
+ r.wait("going again", func(c *Conversation) bool { v := c.Turns[turn]; return v.State == wire.TurnRunning && v.Reason == "" })
+ runner.Send(r.ctx, "r-d1", wire.FrameDelta, wire.DeltaReport{TurnID: turn, Attempt: 1, Offset: 0, Text: "Partial"})
+ r.wait("draft", func(c *Conversation) bool { return c.Drafts[turn] == "Partial" })
+ // Claude refused on quota: attempt 2 on Codex.
+ runner.Send(r.ctx, "r-retry", wire.FrameTurn, wire.TurnReport{TurnID: turn, Attempt: 2, State: wire.TurnRunning})
+ r.wait("attempt 2, no draft", func(c *Conversation) bool { return c.Turns[turn].Attempt == 2 && c.Drafts[turn] == "" })
+ runner.Send(r.ctx, "r-stale", wire.FrameDelta, wire.DeltaReport{TurnID: turn, Attempt: 1, Offset: 7, Text: " old"})
+ runner.Send(r.ctx, "r-d2", wire.FrameDelta, wire.DeltaReport{TurnID: turn, Attempt: 2, Offset: 0, Text: "Done."})
+ r.wait("new draft", func(c *Conversation) bool { return c.Drafts[turn] == "Done." })
+ reset := time.Date(2026, 11, 10, 10, 0, 0, 0, time.UTC)
+ reply := wire.Reply{TurnID: turn, Attempt: 2, Text: "Done.", Usage: wire.Usage{InputTokens: 5120, OutputTokens: 88, CachedInputTokens: 4096, ReasoningOutputTokens: 40, Provider: "codex", Model: "gpt-6-astra", Connection: "codex-1"}, Switched: &wire.Switched{From: "claude", To: "codex", Window: "seven_day", ResetsAt: &reset}}
+ runner.Send(r.ctx, "r-reply", wire.FrameReply, reply)
+ r.wait("replied", func(c *Conversation) bool { return c.Turns[turn].State == wire.TurnReplied && len(c.Replies()) == 1 })
+ m := r.conv.Replies()[0]
+ if m.Switched == nil || m.Switched.To != "codex" || !m.Switched.ResetsAt.Equal(reset) {
+ t.Fatalf("switched %+v", m.Switched)
+ }
+ if v, _ := r.client.Turn(r.ctx, turn); v.Connection != "codex-1" || v.Attempt != 2 {
+ t.Fatalf("turn %+v", v)
+ }
+ page = r.inst.Get(t, "/conversation")
+ if !strings.Contains(page, "Switched to Codex; Claude&#39;s limit resets Tue 10:00 UTC") || strings.Contains(page, "data-no-connection") {
+ t.Fatalf("switched line missing from the page")
+ }
+ var rows, input, cached, reasoning int64
+ var provider, model, conn, role string
+ err = r.inst.DB.Writer().QueryRow("SELECT count(*), sum(input_tokens), sum(cached_input_tokens), sum(reasoning_output_tokens), max(provider), max(model), max(connection), max(role) FROM chat_usage WHERE turn_id = ?", turn).Scan(&rows, &input, &cached, &reasoning, &provider, &model, &conn, &role)
+ if err != nil || rows != 1 || input != 5120 || cached != 4096 || reasoning != 40 || provider != "codex" || model != "gpt-6-astra" || conn != "codex-1" || role != "coordinator" {
+ t.Fatalf("usage %d %d %d %d %s %s %s %s %v", rows, input, cached, reasoning, provider, model, conn, role, err)
+ }
+}
diff --git a/internal/thintest/instance.go b/internal/thintest/instance.go
index 4835370a..dbdbae35 100644
--- a/internal/thintest/instance.go
+++ b/internal/thintest/instance.go
@@ -267,3 +267,20 @@ func Status(err error) int {
}
return 0
}
+
+// Get reads a page as the owner's browser session, which must answer 200.
+func (i *Instance) Get(t testing.TB, path string) string {
+ t.Helper()
+ req, _ := http.NewRequest("GET", i.URL+path, nil)
+ req.AddCookie(i.Cookie())
+ res, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer res.Body.Close()
+ raw, _ := io.ReadAll(res.Body)
+ if res.StatusCode != 200 {
+ t.Fatalf("GET %s: %d %s", path, res.StatusCode, raw)
+ }
+ return string(raw)
+}
diff --git a/internal/wire/wiretest/testdata/api/connections.json b/internal/wire/wiretest/testdata/api/connections.json
index ac31a81b..a7dbb18d 100644
--- a/internal/wire/wiretest/testdata/api/connections.json
+++ b/internal/wire/wiretest/testdata/api/connections.json
@@ -1 +1 @@
-{"items":[{"id":"cn_0001","revision":4,"runner_id":"rn_0001","local_id":"claude-a","provider":"claude","kind":"subscription","label":"owner@example.com","state":"limited","reason":"","plan":"","headroom":{"utilization":1,"resets_at":"2026-11-10T10:00:00Z","windows":[{"name":"seven_day","used_percent":100,"minutes":10080,"resets_at":"2026-11-10T10:00:00Z"}]},"prompt":null,"created_at":"2026-11-06T09:00:00Z","updated_at":"2026-11-08T09:59:00Z"},{"id":"cn_0002","revision":2,"runner_id":"rn_0001","local_id":"","provider":"codex","kind":"subscription","label":"","state":"connecting","reason":"","plan":"","headroom":null,"prompt":{"kind":"device_code","url":"https://auth.openai.com/codex/device","code":"ABCD-1234"},"created_at":"2026-11-08T10:00:00Z","updated_at":"2026-11-08T10:00:01Z"}]}
+{"items":[{"id":"cn_0001","revision":4,"runner_id":"rn_0001","local_id":"claude-a","provider":"claude","kind":"subscription","label":"owner@example.com","state":"limited","reason":"","plan":"","headroom":{"utilization":1,"resets_at":"2026-11-10T10:00:00Z","windows":[{"name":"seven_day","used_percent":100,"minutes":10080,"resets_at":"2026-11-10T10:00:00Z"}]},"prompt":null,"created_at":"2026-11-06T09:00:00Z","updated_at":"2026-11-08T09:59:00Z"},{"id":"cn_0002","revision":3,"runner_id":"rn_0001","local_id":"codex-1","provider":"codex","kind":"subscription","label":"owner@example.com","state":"healthy","reason":"","plan":"pro","headroom":{"utilization":0.12,"resets_at":null,"windows":[{"name":"primary","used_percent":12,"minutes":300,"resets_at":"2026-11-08T14:00:00Z"}]},"prompt":null,"created_at":"2026-11-08T10:00:00Z","updated_at":"2026-11-08T10:00:01Z"}]}