package thin import ( "context" "encoding/json" "os" "path/filepath" "strings" "testing" "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" ) // The controller's ruling #7: in production a stale Codex reading is // refreshed by the app-server's account/rateLimits/read, run as the // hourly refresh runs (the source home under its lock); Claude has no // such read and stays as last reported. The reading is stamped with the // time it was taken, and a reading that says the same again is no new // reading for held steps. func TestCodexReadingInProduction(t *testing.T) { r := newConnectorRig(t) r.cfg.ScratchRoot = filepath.Join(t.TempDir(), "scratch") reads := 0 limits := json.RawMessage(`{"primary":{"usedPercent":61,"windowDurationMins":300,"resetsAt":1762941600},"secondary":{"usedPercent":12,"windowDurationMins":10080,"resetsAt":1763287200},"planType":"pro","rateLimitReachedType":null}`) read := func(_ context.Context, b provider.Binding) (provider.Identity, json.RawMessage, error) { reads++ if b.Home != r.home || b.Provider != wire.ProviderCodex { t.Fatalf("read %+v", b) } return provider.Identity{AccountID: "a@example.com", ProviderVersion: "1"}, limits, nil } reading := CodexReading(r.cfg, read, time.Second) b, ok := r.conns.Binding("codex-1") if !ok { t.Fatal("no binding") } // The home as a sign-in leaves it: its identity and its credential. identity, _ := json.Marshal(b.ExpectedIdentity) for name, body := range map[string][]byte{provider.IdentityFile: identity, "auth.json": []byte(`{"tokens":{}}`)} { if err := os.WriteFile(filepath.Join(r.home, name), body, 0600); err != nil { t.Fatal(err) } } l, err := reading(context.Background(), b) if err != nil || l == nil || reads != 1 || len(l.Headroom.Windows) != 2 || l.Headroom.Windows[0].UsedPercent != 61 { t.Fatalf("codex: %+v %v (%d reads)", l, err, reads) } for _, other := range []runner.AccountBinding{{ID: "claude-1", Provider: wire.ProviderClaude}, {ID: "codex-t", Provider: wire.ProviderCodex, Kind: wire.KindToken}, {ID: "tensorx-1", Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey}} { if l, err := reading(context.Background(), other); l != nil || err != nil { t.Fatalf("%s read: %+v %v", other.ID, l, err) } } if reads != 1 { t.Fatalf("%d reads: only Codex subscriptions are read", reads) } // Observe stamps the reading's time; the same figures again move the // time only, and wake no held step. woken := 0 r.conns.Readings = func() { woken++ } at := time.Date(2026, 11, 12, 10, 0, 0, 0, time.UTC) r.conns.now = func() time.Time { return at } r.conns.Observe("codex-1", *l, "") held := func() *wire.Headroom { for _, h := range r.conns.Held() { if h.LocalID == "codex-1" { return h.Headroom } } return nil } if h := held(); h == nil || h.CheckedAt == nil || !h.CheckedAt.Equal(at) { t.Fatalf("reading time %+v", h) } at = at.Add(20 * time.Minute) r.conns.Observe("codex-1", *l, "") if h := held(); h.CheckedAt == nil || !h.CheckedAt.Equal(at) || woken != 0 { t.Fatalf("the same reading again: time %v, woke %d", h.CheckedAt, woken) } if l.Headroom.CheckedAt != nil { t.Fatal("Observe changed the caller's reading") } l.Headroom.Windows[0].UsedPercent = 70 r.conns.Observe("codex-1", *l, "") if woken != 1 { t.Fatalf("a new reading woke %d", woken) } } // A reading's age is its own time: a connection whose row was written // just now (a state change) but whose reading is sixteen minutes old is // refreshed before the scheduler decides. func TestScheduleRefreshUsesReadingTime(t *testing.T) { r := newSchedRig(t, "claude-a") base := time.Now() r.conns.now = func() time.Time { return base.Add(-16 * time.Minute) } r.reading("claude-a", 0.9, base.Add(time.Hour)) r.conns.now = func() time.Time { return base } // The row is written again now, the reading unchanged. r.conns.mu.Lock() cs := r.conns.live["claude-a"] r.conns.save("claude-a", cs) r.conns.mu.Unlock() probes := 0 r.conns.Reading = func(context.Context, runner.AccountBinding) (*connect.Limit, error) { probes++ at := base.Add(time.Hour) return &connect.Limit{Headroom: &wire.Headroom{Windows: []wire.Window{{Name: "five_hour", UsedPercent: 10, Minutes: 300, ResetsAt: &at}}}}, nil } row := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk", StepID: "s", Attempt: 1, Specialist: wire.SpecialistEngineering}} if d, _ := r.conns.decide(r.ctx, row, connect.RoleEngineering, keptRef{}, nil, nil); !d.d.Run || probes != 1 { t.Fatalf("a sixteen-minute-old reading: %+v, %d probes", d.d, probes) } } // TestHandshakeHelloWithholdsReadingTimes: the first hello goes out // before the instance says its protocol, so no headroom in it says when // it was read; after a protocol 15 welcome the next hello, sent at once, // does; at 14 none ever does. func TestHandshakeHelloWithholdsReadingTimes(t *testing.T) { at := time.Date(2026, 11, 12, 9, 58, 0, 0, time.UTC) hello := func() wire.Hello { return wire.Hello{Repos: []string{}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Versions: map[string]string{"runner": "test", "claude": "2.1.312"}, Connections: []wire.HeldConnection{{LocalID: "codex-1", Person: connPerson, Provider: wire.ProviderCodex, Kind: wire.KindSubscription, State: wire.ConnHealthy, Headroom: &wire.Headroom{Windows: []wire.Window{}, CheckedAt: &at}}}} } for _, protocol := range []int{wire.ProtocolScheduler, wire.ProtocolReadings} { inst := newFakeInstance(t) link, _, _, _ := startLinkWith(t, inst.url, &stubCoordinator{}, hello) c := <-inst.conns _, raw := read(t, c, wire.FrameHello) if strings.Contains(string(raw), `"checked_at"`) || !strings.Contains(string(raw), `"codex-1"`) { t.Fatalf("handshake hello: %s", raw) } welcome, _ := json.Marshal(wire.Frame{ID: "w-r", Type: wire.FrameWelcome, Data: json.RawMessage(`{"generation":3,"runner_id":"RUNNER1","protocol":` + itoa(int64(protocol)) + `,"role":"primary"}`)}) write(t, c, welcome) read(t, c, wire.FrameSync) if protocol < wire.ProtocolReadings { link.HelloSoon() } _, raw = read(t, c, wire.FrameHello) if got := strings.Contains(string(raw), `"checked_at":"2026-11-12T09:58:00Z"`); got != (protocol >= wire.ProtocolReadings) { t.Fatalf("protocol %d hello: %s", protocol, raw) } } }