Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-5549: fix(agent): stop reporting a failed model discovery as a real catalog (#6196)

Bohan Jiang44ce16d9b8d5
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 92f2a3e4ff..f3762491e6 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -2922,7 +2922,7 @@ func (d *Daemon) handleModelList(ctx context.Context, rt Runtime, requestID stri
// Self-heal a pinned executable path an in-place upgrade deleted (MUL-4486).
entry, _ = d.resolveAgentEntry(ctx, rt.Provider, entry)
- models, err := agent.ListModels(ctx, rt.Provider, entry.Path)
+ catalog, err := agent.ListModels(ctx, rt.Provider, entry.Path)
if err != nil {
d.reportModelListResult(ctx, rt, requestID, map[string]any{
"status": "failed",
@@ -2930,6 +2930,11 @@ func (d *Daemon) handleModelList(ctx context.Context, rt Runtime, requestID stri
})
return
}
+ models := catalog.Models
+ if catalog.Fallback {
+ d.logger.Warn("model discovery fell back to a static catalog; reporting it as non-authoritative",
+ "runtime_id", rt.ID, "provider", rt.Provider, "path", entry.Path, "count", len(models))
+ }
// Wire format matches handler.ModelEntry. Use a struct (not
// map[string]string) so the Default bool and the per-model
@@ -2993,6 +2998,10 @@ func (d *Daemon) handleModelList(ctx context.Context, rt Runtime, requestID stri
"status": "completed",
"models": wire,
"supported": agent.ModelSelectionSupported(rt.Provider),
+ // Additive field: the models are still worth rendering, but the server
+ // must not persist them as this runtime's real catalog (MUL-5549).
+ // Older servers ignore it and keep the previous behaviour.
+ "fallback": catalog.Fallback,
})
}
diff --git a/server/internal/handler/runtime_model_catalog.go b/server/internal/handler/runtime_model_catalog.go
index 7962df05a9..586fc179e5 100644
--- a/server/internal/handler/runtime_model_catalog.go
+++ b/server/internal/handler/runtime_model_catalog.go
@@ -92,8 +92,49 @@ type ModelCatalogCache interface {
// remembering. `supported=false` runtimes have no picker at all, and an empty
// catalog is treated as a transient failure rather than an authoritative
// "this runtime has no models".
-func cacheableModelCatalog(models []ModelEntry, supported bool) bool {
- return supported && len(models) > 0
+//
+// `fallback` closes the hole those two checks left open. Several providers
+// answer a failed discovery with a non-empty static stand-in, which sails past
+// the emptiness check and gets stored as last-known-good — so one transient
+// failure pins a catalog the runtime never advertised for the full 24h serve
+// window. For codebuddy the stand-in does not share a single ID with the real
+// catalog, making every pick an ID the CLI rejects (MUL-5549).
+func cacheableModelCatalog(models []ModelEntry, supported, fallback bool) bool {
+ return supported && !fallback && len(models) > 0
+}
+
+// modelCatalogCacheAction is what a completed discovery report should do to the
+// runtime's cached catalog.
+type modelCatalogCacheAction int
+
+const (
+ // modelCatalogCacheStore writes the report as the new last-known-good.
+ modelCatalogCacheStore modelCatalogCacheAction = iota
+ // modelCatalogCacheDrop discards any snapshot: the report is authoritative
+ // and says this runtime no longer advertises the catalog we held.
+ modelCatalogCacheDrop
+ // modelCatalogCacheKeep leaves the cache untouched: the report is not
+ // authoritative, so it is neither worth storing nor grounds to discard a
+ // real catalog we already have.
+ modelCatalogCacheKeep
+)
+
+// modelCatalogCacheDecision maps a completed report onto its cache action.
+//
+// The fallback case is the MUL-5549 fix and is deliberately Keep, not Drop: a
+// static stand-in tells us nothing about what the runtime supports, so letting
+// it evict a real catalog would turn one transient discovery failure into a
+// downgrade. That matches how a `failed` report is already handled — serving
+// the last known good list through a transient failure is the point of the
+// cache.
+func modelCatalogCacheDecision(models []ModelEntry, supported, fallback bool) modelCatalogCacheAction {
+ if fallback {
+ return modelCatalogCacheKeep
+ }
+ if cacheableModelCatalog(models, supported, fallback) {
+ return modelCatalogCacheStore
+ }
+ return modelCatalogCacheDrop
}
// cloneModelEntries deep-copies a catalog so the in-memory backend hands out
@@ -161,7 +202,9 @@ func (c *InMemoryModelCatalogCache) Get(_ context.Context, runtimeID string) (*M
}
func (c *InMemoryModelCatalogCache) Put(_ context.Context, runtimeID string, models []ModelEntry, supported bool) error {
- if runtimeID == "" || !cacheableModelCatalog(models, supported) {
+ // fallback=false: ReportModelListResult refuses to Put a fallback catalog
+ // at all, so anything reaching a cache backend is a real discovery result.
+ if runtimeID == "" || !cacheableModelCatalog(models, supported, false) {
return nil
}
c.mu.Lock()
diff --git a/server/internal/handler/runtime_model_catalog_fallback_test.go b/server/internal/handler/runtime_model_catalog_fallback_test.go
new file mode 100644
index 0000000000..90e5f38a2b
--- /dev/null
+++ b/server/internal/handler/runtime_model_catalog_fallback_test.go
@@ -0,0 +1,250 @@
+package handler
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/go-chi/chi/v5"
+)
+
+// reportModelList drives the real ReportModelListResult endpoint as a daemon
+// would, including chi URL params and daemon auth, and returns the response
+// recorder. Going through the handler (rather than decoding into a struct the
+// test declares itself) is what makes these tests catch a wrong JSON tag or a
+// mis-wired cache branch in production code.
+func reportModelList(t *testing.T, requestID string, body map[string]any) *httptest.ResponseRecorder {
+ t.Helper()
+ req := newDaemonTokenRequest(
+ http.MethodPost,
+ "/api/daemon/runtimes/"+testRuntimeID+"/models/"+requestID+"/result",
+ body, testWorkspaceID, "daemon-mul5549",
+ )
+ rctx := chi.NewRouteContext()
+ rctx.URLParams.Add("runtimeId", testRuntimeID)
+ rctx.URLParams.Add("requestId", requestID)
+ req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
+
+ w := httptest.NewRecorder()
+ testHandler.ReportModelListResult(w, req)
+ return w
+}
+
+// withModelListStores swaps in fresh model-list stores for one test and
+// restores the originals afterwards, so cases cannot leak state into each other
+// or into the rest of the suite.
+func withModelListStores(t *testing.T) ModelCatalogCache {
+ t.Helper()
+ origStore, origCache := testHandler.ModelListStore, testHandler.ModelCatalogCache
+ cache := NewInMemoryModelCatalogCache()
+ testHandler.ModelListStore = NewInMemoryModelListStore()
+ testHandler.ModelCatalogCache = cache
+ t.Cleanup(func() {
+ testHandler.ModelListStore, testHandler.ModelCatalogCache = origStore, origCache
+ })
+ return cache
+}
+
+// TestReportModelListResult_FallbackDoesNotPoisonCache is the MUL-5549
+// regression, driven end to end through the handler.
+//
+// A runtime discovers its real catalog, then hits a transient discovery failure
+// and the daemon reports the static stand-in. Before the fix that stand-in was
+// indistinguishable from a real catalog: non-empty and `supported`, so it was
+// stored as last-known-good and served for the full 24h window — pinning one
+// blip as the answer for a day. It must now leave the cached catalog untouched.
+func TestReportModelListResult_FallbackDoesNotPoisonCache(t *testing.T) {
+ ctx := context.Background()
+ cache := withModelListStores(t)
+
+ // 1. A real discovery lands and is cached.
+ real, err := testHandler.ModelListStore.Create(ctx, testRuntimeID)
+ if err != nil {
+ t.Fatalf("create: %v", err)
+ }
+ if w := reportModelList(t, real.ID, map[string]any{
+ "status": "completed",
+ "supported": true,
+ "models": []map[string]any{
+ {"id": "hy3", "label": "Hy3", "default": true},
+ {"id": "glm-5.2", "label": "GLM 5.2"},
+ },
+ }); w.Code != http.StatusOK {
+ t.Fatalf("report real catalog: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ snapshot, err := cache.Get(ctx, testRuntimeID)
+ if err != nil || snapshot == nil {
+ t.Fatalf("expected the real catalog to be cached: snapshot=%v err=%v", snapshot, err)
+ }
+ if len(snapshot.Models) != 2 || snapshot.Models[0].ID != "hy3" {
+ t.Fatalf("unexpected cached catalog: %+v", snapshot.Models)
+ }
+
+ // 2. Discovery fails; the daemon reports the static stand-in.
+ fallback, err := testHandler.ModelListStore.Create(ctx, testRuntimeID)
+ if err != nil {
+ t.Fatalf("create: %v", err)
+ }
+ if w := reportModelList(t, fallback.ID, map[string]any{
+ "status": "completed",
+ "supported": true,
+ "fallback": true,
+ "models": []map[string]any{
+ {"id": "claude-sonnet-4.6", "label": "Claude Sonnet 4.6", "default": true},
+ {"id": "gpt-5.5", "label": "GPT 5.5"},
+ },
+ }); w.Code != http.StatusOK {
+ t.Fatalf("report fallback: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ // The stand-in is still returned to whoever asked for THIS request...
+ stored, err := testHandler.ModelListStore.Get(ctx, fallback.ID)
+ if err != nil || stored == nil {
+ t.Fatalf("expected the fallback report to be stored: %v %v", stored, err)
+ }
+ if len(stored.Models) != 2 {
+ t.Errorf("the fallback list must still reach the picker, got %+v", stored.Models)
+ }
+
+ // ...but it must not have replaced or evicted the real catalog.
+ snapshot, err = cache.Get(ctx, testRuntimeID)
+ if err != nil {
+ t.Fatalf("get: %v", err)
+ }
+ if snapshot == nil {
+ t.Fatal("a fallback report must not evict the last known good catalog")
+ }
+ if len(snapshot.Models) != 2 || snapshot.Models[0].ID != "hy3" {
+ t.Errorf("cached catalog was overwritten by the stand-in: %+v", snapshot.Models)
+ }
+}
+
+// TestReportModelListResult_OmittedFallbackKeepsOldDaemonBehaviour pins
+// backward compatibility: a daemon that predates the `fallback` field omits it,
+// which must decode to false so its reports still warm the cache exactly as
+// they did before. Reported through the real handler so a renamed JSON tag
+// would surface here.
+func TestReportModelListResult_OmittedFallbackKeepsOldDaemonBehaviour(t *testing.T) {
+ ctx := context.Background()
+ cache := withModelListStores(t)
+
+ req, err := testHandler.ModelListStore.Create(ctx, testRuntimeID)
+ if err != nil {
+ t.Fatalf("create: %v", err)
+ }
+ if w := reportModelList(t, req.ID, map[string]any{
+ "status": "completed",
+ "supported": true,
+ "models": []map[string]any{{"id": "kimi-k3-1", "label": "Kimi K3 1"}},
+ }); w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ snapshot, err := cache.Get(ctx, testRuntimeID)
+ if err != nil {
+ t.Fatalf("get: %v", err)
+ }
+ if snapshot == nil || len(snapshot.Models) != 1 || snapshot.Models[0].ID != "kimi-k3-1" {
+ t.Fatalf("an older daemon's report must still be cached: %+v", snapshot)
+ }
+}
+
+// TestReportModelListResult_EmptyCatalogStillDropsSnapshot guards the case the
+// fallback flag must NOT swallow: an authoritative empty result really does say
+// the runtime no longer advertises what we cached, so the snapshot goes.
+func TestReportModelListResult_EmptyCatalogStillDropsSnapshot(t *testing.T) {
+ ctx := context.Background()
+ cache := withModelListStores(t)
+
+ seeded, err := testHandler.ModelListStore.Create(ctx, testRuntimeID)
+ if err != nil {
+ t.Fatalf("create: %v", err)
+ }
+ if w := reportModelList(t, seeded.ID, map[string]any{
+ "status": "completed",
+ "supported": true,
+ "models": []map[string]any{{"id": "hy3", "label": "Hy3"}},
+ }); w.Code != http.StatusOK {
+ t.Fatalf("seed: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ empty, err := testHandler.ModelListStore.Create(ctx, testRuntimeID)
+ if err != nil {
+ t.Fatalf("create: %v", err)
+ }
+ if w := reportModelList(t, empty.ID, map[string]any{
+ "status": "completed",
+ "supported": true,
+ "models": []map[string]any{},
+ }); w.Code != http.StatusOK {
+ t.Fatalf("empty report: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ snapshot, err := cache.Get(ctx, testRuntimeID)
+ if err != nil {
+ t.Fatalf("get: %v", err)
+ }
+ if snapshot != nil {
+ t.Errorf("an authoritative empty catalog must drop the snapshot, still have %+v", snapshot.Models)
+ }
+}
+
+// TestModelCatalogCacheDecision pins the three-way branch ReportModelListResult
+// takes on a completed report.
+//
+// The fallback row is the MUL-5549 regression. A static stand-in is non-empty
+// and `supported`, so it used to be indistinguishable from a real catalog and
+// got stored as last-known-good for the full 24h serve window. It must now be
+// Keep: not stored, but also not allowed to evict a real catalog we already
+// hold — a stand-in is no evidence about what the runtime supports.
+func TestModelCatalogCacheDecision(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ models []ModelEntry
+ supported bool
+ fallback bool
+ want modelCatalogCacheAction
+ }{
+ {
+ name: "real non-empty catalog is stored",
+ models: sampleCatalog(),
+ supported: true,
+ want: modelCatalogCacheStore,
+ },
+ {
+ name: "fallback catalog leaves the cache alone",
+ models: sampleCatalog(),
+ supported: true,
+ fallback: true,
+ want: modelCatalogCacheKeep,
+ },
+ {
+ name: "authoritatively empty catalog drops the snapshot",
+ models: nil,
+ supported: true,
+ want: modelCatalogCacheDrop,
+ },
+ {
+ name: "runtime that ignores model selection drops the snapshot",
+ models: sampleCatalog(),
+ supported: false,
+ want: modelCatalogCacheDrop,
+ },
+ {
+ name: "an empty fallback still only keeps",
+ models: nil,
+ supported: true,
+ fallback: true,
+ want: modelCatalogCacheKeep,
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ got := modelCatalogCacheDecision(tc.models, tc.supported, tc.fallback)
+ if got != tc.want {
+ t.Errorf("modelCatalogCacheDecision = %v, want %v", got, tc.want)
+ }
+ })
+ }
+}
diff --git a/server/internal/handler/runtime_model_catalog_redis_cache.go b/server/internal/handler/runtime_model_catalog_redis_cache.go
index 70ab5a5e4e..eab81fe546 100644
--- a/server/internal/handler/runtime_model_catalog_redis_cache.go
+++ b/server/internal/handler/runtime_model_catalog_redis_cache.go
@@ -65,7 +65,9 @@ func (c *RedisModelCatalogCache) Get(ctx context.Context, runtimeID string) (*Mo
}
func (c *RedisModelCatalogCache) Put(ctx context.Context, runtimeID string, models []ModelEntry, supported bool) error {
- if runtimeID == "" || !cacheableModelCatalog(models, supported) {
+ // fallback=false: ReportModelListResult refuses to Put a fallback catalog
+ // at all, so anything reaching a cache backend is a real discovery result.
+ if runtimeID == "" || !cacheableModelCatalog(models, supported, false) {
return nil
}
snapshot := ModelCatalogSnapshot{
diff --git a/server/internal/handler/runtime_model_catalog_test.go b/server/internal/handler/runtime_model_catalog_test.go
index ea99b0e057..6c3c87f881 100644
--- a/server/internal/handler/runtime_model_catalog_test.go
+++ b/server/internal/handler/runtime_model_catalog_test.go
@@ -381,18 +381,24 @@ func TestRequestDaemonPendingWork_PrefersNotifier(t *testing.T) {
// between warming the cache and dropping a snapshot the runtime no longer
// advertises.
func TestCacheableModelCatalog(t *testing.T) {
- if !cacheableModelCatalog(sampleCatalog(), true) {
+ if !cacheableModelCatalog(sampleCatalog(), true, false) {
t.Error("a supported, non-empty catalog must be cacheable")
}
- if cacheableModelCatalog(sampleCatalog(), false) {
+ if cacheableModelCatalog(sampleCatalog(), false, false) {
t.Error("a runtime that ignores model selection must not be cached")
}
- if cacheableModelCatalog(nil, true) {
+ if cacheableModelCatalog(nil, true, false) {
t.Error("an empty catalog is a transient failure, not a cacheable answer")
}
- if cacheableModelCatalog([]ModelEntry{}, true) {
+ if cacheableModelCatalog([]ModelEntry{}, true, false) {
t.Error("an empty (non-nil) catalog is not cacheable either")
}
+ // The MUL-5549 hole: a fallback catalog is non-empty and `supported`, so
+ // both checks above pass it. Only the fallback flag keeps a static
+ // stand-in out of the 24h serve window.
+ if cacheableModelCatalog(sampleCatalog(), true, true) {
+ t.Error("a fallback catalog must never be cached as the runtime's real catalog")
+ }
}
// TestCachedModelListResponse_WireShape pins what a cache hit looks like on the
diff --git a/server/internal/handler/runtime_models.go b/server/internal/handler/runtime_models.go
index 95a4b7ce18..88a7e2c534 100644
--- a/server/internal/handler/runtime_models.go
+++ b/server/internal/handler/runtime_models.go
@@ -376,7 +376,9 @@ func (h *Handler) cachedModelCatalog(ctx context.Context, runtimeID string) *Mod
slog.Warn("model catalog cache read failed", "error", err, "runtime_id", runtimeID)
return nil
}
- if snapshot == nil || !cacheableModelCatalog(snapshot.Models, snapshot.Supported) {
+ // fallback=false: a stored snapshot is by construction a real discovery
+ // result — fallback catalogs never enter the cache.
+ if snapshot == nil || !cacheableModelCatalog(snapshot.Models, snapshot.Supported, false) {
return nil
}
return snapshot
@@ -477,6 +479,11 @@ func (h *Handler) ReportModelListResult(w http.ResponseWriter, r *http.Request)
Models []ModelEntry `json:"models"`
Supported *bool `json:"supported"`
Error string `json:"error"`
+ // Fallback marks a completed report whose models are a static
+ // stand-in the provider substituted after discovery failed, not the
+ // runtime's real catalog. Older daemons omit it; absent means "this
+ // daemon cannot tell us", which stays the pre-MUL-5549 behaviour.
+ Fallback bool `json:"fallback"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
@@ -509,13 +516,24 @@ func (h *Handler) ReportModelListResult(w http.ResponseWriter, r *http.Request)
// serving a catalog the runtime no longer advertises. Failed reports
// deliberately leave the cache alone — serving the last known good list
// through a transient discovery failure is the point of the cache.
+ //
+ // A fallback report is a failed report wearing a completed label: the
+ // models are a static stand-in, so they are neither fresh truth to
+ // store nor grounds to discard a real catalog we already hold. Treat it
+ // like a failure and leave the cache untouched (MUL-5549).
if h.ModelCatalogCache != nil {
- if cacheableModelCatalog(body.Models, supported) {
+ switch modelCatalogCacheDecision(body.Models, supported, body.Fallback) {
+ case modelCatalogCacheStore:
if err := h.ModelCatalogCache.Put(r.Context(), runtimeID, body.Models, supported); err != nil {
slog.Warn("model catalog cache write failed", "error", err, "runtime_id", runtimeID)
}
- } else if err := h.ModelCatalogCache.Invalidate(r.Context(), runtimeID); err != nil {
- slog.Warn("model catalog cache invalidate failed", "error", err, "runtime_id", runtimeID)
+ case modelCatalogCacheDrop:
+ if err := h.ModelCatalogCache.Invalidate(r.Context(), runtimeID); err != nil {
+ slog.Warn("model catalog cache invalidate failed", "error", err, "runtime_id", runtimeID)
+ }
+ case modelCatalogCacheKeep:
+ slog.Debug("model discovery reported a fallback catalog; leaving cached catalog untouched",
+ "runtime_id", runtimeID, "count", len(body.Models))
}
}
} else {
diff --git a/server/pkg/agent/antigravity.go b/server/pkg/agent/antigravity.go
index af842309f1..1fc529fd87 100644
--- a/server/pkg/agent/antigravity.go
+++ b/server/pkg/agent/antigravity.go
@@ -62,7 +62,7 @@ func (b *antigravityBackend) Execute(ctx context.Context, prompt string, opts Ex
// hiccup (see antigravityModelError).
if opts.Model != "" {
catalog, _ := ListModels(ctx, "antigravity", execPath)
- if err := antigravityModelError(opts.Model, catalog); err != nil {
+ if err := antigravityModelError(opts.Model, catalog.Models); err != nil {
return nil, err
}
}
diff --git a/server/pkg/agent/codebuddy_discovery_fallback_test.go b/server/pkg/agent/codebuddy_discovery_fallback_test.go
new file mode 100644
index 0000000000..0eeadedbcb
--- /dev/null
+++ b/server/pkg/agent/codebuddy_discovery_fallback_test.go
@@ -0,0 +1,250 @@
+//go:build !windows
+
+package agent
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "testing"
+)
+
+// writeCodebuddyStub writes an executable stub at <dir>/codebuddy whose
+// `--help` behaviour is supplied by body. Tests use a stub rather than the
+// real CLI so the default suite never executes a user-installed agent binary.
+func writeCodebuddyStub(t *testing.T, body string) string {
+ t.Helper()
+ path := filepath.Join(t.TempDir(), "codebuddy")
+ if err := os.WriteFile(path, []byte(body), 0o755); err != nil {
+ t.Fatalf("write codebuddy stub: %v", err)
+ }
+ return path
+}
+
+// resetCodebuddyHelpCache drops any memoised --help output for path so each
+// case actually re-runs the stub. codebuddyHelpStore is a package global.
+func resetCodebuddyHelpCache(t *testing.T, path string) {
+ t.Helper()
+ drop := func() {
+ codebuddyHelpMu.Lock()
+ delete(codebuddyHelpStore, path)
+ codebuddyHelpMu.Unlock()
+ }
+ drop()
+ t.Cleanup(drop)
+}
+
+// TestCodebuddyHelpOutputRejectsFailedExec is the MUL-5549 regression: a
+// `#!/usr/bin/env node` codebuddy whose interpreter is not on a GUI-launched
+// daemon's PATH exits 127 and prints `env: node: No such file or directory` on
+// stderr. codebuddyHelpOutput used to discard the exit status and hand that
+// stderr back as if it were help text, so every parser downstream silently
+// fell back — and the failure was then memoised for codebuddyHelpTTL.
+func TestCodebuddyHelpOutputRejectsFailedExec(t *testing.T) {
+ path := writeCodebuddyStub(t, "#!/bin/sh\necho 'env: node: No such file or directory' >&2\nexit 127\n")
+ resetCodebuddyHelpCache(t, path)
+
+ if got := codebuddyHelpOutput(context.Background(), path); got != "" {
+ t.Fatalf("a non-zero exit must yield no help text, got %q", got)
+ }
+
+ codebuddyHelpMu.Lock()
+ _, cached := codebuddyHelpStore[path]
+ codebuddyHelpMu.Unlock()
+ if cached {
+ t.Error("a failed --help must not be cached; it would pin the failure for codebuddyHelpTTL")
+ }
+}
+
+// TestDiscoverCodebuddyModelsMarksFallback pins that every degraded path is
+// reported as Fallback. Before MUL-5549 all three returned (staticModels, nil),
+// which the daemon reported as a successful discovery and the server then
+// cached as this runtime's real catalog for 24h.
+func TestDiscoverCodebuddyModelsMarksFallback(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ path string
+ }{
+ {"binary missing", missingAgentExecutable(t, "codebuddy")},
+ {"help exec fails", writeCodebuddyStub(t, "#!/bin/sh\necho 'env: node: No such file or directory' >&2\nexit 127\n")},
+ {"help has no model line", writeCodebuddyStub(t, "#!/bin/sh\necho 'Usage: codebuddy [options]'\n")},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ resetCodebuddyHelpCache(t, tc.path)
+
+ catalog, err := discoverCodebuddyModels(context.Background(), tc.path)
+ if err != nil {
+ t.Fatalf("discoverCodebuddyModels: %v", err)
+ }
+ if !catalog.Fallback {
+ t.Error("a degraded discovery must be marked Fallback")
+ }
+ // The models are still returned — the picker stays populated.
+ if len(catalog.Models) == 0 {
+ t.Error("expected the static stand-in to still be offered to the UI")
+ }
+ })
+ }
+}
+
+// TestDiscoverCodebuddyModelsRealHelpIsNotFallback is the other half: a stub
+// emitting the real v2.130.0 `--model` line must parse and must NOT be marked
+// Fallback, so a genuine catalog still reaches the cache.
+func TestDiscoverCodebuddyModelsRealHelpIsNotFallback(t *testing.T) {
+ const helpLine = ` --model <model> Model for the current session. Please provide the model ID. ` +
+ `Currently supported: (hy3, glm-5.2, minimax-m3, kimi-k3-1, deepseek-v4-pro)`
+ path := writeCodebuddyStub(t, "#!/bin/sh\ncat <<'EOF'\nUsage: codebuddy [options]\n"+helpLine+"\nEOF\n")
+ resetCodebuddyHelpCache(t, path)
+
+ catalog, err := discoverCodebuddyModels(context.Background(), path)
+ if err != nil {
+ t.Fatalf("discoverCodebuddyModels: %v", err)
+ }
+ if catalog.Fallback {
+ t.Error("a parsed catalog must not be marked Fallback")
+ }
+ if len(catalog.Models) != 5 || catalog.Models[0].ID != "hy3" {
+ t.Fatalf("unexpected catalog: %+v", catalog.Models)
+ }
+ // The static stand-in shares no IDs with the real catalog, which is what
+ // made the silent fallback user-visible in the first place.
+ for _, m := range catalog.Models {
+ for _, static := range codebuddyStaticModels() {
+ if m.ID == static.ID {
+ t.Fatalf("real and fallback catalogs must stay distinguishable, both have %q", m.ID)
+ }
+ }
+ }
+}
+
+// countingCodebuddyStub writes a codebuddy stub that appends a line to a
+// counter file on every `--help` invocation, so a test can assert how many
+// times the (slow, 35s-capped) command actually ran. helpBody is emitted on
+// stdout for --help; --version always succeeds so runtime registration and the
+// thinking-cache key lookup behave normally.
+func countingCodebuddyStub(t *testing.T, helpBody string, helpExit int) (path, counter string) {
+ t.Helper()
+ dir := t.TempDir()
+ counter = filepath.Join(dir, "help-calls")
+ path = filepath.Join(dir, "codebuddy")
+ script := "#!/bin/sh\n" +
+ "case \"$1\" in\n" +
+ " --version) echo '2.130.0'; exit 0 ;;\n" +
+ " --help) echo call >> " + counter + "\n" +
+ " cat <<'HELPEOF'\n" + helpBody + "\nHELPEOF\n" +
+ " exit " + itoa(helpExit) + " ;;\n" +
+ "esac\n" +
+ "exit 0\n"
+ if err := os.WriteFile(path, []byte(script), 0o755); err != nil {
+ t.Fatalf("write counting stub: %v", err)
+ }
+ return path, counter
+}
+
+func itoa(n int) string { return strconv.Itoa(n) }
+
+func helpCallCount(t *testing.T, counter string) int {
+ t.Helper()
+ b, err := os.ReadFile(counter)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return 0
+ }
+ t.Fatalf("read counter: %v", err)
+ }
+ return len(strings.Fields(string(b)))
+}
+
+// TestListModelsCodebuddyRunsHelpAtMostOnce is the MUL-5549 follow-up: model
+// discovery and effort discovery both read `codebuddy --help`, and the effort
+// pass used to call it independently. That was masked while a failed --help was
+// wrongly memoised; once failures correctly stopped being cached, the failure
+// path ran the 35s command TWICE in one request — past the server's 60s running
+// timeout, so the request timed out and the late report was discarded as stale.
+// The user then got no list at all, not even the fallback.
+//
+// Both paths must therefore run --help exactly once. This goes through the full
+// ListModels entry point, since that is where the second call was introduced.
+func TestListModelsCodebuddyRunsHelpAtMostOnce(t *testing.T) {
+ const realHelp = "Usage: codebuddy [options]\n" +
+ " --model <model> Currently supported: (hy3, glm-5.2, kimi-k3-1)\n" +
+ " --effort <level> Reasoning effort level (low, medium, high, xhigh)"
+
+ for _, tc := range []struct {
+ name string
+ helpBody string
+ helpExit int
+ wantFallback bool
+ }{
+ {name: "help succeeds", helpBody: realHelp, helpExit: 0},
+ // The original #6180 failure: interpreter missing, exit 127.
+ {name: "help fails", helpBody: "env: node: No such file or directory", helpExit: 127, wantFallback: true},
+ // Help runs but carries no model line (older//unauthenticated CLI).
+ {name: "help unparseable", helpBody: "Usage: codebuddy [options]", helpExit: 0, wantFallback: true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ path, counter := countingCodebuddyStub(t, tc.helpBody, tc.helpExit)
+ resetCodebuddyHelpCache(t, path)
+ // cachedDiscovery and the thinking cache are package globals; clear
+ // both so this case actually executes the stub.
+ modelCacheMu.Lock()
+ delete(modelCache, "codebuddy")
+ modelCacheMu.Unlock()
+ resetThinkingCacheForTests()
+ t.Cleanup(resetThinkingCacheForTests)
+
+ catalog, err := ListModels(context.Background(), "codebuddy", path)
+ if err != nil {
+ t.Fatalf("ListModels(codebuddy): %v", err)
+ }
+ if catalog.Fallback != tc.wantFallback {
+ t.Errorf("Fallback = %v, want %v", catalog.Fallback, tc.wantFallback)
+ }
+ if got := helpCallCount(t, counter); got != 1 {
+ t.Errorf("`codebuddy --help` ran %d times, want exactly 1 — "+
+ "two 35s attempts in one request exceed the server's 60s running timeout", got)
+ }
+ // Whichever path was taken, the picker still gets models and the
+ // thinking picker still gets levels.
+ if len(catalog.Models) == 0 {
+ t.Fatal("expected a non-empty catalog")
+ }
+ if catalog.Models[0].Thinking == nil || len(catalog.Models[0].Thinking.SupportedLevels) == 0 {
+ t.Error("expected effort levels to be annotated on both the real and fallback paths")
+ }
+ })
+ }
+}
+
+// TestCachedDiscoveryDoesNotCacheFallback pins that a fallback never occupies
+// the daemon's 60s discovery cache: the next request must be free to retry.
+func TestCachedDiscoveryDoesNotCacheFallback(t *testing.T) {
+ const key = "test-cache-fallback"
+ reset := func() {
+ modelCacheMu.Lock()
+ delete(modelCache, key)
+ modelCacheMu.Unlock()
+ }
+ reset()
+ t.Cleanup(reset)
+
+ calls := 0
+ fn := func() (Catalog, error) {
+ calls++
+ return Catalog{Models: []Model{{ID: "stand-in"}}, Fallback: true}, nil
+ }
+ for i := 0; i < 2; i++ {
+ got, err := cachedDiscovery(key, fn)
+ if err != nil {
+ t.Fatalf("cachedDiscovery: %v", err)
+ }
+ if !got.Fallback {
+ t.Error("cachedDiscovery must preserve the Fallback marker")
+ }
+ }
+ if calls != 2 {
+ t.Fatalf("a fallback must not be cached: expected fn called 2x, got %d", calls)
+ }
+}
diff --git a/server/pkg/agent/grok_test.go b/server/pkg/agent/grok_test.go
index 2acbe68834..df0728fc9f 100644
--- a/server/pkg/agent/grok_test.go
+++ b/server/pkg/agent/grok_test.go
@@ -743,12 +743,15 @@ func TestDiscoverGrokModelsWaitsForAdvertisedAuth(t *testing.T) {
t.Setenv("GROK_AUTH_METHODS", "api")
t.Setenv("XAI_API_KEY", "test-only-key")
- models, err := discoverGrokModels(context.Background(), fakePath)
+ catalog, err := discoverGrokModels(context.Background(), fakePath)
if err != nil {
t.Fatalf("discover grok models: %v", err)
}
- if len(models) != 2 || models[0].ID != "grok-4.5" {
- t.Fatalf("unexpected models: %+v", models)
+ if len(catalog.Models) != 2 || catalog.Models[0].ID != "grok-4.5" {
+ t.Fatalf("unexpected models: %+v", catalog.Models)
+ }
+ if catalog.Fallback {
+ t.Error("a successful ACP discovery must not be marked Fallback")
}
raw, err := os.ReadFile(requestsFile)
if err != nil {
@@ -786,12 +789,15 @@ func TestDiscoverGrokModelsStopsOnAuthFailures(t *testing.T) {
t.Setenv("GROK_AUTH_FAIL", tc.authFail)
t.Setenv("XAI_API_KEY", "")
- models, err := discoverGrokModels(context.Background(), fakePath)
+ catalog, err := discoverGrokModels(context.Background(), fakePath)
if err != nil {
t.Fatalf("discover grok models: %v", err)
}
- if len(models) != 2 || models[0].ID != "grok-4.5" {
- t.Fatalf("expected static fallback, got %+v", models)
+ if len(catalog.Models) != 2 || catalog.Models[0].ID != "grok-4.5" {
+ t.Fatalf("expected static fallback, got %+v", catalog.Models)
+ }
+ if !catalog.Fallback {
+ t.Error("static fallback must be marked Fallback so it is never cached as the real catalog")
}
raw, err := os.ReadFile(requestsFile)
if err != nil {
diff --git a/server/pkg/agent/models.go b/server/pkg/agent/models.go
index a9e045f654..fb0028a5d9 100644
--- a/server/pkg/agent/models.go
+++ b/server/pkg/agent/models.go
@@ -75,6 +75,32 @@ type ThinkingLevel struct {
Description string `json:"description,omitempty"`
}
+// Catalog is the outcome of one model-discovery round: the models to show,
+// plus whether they were actually discovered.
+type Catalog struct {
+ Models []Model
+ // Fallback reports that discovery did not succeed and Models is a static
+ // stand-in rather than the runtime's real catalog.
+ //
+ // Several providers (codebuddy, copilot, cursor, grok) answer a failed
+ // discovery with a baked-in list so the picker still has something to
+ // show. That is a reasonable UI affordance and a terrible thing to
+ // persist: it is not what the runtime actually supports, and for
+ // codebuddy the static IDs and the real ones do not overlap at all, so
+ // every pick is an ID the CLI rejects. Callers must therefore never
+ // treat a fallback catalog as authoritative — in particular it must not
+ // enter the server's day-scale model-catalog cache, which would pin one
+ // transient failure as the answer for 24h (MUL-5549).
+ Fallback bool
+}
+
+// discovered adapts a plain `([]Model, error)` discovery function to Catalog
+// for providers that have no static fallback — for them a failure is already
+// reported as an empty list or an error, which downstream guards handle.
+func discovered(models []Model, err error) (Catalog, error) {
+ return Catalog{Models: models}, err
+}
+
// modelCache memoizes dynamic discovery calls so repeated UI loads
// don't re-shell the agent CLI. Entries expire after cacheTTL.
type modelCacheEntry struct {
@@ -102,93 +128,93 @@ const modelCacheTTL = 60 * time.Second
//
// executablePath lets the caller point at a non-default binary; pass
// "" to use the provider's default name on PATH.
-func ListModels(ctx context.Context, providerType, executablePath string) ([]Model, error) {
+func ListModels(ctx context.Context, providerType, executablePath string) (Catalog, error) {
switch providerType {
case "claude":
models := claudeStaticModels()
annotateClaudeThinking(ctx, models, executablePath)
- return models, nil
+ // Claude's catalog is static by design, not by failure: there is no
+ // discovery step to fall back from, so this is authoritative.
+ return Catalog{Models: models}, nil
case "codex":
- return cachedDiscovery(discoveryCacheKey(providerType, executablePath), func() ([]Model, error) {
- return discoverCodexModels(ctx, executablePath), nil
+ return cachedDiscovery(discoveryCacheKey(providerType, executablePath), func() (Catalog, error) {
+ return discovered(discoverCodexModels(ctx, executablePath), nil)
})
case "antigravity":
// agy 1.0.6 added a `--model` flag plus an `agy models` catalog
// command (MUL-3125). Enumerate it on demand like the other
// dynamic-discovery backends.
- return cachedDiscovery(providerType, func() ([]Model, error) {
- return discoverAntigravityModels(ctx, executablePath)
+ return cachedDiscovery(providerType, func() (Catalog, error) {
+ return discovered(discoverAntigravityModels(ctx, executablePath))
})
case "traecli":
// Official TRAE CLI is ACP-native: it returns its model catalog from
// session/new. Enumerate it on demand like the other ACP backends
// (requires a logged-in traecli; falls back to manual entry on error).
- return cachedDiscovery(providerType, func() ([]Model, error) {
- return discoverTraecliModels(ctx, executablePath)
+ return cachedDiscovery(providerType, func() (Catalog, error) {
+ return discovered(discoverTraecliModels(ctx, executablePath))
})
case "cursor":
- return cachedDiscovery(providerType, func() ([]Model, error) {
+ return cachedDiscovery(providerType, func() (Catalog, error) {
return discoverCursorModels(ctx, executablePath)
})
case "copilot":
- return cachedDiscovery(providerType, func() ([]Model, error) {
+ return cachedDiscovery(providerType, func() (Catalog, error) {
return discoverCopilotModels(ctx, executablePath)
})
case "hermes":
- return cachedDiscovery(providerType, func() ([]Model, error) {
- return discoverHermesModels(ctx, executablePath)
+ return cachedDiscovery(providerType, func() (Catalog, error) {
+ return discovered(discoverHermesModels(ctx, executablePath))
})
case "kimi":
- return cachedDiscovery(providerType, func() ([]Model, error) {
- return discoverKimiModels(ctx, executablePath)
+ return cachedDiscovery(providerType, func() (Catalog, error) {
+ return discovered(discoverKimiModels(ctx, executablePath))
})
case "kiro":
- return cachedDiscovery(providerType, func() ([]Model, error) {
- return discoverKiroModels(ctx, executablePath)
+ return cachedDiscovery(providerType, func() (Catalog, error) {
+ return discovered(discoverKiroModels(ctx, executablePath))
})
case "qoder":
- return cachedDiscovery(providerType, func() ([]Model, error) {
- return discoverQoderModels(ctx, executablePath)
+ return cachedDiscovery(providerType, func() (Catalog, error) {
+ return discovered(discoverQoderModels(ctx, executablePath))
})
case "opencode":
- return cachedDiscovery(discoveryCacheKey(providerType, executablePath), func() ([]Model, error) {
- return discoverOpenCodeModels(ctx, executablePath)
+ return cachedDiscovery(discoveryCacheKey(providerType, executablePath), func() (Catalog, error) {
+ return discovered(discoverOpenCodeModels(ctx, executablePath))
})
case "deveco":
- return cachedDiscovery(discoveryCacheKey(providerType, executablePath), func() ([]Model, error) {
- return discoverDevecoModels(ctx, executablePath)
+ return cachedDiscovery(discoveryCacheKey(providerType, executablePath), func() (Catalog, error) {
+ return discovered(discoverDevecoModels(ctx, executablePath))
})
case "pi":
- return cachedDiscovery(providerType, func() ([]Model, error) {
- return discoverPiModels(ctx, executablePath)
+ return cachedDiscovery(providerType, func() (Catalog, error) {
+ return discovered(discoverPiModels(ctx, executablePath))
})
case "openclaw":
- return cachedDiscovery(providerType, func() ([]Model, error) {
- return discoverOpenclawAgents(ctx, executablePath)
+ return cachedDiscovery(providerType, func() (Catalog, error) {
+ return discovered(discoverOpenclawAgents(ctx, executablePath))
})
case "codebuddy":
- return cachedDiscovery(providerType, func() ([]Model, error) {
- models, err := discoverCodebuddyModels(ctx, executablePath)
- if err != nil {
- return nil, err
- }
- annotateCodebuddyThinking(ctx, models, executablePath)
- return models, nil
+ // discoverCodebuddyModels owns the thinking annotation too, so the one
+ // `--help` capture feeds both catalogs. Annotating out here would run
+ // the command a second time (MUL-5549).
+ return cachedDiscovery(providerType, func() (Catalog, error) {
+ return discoverCodebuddyModels(ctx, executablePath)
})
case "qwen":
// Qwen Code has no account-independent headless model catalog. An
// empty list keeps the runtime default and manual model entry available
// without advertising a Token-Plan-specific model to other accounts.
- return []Model{}, nil
+ return Catalog{Models: []Model{}}, nil
case "grok":
// xAI Grok Build is ACP-native (`grok agent stdio`); model catalog
// comes from session/new. Falls back to a small static list so the
// UI picker stays usable offline / unauthenticated.
- return cachedDiscovery(providerType, func() ([]Model, error) {
+ return cachedDiscovery(providerType, func() (Catalog, error) {
return discoverGrokModels(ctx, executablePath)
})
default:
- return nil, fmt.Errorf("unknown agent type: %q", providerType)
+ return Catalog{}, fmt.Errorf("unknown agent type: %q", providerType)
}
}
@@ -270,18 +296,18 @@ func modelHasKnownPrefix(model string) bool {
// The cache is keyed on providerType only; callers that need to
// distinguish discovery by host/user should include that in the key
// if we ever introduce such a mode.
-func cachedDiscovery(key string, fn func() ([]Model, error)) ([]Model, error) {
+func cachedDiscovery(key string, fn func() (Catalog, error)) (Catalog, error) {
modelCacheMu.Lock()
if entry, ok := modelCache[key]; ok && time.Now().Before(entry.expiresAt) {
out := entry.models
modelCacheMu.Unlock()
- return out, nil
+ return Catalog{Models: out}, nil
}
modelCacheMu.Unlock()
- models, err := fn()
+ catalog, err := fn()
if err != nil {
- return nil, err
+ return Catalog{}, err
}
// Don't cache an empty result. Zero models is almost always a transient
@@ -289,14 +315,20 @@ func cachedDiscovery(key string, fn func() ([]Model, error)) ([]Model, error) {
// a runtime that genuinely has no models; caching it would keep the picker
// blank for the full TTL even after the cause clears. Skipping the cache
// lets the next request retry immediately. See #3729.
- if len(models) == 0 {
- return models, nil
+ //
+ // A fallback catalog is the same situation wearing a disguise: non-empty,
+ // but only because discovery failed and the provider substituted a static
+ // list. Caching it would hold the stand-in for the full TTL and stop the
+ // next request from retrying, which is exactly the recovery path we want
+ // to keep open (MUL-5549).
+ if len(catalog.Models) == 0 || catalog.Fallback {
+ return catalog, nil
}
modelCacheMu.Lock()
- modelCache[key] = modelCacheEntry{models: models, expiresAt: time.Now().Add(modelCacheTTL)}
+ modelCache[key] = modelCacheEntry{models: catalog.Models, expiresAt: time.Now().Add(modelCacheTTL)}
modelCacheMu.Unlock()
- return models, nil
+ return catalog, nil
}
func discoveryCacheKey(providerType, executablePath string) string {
@@ -878,7 +910,7 @@ func discoverKiroModels(ctx context.Context, executablePath string) ([]Model, er
// drives `initialize` + `session/new`, neither of which triggers
// a tool-permission prompt — the model catalog is part of the
// session/new response itself.
-func discoverCopilotModels(ctx context.Context, executablePath string) ([]Model, error) {
+func discoverCopilotModels(ctx context.Context, executablePath string) (Catalog, error) {
models, err := discoverACPModels(ctx, executablePath, acpDiscoveryProvider{
defaultBin: "copilot",
clientName: "multica-model-discovery",
@@ -886,14 +918,14 @@ func discoverCopilotModels(ctx context.Context, executablePath string) ([]Model,
acpArgs: []string{"--acp"},
})
if err != nil || len(models) == 0 {
- return copilotStaticModels(), nil
+ return Catalog{Models: copilotStaticModels(), Fallback: true}, nil
}
for i := range models {
if models[i].Provider == "" {
models[i].Provider = inferCopilotProvider(models[i].ID)
}
}
- return models, nil
+ return Catalog{Models: models}, nil
}
// discoverQoderModels spins up `qodercli --yolo --acp` and parses models from session/new.
@@ -1358,7 +1390,7 @@ func parseAntigravityModels(output string) []Model {
// discoverGrokModels spins up `grok agent --always-approve stdio` and parses
// the model catalog from session/new (same shape as Kiro/Qoder/Trae). Requires
// an authenticated Grok CLI; on any failure falls back to grokStaticModels.
-func discoverGrokModels(ctx context.Context, executablePath string) ([]Model, error) {
+func discoverGrokModels(ctx context.Context, executablePath string) (Catalog, error) {
// Match the daemon's runtime launch: `--no-auto-update` (global) so a
// background update check can't stall discovery. Auth is selected only
// after initialize returns the methods this installed CLI actually offers.
@@ -1376,7 +1408,7 @@ func discoverGrokModels(ctx context.Context, executablePath string) ([]Model, er
if err != nil {
slog.Debug("grok model discovery fell back to static catalog", "error", err)
}
- return grokStaticModels(), nil
+ return Catalog{Models: grokStaticModels(), Fallback: true}, nil
}
for i := range models {
if models[i].Provider == "" {
@@ -1384,7 +1416,7 @@ func discoverGrokModels(ctx context.Context, executablePath string) ([]Model, er
}
}
annotateGrokThinking(models)
- return models, nil
+ return Catalog{Models: models}, nil
}
// grokStaticModels is the offline fallback catalog for the Grok Build CLI.
@@ -1421,12 +1453,12 @@ func annotateGrokThinking(models []Model) {
// suffixes) — static baking would be obsolete within weeks. On any
// failure we fall back to the minimal static catalog so the UI
// stays usable when cursor-agent isn't installed on the daemon host.
-func discoverCursorModels(ctx context.Context, executablePath string) ([]Model, error) {
+func discoverCursorModels(ctx context.Context, executablePath string) (Catalog, error) {
if executablePath == "" {
executablePath = "cursor-agent"
}
if _, err := exec.LookPath(executablePath); err != nil {
- return cursorStaticModels(), nil
+ return Catalog{Models: cursorStaticModels(), Fallback: true}, nil
}
// 15s to match the other network-backed discovery paths (pi/opencode/ACP);
// cursor-agent fetches its frequently-changing catalog, so a tight cap can
@@ -1437,13 +1469,13 @@ func discoverCursorModels(ctx context.Context, executablePath string) ([]Model,
hideAgentWindow(cmd)
out, err := cmd.Output()
if err != nil && len(out) == 0 {
- return cursorStaticModels(), nil
+ return Catalog{Models: cursorStaticModels(), Fallback: true}, nil
}
models := parseCursorModels(string(out))
if len(models) == 0 {
- return cursorStaticModels(), nil
+ return Catalog{Models: cursorStaticModels(), Fallback: true}, nil
}
- return models, nil
+ return Catalog{Models: models}, nil
}
// parseCursorModels extracts model IDs from `cursor-agent --list-models`.
@@ -1693,25 +1725,46 @@ func isOpenclawIdentifier(s string) bool {
// line in `codebuddy --help` output.
var codebuddyModelRe = regexp.MustCompile(`--model\s*<[^>]+>\s*.*?Currently supported:\s*\(([^)]+)\)`)
-// discoverCodebuddyModels runs `codebuddy --help` and extracts the
-// supported model list from its output. Falls back to a static list
-// when the binary is missing or the output cannot be parsed.
-func discoverCodebuddyModels(ctx context.Context, executablePath string) ([]Model, error) {
+// discoverCodebuddyModels runs `codebuddy --help` and extracts the supported
+// model list from its output, falling back to a static list when the binary is
+// missing or the output cannot be parsed.
+//
+// It runs `--help` AT MOST ONCE per call: the single capture feeds both the
+// model catalog and the per-model effort catalog, and the fallback paths skip
+// the effort pass entirely. A slow or failing --help therefore cannot be paid
+// for twice inside one model-list request, which would exceed the server's 60s
+// running timeout and cost the user even the fallback list (MUL-5549).
+func discoverCodebuddyModels(ctx context.Context, executablePath string) (Catalog, error) {
if executablePath == "" {
executablePath = "codebuddy"
}
if _, err := exec.LookPath(executablePath); err != nil {
- return codebuddyStaticModels(), nil
+ return codebuddyFallbackCatalog(), nil
}
helpOut := codebuddyHelpOutput(ctx, executablePath)
if helpOut == "" {
- return codebuddyStaticModels(), nil
+ return codebuddyFallbackCatalog(), nil
}
models := parseCodebuddyModels(helpOut)
if len(models) == 0 {
- return codebuddyStaticModels(), nil
+ return codebuddyFallbackCatalog(), nil
}
- return models, nil
+ annotateCodebuddyThinking(ctx, models, executablePath, helpOut)
+ return Catalog{Models: models}, nil
+}
+
+// codebuddyFallbackCatalog is the static stand-in for a failed discovery.
+//
+// It applies the static effort levels directly instead of shelling out again:
+// whatever broke `--help` for the model catalog (missing binary, missing `node`
+// interpreter, timeout) breaks it for the effort catalog too, and a second 35s
+// attempt inside one request would push past the server's 60s running timeout —
+// costing the user even the fallback list this function exists to provide
+// (MUL-5549).
+func codebuddyFallbackCatalog() Catalog {
+ models := codebuddyStaticModels()
+ applyCodebuddyStaticThinking(models)
+ return Catalog{Models: models, Fallback: true}
}
// parseCodebuddyModels extracts model IDs from codebuddy --help output.
diff --git a/server/pkg/agent/models_test.go b/server/pkg/agent/models_test.go
index 74c68adcbc..3712c8a49f 100644
--- a/server/pkg/agent/models_test.go
+++ b/server/pkg/agent/models_test.go
@@ -38,9 +38,12 @@ func TestListModelsQwenUsesRuntimeDefaultAndManualEntry(t *testing.T) {
if err != nil {
t.Fatalf("ListModels(qwen) error: %v", err)
}
- if len(got) != 0 {
+ if len(got.Models) != 0 {
t.Fatalf("ListModels(qwen) = %+v, want no account-specific static catalog", got)
}
+ if got.Fallback {
+ t.Error("qwen's empty catalog is deliberate, not a discovery fallback")
+ }
}
func TestListModelsCopilotFallsBackToStatic(t *testing.T) {
@@ -58,11 +61,14 @@ func TestListModelsCopilotFallsBackToStatic(t *testing.T) {
if err != nil {
t.Fatalf("ListModels(copilot) error: %v", err)
}
- if len(got) == 0 {
+ if len(got.Models) == 0 {
t.Fatal("expected static fallback models, got empty list")
}
+ if !got.Fallback {
+ t.Error("a static stand-in must be marked Fallback so it is never cached as the real catalog")
+ }
ids := map[string]bool{}
- for _, m := range got {
+ for _, m := range got.Models {
ids[m.ID] = true
}
if !ids["gpt-5.4"] || !ids["claude-sonnet-4.6"] {
@@ -367,7 +373,7 @@ func TestListModelsHermesWithoutBinary(t *testing.T) {
if err != nil {
t.Fatalf("ListModels(hermes) error: %v", err)
}
- if got == nil {
+ if got.Models == nil {
t.Error("expected non-nil slice even when binary is missing")
}
}
@@ -382,7 +388,7 @@ func TestListModelsKiroWithoutBinary(t *testing.T) {
if err != nil {
t.Fatalf("ListModels(kiro) error: %v", err)
}
- if got == nil {
+ if got.Models == nil {
t.Error("expected non-nil slice even when binary is missing")
}
}
@@ -397,7 +403,7 @@ func TestListModelsQoderWithoutBinary(t *testing.T) {
if err != nil {
t.Fatalf("ListModels(qoder) error: %v", err)
}
- if got == nil {
+ if got.Models == nil {
t.Error("expected non-nil slice even when binary is missing")
}
}
@@ -591,16 +597,16 @@ func TestCachedDiscoveryDoesNotCacheEmpty(t *testing.T) {
t.Cleanup(resetCache)
emptyCalls := 0
- empty := func() ([]Model, error) {
+ empty := func() (Catalog, error) {
emptyCalls++
- return []Model{}, nil
+ return Catalog{Models: []Model{}}, nil
}
for i := 0; i < 2; i++ {
got, err := cachedDiscovery(emptyKey, empty)
if err != nil {
t.Fatalf("cachedDiscovery: %v", err)
}
- if len(got) != 0 {
+ if len(got.Models) != 0 {
t.Fatalf("expected empty result, got %+v", got)
}
}
@@ -609,9 +615,9 @@ func TestCachedDiscoveryDoesNotCacheEmpty(t *testing.T) {
}
nonEmptyCalls := 0
- nonEmpty := func() ([]Model, error) {
+ nonEmpty := func() (Catalog, error) {
nonEmptyCalls++
- return []Model{{ID: "provider/model"}}, nil
+ return Catalog{Models: []Model{{ID: "provider/model"}}}, nil
}
for i := 0; i < 2; i++ {
if _, err := cachedDiscovery(nonEmptyKey, nonEmpty); err != nil {
@@ -1213,9 +1219,9 @@ func TestParseAntigravityModelsEmpty(t *testing.T) {
func TestCachedDiscovery(t *testing.T) {
calls := 0
- fn := func() ([]Model, error) {
+ fn := func() (Catalog, error) {
calls++
- return []Model{{ID: "x", Label: "x"}}, nil
+ return Catalog{Models: []Model{{ID: "x", Label: "x"}}}, nil
}
// First call populates the cache; reset for isolation.
modelCacheMu.Lock()
diff --git a/server/pkg/agent/thinking.go b/server/pkg/agent/thinking.go
index a01fcfc675..e9f3c52a66 100644
--- a/server/pkg/agent/thinking.go
+++ b/server/pkg/agent/thinking.go
@@ -3,6 +3,7 @@ package agent
import (
"context"
"encoding/json"
+ "log/slog"
"os/exec"
"regexp"
"strings"
@@ -453,9 +454,16 @@ var codebuddyEffortLabel = map[string]string{
var codebuddyStaticEffortFallback = []string{"low", "medium", "high", "xhigh"}
-// codebuddyHelpCache caches the raw --help output so both model discovery
-// (models.go) and effort discovery avoid redundant slow CLI invocations.
-// CodeBuddy's --help takes ~30s; calling it twice on cold start wastes ~30s.
+// codebuddyHelpCache memoises the raw --help output across discovery rounds:
+// CodeBuddy's --help can take ~30s, so re-running it for every model-list
+// request would be painful.
+//
+// It is NOT what keeps a single request down to one invocation. That is
+// structural: discoverCodebuddyModels captures the help text once and hands the
+// string to the model and effort parsers, and its failure paths skip the effort
+// pass entirely (MUL-5549). Relying on the cache for that would be wrong — a
+// failed --help is deliberately not cached, so the second caller would re-run
+// the full 35s timeout.
var (
codebuddyHelpMu sync.Mutex
codebuddyHelpStore = map[string]codebuddyHelpEntry{}
@@ -468,9 +476,14 @@ type codebuddyHelpEntry struct {
expiresAt time.Time
}
-// codebuddyHelpOutput runs `codebuddy --help` (cached for codebuddyHelpTTL).
-// Both discoverCodebuddyModels and codebuddyEffortSuperset call this so a
-// single cold invocation feeds both.
+// codebuddyHelpOutput runs `codebuddy --help` (cached for codebuddyHelpTTL) and
+// returns "" when the command could not be run.
+//
+// discoverCodebuddyModels is its only caller. The effort parser deliberately
+// takes an already-captured string instead of calling this itself, so one
+// discovery round can never pay the 35s timeout twice (MUL-5549). Keep it that
+// way: a new caller here reintroduces that bug on the failure path, where
+// nothing is cached to absorb the second run.
func codebuddyHelpOutput(ctx context.Context, executablePath string) string {
if executablePath == "" {
executablePath = "codebuddy"
@@ -487,7 +500,19 @@ func codebuddyHelpOutput(ctx context.Context, executablePath string) string {
defer cancel()
cmd := exec.CommandContext(runCtx, executablePath, "--help")
hideAgentWindow(cmd)
- out, _ := cmd.CombinedOutput()
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ // A non-zero exit or a timeout means this is not usable help text, and
+ // CombinedOutput folds stderr in, so the failure message itself would
+ // be returned as if it were help. The canonical case: `codebuddy` is a
+ // `#!/usr/bin/env node` script installed under nvm, and a GUI-launched
+ // daemon does not inherit the interactive PATH, so the shebang fails
+ // and the "output" is `env: node: No such file or directory`. Returning
+ // that made every parser here silently fall back, and caching it pinned
+ // the failure for codebuddyHelpTTL (MUL-5549).
+ slog.Debug("codebuddy --help failed", "path", executablePath, "error", err)
+ return ""
+ }
result := string(out)
if result != "" {
@@ -498,7 +523,17 @@ func codebuddyHelpOutput(ctx context.Context, executablePath string) string {
return result
}
-func annotateCodebuddyThinking(ctx context.Context, models []Model, executablePath string) {
+// annotateCodebuddyThinking derives the effort catalog from helpOut — the SAME
+// `codebuddy --help` capture the model catalog was parsed from — rather than
+// running the command again.
+//
+// It used to call codebuddyHelpOutput itself. That was free while a failed
+// --help was (wrongly) memoised, but once failures correctly stopped being
+// cached it meant one ListModels could pay the 35s timeout twice, blowing past
+// the server's 60s running timeout and denying the user even the fallback list
+// (MUL-5549). Callers on the failure path skip this entirely and use
+// codebuddyFallbackCatalog, which applies the static levels without exec'ing.
+func annotateCodebuddyThinking(ctx context.Context, models []Model, executablePath, helpOut string) {
if executablePath == "" {
executablePath = "codebuddy"
}
@@ -513,7 +548,20 @@ func annotateCodebuddyThinking(ctx context.Context, models []Model, executablePa
return
}
- levels := codebuddyEffortSuperset(ctx, executablePath)
+ result := codebuddyThinkingByModel(models, codebuddyEffortSuperset(helpOut))
+ thinkingCachePut(key, result)
+
+ for i := range models {
+ if t, ok := result[models[i].ID]; ok && t != nil {
+ models[i].Thinking = t
+ }
+ }
+}
+
+// codebuddyThinkingByModel maps every model onto the shared effort catalog
+// built from levels. CodeBuddy advertises one `--effort` set for the whole CLI,
+// not per model, so every entry gets the same ModelThinking pointer.
+func codebuddyThinkingByModel(models []Model, levels []string) map[string]*ModelThinking {
thinkingLevels := make([]ThinkingLevel, 0, len(levels))
for _, value := range levels {
label, ok := codebuddyEffortLabel[value]
@@ -533,8 +581,14 @@ func annotateCodebuddyThinking(ctx context.Context, models []Model, executablePa
result[m.ID] = thinking
}
}
- thinkingCachePut(key, result)
+ return result
+}
+// applyCodebuddyStaticThinking annotates models with the static effort
+// fallback. Used on the discovery-failure path, where re-running --help to
+// discover the real levels would just fail again — slowly.
+func applyCodebuddyStaticThinking(models []Model) {
+ result := codebuddyThinkingByModel(models, codebuddyStaticEffortFallback)
for i := range models {
if t, ok := result[models[i].ID]; ok && t != nil {
models[i].Thinking = t
@@ -542,8 +596,10 @@ func annotateCodebuddyThinking(ctx context.Context, models []Model, executablePa
}
}
-func codebuddyEffortSuperset(ctx context.Context, executablePath string) []string {
- helpOut := codebuddyHelpOutput(ctx, executablePath)
+// codebuddyEffortSuperset extracts the `--effort` levels from an already
+// captured `codebuddy --help`, falling back to the static set when the help
+// text carries no parseable effort line.
+func codebuddyEffortSuperset(helpOut string) []string {
if helpOut == "" {
return append([]string(nil), codebuddyStaticEffortFallback...)
}
@@ -613,10 +669,11 @@ func ValidateThinkingLevel(ctx context.Context, providerType, executablePath, mo
if model == "" && providerType == "codex" {
return false, nil
}
- models, err := ListModels(ctx, providerType, executablePath)
+ catalog, err := ListModels(ctx, providerType, executablePath)
if err != nil {
return false, err
}
+ models := catalog.Models
target := model
if target == "" {
// Default model = the entry the catalog marks as Default. If no
@@ -664,11 +721,11 @@ func ValidateServiceTier(ctx context.Context, providerType, executablePath, mode
if providerType != "codex" || model == "" {
return false, nil
}
- models, err := ListModels(ctx, providerType, executablePath)
+ catalog, err := ListModels(ctx, providerType, executablePath)
if err != nil {
return false, err
}
- for _, m := range models {
+ for _, m := range catalog.Models {
if m.ID != model {
continue
}