diff --git a/README.md b/README.md index e1f87f83174..1aa963469a1 100644 --- a/README.md +++ b/README.md @@ -30,11 +30,30 @@ Antigravity's published catalog includes `claude-opus-4-6-thinking` and `claude- Strip every entry whose `id` starts with `claude-`, whose `type` is `claude`, or whose `owned_by` is `anthropic` from the `antigravity` array. Applied both to the in-tree `models.json` (so `go test ./...` and local dev see the patched shape) and to `.github/scripts/refresh-model-catalogs.sh` (so upstream catalog refreshes during tagged builds re-apply the strip automatically). After the patch the antigravity OAuth is Gemini-only and Claude requests fall through to the Anthropic OAuth pool. +### Patch 5 — retry a failed model-catalog fetch every 30 s + +`internal/registry/model_updater.go` (`runModelCatalogUpdater`), also used by the Codex and Devin catalog updaters. Backport of the open upstream PR [#6236](https://github.com/router-for-me/CLIProxyAPI/pull/6236). + +Upstream fetches the catalog once at startup and then every 3 h. When the proxy starts before DNS works, the fetch fails and models newer than the embedded catalog answer `400 unknown provider for model` for 3 h. After a failed attempt, retry in 30 s; after any successful fetch, go back to 3 h. Drop this patch when upstream merges #6236 or an equivalent. + +### Patch 6 — register models of loaded auth files before the listener opens + +`sdk/cliproxy/service_lifecycle.go` (`syncPluginModelRuntime` before `server.Start`). Backport of the open upstream PR [#6464](https://github.com/router-for-me/CLIProxyAPI/pull/6464); upstream closed the issue, [#6702](https://github.com/router-for-me/CLIProxyAPI/issues/6702), as not planned. + +Without it, requests in the first second after a restart get `400 unknown provider` for OAuth-file models, because those models are registered only after the file watcher's first load. + +### Patch 7 — wait up to 10 s for the first catalog fetch before listening + +`internal/registry/model_updater.go` (`WaitForStartupModelRefresh`) and `sdk/cliproxy/service_lifecycle.go`. Not upstream; [#6257](https://github.com/router-for-me/CLIProxyAPI/pull/6257) (open) solves the same race with a 503 gate. + +Patch 6 registers models from the catalog in memory at that moment. Right after a restart that is the embedded catalog, so models added upstream since the build still fail until the background fetch lands. The start waits for the first fetch (success or failure) and gives up after 10 s. + ## Tests ```bash go test ./internal/translator/openai/claude/... # Patches 1 + 2 -go test ./internal/registry/... # Patch 4 (catalog integrity) +go test ./internal/registry/... # Patches 4, 5, 7 +go test ./sdk/cliproxy/ -run TestServiceRun_RegistersLoadedAuthModelsBeforeListening # Patch 6 ``` ## Rebase diff --git a/internal/registry/codex_client_models_test.go b/internal/registry/codex_client_models_test.go index e8e105d0149..8fc662677d7 100644 --- a/internal/registry/codex_client_models_test.go +++ b/internal/registry/codex_client_models_test.go @@ -170,7 +170,9 @@ func TestRefreshCodexClientModelsKeepsLastValidSnapshot(t *testing.T) { before, revision := GetCodexClientModelsSnapshot() codexClientModelsURLs = urls - tryRefreshCodexClientModels(context.Background(), "test refresh") + if tryRefreshCodexClientModels(context.Background(), "test refresh") { + t.Fatal("failed refresh reported success") + } after, afterRevision := GetCodexClientModelsSnapshot() if string(after) != string(before) { t.Fatal("failed remote refresh replaced last valid catalog") @@ -198,6 +200,36 @@ func testCodexClientModel(slug string, priority int) map[string]any { } } +func TestRefreshCodexClientModelsSuccessAndUnchanged(t *testing.T) { + original, _ := GetCodexClientModelsSnapshot() + previousURLs := codexClientModelsURLs + t.Cleanup(func() { + codexClientModelsURLs = previousURLs + if _, err := loadCodexClientModelsFromBytes(original, "test cleanup"); err != nil { + t.Fatalf("restore original catalog: %v", err) + } + }) + catalog := testCodexClientCatalog(t, testCodexClientModel("gpt-5.5", 1), testCodexClientModel("test-new-model", 2)) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write(catalog) + })) + defer server.Close() + codexClientModelsURLs = []string{server.URL} + if !tryRefreshCodexClientModels(context.Background(), "test refresh") { + t.Fatal("valid refresh reported failure") + } + after, revision := GetCodexClientModelsSnapshot() + if string(after) != string(catalog) { + t.Fatal("successful refresh did not publish the fetched catalog") + } + if !tryRefreshCodexClientModels(context.Background(), "test unchanged refresh") { + t.Fatal("unchanged catalog should count as a successful refresh") + } + if got := GetCodexClientModelsRevision(); got != revision { + t.Fatalf("unchanged catalog revision = %d, want %d", got, revision) + } +} + func testCodexClientCatalog(t *testing.T, models ...map[string]any) []byte { t.Helper() data, err := json.Marshal(map[string]any{"models": models}) diff --git a/internal/registry/codex_client_models_updater.go b/internal/registry/codex_client_models_updater.go index c556daad0e2..c2588835407 100644 --- a/internal/registry/codex_client_models_updater.go +++ b/internal/registry/codex_client_models_updater.go @@ -5,7 +5,6 @@ import ( "io" "net/http" "sync" - "time" log "github.com/sirupsen/logrus" ) @@ -29,38 +28,27 @@ func StartCodexClientModelsUpdater(ctx context.Context) { } func runCodexClientModelsUpdater(ctx context.Context) { - tryRefreshCodexClientModels(ctx, "startup Codex client model refresh") - - ticker := time.NewTicker(modelsRefreshInterval) - defer ticker.Stop() - log.Infof("periodic Codex client model refresh started (interval=%s)", modelsRefreshInterval) - for { - select { - case <-ctx.Done(): - return - case <-ticker.C: - tryRefreshCodexClientModels(ctx, "periodic Codex client model refresh") - } - } + runModelCatalogUpdater(ctx, "Codex client model refresh", tryRefreshCodexClientModels) } -func tryRefreshCodexClientModels(ctx context.Context, label string) { +func tryRefreshCodexClientModels(ctx context.Context, label string) bool { data, sourceURL := fetchCodexClientModelsFromRemote(ctx) if data == nil { log.Warnf("%s: fetch failed from all URLs, keeping current data", label) - return + return false } changed, err := loadCodexClientModelsFromBytes(data, sourceURL) if err != nil { log.Warnf("%s: fetched catalog rejected, keeping current data: %v", label, err) - return + return false } if !changed { log.Infof("%s completed from %s, no changes detected", label, sourceURL) - return + return true } log.Infof("%s completed from %s, catalog updated", label, sourceURL) + return true } func fetchCodexClientModelsFromRemote(ctx context.Context) ([]byte, string) { diff --git a/internal/registry/devin_models_test.go b/internal/registry/devin_models_test.go index df9a3a98a36..1c89e00e31f 100644 --- a/internal/registry/devin_models_test.go +++ b/internal/registry/devin_models_test.go @@ -160,7 +160,9 @@ func TestDevinModelsRemoteFetchFallback(t *testing.T) { } // Attempt refresh from failing remote - tryRefreshDevinModels(context.Background(), "test failing refresh") + if tryRefreshDevinModels(context.Background(), "test failing refresh") { + t.Fatal("failed refresh reported success") + } afterCount := len(GetDevinModels()) if afterCount != initialCount { @@ -185,7 +187,12 @@ func TestDevinModelsRemoteFetchFallback(t *testing.T) { defer tsValid.Close() devinModelsURLs = []string{tsValid.URL + "/devin_models.json"} - tryRefreshDevinModels(context.Background(), "test succeeding refresh") + if !tryRefreshDevinModels(context.Background(), "test succeeding refresh") { + t.Fatal("valid refresh reported failure") + } + if !tryRefreshDevinModels(context.Background(), "test unchanged refresh") { + t.Fatal("unchanged catalog should count as a successful refresh") + } updatedModels := GetDevinModels() if len(updatedModels) != 1 || updatedModels[0].ID != "devin/custom-test-model" { diff --git a/internal/registry/devin_models_updater.go b/internal/registry/devin_models_updater.go index 80d673cdeaa..f3eca019d41 100644 --- a/internal/registry/devin_models_updater.go +++ b/internal/registry/devin_models_updater.go @@ -5,7 +5,6 @@ import ( "io" "net/http" "sync" - "time" log "github.com/sirupsen/logrus" ) @@ -29,38 +28,27 @@ func StartDevinModelsUpdater(ctx context.Context) { } func runDevinModelsUpdater(ctx context.Context) { - tryRefreshDevinModels(ctx, "startup Devin model refresh") - - ticker := time.NewTicker(modelsRefreshInterval) - defer ticker.Stop() - log.Infof("periodic Devin model refresh started (interval=%s)", modelsRefreshInterval) - for { - select { - case <-ctx.Done(): - return - case <-ticker.C: - tryRefreshDevinModels(ctx, "periodic Devin model refresh") - } - } + runModelCatalogUpdater(ctx, "Devin model refresh", tryRefreshDevinModels) } -func tryRefreshDevinModels(ctx context.Context, label string) { +func tryRefreshDevinModels(ctx context.Context, label string) bool { data, sourceURL := fetchDevinModelsFromRemote(ctx) if data == nil { log.Warnf("%s: fetch failed from all URLs, keeping current data (embedded or cached fallback)", label) - return + return false } changed, err := loadDevinModelsFromBytes(data, sourceURL) if err != nil { log.Warnf("%s: fetched catalog rejected, keeping current data: %v", label, err) - return + return false } if !changed { log.Infof("%s completed from %s, no changes detected", label, sourceURL) - return + return true } log.Infof("%s completed from %s, catalog updated", label, sourceURL) + return true } func fetchDevinModelsFromRemote(ctx context.Context) ([]byte, string) { diff --git a/internal/registry/model_updater.go b/internal/registry/model_updater.go index c740056a952..a31309bf4f8 100644 --- a/internal/registry/model_updater.go +++ b/internal/registry/model_updater.go @@ -18,6 +18,7 @@ import ( const ( modelsFetchTimeout = 30 * time.Second modelsRefreshInterval = 3 * time.Hour + modelsRetryInterval = 30 * time.Second ) var modelsURLs = []string{ @@ -37,6 +38,42 @@ var modelsCatalogStore = &modelStore{} var updaterOnce sync.Once +// The first catalog fetch runs in the background. Service.Run waits for it +// (bounded) so models newer than the embedded catalog are registered before +// the listener opens instead of answering 400 unknown provider. +var ( + startupRefreshStarted = make(chan struct{}) + startupRefreshFinished = make(chan struct{}) + startupRefreshDoneOnce sync.Once +) + +func markStartupModelRefreshFinished() { + startupRefreshDoneOnce.Do(func() { close(startupRefreshFinished) }) +} + +// WaitForStartupModelRefresh blocks until the first model catalog fetch has +// finished (successfully or not), the timeout passes, or ctx ends. It returns +// at once when the updater was never started (local-model or Home mode). +// It reports whether the first fetch finished. +func WaitForStartupModelRefresh(ctx context.Context, timeout time.Duration) bool { + select { + case <-startupRefreshStarted: + default: + return false + } + timer := time.NewTimer(timeout) + defer timer.Stop() + select { + case <-startupRefreshFinished: + return true + case <-timer.C: + log.Warnf("startup model refresh still running after %s; opening the listener with the current catalog", timeout) + return false + case <-ctx.Done(): + return false + } +} + // ModelRefreshCallback is invoked when startup or periodic model refresh detects changes. // changedProviders contains the provider names whose model definitions changed. type ModelRefreshCallback func(changedProviders []string) @@ -77,49 +114,50 @@ func init() { // Safe to call multiple times; only one updater will run. func StartModelsUpdater(ctx context.Context) { updaterOnce.Do(func() { + close(startupRefreshStarted) go runModelsUpdater(ctx) }) } func runModelsUpdater(ctx context.Context) { - tryStartupRefresh(ctx) - periodicRefresh(ctx) + runModelCatalogUpdater(ctx, "model refresh", func(ctx context.Context, label string) bool { + defer markStartupModelRefreshFinished() + return tryRefreshModels(ctx, label) + }) } -func periodicRefresh(ctx context.Context) { - ticker := time.NewTicker(modelsRefreshInterval) - defer ticker.Stop() - log.Infof("periodic model refresh started (interval=%s)", modelsRefreshInterval) - for { +// runModelCatalogUpdater keeps failed refreshes from leaving the fallback catalog +// in use for the full refresh interval, including when networking is not ready at +// startup. A successful fetch, even without changes, restores the normal cadence. +func runModelCatalogUpdater(ctx context.Context, name string, refresh func(context.Context, string) bool) { + label := "startup " + name + for ctx.Err() == nil { + delay := modelsRefreshInterval + if !refresh(ctx, label) { + delay = modelsRetryInterval + } + if ctx.Err() != nil { + return + } + log.WithField("next_refresh_after", delay).Debugf("%s scheduled", name) + timer := time.NewTimer(delay) select { case <-ctx.Done(): + timer.Stop() return - case <-ticker.C: - tryPeriodicRefresh(ctx) + case <-timer.C: } + label = "periodic " + name } } -// tryPeriodicRefresh fetches models from remote, compares with the current -// catalog, and notifies the registered callback if any provider changed. -func tryPeriodicRefresh(ctx context.Context) { - tryRefreshModels(ctx, "periodic model refresh") -} - -// tryStartupRefresh fetches models from remote in the background during -// process startup. It uses the same change detection as periodic refresh so -// existing auth registrations can be updated after the callback is registered. -func tryStartupRefresh(ctx context.Context) { - tryRefreshModels(ctx, "startup model refresh") -} - -func tryRefreshModels(ctx context.Context, label string) { +func tryRefreshModels(ctx context.Context, label string) bool { oldData := getModels() parsed, url := fetchModelsFromRemote(ctx) if parsed == nil { log.Warnf("%s: fetch failed from all URLs, keeping current data", label) - return + return false } if len(parsed.Meta) == 0 && oldData != nil && len(oldData.Meta) > 0 { @@ -136,11 +174,12 @@ func tryRefreshModels(ctx context.Context, label string) { if len(changed) == 0 { log.Infof("%s completed from %s, no changes detected", label, url) - return + return true } log.Infof("%s completed from %s, changes detected for providers: %v", label, url, changed) notifyModelRefresh(changed) + return true } // fetchModelsFromRemote tries all remote URLs and returns the parsed model catalog diff --git a/internal/registry/model_updater_retry_test.go b/internal/registry/model_updater_retry_test.go new file mode 100644 index 00000000000..38b4bb36965 --- /dev/null +++ b/internal/registry/model_updater_retry_test.go @@ -0,0 +1,88 @@ +package registry + +import ( + "context" + "reflect" + "testing" + "testing/synctest" + "time" +) + +func TestModelCatalogUpdaterRetryAndRecovery(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + start := time.Now() + outcomes := []bool{false, false, true, true, false, true} + var attempts []time.Duration + runModelCatalogUpdater(ctx, "test refresh", func(_ context.Context, label string) bool { + index := len(attempts) + wantLabel := "periodic test refresh" + if index == 0 { + wantLabel = "startup test refresh" + } + if label != wantLabel { + t.Errorf("attempt %d label = %q, want %q", index, label, wantLabel) + } + attempts = append(attempts, time.Since(start)) + if len(attempts) == len(outcomes) { + cancel() + } + return outcomes[index] + }) + want := []time.Duration{ + 0, + 30 * time.Second, + time.Minute, + 3*time.Hour + time.Minute, + 6*time.Hour + time.Minute, + 6*time.Hour + 90*time.Second, + } + if !reflect.DeepEqual(attempts, want) { + t.Fatalf("refresh times = %v, want %v", attempts, want) + } + }) +} + +func TestModelCatalogUpdaterCancellation(t *testing.T) { + for _, success := range []bool{false, true} { + name := "retry wait" + if success { + name = "periodic wait" + } + t.Run(name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + attempts := 0 + done := make(chan struct{}) + start := time.Now() + go func() { + defer close(done) + runModelCatalogUpdater(ctx, "test refresh", func(context.Context, string) bool { + attempts++ + return success + }) + }() + synctest.Wait() + cancel() + <-done + if attempts != 1 { + t.Fatalf("refresh attempts = %d, want 1", attempts) + } + if elapsed := time.Since(start); elapsed != 0 { + t.Fatalf("cancellation waited %s for timer, want immediate return", elapsed) + } + }) + }) + } +} + +func TestModelCatalogUpdaterAlreadyCanceled(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + runModelCatalogUpdater(ctx, "test refresh", func(context.Context, string) bool { + t.Fatal("refresh called after cancellation") + return false + }) +} diff --git a/internal/registry/model_updater_startup_wait_test.go b/internal/registry/model_updater_startup_wait_test.go new file mode 100644 index 00000000000..88c510202f1 --- /dev/null +++ b/internal/registry/model_updater_startup_wait_test.go @@ -0,0 +1,64 @@ +package registry + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" +) + +// The only test in the package that starts the real updater: its start and +// finish signals are process-wide and close once. +func TestWaitForStartupModelRefresh(t *testing.T) { + t.Run("returns at once when the updater was never started", func(t *testing.T) { + start := time.Now() + if WaitForStartupModelRefresh(context.Background(), 5*time.Second) { + t.Fatal("reported a finished fetch although the updater never started") + } + if elapsed := time.Since(start); elapsed > time.Second { + t.Fatalf("waited %s for an updater that was never started", elapsed) + } + }) + + t.Run("returns once the first fetch has published the remote catalog", func(t *testing.T) { + var catalog map[string][]map[string]any + if err := json.Unmarshal(embeddedModelsJSON, &catalog); err != nil { + t.Fatalf("decode embedded catalog: %v", err) + } + catalog["claude"] = append(catalog["claude"], map[string]any{"id": "claude-startup-wait-test", "object": "model"}) + body, err := json.Marshal(catalog) + if err != nil { + t.Fatalf("encode catalog: %v", err) + } + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + time.Sleep(200 * time.Millisecond) + _, _ = w.Write(body) + })) + defer server.Close() + + previousURLs, previousData := modelsURLs, getModels() + modelsURLs = []string{server.URL} + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(func() { + cancel() + modelsURLs = previousURLs + modelsCatalogStore.mu.Lock() + modelsCatalogStore.data = previousData + modelsCatalogStore.mu.Unlock() + }) + + StartModelsUpdater(ctx) + if !WaitForStartupModelRefresh(context.Background(), 5*time.Second) { + t.Fatal("first fetch did not finish within 5s") + } + found := false + for _, model := range getModels().Claude { + found = found || model.ID == "claude-startup-wait-test" + } + if !found { + t.Fatal("wait returned before the fetched catalog was published") + } + }) +} diff --git a/internal/registry/model_updater_test.go b/internal/registry/model_updater_test.go new file mode 100644 index 00000000000..46282c1db3a --- /dev/null +++ b/internal/registry/model_updater_test.go @@ -0,0 +1,90 @@ +package registry + +import ( + "context" + "net/http" + "net/http/httptest" + "reflect" + "testing" +) + +func TestRefreshModelsRetainsCatalogAndNotifiesRecovery(t *testing.T) { + previousURLs := modelsURLs + previousData := getModels() + refreshCallbackMu.Lock() + previousCallback := refreshCallback + previousPending := pendingRefreshChanges + refreshCallback = nil + pendingRefreshChanges = nil + refreshCallbackMu.Unlock() + t.Cleanup(func() { + modelsURLs = previousURLs + modelsCatalogStore.mu.Lock() + modelsCatalogStore.data = previousData + modelsCatalogStore.mu.Unlock() + refreshCallbackMu.Lock() + refreshCallback = previousCallback + pendingRefreshChanges = previousPending + refreshCallbackMu.Unlock() + }) + if err := loadModelsFromBytes([]byte(`{"codex-team":[{"id":"existing-model"}]}`), "test"); err != nil { + t.Fatalf("load initial catalog: %v", err) + } + initialData := getModels() + var notifications [][]string + SetModelRefreshCallback(func(providers []string) { + notifications = append(notifications, providers) + }) + status := http.StatusServiceUnavailable + body := "unavailable" + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(status) + _, _ = w.Write([]byte(body)) + })) + defer server.Close() + modelsURLs = []string{server.URL} + + for _, tc := range []struct { + name string + status int + body string + }{ + {"unavailable", http.StatusServiceUnavailable, "unavailable"}, + {"invalid catalog", http.StatusOK, `{"codex-team":[{}]}`}, + } { + t.Run(tc.name, func(t *testing.T) { + status, body = tc.status, tc.body + if tryRefreshModels(context.Background(), "test refresh") { + t.Fatal("failed refresh reported success") + } + if getModels() != initialData || len(notifications) != 0 { + t.Fatal("failed refresh changed the catalog or notified consumers") + } + }) + } + + status = http.StatusOK + body = `{"codex-team":[{"id":"existing-model"},{"id":"new-model"}]}` + if !tryRefreshModels(context.Background(), "test recovery") { + t.Fatal("valid refresh reported failure") + } + models := GetCodexTeamModels() + found := false + for _, model := range models { + if model.ID == "new-model" { + found = true + } + } + if !found { + t.Fatal("recovered catalog does not expose the new model") + } + if !reflect.DeepEqual(notifications, [][]string{{"codex"}}) { + t.Fatalf("notifications = %v, want [[codex]]", notifications) + } + if !tryRefreshModels(context.Background(), "test unchanged refresh") { + t.Fatal("unchanged catalog should count as a successful refresh") + } + if len(notifications) != 1 { + t.Fatalf("unchanged catalog notified consumers again: %v", notifications) + } +} diff --git a/sdk/cliproxy/service_lifecycle.go b/sdk/cliproxy/service_lifecycle.go index 9195a30baf6..cce387dc4ea 100644 --- a/sdk/cliproxy/service_lifecycle.go +++ b/sdk/cliproxy/service_lifecycle.go @@ -20,6 +20,11 @@ import ( log "github.com/sirupsen/logrus" ) +// startupModelRefreshWait caps how long a start waits for the first catalog +// fetch. A fetch normally takes under a second; a black-holed network would +// otherwise hold the port closed for the full 2 x 30 s fetch timeouts. +const startupModelRefreshWait = 10 * time.Second + // Run starts the service and blocks until the context is cancelled or the server stops. // It initializes all components including authentication, file watching, HTTP server, // and starts processing requests. The method blocks until the context is cancelled. @@ -125,9 +130,12 @@ func (s *Service) Run(ctx context.Context) error { // handlers no longer depend on legacy clients; pass nil slice initially s.server = api.NewServer(s.cfg, s.coreManager, s.accessManager, s.configPath, s.serverOptions...) s.syncPluginRuntimeConfig(ctx) - if homeEnabled { - s.syncPluginModelRuntime(ctx) - } + // Register models for the auths loaded above before the listener + // opens; otherwise requests that arrive before the watcher's first load + // fail with model_not_found. Wait for the first catalog fetch first, so + // the registration includes models newer than the embedded catalog. + registry.WaitForStartupModelRefresh(ctx, startupModelRefreshWait) + s.syncPluginModelRuntime(ctx) if s.authManager == nil { s.authManager = newDefaultAuthManager() diff --git a/sdk/cliproxy/service_startup_models_test.go b/sdk/cliproxy/service_startup_models_test.go new file mode 100644 index 00000000000..358ddc91410 --- /dev/null +++ b/sdk/cliproxy/service_startup_models_test.go @@ -0,0 +1,63 @@ +package cliproxy + +import ( + "context" + "os" + "path/filepath" + "testing" + "time" + + "github.com/router-for-me/CLIProxyAPI/v7/internal/config" +) + +// Models for auths loaded from the auth directory must be registered before +// the HTTP listener opens, not only after the file watcher's first load. +func TestServiceRun_RegistersLoadedAuthModelsBeforeListening(t *testing.T) { + authDir := t.TempDir() + authJSON := []byte(`{"type":"codex","email":"startup@example.com","access_token":"test-access","expired":"2999-01-01T00:00:00Z"}`) + if errWrite := os.WriteFile(filepath.Join(authDir, "codex-startup.json"), authJSON, 0o600); errWrite != nil { + t.Fatalf("failed to write auth file: %v", errWrite) + } + t.Cleanup(func() { GlobalModelRegistry().UnregisterClient("codex-startup.json") }) + + cfgPath := filepath.Join(t.TempDir(), "config.yaml") + if errWrite := os.WriteFile(cfgPath, []byte("{}"), 0o644); errWrite != nil { + t.Fatalf("failed to write config: %v", errWrite) + } + cfg := &config.Config{Host: "127.0.0.1", Port: 0, AuthDir: authDir} + + modelsAtStart := make(chan int, 1) + service, errBuild := NewBuilder(). + WithConfig(cfg). + WithConfigPath(cfgPath). + WithHooks(Hooks{OnBeforeStart: func(*config.Config) { + modelsAtStart <- len(GlobalModelRegistry().GetModelsForClient("codex-startup.json")) + }}). + Build() + if errBuild != nil { + t.Fatalf("failed to build service: %v", errBuild) + } + + ctx, cancel := context.WithCancel(context.Background()) + runDone := make(chan error, 1) + go func() { runDone <- service.Run(ctx) }() + + select { + case n := <-modelsAtStart: + if n == 0 { + t.Fatal("no models registered for the loaded auth before the listener started") + } + case errRun := <-runDone: + cancel() + t.Fatalf("service.Run returned before start: %v", errRun) + case <-time.After(10 * time.Second): + cancel() + t.Fatal("timed out waiting for OnBeforeStart") + } + cancel() + select { + case <-runDone: + case <-time.After(10 * time.Second): + t.Fatal("service.Run did not stop") + } +}