From 1ef4a8696deac518fd830de0ccd40eb8e0a33b25 Mon Sep 17 00:00:00 2001 From: oniisanlabs <1436535+oniisanlabs@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:33:18 +0100 Subject: [PATCH 01/13] fix(chatgpt): preserve account discovery and report fallback failures Resolve onboarding and wizard OAuth ownership with the matching account identity, keep failed subscription lookups as errors, refresh provider-aware model listings, and report redacted failures with a small retry action. Scope cached results to their profile and ignore superseded refreshes. Refs Twigpine/zero#1177 (discovery portion) --- docs/oauth-subscriptions.md | 7 + .../chatgpt_catalog_test.go | 131 ++++++++ internal/providermodeldiscovery/discovery.go | 61 +++- internal/tui/chatgpt_models_test.go | 283 ++++++++++++++++++ internal/tui/command_center.go | 3 +- internal/tui/model.go | 24 +- internal/tui/model_catalog.go | 28 +- internal/tui/onboarding.go | 3 +- internal/tui/picker.go | 79 ++++- internal/tui/provider_wizard_discovery.go | 5 +- internal/tui/view.go | 6 +- 11 files changed, 606 insertions(+), 24 deletions(-) create mode 100644 internal/providermodeldiscovery/chatgpt_catalog_test.go create mode 100644 internal/tui/chatgpt_models_test.go diff --git a/docs/oauth-subscriptions.md b/docs/oauth-subscriptions.md index 6bb70c98df..ad81c81b0c 100644 --- a/docs/oauth-subscriptions.md +++ b/docs/oauth-subscriptions.md @@ -99,6 +99,13 @@ Pick **Sign in with OAuth** → the list of providers that do real OAuth → cho `ZERO_OAUTH_ALLOW_PRESETS=1`. As of mid-2026 the Codex backend is Cloudflare-gated: requests from a non-Codex client can still be challenged, and the `chatgpt-proxy` route in §2 is the conservative fallback. + + ChatGPT model availability comes from the authenticated Codex catalog. Open + `/model` or run `/model list` to refresh it; `Ctrl+R` retries from the picker. + If discovery fails, the picker reports the error and labels fallback suggestions + as unverified. Public OpenAI metadata can enrich live models but cannot establish + subscription access. `zero providers models chatgpt` probes the live endpoint + directly and reports failures. - **Hugging Face — opt-in preset, BYO client_id** — `zero auth login huggingface` (or `--device` for headless) opens a Hugging Face OAuth flow. The bearer works on the OpenAI-compatible router at `https://router.huggingface.co/v1` for hundreds diff --git a/internal/providermodeldiscovery/chatgpt_catalog_test.go b/internal/providermodeldiscovery/chatgpt_catalog_test.go new file mode 100644 index 0000000000..4af1c3b4f8 --- /dev/null +++ b/internal/providermodeldiscovery/chatgpt_catalog_test.go @@ -0,0 +1,131 @@ +package providermodeldiscovery + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/Twigpine/zero/internal/config" + "github.com/Twigpine/zero/internal/providercatalog" +) + +func chatGPTTestProfile(baseURL string) (providercatalog.Descriptor, config.ProviderProfile) { + provider, _ := providercatalog.Get("chatgpt") + return provider, config.ProviderProfile{ + Name: "subscription", CatalogID: "chatgpt", ProviderKind: config.ProviderKindOpenAICompatible, + BaseURL: baseURL + "/backend-api/codex", APIKey: "test-bearer", + } +} + +func TestChatGPTCatalogRequiresLiveDiscovery(t *testing.T) { + for _, response := range []string{"unauthorized", "empty", "non-coding"} { + t.Run(response, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api.json" { + _, _ = w.Write([]byte(`{"openai":{"models":{"gpt-stale":{"id":"gpt-stale","tool_call":true}}}}`)) + return + } + switch response { + case "unauthorized": + http.Error(w, "login expired", http.StatusUnauthorized) + case "empty": + _, _ = w.Write([]byte(`{"models":[]}`)) + case "non-coding": + _, _ = w.Write([]byte(`{"models":[{"slug":"gpt-image-1"}]}`)) + } + })) + defer server.Close() + provider, profile := chatGPTTestProfile(server.URL) + models, err := DiscoverCatalog(context.Background(), provider, profile, Options{ + HTTPClient: server.Client(), ModelsDevURL: server.URL + "/api.json", + }) + if err == nil || len(models) != 0 { + t.Fatalf("failed subscription discovery returned models=%v err=%v; public metadata must not claim account availability", modelIDs(models), err) + } + }) + } +} + +func TestChatGPTCatalogProbesLiveBeforeOptionalMetadata(t *testing.T) { + var liveSeen atomic.Bool + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api.json" { + if !liveSeen.Load() { + t.Error("optional public metadata was fetched before the subscription catalog") + } + http.Error(w, "metadata unavailable", http.StatusServiceUnavailable) + return + } + liveSeen.Store(true) + _, _ = w.Write([]byte(`{"models":[{"slug":"gpt-future-coder","visibility":"list","context_window":123456}]}`)) + })) + defer server.Close() + provider, profile := chatGPTTestProfile(server.URL) + models, err := DiscoverCatalog(context.Background(), provider, profile, Options{ + HTTPClient: server.Client(), ModelsDevURL: server.URL + "/api.json", + }) + if err != nil || len(models) != 1 || models[0].ID != "gpt-future-coder" || models[0].ContextWindow != 123456 { + t.Fatalf("live models lost when metadata failed: models=%v err=%v", models, err) + } +} + +func TestChatGPTCatalogBoundsOptionalMetadata(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api.json" { + <-r.Context().Done() + return + } + _, _ = w.Write([]byte(`{"models":[{"slug":"gpt-future-coder"}]}`)) + })) + defer server.Close() + provider, profile := chatGPTTestProfile(server.URL) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + models, err := DiscoverCatalog(ctx, provider, profile, Options{ + HTTPClient: server.Client(), ModelsDevURL: server.URL + "/api.json", + }) + if err != nil || strings.Join(modelIDs(models), ",") != "gpt-future-coder" { + t.Fatalf("slow metadata prevented live results: models=%v err=%v", modelIDs(models), err) + } +} + +func TestChatGPTDiscoveryRedactsRefreshedOAuthBearer(t *testing.T) { + const oldToken, newToken = "opaque-old-subscription", "opaque-new-subscription" + for _, split := range []string{"", "\x00", "\x1b", "\u0085", "\x1b[31m"} { + t.Run(fmt.Sprintf("split-%x", split), func(t *testing.T) { + var requests int + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests++ + body := "expired " + oldToken + if requests > 1 { + body = "expired opaque-" + split + "new-subscription and " + oldToken + } + http.Error(w, body, http.StatusUnauthorized) + })) + defer server.Close() + _, profile := chatGPTTestProfile(server.URL) + profile.APIKey = "" + _, err := Discover(context.Background(), profile, Options{ + HTTPClient: server.Client(), + OAuthResolver: func(_ context.Context, force bool) (string, string, bool, error) { + token := oldToken + if force { + token = newToken + } + return "Authorization", "Bearer " + token, true, nil + }, + }) + if err == nil || requests != 2 { + t.Fatalf("expected failed refresh retry: requests=%d err=%v", requests, err) + } + if strings.Contains(err.Error(), oldToken) || strings.Contains(err.Error(), "new-subscription") { + t.Fatalf("discovery error exposed OAuth bearer: %v", err) + } + }) + } +} diff --git a/internal/providermodeldiscovery/discovery.go b/internal/providermodeldiscovery/discovery.go index 9087ea6d7a..054e484a52 100644 --- a/internal/providermodeldiscovery/discovery.go +++ b/internal/providermodeldiscovery/discovery.go @@ -10,6 +10,9 @@ import ( "sort" "strings" "time" + "unicode" + + "github.com/charmbracelet/x/ansi" "github.com/Twigpine/zero/internal/config" "github.com/Twigpine/zero/internal/providercatalog" @@ -55,6 +58,24 @@ type Options struct { } func DiscoverCatalog(ctx context.Context, provider providercatalog.Descriptor, profile config.ProviderProfile, options Options) ([]Model, error) { + if providercatalog.NormalizeID(provider.ID) == "chatgpt" { + // Public OpenAI metadata cannot establish subscription entitlements. Probe + // the account first and surface failures instead of calling metadata live. + liveModels, err := Discover(ctx, profile, options) + if err != nil { + return nil, err + } + // Enrichment is optional and must not consume the caller's entire discovery + // budget, leaving a working subscription looking unavailable. + metadataCtx, cancel := context.WithTimeout(ctx, time.Second) + defer cancel() + catalogModels, _ := fetchCatalogModels(metadataCtx, provider, options) + models := mergeLiveModels(provider, liveModels, catalogModels) + if len(models) == 0 { + return nil, fmt.Errorf("ChatGPT models endpoint returned no visible coding models") + } + return models, nil + } catalogModels, catalogErr := fetchCatalogModels(ctx, provider, options) // OpenRouter and OpenGateway publish public live model lists. Probe them even // without credentials so the picker stays current before a key is entered. @@ -269,29 +290,43 @@ func fetchProviderModels(ctx context.Context, endpoint string, profile config.Pr if client == nil { client = &http.Client{Timeout: 10 * time.Second} } - response, err := providerio.SendWithAuthRetry(ctx, client, http.MethodGet, endpoint, nil, auth, options.OAuthResolver, func(request *http.Request) { + resolver := options.OAuthResolver + var resolvedSecrets []string + if resolver != nil { + resolver = func(ctx context.Context, force bool) (string, string, bool, error) { + header, value, ok, err := options.OAuthResolver(ctx, force) + if ok { + // Include both attempts: an upstream may echo either the rejected + // bearer or its replacement in a failure response. + resolvedSecrets = append(resolvedSecrets, value, strings.TrimSpace(strings.TrimPrefix(value, "Bearer "))) + } + return header, value, ok, err + } + } + redact := func(err error) error { return redactDiscoveryError(err, profile, resolvedSecrets...) } + response, err := providerio.SendWithAuthRetry(ctx, client, http.MethodGet, endpoint, nil, auth, resolver, func(request *http.Request) { request.Header.Set("Accept", "application/json") if configure != nil { configure(request) } }, 1) if err != nil { - return nil, redactDiscoveryError(err, profile) + return nil, redact(err) } defer response.Body.Close() // OpenRouter's full catalog is ~0.5MB today; keep headroom for growth. body, err := io.ReadAll(io.LimitReader(response.Body, 4<<20)) if err != nil { - return nil, redactDiscoveryError(err, profile) + return nil, redact(err) } if response.StatusCode < 200 || response.StatusCode >= 300 { - return nil, redactDiscoveryError(fmt.Errorf("models endpoint returned %s: %s", response.Status, strings.TrimSpace(string(body))), profile) + return nil, redact(fmt.Errorf("models endpoint returned %s: %s", response.Status, strings.TrimSpace(string(body)))) } models, err := parseModelsResponse(body) if err != nil { - return nil, redactDiscoveryError(err, profile) + return nil, redact(err) } return models, nil } @@ -714,14 +749,20 @@ func firstDiscoverySource(values ...string) string { return "" } -func redactDiscoveryError(err error, profile config.ProviderProfile) error { +func redactDiscoveryError(err error, profile config.ProviderProfile, secrets ...string) error { if err == nil { return nil } - return fmt.Errorf("%s", redaction.RedactString(err.Error(), redaction.Options{ExtraSecretValues: []string{ - profile.APIKey, - profile.AuthHeaderValue, - }})) + // Normalize before matching so terminal rendering cannot reassemble a + // credential split by an escape sequence or an invisible control byte. + message := strings.Map(func(r rune) rune { + if r == '\n' || r == '\r' || r == '\t' || !unicode.IsControl(r) { + return r + } + return -1 + }, ansi.Strip(err.Error())) + secrets = append(secrets, profile.APIKey, profile.AuthHeaderValue) + return fmt.Errorf("%s", redaction.RedactString(message, redaction.Options{ExtraSecretValues: secrets})) } func displayProviderName(profile config.ProviderProfile) string { diff --git a/internal/tui/chatgpt_models_test.go b/internal/tui/chatgpt_models_test.go new file mode 100644 index 0000000000..0d1eb89813 --- /dev/null +++ b/internal/tui/chatgpt_models_test.go @@ -0,0 +1,283 @@ +package tui + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "path/filepath" + "strings" + "testing" + "time" + + tea "charm.land/bubbletea/v2" + + "github.com/Twigpine/zero/internal/config" + "github.com/Twigpine/zero/internal/modelregistry" + "github.com/Twigpine/zero/internal/oauth" + "github.com/Twigpine/zero/internal/providercatalog" + "github.com/Twigpine/zero/internal/providermodeldiscovery" + "github.com/Twigpine/zero/internal/zeroruntime" +) + +func isolateSubscriptionTest(t *testing.T) { + t.Helper() + root := t.TempDir() + for _, name := range []string{"HOME", "USERPROFILE", "APPDATA", "LOCALAPPDATA", "XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"} { + t.Setenv(name, root) + } + t.Setenv("ZERO_OAUTH_STORAGE", "file") + t.Setenv("ZERO_OAUTH_TOKENS_PATH", filepath.Join(root, "oauth.json")) + t.Setenv("ZERO_DISABLE_MODELS_FETCH", "1") +} + +func subscriptionTestModel(t *testing.T) model { + t.Helper() + isolateSubscriptionTest(t) + return newModel(context.Background(), Options{ + Cwd: t.TempDir(), UserConfigPath: filepath.Join(t.TempDir(), "config.json"), + ProviderName: "subscription", ModelName: "gpt-existing", + ProviderProfile: config.ProviderProfile{ + Name: "subscription", CatalogID: "chatgpt", Model: "gpt-existing", + ProviderKind: config.ProviderKindOpenAICompatible, BaseURL: "https://chatgpt.com/backend-api/codex", + }, + }) +} + +func TestSubscriptionModelListIncludesDiscoveredModels(t *testing.T) { + m := subscriptionTestModel(t) + m = m.applyModelPickerModelsDiscovered(modelPickerModelsDiscoveredMsg{ + providerID: "chatgpt", models: []providermodeldiscovery.Model{{ID: "gpt-future-coder", Description: "Future coder"}}, + }) + text := m.modelListText() + for _, want := range []string{"gpt-future-coder", "subscription", "live"} { + if !strings.Contains(text, want) { + t.Fatalf("/model list lacks %q after live discovery:\n%s", want, text) + } + } + registry, err := modelregistry.DefaultRegistry() + if err != nil { + t.Fatal(err) + } + if target, ok := m.resolveModelSwitchTarget(registry, "gpt-future-coder"); !ok || target.modelID != "gpt-future-coder" { + t.Fatal("listed subscription model is not selectable") + } +} + +func TestSubscriptionPickerReportsDiscoveryFailureAndRecovery(t *testing.T) { + m := subscriptionTestModel(t) + m.picker = m.newModelPicker() + m = m.applyModelPickerModelsDiscovered(modelPickerModelsDiscoveredMsg{ + providerID: "chatgpt", err: errors.New("expired login"), + }) + text := m.modelPickerOverlay(100) + for _, want := range []string{"expired login", "fallback", "Ctrl+R"} { + if !strings.Contains(text, want) { + t.Fatalf("picker hides %q after discovery failure:\n%s", want, text) + } + } + m = m.applyModelPickerModelsDiscovered(modelPickerModelsDiscoveredMsg{ + providerID: "chatgpt", models: []providermodeldiscovery.Model{{ID: "gpt-future-coder"}}, + }) + if text := m.modelPickerOverlay(100); strings.Contains(text, "expired login") || strings.Contains(text, "unverified") { + t.Fatalf("successful refresh kept fallback warning:\n%s", text) + } +} + +func TestSubscriptionFallbackSuggestionsAreUnverified(t *testing.T) { + m := subscriptionTestModel(t) + m.picker = m.newModelPicker() + if text := m.modelPickerOverlay(110); !strings.Contains(text, "unverified") { + t.Fatalf("subscription fallback is not labeled unverified:\n%s", text) + } +} + +func TestSubscriptionModelListRefreshesWithoutOpeningPicker(t *testing.T) { + m := subscriptionTestModel(t) + m.discoverProviderModels = func(_ context.Context, profile config.ProviderProfile) ([]providermodeldiscovery.Model, error) { + if profile.Name != "subscription" || profile.CatalogID != "chatgpt" { + t.Fatalf("discovery lost profile identity: %#v", profile) + } + return []providermodeldiscovery.Model{{ID: "gpt-future-coder"}}, nil + } + m.input.SetValue("/model list") + updated, cmd := m.Update(testKey(tea.KeyEnter)) + if cmd == nil { + t.Fatal("/model list must discover the subscription even before /model is opened") + } + updated, _ = updated.(model).Update(cmd()) + next := updated.(model) + if !transcriptContains(next.transcript, "gpt-future-coder") || next.providerName != "subscription" { + t.Fatal("/model list omitted the refreshed model or changed providers") + } +} + +func TestSubscriptionDiscoveredModelSwitchKeepsOAuthProvider(t *testing.T) { + m := subscriptionTestModel(t) + m.userConfigPath = "" // This fixture models an unsaved session profile. + m.modelPickerLiveByProvider = map[string][]providermodeldiscovery.Model{ + "subscription": {{ID: "gpt-future-coder"}}, + } + var rebuilt config.ProviderProfile + m.newProvider = func(profile config.ProviderProfile) (zeroruntime.Provider, error) { + rebuilt = profile + return &fakeProvider{}, nil + } + next, _, err := m.handleModelCommand("openai/gpt-future-coder") + if err != nil { + t.Fatal(err) + } + if next.modelName != "gpt-future-coder" || next.providerName != "subscription" || rebuilt.CatalogID != "chatgpt" || rebuilt.BaseURL != m.providerProfile.BaseURL { + t.Fatalf("switch lost its subscription route: model=%q provider=%q profile=%#v", next.modelName, next.providerName, rebuilt) + } +} + +func TestSubscriptionPickerKeepsAccountErrorsIndependent(t *testing.T) { + m := subscriptionTestModel(t) + m.savedProviders = []config.ProviderProfile{m.providerProfile, { + Name: "second-account", CatalogID: "chatgpt", BaseURL: m.providerProfile.BaseURL, + ProviderKind: config.ProviderKindOpenAICompatible, + }} + m.picker = m.newModelPicker() + m = m.applyModelPickerModelsDiscovered(modelPickerModelsDiscoveredMsg{ + providerID: "chatgpt", endpointKey: "subscription", err: errors.New("expired subscription"), + }) + m = m.applyModelPickerModelsDiscovered(modelPickerModelsDiscoveredMsg{ + providerID: "chatgpt", endpointKey: "second-account", models: []providermodeldiscovery.Model{{ID: "gpt-second-account"}}, + }) + if !strings.Contains(m.modelPickerOverlay(100), "expired subscription") { + t.Fatal("another account's success cleared the first account's failure") + } +} + +func TestSubscriptionModelsDoNotCrossAccountProfiles(t *testing.T) { + m := subscriptionTestModel(t) + m = m.applyModelPickerModelsDiscovered(modelPickerModelsDiscoveredMsg{ + providerID: "chatgpt", endpointKey: "second-account", models: []providermodeldiscovery.Model{{ID: "gpt-second-account"}}, + }) + registry, err := modelregistry.DefaultRegistry() + if err != nil { + t.Fatal(err) + } + if _, ok := m.resolveModelSwitchTarget(registry, "gpt-second-account"); ok { + t.Fatal("another account's entitlement leaked into the active account") + } +} + +func TestSubscriptionPickerRetriesFromKeyboard(t *testing.T) { + m := subscriptionTestModel(t) + m.picker = m.newModelPicker() + m = m.applyModelPickerModelsDiscovered(modelPickerModelsDiscoveredMsg{ + providerID: "chatgpt", endpointKey: "subscription", err: errors.New("expired subscription"), + }) + m.discoverProviderModels = func(context.Context, config.ProviderProfile) ([]providermodeldiscovery.Model, error) { + return []providermodeldiscovery.Model{{ID: "gpt-refreshed"}}, nil + } + updated, cmd := m.Update(testKeyCtrl('r')) + if cmd == nil || updated.(model).picker.query != "" { + t.Fatal("Ctrl+R must retry discovery without changing the search") + } + updated, _ = updated.(model).Update(cmd()) + next := updated.(model) + if strings.Contains(next.modelPickerOverlay(100), "expired subscription") || !contains(pickerValues(next.picker.items), "gpt-refreshed") { + t.Fatal("successful keyboard retry did not refresh models and clear its account's error") + } +} + +func TestSubscriptionPickerRedactsDiscoveryErrors(t *testing.T) { + const secret = "opaque-subscription-bearer" + for _, split := range []string{"", "\x00", "\x1b", "\u0085", "\x1b[31m"} { + t.Run(fmt.Sprintf("split-%x", split), func(t *testing.T) { + m := subscriptionTestModel(t) + m.picker = m.newModelPicker() + m = m.applyModelPickerModelsDiscovered(modelPickerModelsDiscoveredMsg{ + providerID: "chatgpt", err: errors.New("request failed with opaque-" + split + "subscription-bearer"), secrets: []string{secret}, + }) + if text := m.modelPickerOverlay(100); strings.Contains(text, "subscription-bearer") || !strings.Contains(text, "request failed") { + t.Fatalf("discovery error was not safely rendered: %s", text) + } + }) + } +} + +func TestSubscriptionPickerIgnoresSupersededRefresh(t *testing.T) { + m := subscriptionTestModel(t) + m.modelPickerDiscoveryGeneration = 2 + m.picker = m.newModelPicker() + updated, _ := m.Update(modelPickerModelsDiscoveredMsg{ + providerID: "chatgpt", endpointKey: "subscription", generation: 2, + models: []providermodeldiscovery.Model{{ID: "gpt-current-result"}}, + }) + updated, _ = updated.(model).Update(modelPickerModelsDiscoveredMsg{ + providerID: "chatgpt", endpointKey: "subscription", generation: 1, err: errors.New("old refresh failed"), + }) + next := updated.(model) + if strings.Contains(next.modelPickerOverlay(100), "old refresh failed") { + t.Fatal("a superseded request overwrote the current discovery status") + } +} + +type subscriptionTransport func(*http.Request) (*http.Response, error) + +func (f subscriptionTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } + +func TestSubscriptionSetupDiscoveryUsesOAuthAccount(t *testing.T) { + for _, entryPoint := range []string{"wizard", "setup"} { + t.Run(entryPoint, func(t *testing.T) { + m := subscriptionTestModel(t) + store, err := oauth.NewStore(oauth.StoreOptions{}) + if err != nil { + t.Fatal(err) + } + if err := store.Save(oauth.ProviderKey("chatgpt"), oauth.Token{ + AccessToken: "test-subscription-bearer", Account: "test-subscription-account", ExpiresAt: time.Now().Add(time.Hour), + }); err != nil { + t.Fatal(err) + } + previousTransport := http.DefaultTransport + t.Cleanup(func() { http.DefaultTransport = previousTransport }) + var liveRequests int + http.DefaultTransport = subscriptionTransport(func(r *http.Request) (*http.Response, error) { + body := `{}` + if r.URL.Host == "chatgpt.com" { + liveRequests++ + if r.Header.Get("Authorization") != "Bearer test-subscription-bearer" || r.Header.Get("chatgpt-account-id") != "test-subscription-account" { + t.Error("setup discovery did not use the bearer and account from the same OAuth login") + } + body = `{"models":[{"slug":"gpt-future-coder"}]}` + } else if r.URL.Host != "models.dev" { + t.Fatalf("unexpected external request: %s", r.URL.Host) + } + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil + }) + var cmd tea.Cmd + if entryPoint == "wizard" { + provider, _ := providercatalog.Get("chatgpt") + m.providerWizard = &providerWizardState{providers: []providercatalog.Descriptor{provider}, step: providerWizardStepModel} + cmd = m.providerModelDiscoveryCmd() + } else { + m.setup.providers = []SetupProviderOption{{ID: "chatgpt"}} + cmd = m.setupModelDiscoveryCmd(1) + } + if cmd == nil { + t.Fatal("missing setup discovery command") + } + switch msg := cmd().(type) { + case providerModelsDiscoveredMsg: + if msg.err != nil || len(msg.models) != 1 { + t.Fatalf("wizard discovery failed: %v", msg.err) + } + case setupModelsDiscoveredMsg: + if msg.err != nil || len(msg.models) != 1 { + t.Fatalf("first-run discovery failed: %v", msg.err) + } + default: + t.Fatalf("unexpected discovery message %T", msg) + } + if liveRequests != 1 { + t.Fatalf("live discovery requests = %d, want 1", liveRequests) + } + }) + } +} diff --git a/internal/tui/command_center.go b/internal/tui/command_center.go index 8a766e1910..0c727d1b09 100644 --- a/internal/tui/command_center.go +++ b/internal/tui/command_center.go @@ -781,8 +781,9 @@ func (m model) resolveModelSwitchTarget(registry modelregistry.Registry, args st }, true } if provider, ok := m.activeProviderDescriptor(); ok { + discovered, _ := m.discoveredModelsForActiveRoute() for _, candidate := range providerModelSwitchCandidates(provider.ID, args) { - for _, model := range m.modelPickerLiveByProvider[provider.ID] { + for _, model := range discovered { if strings.EqualFold(model.ID, candidate) { return modelSwitchTarget{modelID: model.ID}, true } diff --git a/internal/tui/model.go b/internal/tui/model.go index 2ac1fddde2..04ec7a8cd5 100644 --- a/internal/tui/model.go +++ b/internal/tui/model.go @@ -577,6 +577,10 @@ type model struct { // catalog descriptor ID), so /model shows each provider's real current models — // the same list the provider-setup wizard discovers — not the static catalog. modelPickerLiveByProvider map[string][]providermodeldiscovery.Model + // Discovery errors and generations belong to the provider lookup, not the + // active model, so concurrent results cannot clear another account's status. + modelPickerErrorsByProvider map[string]string + modelPickerDiscoveryGeneration int // ollamaContextWindowByModel holds context-window sizes fetched from a local // Ollama daemon's native /api/show endpoint (keyed by model name), for // custom/local models that have no curated-catalog entry and whose @@ -2093,6 +2097,11 @@ func (m model) updateModel(msg tea.Msg) (tea.Model, tea.Cmd) { if m.noBlockingModal() { return m, readClipboardImageCmd() } + case keyCtrl(msg, 'r'): + if m.picker != nil && m.picker.kind == pickerModel { + m.modelPickerDiscoveryGeneration++ + return m, m.modelPickerDiscoveryCmds() + } case keyCtrl(msg, 'f'): if m.picker != nil && m.picker.kind == pickerModel { if m.modelPickerIsLoading() { @@ -3214,7 +3223,14 @@ func (m model) updateModel(msg tea.Msg) (tea.Model, tea.Cmd) { case setupOAuthDeviceMsg: return m.applySetupOAuthDeviceCode(msg) case modelPickerModelsDiscoveredMsg: - return m.applyModelPickerModelsDiscovered(msg), nil + if msg.generation != 0 && msg.generation != m.modelPickerDiscoveryGeneration { + return m, nil + } + m = m.applyModelPickerModelsDiscovered(msg) + if msg.showList { + m.transcript = reduceTranscript(m.transcript, transcriptAction{kind: actionAppendSystem, text: m.modelListText()}) + } + return m, nil case tea.ColorProfileMsg: m.petColorProfile = msg.Profile return m, nil @@ -5124,6 +5140,12 @@ func (m model) dispatchCommand(command parsedCommand) (tea.Model, tea.Cmd) { m.transcript = reduceTranscript(m.transcript, transcriptAction{kind: actionAppendSystem, text: m.providerText()}) return m, nil case commandModel: + if arg := strings.ToLower(strings.TrimSpace(command.text)); arg == "list" || arg == "ls" { + m.modelPickerDiscoveryGeneration++ + if cmd := m.modelListDiscoveryCmd(); cmd != nil { + return m, cmd + } + } if strings.TrimSpace(command.text) == "" { if m.pending { m.transcript = reduceTranscript(m.transcript, transcriptAction{kind: actionAppendSystem, text: pickerBusyText(command.name)}) diff --git a/internal/tui/model_catalog.go b/internal/tui/model_catalog.go index 645cc1309c..54edf1318e 100644 --- a/internal/tui/model_catalog.go +++ b/internal/tui/model_catalog.go @@ -5,6 +5,7 @@ import ( "sort" "strings" + "github.com/Twigpine/zero/internal/config" "github.com/Twigpine/zero/internal/modelregistry" "github.com/Twigpine/zero/internal/providermodeldiscovery" ) @@ -24,12 +25,26 @@ func (m model) modelListText() string { return models[i].Provider < models[j].Provider }) modelLines := []string{} - for _, model := range models { - marker := " " - if activeID != "" && model.ID == activeID { - marker = "*" + source := "global model registry" + if config.HasProviderProfile(m.providerProfile) { + source = "fallback suggestions (unverified)" + if _, ok := m.discoveredModelsForActiveRoute(); ok { + source = "live provider discovery" + } + // Keep the configured model visible even if it is no longer advertised; + // an explicit saved selection is never migrated by catalog refresh. + modelLines = append(modelLines, fmt.Sprintf("* %s (%s) - current selection", m.modelName, m.providerName)) + for _, item := range m.savedProviderModelPickerItems(m.providerProfile, m.providerName, m.modelName) { + modelLines = append(modelLines, fmt.Sprintf(" %s (%s) - %s", item.Value, m.providerName, item.Label)) + } + } else { + for _, model := range models { + marker := " " + if activeID != "" && model.ID == activeID { + marker = "*" + } + modelLines = append(modelLines, fmt.Sprintf("%s %s (%s) - %s", marker, model.ID, model.Provider, model.DisplayName)) } - modelLines = append(modelLines, fmt.Sprintf("%s %s (%s) - %s", marker, model.ID, model.Provider, model.DisplayName)) } return renderCommandOutput(commandOutput{ Title: "Models", @@ -41,6 +56,7 @@ func (m model) modelListText() string { "Active model: " + displayValue(m.modelName, "none"), "provider: " + displayValue(m.providerName, "none"), "effort: " + m.effortDisplay(), + "model source: " + source, }, }, { @@ -48,7 +64,7 @@ func (m model) modelListText() string { Lines: modelLines, }, }, - Hints: []string{"use /model to switch this TUI session"}, + Hints: append(m.modelPickerDiscoveryNotices(), "use /model to switch this TUI session; /model list refreshes availability"), }) } diff --git a/internal/tui/onboarding.go b/internal/tui/onboarding.go index 0029877867..560c43aa25 100644 --- a/internal/tui/onboarding.go +++ b/internal/tui/onboarding.go @@ -943,8 +943,9 @@ func (m model) setupModelDiscoveryCmd(gen uint64) tea.Cmd { baseSecrets := []string{m.setup.apiKey.Value()} discover := m.discoverProviderModels if discover == nil { + discoveryOptions := m.modelPickerDiscoveryOptions(providerWizardDiscoveryProfile(provider, pastedKey, m.setupBaseURL(option))) discover = func(ctx context.Context, profile config.ProviderProfile) ([]providermodeldiscovery.Model, error) { - return providermodeldiscovery.DiscoverCatalog(ctx, provider, profile, providermodeldiscovery.Options{}) + return providermodeldiscovery.DiscoverCatalog(ctx, provider, profile, discoveryOptions) } } providerID := provider.ID diff --git a/internal/tui/picker.go b/internal/tui/picker.go index 0490ff7516..73fd3cb473 100644 --- a/internal/tui/picker.go +++ b/internal/tui/picker.go @@ -2,12 +2,14 @@ package tui import ( "context" + "fmt" "os" "sort" "strings" "time" tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/ansi" "github.com/Twigpine/zero/internal/config" "github.com/Twigpine/zero/internal/modelregistry" @@ -16,6 +18,7 @@ import ( "github.com/Twigpine/zero/internal/providermodelcatalog" "github.com/Twigpine/zero/internal/providermodeldiscovery" "github.com/Twigpine/zero/internal/providers" + "github.com/Twigpine/zero/internal/redaction" ) // pickerKind identifies which command a picker selection feeds back into. @@ -386,6 +389,7 @@ func (m model) openModelPicker() (model, tea.Cmd) { } m.picker = picker m.clearModelPickerLoadState() + m.modelPickerDiscoveryGeneration++ // Live-discover every usable provider's real models in the background. The list // shows immediately from the static catalog and each provider's section refreshes // as its discovery returns — no blocking overlay. @@ -452,16 +456,67 @@ func (m model) modelPickerProviderDiscoveryCmd(descriptor providercatalog.Descri k = resolved } } - models, err := discover(ctx, providerWizardDiscoveryProfile(descriptor, k, authed.BaseURL)) + discoveryProfile := providerWizardDiscoveryProfile(descriptor, k, authed.BaseURL) + discoveryProfile.Name = authed.Name + models, err := discover(ctx, discoveryProfile) return modelPickerModelsDiscoveredMsg{ providerID: providerID, endpointKey: endpointKey, models: models, err: err, + secrets: []string{k, authed.APIKey, authed.AuthHeaderValue}, + generation: m.modelPickerDiscoveryGeneration, } } } +// modelListDiscoveryCmd refreshes the active account before printing /model list. +// The popup and text command share both the discovery path and its cached results. +func (m model) modelListDiscoveryCmd() tea.Cmd { + descriptor, ok := m.activeProviderDescriptor() + if !ok || !config.HasProviderProfile(m.providerProfile) { + return nil + } + cmd := m.modelPickerProviderDiscoveryCmd(descriptor, m.providerProfile) + if cmd == nil { + return nil + } + return func() tea.Msg { + msg := cmd().(modelPickerModelsDiscoveredMsg) + msg.showList = true + return msg + } +} + +func (m model) modelPickerDiscoveryNotices() []string { + var notices []string + if status := strings.TrimSpace(m.modelPickerLoadError); status != "" { + notices = append(notices, status) + } + for _, profile := range m.modelPickerProviders() { + descriptor, ok := m.descriptorForProfile(profile) + if !ok { + continue + } + key := providerEndpointKey(profile, descriptor) + failure := m.modelPickerErrorsByProvider[key] + if failure == "" { + failure = m.modelPickerErrorsByProvider[descriptor.ID] + } + label := firstProviderDisplayValue(profile.Name, descriptor.Name) + if failure != "" { + source := "fallback suggestions (unverified)" + if len(m.modelPickerLiveByProvider[key]) > 0 || len(m.modelPickerLiveByProvider[descriptor.ID]) > 0 { + source = "previously discovered models" + } + notices = append(notices, fmt.Sprintf("%s: %s; refresh failed: %s. Ctrl+R to retry.", label, source, failure)) + } else if descriptor.ID == "chatgpt" && len(m.modelPickerLiveByProvider[key]) == 0 && len(m.modelPickerLiveByProvider[descriptor.ID]) == 0 { + notices = append(notices, label+": fallback suggestions (unverified). Ctrl+R to refresh.") + } + } + return notices +} + func (m model) modelPickerDiscoveryOptions(profile config.ProviderProfile) providermodeldiscovery.Options { oauthResolver, loginKey := providers.OAuthLoginForProfile(profile) return providermodeldiscovery.Options{ @@ -941,6 +996,9 @@ type modelPickerModelsDiscoveredMsg struct { endpointKey string models []providermodeldiscovery.Model err error + secrets []string + showList bool + generation int } // ollamaContextWindowDiscoveredMsg carries the result of an async /api/show @@ -1027,6 +1085,21 @@ func profileMatchesProviderBaseURL(profile config.ProviderProfile, provider prov func (m model) applyModelPickerModelsDiscovered(msg modelPickerModelsDiscoveredMsg) model { m.modelPickerLoading = false m.modelPickerLoadingProviderID = "" + key := firstProviderDisplayValue(msg.endpointKey, msg.providerID) + errorsByProvider := make(map[string]string, len(m.modelPickerErrorsByProvider)+1) + for k, v := range m.modelPickerErrorsByProvider { + errorsByProvider[k] = v + } + delete(errorsByProvider, key) + if msg.err != nil { + // Normalize terminal controls before matching: removing a control after + // redaction could reassemble a split credential in the rendered message. + message := sanitizeCardField(ansi.Strip(msg.err.Error())) + errorsByProvider[key] = truncateTUIOutput(redaction.RedactString(message, redaction.Options{ExtraSecretValues: msg.secrets}), 240) + } else if len(msg.models) == 0 { + errorsByProvider[key] = "models endpoint returned no visible coding models" + } + m.modelPickerErrorsByProvider = errorsByProvider if msg.err != nil || len(msg.models) == 0 { return m } @@ -1038,7 +1111,9 @@ func (m model) applyModelPickerModelsDiscovered(msg modelPickerModelsDiscoveredM if msg.endpointKey != "" { newMap[msg.endpointKey] = modelsCopy } - if msg.providerID != "" && (!genericProviderCatalogID(msg.providerID) || msg.endpointKey == "") { + // Subscription catalogs belong to the account/profile, so a second ChatGPT + // login must not overwrite another profile's entitlements under a shared ID. + if msg.providerID != "" && ((!genericProviderCatalogID(msg.providerID) && msg.providerID != "chatgpt") || msg.endpointKey == "") { newMap[msg.providerID] = modelsCopy } m.modelPickerLiveByProvider = newMap diff --git a/internal/tui/provider_wizard_discovery.go b/internal/tui/provider_wizard_discovery.go index 564735fd49..ea2f26f6d2 100644 --- a/internal/tui/provider_wizard_discovery.go +++ b/internal/tui/provider_wizard_discovery.go @@ -235,8 +235,11 @@ func (m model) providerModelDiscoveryCmd() tea.Cmd { needOAuthToken := strings.TrimSpace(pastedKey) == "" && provider.OAuth && !provider.OAuthMintsKey discover := m.discoverProviderModels if discover == nil { + // Resolve ownership before materializing an OAuth bearer as APIKey for + // the request: a materialized bearer otherwise looks like explicit key auth. + discoveryOptions := m.modelPickerDiscoveryOptions(providerWizardDiscoveryProfile(provider, pastedKey, wizard.baseURL)) discover = func(ctx context.Context, profile config.ProviderProfile) ([]providermodeldiscovery.Model, error) { - return providermodeldiscovery.DiscoverCatalog(ctx, provider, profile, providermodeldiscovery.Options{}) + return providermodeldiscovery.DiscoverCatalog(ctx, provider, profile, discoveryOptions) } } diff --git a/internal/tui/view.go b/internal/tui/view.go index 71d7f941a1..e27d55e037 100644 --- a/internal/tui/view.go +++ b/internal/tui/view.go @@ -1071,8 +1071,10 @@ func (m model) renderModelPickerOverlay(width, start, count int) string { searchInset := lipgloss.Width("❯ ") searchPrefix := transparentSurface(zeroTheme.ink).Render(strings.Repeat(" ", searchInset)) lines = append(lines, fillPaletteLine(searchPrefix+renderModelPickerSearchLine(m.picker.query, maxInt(1, innerWidth-searchInset)), innerWidth, transparentSurface)) - if status := strings.TrimSpace(m.modelPickerLoadError); status != "" { - lines = append(lines, fillPaletteLine(searchPrefix+zeroTheme.faint.Render(status), innerWidth, transparentSurface)) + for _, status := range m.modelPickerDiscoveryNotices() { + for _, line := range strings.Split(ansi.Wrap(status, maxInt(1, innerWidth-searchInset), ""), "\n") { + lines = append(lines, fillPaletteLine(searchPrefix+zeroTheme.faint.Render(line), innerWidth, transparentSurface)) + } } lines = append(lines, zeroTheme.line.Render(strings.Repeat("─", innerWidth))) lastGroup := "" From c0b6d59ae4b5436ee1e42c2efdb03c856ea1c3b5 Mon Sep 17 00:00:00 2001 From: oniisanlabs <1436535+oniisanlabs@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:56:52 +0100 Subject: [PATCH 02/13] fix(tui): use working retry hints in model list output Use /model list in transcript discovery notices and retain Ctrl+R in the picker. Cover both unverified fallback and failed-discovery hints with a regression test. Refs Twigpine/zero#1177 --- internal/tui/chatgpt_models_test.go | 23 +++++++++++++++++++++++ internal/tui/model_catalog.go | 2 +- internal/tui/picker.go | 6 +++--- internal/tui/view.go | 2 +- 4 files changed, 28 insertions(+), 5 deletions(-) diff --git a/internal/tui/chatgpt_models_test.go b/internal/tui/chatgpt_models_test.go index 0d1eb89813..c4a2cb5974 100644 --- a/internal/tui/chatgpt_models_test.go +++ b/internal/tui/chatgpt_models_test.go @@ -93,6 +93,29 @@ func TestSubscriptionFallbackSuggestionsAreUnverified(t *testing.T) { } } +func TestSubscriptionDiscoveryHintsMatchTheirEntryPoint(t *testing.T) { + for _, failed := range []bool{false, true} { + t.Run(fmt.Sprintf("failed-%v", failed), func(t *testing.T) { + m := subscriptionTestModel(t) + action := "refresh" + if failed { + action = "retry" + m = m.applyModelPickerModelsDiscovered(modelPickerModelsDiscoveredMsg{ + providerID: "chatgpt", endpointKey: "subscription", err: errors.New("expired login"), + }) + } + text := m.modelListText() + if strings.Contains(text, "Ctrl+R") || !strings.Contains(text, "Run /model list to "+action) { + t.Fatalf("transcript must offer a usable %s command instead of the picker shortcut:\n%s", action, text) + } + m.picker = m.newModelPicker() + if text := m.modelPickerOverlay(100); !strings.Contains(text, "Ctrl+R") || strings.Contains(text, "Run /model list") { + t.Fatalf("picker must retain its keyboard shortcut:\n%s", text) + } + }) + } +} + func TestSubscriptionModelListRefreshesWithoutOpeningPicker(t *testing.T) { m := subscriptionTestModel(t) m.discoverProviderModels = func(_ context.Context, profile config.ProviderProfile) ([]providermodeldiscovery.Model, error) { diff --git a/internal/tui/model_catalog.go b/internal/tui/model_catalog.go index 54edf1318e..3be5db40ca 100644 --- a/internal/tui/model_catalog.go +++ b/internal/tui/model_catalog.go @@ -64,7 +64,7 @@ func (m model) modelListText() string { Lines: modelLines, }, }, - Hints: append(m.modelPickerDiscoveryNotices(), "use /model to switch this TUI session; /model list refreshes availability"), + Hints: append(m.modelPickerDiscoveryNotices("Run /model list"), "use /model to switch this TUI session; /model list refreshes availability"), }) } diff --git a/internal/tui/picker.go b/internal/tui/picker.go index 73fd3cb473..38d0dc31b4 100644 --- a/internal/tui/picker.go +++ b/internal/tui/picker.go @@ -488,7 +488,7 @@ func (m model) modelListDiscoveryCmd() tea.Cmd { } } -func (m model) modelPickerDiscoveryNotices() []string { +func (m model) modelPickerDiscoveryNotices(refreshAction string) []string { var notices []string if status := strings.TrimSpace(m.modelPickerLoadError); status != "" { notices = append(notices, status) @@ -509,9 +509,9 @@ func (m model) modelPickerDiscoveryNotices() []string { if len(m.modelPickerLiveByProvider[key]) > 0 || len(m.modelPickerLiveByProvider[descriptor.ID]) > 0 { source = "previously discovered models" } - notices = append(notices, fmt.Sprintf("%s: %s; refresh failed: %s. Ctrl+R to retry.", label, source, failure)) + notices = append(notices, fmt.Sprintf("%s: %s; refresh failed: %s. %s to retry.", label, source, failure, refreshAction)) } else if descriptor.ID == "chatgpt" && len(m.modelPickerLiveByProvider[key]) == 0 && len(m.modelPickerLiveByProvider[descriptor.ID]) == 0 { - notices = append(notices, label+": fallback suggestions (unverified). Ctrl+R to refresh.") + notices = append(notices, label+": fallback suggestions (unverified). "+refreshAction+" to refresh.") } } return notices diff --git a/internal/tui/view.go b/internal/tui/view.go index e27d55e037..0e3b2b942d 100644 --- a/internal/tui/view.go +++ b/internal/tui/view.go @@ -1071,7 +1071,7 @@ func (m model) renderModelPickerOverlay(width, start, count int) string { searchInset := lipgloss.Width("❯ ") searchPrefix := transparentSurface(zeroTheme.ink).Render(strings.Repeat(" ", searchInset)) lines = append(lines, fillPaletteLine(searchPrefix+renderModelPickerSearchLine(m.picker.query, maxInt(1, innerWidth-searchInset)), innerWidth, transparentSurface)) - for _, status := range m.modelPickerDiscoveryNotices() { + for _, status := range m.modelPickerDiscoveryNotices("Ctrl+R") { for _, line := range strings.Split(ansi.Wrap(status, maxInt(1, innerWidth-searchInset), ""), "\n") { lines = append(lines, fillPaletteLine(searchPrefix+zeroTheme.faint.Render(line), innerWidth, transparentSurface)) } From 81a434ea8c5e26874afbbf52b0c3947d9a38d96a Mon Sep 17 00:00:00 2001 From: oniisanlabs <1436535+oniisanlabs@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:31:27 +0100 Subject: [PATCH 03/13] fix(tui): scope discovery notices to refreshed accounts Limit model-list notices to the active profile and retain all-profile notices in the picker. Prevent a canonical ChatGPT profile cache from being borrowed by another account, and share wrapped notice rows with mouse hit testing. Cover inactive-profile fallback/failure cases, canonical profile lookup, and pointer selection after notices. Refs Twigpine/zero#1177 --- internal/tui/chatgpt_models_test.go | 67 +++++++++++++++++++++++++++-- internal/tui/model_catalog.go | 2 +- internal/tui/mouse.go | 5 +-- internal/tui/mouse_test.go | 30 +++++++++++++ internal/tui/picker.go | 24 ++++++++--- internal/tui/view.go | 16 +++++-- 6 files changed, 125 insertions(+), 19 deletions(-) diff --git a/internal/tui/chatgpt_models_test.go b/internal/tui/chatgpt_models_test.go index c4a2cb5974..71b703eddf 100644 --- a/internal/tui/chatgpt_models_test.go +++ b/internal/tui/chatgpt_models_test.go @@ -48,7 +48,7 @@ func subscriptionTestModel(t *testing.T) model { func TestSubscriptionModelListIncludesDiscoveredModels(t *testing.T) { m := subscriptionTestModel(t) m = m.applyModelPickerModelsDiscovered(modelPickerModelsDiscoveredMsg{ - providerID: "chatgpt", models: []providermodeldiscovery.Model{{ID: "gpt-future-coder", Description: "Future coder"}}, + providerID: "chatgpt", endpointKey: "subscription", models: []providermodeldiscovery.Model{{ID: "gpt-future-coder", Description: "Future coder"}}, }) text := m.modelListText() for _, want := range []string{"gpt-future-coder", "subscription", "live"} { @@ -69,7 +69,7 @@ func TestSubscriptionPickerReportsDiscoveryFailureAndRecovery(t *testing.T) { m := subscriptionTestModel(t) m.picker = m.newModelPicker() m = m.applyModelPickerModelsDiscovered(modelPickerModelsDiscoveredMsg{ - providerID: "chatgpt", err: errors.New("expired login"), + providerID: "chatgpt", endpointKey: "subscription", err: errors.New("expired login"), }) text := m.modelPickerOverlay(100) for _, want := range []string{"expired login", "fallback", "Ctrl+R"} { @@ -78,7 +78,7 @@ func TestSubscriptionPickerReportsDiscoveryFailureAndRecovery(t *testing.T) { } } m = m.applyModelPickerModelsDiscovered(modelPickerModelsDiscoveredMsg{ - providerID: "chatgpt", models: []providermodeldiscovery.Model{{ID: "gpt-future-coder"}}, + providerID: "chatgpt", endpointKey: "subscription", models: []providermodeldiscovery.Model{{ID: "gpt-future-coder"}}, }) if text := m.modelPickerOverlay(100); strings.Contains(text, "expired login") || strings.Contains(text, "unverified") { t.Fatalf("successful refresh kept fallback warning:\n%s", text) @@ -116,6 +116,65 @@ func TestSubscriptionDiscoveryHintsMatchTheirEntryPoint(t *testing.T) { } } +func TestSubscriptionModelListNoticesOnlyDescribeRefreshedProfile(t *testing.T) { + for _, failed := range []bool{false, true} { + t.Run(fmt.Sprintf("inactive-failed-%v", failed), func(t *testing.T) { + m := subscriptionTestModel(t) + inactive := m.providerProfile + inactive.Name = "chatgpt" + m.savedProviders = []config.ProviderProfile{m.providerProfile, inactive} + if failed { + m = m.applyModelPickerModelsDiscovered(modelPickerModelsDiscoveredMsg{ + providerID: "chatgpt", endpointKey: "chatgpt", err: errors.New("inactive login expired"), + }) + } + var refreshed []string + m.discoverProviderModels = func(_ context.Context, profile config.ProviderProfile) ([]providermodeldiscovery.Model, error) { + refreshed = append(refreshed, profile.Name) + return []providermodeldiscovery.Model{{ID: "gpt-active-account"}}, nil + } + m.input.SetValue("/model list") + updated, cmd := m.Update(testKey(tea.KeyEnter)) + if cmd == nil { + t.Fatal("missing active-profile refresh") + } + updated, _ = updated.(model).Update(cmd()) + next := updated.(model) + if len(refreshed) != 1 || refreshed[0] != "subscription" { + t.Fatalf("/model list refreshed %#v, want only the active profile", refreshed) + } + if text := next.modelListText(); strings.Contains(text, "unverified") || strings.Contains(text, "inactive login expired") { + t.Fatalf("active-profile transcript advertised an inactive profile's refresh:\n%s", text) + } + next.picker = next.newModelPicker() + if text := next.modelPickerOverlay(110); !strings.Contains(text, "unverified") || !strings.Contains(text, "Ctrl+R") || (failed && !strings.Contains(text, "inactive login expired")) { + t.Fatalf("picker must keep inactive-profile notices with its all-profile refresh:\n%s", text) + } + }) + } +} + +func TestSubscriptionCanonicalProfileDoesNotSupplyAnotherAccount(t *testing.T) { + for _, layer := range []string{"active route", "picker rows"} { + t.Run(layer, func(t *testing.T) { + m := subscriptionTestModel(t) + m = m.applyModelPickerModelsDiscovered(modelPickerModelsDiscoveredMsg{ + providerID: "chatgpt", endpointKey: "chatgpt", models: []providermodeldiscovery.Model{{ID: "gpt-inactive-account"}}, + }) + if layer == "active route" { + if models, ok := m.discoveredModelsForActiveRoute(); ok { + t.Fatalf("active profile borrowed the canonical profile's models: %#v", models) + } + } else { + items := m.savedProviderModelPickerItems(m.providerProfile, m.providerName, m.modelName) + if contains(pickerValues(items), "gpt-inactive-account") { + t.Fatal("active picker rows borrowed the canonical profile's models") + } + } + }) + } +} + func TestSubscriptionModelListRefreshesWithoutOpeningPicker(t *testing.T) { m := subscriptionTestModel(t) m.discoverProviderModels = func(_ context.Context, profile config.ProviderProfile) ([]providermodeldiscovery.Model, error) { @@ -215,7 +274,7 @@ func TestSubscriptionPickerRedactsDiscoveryErrors(t *testing.T) { m := subscriptionTestModel(t) m.picker = m.newModelPicker() m = m.applyModelPickerModelsDiscovered(modelPickerModelsDiscoveredMsg{ - providerID: "chatgpt", err: errors.New("request failed with opaque-" + split + "subscription-bearer"), secrets: []string{secret}, + providerID: "chatgpt", endpointKey: "subscription", err: errors.New("request failed with opaque-" + split + "subscription-bearer"), secrets: []string{secret}, }) if text := m.modelPickerOverlay(100); strings.Contains(text, "subscription-bearer") || !strings.Contains(text, "request failed") { t.Fatalf("discovery error was not safely rendered: %s", text) diff --git a/internal/tui/model_catalog.go b/internal/tui/model_catalog.go index 3be5db40ca..b31d32983e 100644 --- a/internal/tui/model_catalog.go +++ b/internal/tui/model_catalog.go @@ -64,7 +64,7 @@ func (m model) modelListText() string { Lines: modelLines, }, }, - Hints: append(m.modelPickerDiscoveryNotices("Run /model list"), "use /model to switch this TUI session; /model list refreshes availability"), + Hints: append(m.modelPickerDiscoveryNotices([]config.ProviderProfile{m.providerProfile}, "Run /model list"), "use /model to switch this TUI session; /model list refreshes availability"), }) } diff --git a/internal/tui/mouse.go b/internal/tui/mouse.go index 0a20636fca..50f5bb9c06 100644 --- a/internal/tui/mouse.go +++ b/internal/tui/mouse.go @@ -484,11 +484,8 @@ func (m *model) selectModelPickerAtMouse(msg tea.MouseMsg) (mouseSelectionTarget if !ok { return mouseSelectionTarget{}, false } - line := 3 - if strings.TrimSpace(m.modelPickerLoadError) != "" { - line++ - } innerWidth := maxInt(1, modelPickerOverlayWidth(width, m.picker)-4) + line := 3 + len(m.modelPickerDiscoveryNoticeLines(innerWidth)) lastGroup := "" for index := start; index < start+count; index++ { item := m.picker.items[index] diff --git a/internal/tui/mouse_test.go b/internal/tui/mouse_test.go index 3539b60b35..5e039fb751 100644 --- a/internal/tui/mouse_test.go +++ b/internal/tui/mouse_test.go @@ -1035,6 +1035,36 @@ func TestModelPickerMouseUsesRenderedRowBoundaries(t *testing.T) { } } +func TestModelPickerMouseAccountsForWrappedDiscoveryNotices(t *testing.T) { + for _, label := range []string{"target-row", "refresh failed"} { + t.Run(label, func(t *testing.T) { + m := subscriptionTestModel(t) + m.width, m.height = 80, 40 + m.modelPickerErrorsByProvider = map[string]string{"subscription": "login expired; authenticate again before refreshing account models"} + m.picker = &commandPicker{kind: pickerModel, items: []pickerItem{ + {Group: "Models", Label: "first-row", Value: "first"}, + {Group: "Models", Label: "target-row", Value: "target"}, + }} + overlay := m.modelPickerOverlay(80) + rect := m.overlayMouseRect(len(viewLines(overlay)), 80) + for row, text := range strings.Split(plainRender(t, overlay), "\n") { + if !strings.Contains(text, label) { + continue + } + target, ok := m.selectModelPickerAtMouse(testMouseClick(tea.MouseLeft, 40, rect.y+row)) + if label == "target-row" && (!ok || target.Value != "target") { + t.Fatalf("click on rendered model selected %#v, ok=%v; want target", target, ok) + } + if label == "refresh failed" && ok { + t.Fatalf("click on discovery notice selected %#v", target) + } + return + } + t.Fatalf("rendered picker lacks %q", label) + }) + } +} + func TestModelPickerFitsMultilineRowsToViewport(t *testing.T) { for _, selected := range []int{0, 5, 9} { m := mouseTestModel() diff --git a/internal/tui/picker.go b/internal/tui/picker.go index 38d0dc31b4..8a8eae87d5 100644 --- a/internal/tui/picker.go +++ b/internal/tui/picker.go @@ -306,7 +306,8 @@ func (m model) savedProviderModelPickerItems(profile config.ProviderProfile, act if endpointKey != "" { discovered = m.modelPickerLiveByProvider[endpointKey] } - if len(discovered) == 0 && hasDescriptor && !genericProviderCatalogID(descriptor.ID) { + if len(discovered) == 0 && hasDescriptor && !genericProviderCatalogID(descriptor.ID) && + (descriptor.ID != "chatgpt" || strings.TrimSpace(profile.Name) == "") { discovered = m.modelPickerLiveByProvider[descriptor.ID] } @@ -488,29 +489,35 @@ func (m model) modelListDiscoveryCmd() tea.Cmd { } } -func (m model) modelPickerDiscoveryNotices(refreshAction string) []string { +// The caller supplies only profiles that its refresh action can refresh. +func (m model) modelPickerDiscoveryNotices(profiles []config.ProviderProfile, refreshAction string) []string { var notices []string if status := strings.TrimSpace(m.modelPickerLoadError); status != "" { notices = append(notices, status) } - for _, profile := range m.modelPickerProviders() { + for _, profile := range profiles { descriptor, ok := m.descriptorForProfile(profile) if !ok { continue } key := providerEndpointKey(profile, descriptor) failure := m.modelPickerErrorsByProvider[key] - if failure == "" { + catalogFallback := descriptor.ID != "chatgpt" || strings.TrimSpace(profile.Name) == "" + if failure == "" && catalogFallback { failure = m.modelPickerErrorsByProvider[descriptor.ID] } + discovered := m.modelPickerLiveByProvider[key] + if len(discovered) == 0 && catalogFallback { + discovered = m.modelPickerLiveByProvider[descriptor.ID] + } label := firstProviderDisplayValue(profile.Name, descriptor.Name) if failure != "" { source := "fallback suggestions (unverified)" - if len(m.modelPickerLiveByProvider[key]) > 0 || len(m.modelPickerLiveByProvider[descriptor.ID]) > 0 { + if len(discovered) > 0 { source = "previously discovered models" } notices = append(notices, fmt.Sprintf("%s: %s; refresh failed: %s. %s to retry.", label, source, failure, refreshAction)) - } else if descriptor.ID == "chatgpt" && len(m.modelPickerLiveByProvider[key]) == 0 && len(m.modelPickerLiveByProvider[descriptor.ID]) == 0 { + } else if descriptor.ID == "chatgpt" && len(discovered) == 0 { notices = append(notices, label+": fallback suggestions (unverified). "+refreshAction+" to refresh.") } } @@ -957,6 +964,11 @@ func (m model) activeDiscoveryKeys() []string { if key := providerEndpointKey(m.providerProfile, descriptor); key != "" { add(key) } + if hasDescriptor && descriptor.ID == "chatgpt" && strings.TrimSpace(m.providerProfile.Name) != "" { + // The canonical profile may itself be named "chatgpt". Its cache key + // must not become a catalog-wide fallback for a different account. + return keys + } if m.providerProfile.Name != "" { add(m.providerProfile.Name) } diff --git a/internal/tui/view.go b/internal/tui/view.go index 0e3b2b942d..6869b8f311 100644 --- a/internal/tui/view.go +++ b/internal/tui/view.go @@ -1071,10 +1071,8 @@ func (m model) renderModelPickerOverlay(width, start, count int) string { searchInset := lipgloss.Width("❯ ") searchPrefix := transparentSurface(zeroTheme.ink).Render(strings.Repeat(" ", searchInset)) lines = append(lines, fillPaletteLine(searchPrefix+renderModelPickerSearchLine(m.picker.query, maxInt(1, innerWidth-searchInset)), innerWidth, transparentSurface)) - for _, status := range m.modelPickerDiscoveryNotices("Ctrl+R") { - for _, line := range strings.Split(ansi.Wrap(status, maxInt(1, innerWidth-searchInset), ""), "\n") { - lines = append(lines, fillPaletteLine(searchPrefix+zeroTheme.faint.Render(line), innerWidth, transparentSurface)) - } + for _, line := range m.modelPickerDiscoveryNoticeLines(innerWidth) { + lines = append(lines, fillPaletteLine(searchPrefix+zeroTheme.faint.Render(line), innerWidth, transparentSurface)) } lines = append(lines, zeroTheme.line.Render(strings.Repeat("─", innerWidth))) lastGroup := "" @@ -1112,6 +1110,16 @@ func (m model) renderModelPickerOverlay(width, start, count int) string { return centerRenderedBlock(styledBlockFillTitle(overlayWidth, title, lines, zeroTheme.lineStrong, lipgloss.NewStyle()), width) } +// Share wrapped notice rows with mouse hit testing so both agree where models start. +func (m model) modelPickerDiscoveryNoticeLines(innerWidth int) []string { + var lines []string + width := maxInt(1, innerWidth-lipgloss.Width("❯ ")) + for _, status := range m.modelPickerDiscoveryNotices(m.modelPickerProviders(), "Ctrl+R") { + lines = append(lines, strings.Split(ansi.Wrap(status, width, ""), "\n")...) + } + return lines +} + func (m model) modelPickerLoadingOverlay(width int) string { overlayWidth := modelPickerLoadingOverlayWidth(width) innerWidth := maxInt(1, overlayWidth-4) From 3e93ae8ee7dc45f82b0025d4089a8b9bf25b72e1 Mon Sep 17 00:00:00 2001 From: oniisanlabs <1436535+oniisanlabs@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:20:28 +0100 Subject: [PATCH 04/13] fix(chatgpt): normalize invisible error text before redaction --- .../chatgpt_catalog_test.go | 4 +- internal/providermodeldiscovery/discovery.go | 14 +----- internal/providermodeldiscovery/redaction.go | 45 +++++++++++++++++++ internal/tui/chatgpt_models_test.go | 28 +++++++++++- internal/tui/model.go | 5 +++ internal/tui/picker.go | 8 +--- 6 files changed, 81 insertions(+), 23 deletions(-) create mode 100644 internal/providermodeldiscovery/redaction.go diff --git a/internal/providermodeldiscovery/chatgpt_catalog_test.go b/internal/providermodeldiscovery/chatgpt_catalog_test.go index 4af1c3b4f8..cdbbc12a36 100644 --- a/internal/providermodeldiscovery/chatgpt_catalog_test.go +++ b/internal/providermodeldiscovery/chatgpt_catalog_test.go @@ -96,7 +96,7 @@ func TestChatGPTCatalogBoundsOptionalMetadata(t *testing.T) { func TestChatGPTDiscoveryRedactsRefreshedOAuthBearer(t *testing.T) { const oldToken, newToken = "opaque-old-subscription", "opaque-new-subscription" - for _, split := range []string{"", "\x00", "\x1b", "\u0085", "\x1b[31m"} { + for _, split := range []string{"", "\x00", "\x1b", "\u0085", "\x1b[31m", "\u200b", "\u2060", "\ufeff", "\u202e", "\u00ad"} { t.Run(fmt.Sprintf("split-%x", split), func(t *testing.T) { var requests int server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -123,7 +123,7 @@ func TestChatGPTDiscoveryRedactsRefreshedOAuthBearer(t *testing.T) { if err == nil || requests != 2 { t.Fatalf("expected failed refresh retry: requests=%d err=%v", requests, err) } - if strings.Contains(err.Error(), oldToken) || strings.Contains(err.Error(), "new-subscription") { + if !strings.Contains(err.Error(), "expired [REDACTED] and [REDACTED]") || strings.Contains(err.Error(), oldToken) || strings.Contains(err.Error(), "new-subscription") { t.Fatalf("discovery error exposed OAuth bearer: %v", err) } }) diff --git a/internal/providermodeldiscovery/discovery.go b/internal/providermodeldiscovery/discovery.go index 054e484a52..9b1484bd38 100644 --- a/internal/providermodeldiscovery/discovery.go +++ b/internal/providermodeldiscovery/discovery.go @@ -10,16 +10,12 @@ import ( "sort" "strings" "time" - "unicode" - - "github.com/charmbracelet/x/ansi" "github.com/Twigpine/zero/internal/config" "github.com/Twigpine/zero/internal/providercatalog" "github.com/Twigpine/zero/internal/providermodelcatalog" "github.com/Twigpine/zero/internal/providers/openai" "github.com/Twigpine/zero/internal/providers/providerio" - "github.com/Twigpine/zero/internal/redaction" ) const ( @@ -753,16 +749,8 @@ func redactDiscoveryError(err error, profile config.ProviderProfile, secrets ... if err == nil { return nil } - // Normalize before matching so terminal rendering cannot reassemble a - // credential split by an escape sequence or an invisible control byte. - message := strings.Map(func(r rune) rune { - if r == '\n' || r == '\r' || r == '\t' || !unicode.IsControl(r) { - return r - } - return -1 - }, ansi.Strip(err.Error())) secrets = append(secrets, profile.APIKey, profile.AuthHeaderValue) - return fmt.Errorf("%s", redaction.RedactString(message, redaction.Options{ExtraSecretValues: secrets})) + return RedactError(err, secrets...) } func displayProviderName(profile config.ProviderProfile) string { diff --git a/internal/providermodeldiscovery/redaction.go b/internal/providermodeldiscovery/redaction.go new file mode 100644 index 0000000000..cf01e8bb2c --- /dev/null +++ b/internal/providermodeldiscovery/redaction.go @@ -0,0 +1,45 @@ +package providermodeldiscovery + +import ( + "fmt" + "strings" + "unicode" + + "github.com/Twigpine/zero/internal/redaction" + "github.com/charmbracelet/x/ansi" +) + +// RedactError normalizes terminal error text before matching credentials so +// invisible characters cannot split a secret across literal redaction matches. +// Discovery callers and the TUI share this boundary, including injected errors. +func RedactError(err error, secrets ...string) error { + if err == nil { + return nil + } + message := strings.Map(func(r rune) rune { + if unicode.Is(unicode.Cf, r) { + return -1 + } + return r + }, err.Error()) + var terminal strings.Builder + for i := 0; i < len(message); i++ { + // Preserve CSI and terminal string introducers for ANSI stripping. Treat + // other ESC bytes as lone controls, rather than consuming the next letter + // of a credential as a two-byte terminal command. + if message[i] == '\x1b' && (i+1 == len(message) || !strings.ContainsRune("[]PX^_\\", rune(message[i+1]))) { + continue + } + terminal.WriteByte(message[i]) + } + message = strings.Map(func(r rune) rune { + if r == '\n' || r == '\r' || r == '\t' { + return r + } + if unicode.IsControl(r) || unicode.Is(unicode.Cf, r) { + return -1 + } + return r + }, ansi.Strip(terminal.String())) + return fmt.Errorf("%s", redaction.RedactString(message, redaction.Options{ExtraSecretValues: secrets})) +} diff --git a/internal/tui/chatgpt_models_test.go b/internal/tui/chatgpt_models_test.go index 71b703eddf..39d926c678 100644 --- a/internal/tui/chatgpt_models_test.go +++ b/internal/tui/chatgpt_models_test.go @@ -269,14 +269,20 @@ func TestSubscriptionPickerRetriesFromKeyboard(t *testing.T) { func TestSubscriptionPickerRedactsDiscoveryErrors(t *testing.T) { const secret = "opaque-subscription-bearer" - for _, split := range []string{"", "\x00", "\x1b", "\u0085", "\x1b[31m"} { + for _, split := range []string{"", "\x00", "\x1b", "\u0085", "\x1b[31m", "\u200b", "\u2060", "\ufeff", "\u202e", "\u00ad"} { t.Run(fmt.Sprintf("split-%x", split), func(t *testing.T) { m := subscriptionTestModel(t) m.picker = m.newModelPicker() m = m.applyModelPickerModelsDiscovered(modelPickerModelsDiscoveredMsg{ providerID: "chatgpt", endpointKey: "subscription", err: errors.New("request failed with opaque-" + split + "subscription-bearer"), secrets: []string{secret}, }) - if text := m.modelPickerOverlay(100); strings.Contains(text, "subscription-bearer") || !strings.Contains(text, "request failed") { + if got := m.modelPickerErrorsByProvider["subscription"]; got != "request failed with [REDACTED]" { + t.Fatalf("stored error = %q", got) + } + if text := m.modelListText(); !strings.Contains(text, "request failed with [REDACTED]") { + t.Fatalf("transcript error was not redacted: %s", text) + } + if text := m.modelPickerOverlay(100); strings.Contains(text, "subscription-bearer") || !strings.Contains(text, "[REDACTED]") { t.Fatalf("discovery error was not safely rendered: %s", text) } }) @@ -363,3 +369,21 @@ func TestSubscriptionSetupDiscoveryUsesOAuthAccount(t *testing.T) { }) } } + +func TestSubscriptionSupersededModelListStillPrints(t *testing.T) { + m := subscriptionTestModel(t) + m.modelPickerDiscoveryGeneration = 2 + m.modelPickerLoading = true + m.modelPickerLiveByProvider = map[string][]providermodeldiscovery.Model{"subscription": {{ID: "gpt-current-result"}}} + updated, _ := m.Update(modelPickerModelsDiscoveredMsg{ + providerID: "chatgpt", endpointKey: "subscription", generation: 1, showList: true, + models: []providermodeldiscovery.Model{{ID: "gpt-stale-result"}}, + }) + next := updated.(model) + if !transcriptContains(next.transcript, "gpt-current-result") { + t.Fatal("superseded model list never printed current models") + } + if transcriptContains(next.transcript, "gpt-stale-result") || !next.modelPickerLoading { + t.Fatal("superseded list altered current discovery") + } +} diff --git a/internal/tui/model.go b/internal/tui/model.go index 04ec7a8cd5..bac231128c 100644 --- a/internal/tui/model.go +++ b/internal/tui/model.go @@ -3224,6 +3224,11 @@ func (m model) updateModel(msg tea.Msg) (tea.Model, tea.Cmd) { return m.applySetupOAuthDeviceCode(msg) case modelPickerModelsDiscoveredMsg: if msg.generation != 0 && msg.generation != m.modelPickerDiscoveryGeneration { + // Honor an explicit list request using current state without letting + // an older response overwrite the newer discovery or its loading flag. + if msg.showList { + m.transcript = reduceTranscript(m.transcript, transcriptAction{kind: actionAppendSystem, text: m.modelListText()}) + } return m, nil } m = m.applyModelPickerModelsDiscovered(msg) diff --git a/internal/tui/picker.go b/internal/tui/picker.go index 8a8eae87d5..9e49e87d7d 100644 --- a/internal/tui/picker.go +++ b/internal/tui/picker.go @@ -9,7 +9,6 @@ import ( "time" tea "charm.land/bubbletea/v2" - "github.com/charmbracelet/x/ansi" "github.com/Twigpine/zero/internal/config" "github.com/Twigpine/zero/internal/modelregistry" @@ -18,7 +17,6 @@ import ( "github.com/Twigpine/zero/internal/providermodelcatalog" "github.com/Twigpine/zero/internal/providermodeldiscovery" "github.com/Twigpine/zero/internal/providers" - "github.com/Twigpine/zero/internal/redaction" ) // pickerKind identifies which command a picker selection feeds back into. @@ -1104,10 +1102,8 @@ func (m model) applyModelPickerModelsDiscovered(msg modelPickerModelsDiscoveredM } delete(errorsByProvider, key) if msg.err != nil { - // Normalize terminal controls before matching: removing a control after - // redaction could reassemble a split credential in the rendered message. - message := sanitizeCardField(ansi.Strip(msg.err.Error())) - errorsByProvider[key] = truncateTUIOutput(redaction.RedactString(message, redaction.Options{ExtraSecretValues: msg.secrets}), 240) + message := providermodeldiscovery.RedactError(msg.err, msg.secrets...).Error() + errorsByProvider[key] = truncateTUIOutput(sanitizeCardField(message), 240) } else if len(msg.models) == 0 { errorsByProvider[key] = "models endpoint returned no visible coding models" } From 25cb969ed0e2f5e465b69e980fc0e85ab52b8440 Mon Sep 17 00:00:00 2001 From: oniisanlabs <1436535+oniisanlabs@users.noreply.github.com> Date: Thu, 5 Nov 2026 12:57:20 -0500 Subject: [PATCH 05/13] fix(chatgpt): withhold credentials damaged by escapes and cap notices ANSI stripping consumes a CSI's final byte, and any letter is a valid final byte, so "opaque-\x1b[subscription" displayed one byte short of the secret and passed redaction. Compare the displayed text against raw readings that keep the consumed bytes (with and without CSI parameters); if a raw reading matches more secrets, withhold the whole message. Also drop default-ignorable code points and variation selectors (U+034F, U+FE0F, U+180B) that split a secret invisibly, and cap discovery notices in the model picker at four rows so several failing accounts cannot push the model rows and footer out of view. /model list still prints them all. Refs Twigpine/zero#1177 Co-Authored-By: Claude Opus 5.5 --- .../chatgpt_catalog_test.go | 12 ++- internal/providermodeldiscovery/redaction.go | 73 +++++++++++++++++-- .../providermodeldiscovery/redaction_test.go | 48 ++++++++++++ internal/tui/mouse_test.go | 38 ++++++++++ internal/tui/view.go | 34 ++++++++- 5 files changed, 195 insertions(+), 10 deletions(-) create mode 100644 internal/providermodeldiscovery/redaction_test.go diff --git a/internal/providermodeldiscovery/chatgpt_catalog_test.go b/internal/providermodeldiscovery/chatgpt_catalog_test.go index cdbbc12a36..83dfd6cc57 100644 --- a/internal/providermodeldiscovery/chatgpt_catalog_test.go +++ b/internal/providermodeldiscovery/chatgpt_catalog_test.go @@ -2,6 +2,7 @@ package providermodeldiscovery import ( "context" + "errors" "fmt" "net/http" "net/http/httptest" @@ -96,7 +97,10 @@ func TestChatGPTCatalogBoundsOptionalMetadata(t *testing.T) { func TestChatGPTDiscoveryRedactsRefreshedOAuthBearer(t *testing.T) { const oldToken, newToken = "opaque-old-subscription", "opaque-new-subscription" - for _, split := range []string{"", "\x00", "\x1b", "\u0085", "\x1b[31m", "\u200b", "\u2060", "\ufeff", "\u202e", "\u00ad"} { + // A CSI whose final byte is a credential letter consumes that letter, so + // the display would hold a damaged copy; those errors are withheld whole. + withheld := map[string]bool{"\x1b[": true, "\x1b[9": true} + for _, split := range []string{"", "\x00", "\x1b", "\u0085", "\x1b[31m", "\u200b", "\u2060", "\ufeff", "\u202e", "\u00ad", "\u034f", "\ufe0f", "\u180b", "\x1b[", "\x1b[9", "\u009b"} { t.Run(fmt.Sprintf("split-%x", split), func(t *testing.T) { var requests int server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -123,6 +127,12 @@ func TestChatGPTDiscoveryRedactsRefreshedOAuthBearer(t *testing.T) { if err == nil || requests != 2 { t.Fatalf("expected failed refresh retry: requests=%d err=%v", requests, err) } + if withheld[split] { + if !errors.Is(err, errWithheldDiscoveryDetails) { + t.Fatalf("damaged OAuth bearer was not withheld: %q", err) + } + return + } if !strings.Contains(err.Error(), "expired [REDACTED] and [REDACTED]") || strings.Contains(err.Error(), oldToken) || strings.Contains(err.Error(), "new-subscription") { t.Fatalf("discovery error exposed OAuth bearer: %v", err) } diff --git a/internal/providermodeldiscovery/redaction.go b/internal/providermodeldiscovery/redaction.go index cf01e8bb2c..5fd7cf9c3f 100644 --- a/internal/providermodeldiscovery/redaction.go +++ b/internal/providermodeldiscovery/redaction.go @@ -1,6 +1,7 @@ package providermodeldiscovery import ( + "errors" "fmt" "strings" "unicode" @@ -9,6 +10,14 @@ import ( "github.com/charmbracelet/x/ansi" ) +// errWithheldDiscoveryDetails replaces an error whose terminal escapes would +// display a damaged copy of a credential that redaction can no longer match. +var errWithheldDiscoveryDetails = errors.New("model discovery failed; error details withheld because they may contain a credential") + +// redactionSentinel marks each redacted span so the displayed and raw readings +// can be compared. Its NUL bytes cannot survive either reading's control strip. +const redactionSentinel = "\x00redacted\x00" + // RedactError normalizes terminal error text before matching credentials so // invisible characters cannot split a secret across literal redaction matches. // Discovery callers and the TUI share this boundary, including injected errors. @@ -17,11 +26,37 @@ func RedactError(err error, secrets ...string) error { return nil } message := strings.Map(func(r rune) rune { - if unicode.Is(unicode.Cf, r) { + if invisibleRune(r) { return -1 } return r }, err.Error()) + displayed := displayedErrorText(message) + // ANSI stripping consumes a sequence's final byte, and any letter is a valid + // final byte, so the display can hold a credential missing one character. + // A second reading keeps those bytes; if it matches a secret the display + // does not, the display shows a damaged copy and the whole text is withheld. + options := redaction.Options{ExtraSecretValues: secrets, Replacement: redactionSentinel} + shown := strings.Count(redaction.RedactString(displayed, options), redactionSentinel) + for _, keepParameters := range []bool{true, false} { + if strings.Count(redaction.RedactString(rawErrorText(message, keepParameters), options), redactionSentinel) > shown { + return errWithheldDiscoveryDetails + } + } + return fmt.Errorf("%s", redaction.RedactString(displayed, redaction.Options{ExtraSecretValues: secrets})) +} + +// invisibleRune reports runes that render as nothing, so they would split a +// secret without leaving a visible gap. Tab and line breaks stay because they +// render as a break. +func invisibleRune(r rune) bool { + return unicode.Is(unicode.Cf, r) || + unicode.Is(unicode.Other_Default_Ignorable_Code_Point, r) || + unicode.Is(unicode.Variation_Selector, r) +} + +// displayedErrorText strips terminal sequences the way a terminal renders them. +func displayedErrorText(message string) string { var terminal strings.Builder for i := 0; i < len(message); i++ { // Preserve CSI and terminal string introducers for ANSI stripping. Treat @@ -32,14 +67,42 @@ func RedactError(err error, secrets ...string) error { } terminal.WriteByte(message[i]) } - message = strings.Map(func(r rune) rune { + return stripControls(ansi.Strip(terminal.String())) +} + +// rawErrorText drops only escape introducers (ESC [, ESC ] and lone ESC) and +// other controls, keeping every byte a terminal sequence would consume. A CSI +// parameter such as the 9 in ESC [ 9 n can belong to the sequence or to the +// secret, so callers read the text both with and without CSI parameter bytes. +func rawErrorText(message string, keepParameters bool) string { + var raw strings.Builder + for i := 0; i < len(message); i++ { + if message[i] != '\x1b' { + raw.WriteByte(message[i]) + continue + } + if i+1 < len(message) && message[i+1] == ']' { + i++ + } else if i+1 < len(message) && message[i+1] == '[' { + i++ + // Parameter (0x30-0x3F) and intermediate (0x20-0x2F) bytes precede + // the final byte that ANSI stripping also consumes. + for !keepParameters && i+1 < len(message) && message[i+1] >= 0x20 && message[i+1] <= 0x3f { + i++ + } + } + } + return stripControls(raw.String()) +} + +func stripControls(s string) string { + return strings.Map(func(r rune) rune { if r == '\n' || r == '\r' || r == '\t' { return r } - if unicode.IsControl(r) || unicode.Is(unicode.Cf, r) { + if unicode.IsControl(r) || invisibleRune(r) { return -1 } return r - }, ansi.Strip(terminal.String())) - return fmt.Errorf("%s", redaction.RedactString(message, redaction.Options{ExtraSecretValues: secrets})) + }, s) } diff --git a/internal/providermodeldiscovery/redaction_test.go b/internal/providermodeldiscovery/redaction_test.go new file mode 100644 index 0000000000..c07c985e04 --- /dev/null +++ b/internal/providermodeldiscovery/redaction_test.go @@ -0,0 +1,48 @@ +package providermodeldiscovery + +import ( + "errors" + "testing" +) + +func TestRedactErrorWithholdsCredentialDamagedByEscapeSequence(t *testing.T) { + const secret = "opaque-subscription-bearer" + // A secret whose own digit reads as a CSI parameter is damaged the same way. + if err := RedactError(errors.New("expired opaque-\x1b[9subscription now"), "opaque-9subscription"); !errors.Is(err, errWithheldDiscoveryDetails) { + t.Fatalf("digit-led damaged secret was not withheld: %q", err) + } + for _, message := range []string{ + "expired opaque-\x1b[subscription-bearer now", + "expired opaque-\x1b[9subscription-bearer now", + "expired opaque-\x1b[?25subscription-bearer now", + "expired opaque-\x1b]subscription-bearer now", + } { + err := RedactError(errors.New(message), secret) + if !errors.Is(err, errWithheldDiscoveryDetails) { + t.Fatalf("RedactError(%q) = %q, want withheld", message, err) + } + } +} + +func TestRedactErrorKeepsVisibleGapsAndOrdinaryText(t *testing.T) { + const secret = "opaque-subscription-bearer" + // A whole sequence between the halves leaves a visible gap in both + // readings, so neither holds the secret and the text is kept as shown. + if got := RedactError(errors.New("expired opaque-\x1b7subscription-bearer now"), secret).Error(); got != "expired opaque-7subscription-bearer now" { + t.Fatalf("whole sequence split: got %q", got) + } + const ordinary = "upstream returned 503:\tservice\nunavailable \x1b[31mretry\x1b[0m" + if got := RedactError(errors.New(ordinary), secret).Error(); got != "upstream returned 503:\tservice\nunavailable retry" { + t.Fatalf("ordinary error text changed: %q", got) + } +} + +func TestRedactErrorDropsDefaultIgnorableSplits(t *testing.T) { + const secret = "opaque-subscription-bearer" + for _, split := range []string{"͏", "️", "᠋", "\U000E0100"} { + got := RedactError(errors.New("expired opaque-"+split+"subscription-bearer now"), secret).Error() + if got != "expired [REDACTED] now" { + t.Fatalf("split %U: got %q", []rune(split)[0], got) + } + } +} diff --git a/internal/tui/mouse_test.go b/internal/tui/mouse_test.go index 5e039fb751..cd5ad71110 100644 --- a/internal/tui/mouse_test.go +++ b/internal/tui/mouse_test.go @@ -2,6 +2,7 @@ package tui import ( "context" + "fmt" "strings" "testing" @@ -1159,3 +1160,40 @@ func setupMouseTestModel() model { m.altScreen = true return m } + +func TestModelPickerCapsDiscoveryNoticesFromManyAccounts(t *testing.T) { + m := subscriptionTestModel(t) + m.width, m.height = 80, 24 + m.modelPickerErrorsByProvider = map[string]string{} + for i := 0; i < 8; i++ { + name := fmt.Sprintf("account-%d", i) + m.savedProviders = append(m.savedProviders, config.ProviderProfile{ + Name: name, CatalogID: "chatgpt", BaseURL: m.providerProfile.BaseURL, + ProviderKind: config.ProviderKindOpenAICompatible, + }) + m.modelPickerErrorsByProvider[name] = "login expired; authenticate again before refreshing account models" + } + m.picker = &commandPicker{kind: pickerModel, items: []pickerItem{ + {Group: "Models", Label: "first-row", Value: "first"}, + {Group: "Models", Label: "target-row", Value: "target"}, + }} + if got := len(m.modelPickerDiscoveryNoticeLines(76)); got > modelPickerMaxNoticeLines { + t.Fatalf("discovery notices use %d rows, want at most %d", got, modelPickerMaxNoticeLines) + } + overlay := m.modelPickerOverlay(80) + text := plainRender(t, overlay) + for _, want := range []string{"target-row", "Esc close", "more discovery notices; /model list shows all."} { + if !strings.Contains(text, want) { + t.Fatalf("picker lacks %q with many failing accounts:\n%s", want, text) + } + } + rect := m.overlayMouseRect(len(viewLines(overlay)), 80) + for row, line := range strings.Split(text, "\n") { + if strings.Contains(line, "target-row") { + target, ok := m.selectModelPickerAtMouse(testMouseClick(tea.MouseLeft, 40, rect.y+row)) + if !ok || target.Value != "target" { + t.Fatalf("click on rendered model selected %#v, ok=%v; want target", target, ok) + } + } + } +} diff --git a/internal/tui/view.go b/internal/tui/view.go index 6869b8f311..dd463d7f71 100644 --- a/internal/tui/view.go +++ b/internal/tui/view.go @@ -6,6 +6,7 @@ import ( "os" "path" "path/filepath" + "slices" "strconv" "strings" @@ -21,6 +22,7 @@ const ( suggestionPaletteMaxWidth = 76 suggestionPaletteMinWidth = 44 pickerOverlayMaxVisible = 10 + modelPickerMaxNoticeLines = 4 pickerOverlayMaxWidth = 92 pickerOverlayMinWidth = 56 modelPickerOverlayMaxWidth = 76 @@ -1110,14 +1112,38 @@ func (m model) renderModelPickerOverlay(width, start, count int) string { return centerRenderedBlock(styledBlockFillTitle(overlayWidth, title, lines, zeroTheme.lineStrong, lipgloss.NewStyle()), width) } -// Share wrapped notice rows with mouse hit testing so both agree where models start. +// Share wrapped notice rows with mouse hit testing so both agree where models +// start. Rows are capped so several failing accounts cannot push the model +// rows and footer out of the overlay; /model list prints every notice. func (m model) modelPickerDiscoveryNoticeLines(innerWidth int) []string { - var lines []string width := maxInt(1, innerWidth-lipgloss.Width("❯ ")) + var wrapped [][]string + total := 0 for _, status := range m.modelPickerDiscoveryNotices(m.modelPickerProviders(), "Ctrl+R") { - lines = append(lines, strings.Split(ansi.Wrap(status, width, ""), "\n")...) + rows := strings.Split(ansi.Wrap(status, width, ""), "\n") + wrapped = append(wrapped, rows) + total += len(rows) } - return lines + if total <= modelPickerMaxNoticeLines { + return slices.Concat(wrapped...) + } + // Keep whole notices while a summary row still fits, and at least the start + // of the first notice so the leading failure stays visible. + var lines []string + shown := 0 + for shown < len(wrapped) && len(lines)+len(wrapped[shown]) < modelPickerMaxNoticeLines { + lines = append(lines, wrapped[shown]...) + shown++ + } + if shown == 0 { + lines = wrapped[0][:modelPickerMaxNoticeLines-1] + shown = 1 + } + more := "… /model list shows the full notice." + if hidden := len(wrapped) - shown; hidden > 0 { + more = fmt.Sprintf("+%d more discovery notices; /model list shows all.", hidden) + } + return append(lines, ansi.Truncate(more, width, "…")) } func (m model) modelPickerLoadingOverlay(width int) string { From 45fc3e389986ca0cc98abb746a434df947efff2d Mon Sep 17 00:00:00 2001 From: oniisanlabs <1436535+oniisanlabs@users.noreply.github.com> Date: Sat, 7 Nov 2026 09:44:55 -0500 Subject: [PATCH 06/13] fix(cli): authenticate headless ChatGPT discovery with the stored login DiscoverCatalog now fails for ChatGPT when the account probe is rejected, but discoveredModelContextWindow still probed with empty Options, so a keyless subscription profile under `zero exec` sent no bearer, got the error, and fell back to the generic context window. Build the OAuth and Codex account resolvers from the authenticated profile for ChatGPT, the same way the TUI and `providers models` already do; every other provider keeps empty options. The regression test stores a ChatGPT login in a temporary token file and probes a fake endpoint that answers only with that bearer and account header. Without the fix it reports `context window = 0, want 123456`. A keyed sibling profile must still not borrow the login. Co-Authored-By: Claude Fable 5.1 --- internal/cli/exec.go | 16 +++++- internal/cli/exec_context_window_test.go | 70 ++++++++++++++++++++++++ 2 files changed, 83 insertions(+), 3 deletions(-) create mode 100644 internal/cli/exec_context_window_test.go diff --git a/internal/cli/exec.go b/internal/cli/exec.go index 8369a90ade..498fef5806 100644 --- a/internal/cli/exec.go +++ b/internal/cli/exec.go @@ -1325,7 +1325,7 @@ func resolveAgentContextWindow(ctx context.Context, registry modelregistry.Regis if window := modelContextWindow(registry, profile.Model); window > 0 { return window } - if window := discoveredModelContextWindow(ctx, profile); window > 0 { + if window := discoveredModelContextWindow(ctx, profile, providermodeldiscovery.Options{}); window > 0 { return window } return modelregistry.AgentContextWindow(0) @@ -1334,7 +1334,9 @@ func resolveAgentContextWindow(ctx context.Context, registry modelregistry.Regis // discoveredModelContextWindow queries the provider's live model list for the // active model's context window. Returns 0 when the provider isn't catalogued, the // credential can't be resolved, discovery fails, or the model reports no window. -func discoveredModelContextWindow(ctx context.Context, profile config.ProviderProfile) int { +// options carries transport overrides (HTTP client, catalog URLs); the credential +// resolvers are always derived here from the authenticated profile. +func discoveredModelContextWindow(ctx context.Context, profile config.ProviderProfile, options providermodeldiscovery.Options) int { descriptor, ok := providercatalog.Get(strings.TrimSpace(profile.CatalogID)) if !ok { return 0 @@ -1349,9 +1351,17 @@ func discoveredModelContextWindow(ctx context.Context, profile config.ProviderPr if strings.TrimSpace(authed.APIKey) == "" && strings.TrimSpace(authed.APIKeyEnv) != "" { authed.APIKey = strings.TrimSpace(os.Getenv(authed.APIKeyEnv)) } + if providercatalog.NormalizeID(descriptor.ID) == "chatgpt" { + // ChatGPT discovery is a live account probe that fails without the stored + // OAuth bearer, so a keyless subscription profile needs the same login the + // runtime provider uses; a profile with its own key keeps that key instead. + resolver, loginKey := oauthLoginForProfile(authed) + options.OAuthResolver = resolver + options.CodexAccountResolver = providers.CodexAccountResolverForLogin(loginKey) + } dctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() - models, err := providermodeldiscovery.DiscoverCatalog(dctx, descriptor, authed, providermodeldiscovery.Options{}) + models, err := providermodeldiscovery.DiscoverCatalog(dctx, descriptor, authed, options) if err != nil { return 0 } diff --git a/internal/cli/exec_context_window_test.go b/internal/cli/exec_context_window_test.go new file mode 100644 index 0000000000..c373851ffe --- /dev/null +++ b/internal/cli/exec_context_window_test.go @@ -0,0 +1,70 @@ +package cli + +import ( + "context" + "net/http" + "net/http/httptest" + "path/filepath" + "testing" + "time" + + "github.com/Twigpine/zero/internal/config" + "github.com/Twigpine/zero/internal/oauth" + "github.com/Twigpine/zero/internal/providermodeldiscovery" +) + +// A keyless ChatGPT profile authenticates headless discovery with its stored +// OAuth login: the live account probe only answers with the bearer and the +// account header present, and the discovered context window must come through +// instead of the generic fallback. Also pins that a profile with its own key +// never borrows the subscription login. +func TestDiscoveredModelContextWindowUsesChatGPTLogin(t *testing.T) { + root := t.TempDir() + for _, key := range []string{"HOME", "USERPROFILE", "APPDATA", "LOCALAPPDATA", "XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME"} { + t.Setenv(key, root) + } + t.Setenv("ZERO_OAUTH_STORAGE", "file") // an inherited "keyring" would ignore the temp path and hit the OS keychain + t.Setenv("ZERO_OAUTH_TOKENS_PATH", filepath.Join(root, "oauth-tokens.json")) + store, err := oauth.NewStore(oauth.StoreOptions{}) + if err != nil { + t.Fatalf("oauth store: %v", err) + } + if err := store.Save(oauth.ProviderKey("chatgpt"), oauth.Token{ + AccessToken: "subscription-bearer", ExpiresAt: time.Now().Add(time.Hour), Account: "acct-123", + }); err != nil { + t.Fatalf("seed login: %v", err) + } + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api.json" { + http.Error(w, "metadata unavailable", http.StatusServiceUnavailable) + return + } + if r.Header.Get("Authorization") != "Bearer subscription-bearer" || r.Header.Get("chatgpt-account-id") != "acct-123" { + http.Error(w, "login required", http.StatusUnauthorized) + return + } + _, _ = w.Write([]byte(`{"models":[{"slug":"gpt-live-coder","visibility":"list","context_window":123456}]}`)) + })) + defer server.Close() + + profile := config.ProviderProfile{ + Name: "chatgpt", CatalogID: "chatgpt", ProviderKind: config.ProviderKindOpenAICompatible, + BaseURL: server.URL + "/backend-api/codex", Model: "gpt-live-coder", + } + // Keep the optional metadata enrichment off the network; the live probe is + // what this test is about. + options := providermodeldiscovery.Options{HTTPClient: server.Client(), ModelsDevURL: server.URL + "/api.json"} + if window := discoveredModelContextWindow(context.Background(), profile, options); window != 123456 { + t.Fatalf("context window = %d, want 123456 from the account-authenticated probe", window) + } + + // A sibling profile that resolves its own key must not reach the stored + // login; the endpoint rejects the key, so discovery yields no window. + keyed := profile + keyed.Name = "chatgpt-keyed" + keyed.APIKey = "own-key" + if window := discoveredModelContextWindow(context.Background(), keyed, options); window != 0 { + t.Fatalf("keyed profile context window = %d, want 0 (must not borrow the OAuth login)", window) + } +} From cba69a0414e2dd6c3490dae92518aa57b340c803 Mon Sep 17 00:00:00 2001 From: oniisanlabs <1436535+oniisanlabs@users.noreply.github.com> Date: Mon, 9 Nov 2026 10:49:03 -0500 Subject: [PATCH 07/13] fix(tui): stop pointing capped picker notices at /model list The picker's notice summary rows promised that /model list shows the hidden or truncated notices, but modelListText reports only the active profile, so notices from other accounts never appear there. Say what was cut without pointing anywhere, and correct the comment that made the same promise. The many-accounts test now fails if any notice row mentions /model list, and a new test covers a single notice longer than the cap. Co-Authored-By: Claude Fable 5.1 --- internal/tui/mouse_test.go | 33 ++++++++++++++++++++++++++++++++- internal/tui/view.go | 8 +++++--- 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/internal/tui/mouse_test.go b/internal/tui/mouse_test.go index cd5ad71110..d46eddd1ed 100644 --- a/internal/tui/mouse_test.go +++ b/internal/tui/mouse_test.go @@ -1182,7 +1182,12 @@ func TestModelPickerCapsDiscoveryNoticesFromManyAccounts(t *testing.T) { } overlay := m.modelPickerOverlay(80) text := plainRender(t, overlay) - for _, want := range []string{"target-row", "Esc close", "more discovery notices; /model list shows all."} { + // The hidden notices belong to other accounts, which /model list does not + // report, so the summary row must not send the user there. + if strings.Contains(text, "/model list") { + t.Fatalf("picker points hidden notices at /model list:\n%s", text) + } + for _, want := range []string{"target-row", "Esc close", "more discovery notices not shown."} { if !strings.Contains(text, want) { t.Fatalf("picker lacks %q with many failing accounts:\n%s", want, text) } @@ -1197,3 +1202,29 @@ func TestModelPickerCapsDiscoveryNoticesFromManyAccounts(t *testing.T) { } } } + +// A single notice longer than the cap is cut rather than hidden; the summary +// row says so without pointing at /model list, which would show the active +// profile's notice only when the cut one belongs to it. +func TestModelPickerTruncatesLongDiscoveryNotice(t *testing.T) { + m := subscriptionTestModel(t) + m.width, m.height = 80, 24 + m.savedProviders = append(m.savedProviders, config.ProviderProfile{ + Name: "other-account", CatalogID: "chatgpt", BaseURL: m.providerProfile.BaseURL, + ProviderKind: config.ProviderKindOpenAICompatible, + }) + m.modelPickerErrorsByProvider = map[string]string{ + "other-account": strings.Repeat("login expired; authenticate again before refreshing account models. ", 12), + } + lines := m.modelPickerDiscoveryNoticeLines(76) + if len(lines) != modelPickerMaxNoticeLines { + t.Fatalf("long notice uses %d rows, want exactly the cap %d", len(lines), modelPickerMaxNoticeLines) + } + text := plainRender(t, strings.Join(lines, "\n")) + if strings.Contains(text, "/model list") { + t.Fatalf("truncated notice points at /model list:\n%s", text) + } + if !strings.Contains(text, "notice truncated") { + t.Fatalf("truncated notice lacks the summary row:\n%s", text) + } +} diff --git a/internal/tui/view.go b/internal/tui/view.go index dd463d7f71..49da994855 100644 --- a/internal/tui/view.go +++ b/internal/tui/view.go @@ -1114,7 +1114,9 @@ func (m model) renderModelPickerOverlay(width, start, count int) string { // Share wrapped notice rows with mouse hit testing so both agree where models // start. Rows are capped so several failing accounts cannot push the model -// rows and footer out of the overlay; /model list prints every notice. +// rows and footer out of the overlay. Hidden notices mostly belong to other +// accounts, and /model list reports only the active profile, so the summary +// row states what was cut without pointing anywhere. func (m model) modelPickerDiscoveryNoticeLines(innerWidth int) []string { width := maxInt(1, innerWidth-lipgloss.Width("❯ ")) var wrapped [][]string @@ -1139,9 +1141,9 @@ func (m model) modelPickerDiscoveryNoticeLines(innerWidth int) []string { lines = wrapped[0][:modelPickerMaxNoticeLines-1] shown = 1 } - more := "… /model list shows the full notice." + more := "… notice truncated." if hidden := len(wrapped) - shown; hidden > 0 { - more = fmt.Sprintf("+%d more discovery notices; /model list shows all.", hidden) + more = fmt.Sprintf("+%d more discovery notices not shown.", hidden) } return append(lines, ansi.Truncate(more, width, "…")) } From c1a0eb6e98a0594b15450663d323b6efdc79ff73 Mon Sep 17 00:00:00 2001 From: oniisanlabs <1436535+oniisanlabs@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:33:17 -0500 Subject: [PATCH 08/13] fix(tui): size the context window from the active ChatGPT account Named ChatGPT profiles cache their live catalog under their own profile key and no longer mirror it into the shared "chatgpt" entry, but modelContextWindow still read that shared entry first, so with two logins the gauges, sidebar usage and compaction could take another account's window for the same model ID. Resolve live windows in the activeDiscoveryKeys order that model switching already uses, then fall back to other entries as before. The regression test seeds two accounts that disagree on a model's window and checks the active one wins while a model only the other account surfaced still resolves. Co-Authored-By: Claude Fable 5.1 --- internal/tui/chatgpt_models_test.go | 27 +++++++++++++++++++++++++++ internal/tui/model_catalog.go | 12 +++++++----- 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/internal/tui/chatgpt_models_test.go b/internal/tui/chatgpt_models_test.go index 39d926c678..8f6cbb376f 100644 --- a/internal/tui/chatgpt_models_test.go +++ b/internal/tui/chatgpt_models_test.go @@ -247,6 +247,33 @@ func TestSubscriptionModelsDoNotCrossAccountProfiles(t *testing.T) { } } +// Two ChatGPT accounts can report different context windows for the same model +// ID. The gauges and compaction must size from the active account's catalog, +// which is cached under its profile key, not from the shared "chatgpt" entry +// another account filled. +func TestSubscriptionContextWindowUsesActiveAccount(t *testing.T) { + m := subscriptionTestModel(t) + m = m.applyModelPickerModelsDiscovered(modelPickerModelsDiscoveredMsg{ + providerID: "chatgpt", endpointKey: "chatgpt", + models: []providermodeldiscovery.Model{ + {ID: "gpt-shared-window", ContextWindow: 111111}, + {ID: "gpt-other-account-only", ContextWindow: 333333}, + }, + }) + m = m.applyModelPickerModelsDiscovered(modelPickerModelsDiscoveredMsg{ + providerID: "chatgpt", endpointKey: m.providerProfile.Name, + models: []providermodeldiscovery.Model{{ID: "gpt-shared-window", ContextWindow: 222222}}, + }) + if got := m.modelContextWindow("gpt-shared-window"); got != 222222 { + t.Fatalf("context window = %d, want the active account's 222222 rather than another account's entry", got) + } + // A model the active account never surfaced still learns its window from + // another entry, as before. + if got := m.modelContextWindow("gpt-other-account-only"); got != 333333 { + t.Fatalf("fallback context window = %d, want 333333 from the other entry", got) + } +} + func TestSubscriptionPickerRetriesFromKeyboard(t *testing.T) { m := subscriptionTestModel(t) m.picker = m.newModelPicker() diff --git a/internal/tui/model_catalog.go b/internal/tui/model_catalog.go index b31d32983e..53821c5ef6 100644 --- a/internal/tui/model_catalog.go +++ b/internal/tui/model_catalog.go @@ -85,11 +85,13 @@ func (m model) modelContextWindow(modelName string) int { if entry, ok := m.modelCatalog.Resolve(trimmed); ok && entry.ContextLimits.ContextWindow > 0 { return entry.ContextLimits.ContextWindow } - // Live-discovered window, preferring the ACTIVE provider's models so a model ID - // shared across providers resolves to the provider actually in use; only then - // fall back to other providers that surfaced the same ID. - if descriptor, ok := m.activeProviderDescriptor(); ok { - if window := discoveredContextWindow(m.modelPickerLiveByProvider[descriptor.ID], trimmed); window > 0 { + // Live-discovered window, preferring the ACTIVE route's models in the same key + // order model switching uses (discoveredModelsForActiveRoute), so a model ID + // shared across providers, or across two ChatGPT accounts whose catalogs are + // cached under their own profile keys, resolves to the account actually in + // use; only then fall back to other entries that surfaced the same ID. + for _, key := range m.activeDiscoveryKeys() { + if window := discoveredContextWindow(m.modelPickerLiveByProvider[key], trimmed); window > 0 { return window } } From dfd5bdfc23dc04a6d4b6f6595b274f03f1736656 Mon Sep 17 00:00:00 2001 From: oniisanlabs <1436535+oniisanlabs@users.noreply.github.com> Date: Fri, 13 Nov 2026 13:07:56 +0100 Subject: [PATCH 09/13] fix(tui): track model discovery requests per account /model list bumped the shared discovery generation while refreshing only the active account, so a result still pending for another account from the picker's refresh of every account was discarded as stale and never reached the cache. Record the newest request generation per discovery key and let a result be superseded only by a newer request for its own key. Opening the picker, Ctrl+R and /model list now record the keys they dispatch. Co-Authored-By: Claude Fable 5.1 --- internal/tui/chatgpt_models_test.go | 45 +++++++++++++++++- internal/tui/image_attach_test.go | 2 +- internal/tui/model.go | 17 ++++--- internal/tui/picker.go | 74 +++++++++++++++++++++-------- 4 files changed, 109 insertions(+), 29 deletions(-) diff --git a/internal/tui/chatgpt_models_test.go b/internal/tui/chatgpt_models_test.go index 8f6cbb376f..659ff4a961 100644 --- a/internal/tui/chatgpt_models_test.go +++ b/internal/tui/chatgpt_models_test.go @@ -318,7 +318,7 @@ func TestSubscriptionPickerRedactsDiscoveryErrors(t *testing.T) { func TestSubscriptionPickerIgnoresSupersededRefresh(t *testing.T) { m := subscriptionTestModel(t) - m.modelPickerDiscoveryGeneration = 2 + m.modelPickerDiscoveryRequests = map[string]int{"subscription": 2} m.picker = m.newModelPicker() updated, _ := m.Update(modelPickerModelsDiscoveredMsg{ providerID: "chatgpt", endpointKey: "subscription", generation: 2, @@ -333,6 +333,47 @@ func TestSubscriptionPickerIgnoresSupersededRefresh(t *testing.T) { } } +// /model list refreshes only the active account. Another account's result from +// the picker's refresh of every account may still be pending when the list +// runs, and must land rather than be discarded as stale. +func TestSubscriptionListRefreshKeepsOtherAccountResult(t *testing.T) { + m := subscriptionTestModel(t) + m.savedProviders = append(m.savedProviders, config.ProviderProfile{ + Name: "other-account", CatalogID: "chatgpt", BaseURL: m.providerProfile.BaseURL, + ProviderKind: config.ProviderKindOpenAICompatible, + }) + m.discoverProviderModels = func(context.Context, config.ProviderProfile) ([]providermodeldiscovery.Model, error) { + return nil, errors.New("discovery commands are not run by this test") + } + m, cmd := m.openModelPicker() + if cmd == nil { + t.Fatal("opening the picker must refresh every account") + } + pickerGeneration := m.modelPickerDiscoveryGeneration + if got := m.modelPickerDiscoveryRequests["other-account"]; got != pickerGeneration { + t.Fatalf("other account request generation = %d, want %d", got, pickerGeneration) + } + m, cmd = m.modelListDiscoveryCmd() + if cmd == nil { + t.Fatal("/model list must refresh the active account") + } + updated, _ := m.Update(modelPickerModelsDiscoveredMsg{ + providerID: "chatgpt", endpointKey: "other-account", generation: pickerGeneration, + models: []providermodeldiscovery.Model{{ID: "gpt-other-account"}}, + }) + next := updated.(model) + if models := next.modelPickerLiveByProvider["other-account"]; len(models) != 1 || models[0].ID != "gpt-other-account" { + t.Fatalf("refreshing the active account discarded the other account's pending result; cached = %#v", models) + } + // The active account's own older result is still superseded by the list refresh. + updated, _ = next.Update(modelPickerModelsDiscoveredMsg{ + providerID: "chatgpt", endpointKey: "subscription", generation: pickerGeneration, err: errors.New("old refresh failed"), + }) + if strings.Contains(updated.(model).modelPickerOverlay(100), "old refresh failed") { + t.Fatal("a superseded request for the active account overwrote its newer refresh") + } +} + type subscriptionTransport func(*http.Request) (*http.Response, error) func (f subscriptionTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } @@ -399,7 +440,7 @@ func TestSubscriptionSetupDiscoveryUsesOAuthAccount(t *testing.T) { func TestSubscriptionSupersededModelListStillPrints(t *testing.T) { m := subscriptionTestModel(t) - m.modelPickerDiscoveryGeneration = 2 + m.modelPickerDiscoveryRequests = map[string]int{"subscription": 2} m.modelPickerLoading = true m.modelPickerLiveByProvider = map[string][]providermodeldiscovery.Model{"subscription": {{ID: "gpt-current-result"}}} updated, _ := m.Update(modelPickerModelsDiscoveredMsg{ diff --git a/internal/tui/image_attach_test.go b/internal/tui/image_attach_test.go index 2544c963d1..906059cbb6 100644 --- a/internal/tui/image_attach_test.go +++ b/internal/tui/image_attach_test.go @@ -805,7 +805,7 @@ func TestModelPickerDiscoveryCmds_OrderIndependence(t *testing.T) { m := newModel(t.Context(), Options{ SavedProviders: order, }) - cmd := m.modelPickerDiscoveryCmds() + _, cmd := m.modelPickerDiscoveryCmds() if cmd == nil { t.Fatalf("expected discovery commands for order %v", order) } diff --git a/internal/tui/model.go b/internal/tui/model.go index bac231128c..9fdce0a1e4 100644 --- a/internal/tui/model.go +++ b/internal/tui/model.go @@ -579,8 +579,12 @@ type model struct { modelPickerLiveByProvider map[string][]providermodeldiscovery.Model // Discovery errors and generations belong to the provider lookup, not the // active model, so concurrent results cannot clear another account's status. - modelPickerErrorsByProvider map[string]string + modelPickerErrorsByProvider map[string]string + // modelPickerDiscoveryGeneration numbers refresh requests; the map records + // the newest request per discovery key so a refresh of one account cannot + // discard another account's still-pending result. modelPickerDiscoveryGeneration int + modelPickerDiscoveryRequests map[string]int // ollamaContextWindowByModel holds context-window sizes fetched from a local // Ollama daemon's native /api/show endpoint (keyed by model name), for // custom/local models that have no curated-catalog entry and whose @@ -2099,8 +2103,7 @@ func (m model) updateModel(msg tea.Msg) (tea.Model, tea.Cmd) { } case keyCtrl(msg, 'r'): if m.picker != nil && m.picker.kind == pickerModel { - m.modelPickerDiscoveryGeneration++ - return m, m.modelPickerDiscoveryCmds() + return m.modelPickerDiscoveryCmds() } case keyCtrl(msg, 'f'): if m.picker != nil && m.picker.kind == pickerModel { @@ -3223,7 +3226,8 @@ func (m model) updateModel(msg tea.Msg) (tea.Model, tea.Cmd) { case setupOAuthDeviceMsg: return m.applySetupOAuthDeviceCode(msg) case modelPickerModelsDiscoveredMsg: - if msg.generation != 0 && msg.generation != m.modelPickerDiscoveryGeneration { + if msg.generation != 0 && msg.generation != m.modelPickerDiscoveryRequests[modelPickerDiscoveryKey(msg.endpointKey, msg.providerID)] { + // Only a newer request for the same account supersedes this result. // Honor an explicit list request using current state without letting // an older response overwrite the newer discovery or its loading flag. if msg.showList { @@ -5146,9 +5150,8 @@ func (m model) dispatchCommand(command parsedCommand) (tea.Model, tea.Cmd) { return m, nil case commandModel: if arg := strings.ToLower(strings.TrimSpace(command.text)); arg == "list" || arg == "ls" { - m.modelPickerDiscoveryGeneration++ - if cmd := m.modelListDiscoveryCmd(); cmd != nil { - return m, cmd + if next, cmd := m.modelListDiscoveryCmd(); cmd != nil { + return next, cmd } } if strings.TrimSpace(command.text) == "" { diff --git a/internal/tui/picker.go b/internal/tui/picker.go index 9e49e87d7d..92772de6b5 100644 --- a/internal/tui/picker.go +++ b/internal/tui/picker.go @@ -388,40 +388,73 @@ func (m model) openModelPicker() (model, tea.Cmd) { } m.picker = picker m.clearModelPickerLoadState() - m.modelPickerDiscoveryGeneration++ // Live-discover every usable provider's real models in the background. The list // shows immediately from the static catalog and each provider's section refreshes // as its discovery returns — no blocking overlay. - return m, m.modelPickerDiscoveryCmds() + return m.modelPickerDiscoveryCmds() +} + +// modelPickerDiscoveryKey names the cache and request-tracking slot a discovery +// result belongs to: the endpoint/profile key, or the catalog ID without one. +func modelPickerDiscoveryKey(endpointKey, providerID string) string { + return firstProviderDisplayValue(endpointKey, providerID) +} + +// requestModelPickerDiscovery starts a new refresh generation and records it +// for every key about to be refreshed, so results for keys this refresh does +// not touch keep their own pending request. +func (m model) requestModelPickerDiscovery(keys ...string) model { + m.modelPickerDiscoveryGeneration++ + requests := make(map[string]int, len(m.modelPickerDiscoveryRequests)+len(keys)) + for k, v := range m.modelPickerDiscoveryRequests { + requests[k] = v + } + for _, key := range keys { + requests[key] = m.modelPickerDiscoveryGeneration + } + m.modelPickerDiscoveryRequests = requests + return m } // modelPickerDiscoveryCmds dispatches a live model-discovery command for each // usable provider (deduped by endpoint key), so /model shows the same real -// models the provider-setup wizard discovers. -func (m model) modelPickerDiscoveryCmds() tea.Cmd { - cmds := []tea.Cmd{} +// models the provider-setup wizard discovers. The returned model records the +// request for each dispatched key. +func (m model) modelPickerDiscoveryCmds() (model, tea.Cmd) { + type request struct { + descriptor providercatalog.Descriptor + profile config.ProviderProfile + } + var requests []request + var keys []string seen := map[string]bool{} for _, profile := range m.modelPickerProviders() { descriptor, ok := m.descriptorForProfile(profile) if !ok { continue } - endpointKey := providerEndpointKey(profile, descriptor) - if endpointKey == "" { - endpointKey = descriptor.ID - } - if seen[endpointKey] { + key := modelPickerDiscoveryKey(providerEndpointKey(profile, descriptor), descriptor.ID) + if seen[key] { continue } - seen[endpointKey] = true - if cmd := m.modelPickerProviderDiscoveryCmd(descriptor, profile); cmd != nil { + seen[key] = true + requests = append(requests, request{descriptor: descriptor, profile: profile}) + keys = append(keys, key) + } + if len(requests) == 0 { + return m, nil + } + m = m.requestModelPickerDiscovery(keys...) + cmds := []tea.Cmd{} + for _, req := range requests { + if cmd := m.modelPickerProviderDiscoveryCmd(req.descriptor, req.profile); cmd != nil { cmds = append(cmds, cmd) } } if len(cmds) == 0 { - return nil + return m, nil } - return tea.Batch(cmds...) + return m, tea.Batch(cmds...) } // modelPickerProviderDiscoveryCmd discovers one provider's live models, resolving @@ -471,16 +504,19 @@ func (m model) modelPickerProviderDiscoveryCmd(descriptor providercatalog.Descri // modelListDiscoveryCmd refreshes the active account before printing /model list. // The popup and text command share both the discovery path and its cached results. -func (m model) modelListDiscoveryCmd() tea.Cmd { +// Only the active account's request is renewed; other accounts' pending picker +// results stay valid. +func (m model) modelListDiscoveryCmd() (model, tea.Cmd) { descriptor, ok := m.activeProviderDescriptor() if !ok || !config.HasProviderProfile(m.providerProfile) { - return nil + return m, nil } + m = m.requestModelPickerDiscovery(modelPickerDiscoveryKey(providerEndpointKey(m.providerProfile, descriptor), descriptor.ID)) cmd := m.modelPickerProviderDiscoveryCmd(descriptor, m.providerProfile) if cmd == nil { - return nil + return m, nil } - return func() tea.Msg { + return m, func() tea.Msg { msg := cmd().(modelPickerModelsDiscoveredMsg) msg.showList = true return msg @@ -1095,7 +1131,7 @@ func profileMatchesProviderBaseURL(profile config.ProviderProfile, provider prov func (m model) applyModelPickerModelsDiscovered(msg modelPickerModelsDiscoveredMsg) model { m.modelPickerLoading = false m.modelPickerLoadingProviderID = "" - key := firstProviderDisplayValue(msg.endpointKey, msg.providerID) + key := modelPickerDiscoveryKey(msg.endpointKey, msg.providerID) errorsByProvider := make(map[string]string, len(m.modelPickerErrorsByProvider)+1) for k, v := range m.modelPickerErrorsByProvider { errorsByProvider[k] = v From f828193196cf7efb759d4528c461e4f84c5598ec Mon Sep 17 00:00:00 2001 From: oniisanlabs <1436535+oniisanlabs@users.noreply.github.com> Date: Fri, 13 Nov 2026 13:07:56 +0100 Subject: [PATCH 10/13] fix(tui): keep the retry key visible when picker notices are cut A failure notice longer than the notice cap lost its trailing "Ctrl+R to retry" text, and the picker footer does not list Ctrl+R, so the failure state hid its recovery action. The summary row now names the retry key, falling back to just that text when a narrow overlay cannot fit the summary. Co-Authored-By: Claude Fable 5.1 --- internal/tui/mouse_test.go | 17 +++++++++++++++-- internal/tui/view.go | 15 +++++++++++---- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/internal/tui/mouse_test.go b/internal/tui/mouse_test.go index d46eddd1ed..33cb47b901 100644 --- a/internal/tui/mouse_test.go +++ b/internal/tui/mouse_test.go @@ -1187,7 +1187,7 @@ func TestModelPickerCapsDiscoveryNoticesFromManyAccounts(t *testing.T) { if strings.Contains(text, "/model list") { t.Fatalf("picker points hidden notices at /model list:\n%s", text) } - for _, want := range []string{"target-row", "Esc close", "more discovery notices not shown."} { + for _, want := range []string{"target-row", "Esc close", "more notices hidden. Ctrl+R to retry."} { if !strings.Contains(text, want) { t.Fatalf("picker lacks %q with many failing accounts:\n%s", want, text) } @@ -1205,7 +1205,9 @@ func TestModelPickerCapsDiscoveryNoticesFromManyAccounts(t *testing.T) { // A single notice longer than the cap is cut rather than hidden; the summary // row says so without pointing at /model list, which would show the active -// profile's notice only when the cut one belongs to it. +// profile's notice only when the cut one belongs to it. The cut removes the +// notice's own retry text, so the summary row has to name Ctrl+R, down to the +// narrowest picker. func TestModelPickerTruncatesLongDiscoveryNotice(t *testing.T) { m := subscriptionTestModel(t) m.width, m.height = 80, 24 @@ -1227,4 +1229,15 @@ func TestModelPickerTruncatesLongDiscoveryNotice(t *testing.T) { if !strings.Contains(text, "notice truncated") { t.Fatalf("truncated notice lacks the summary row:\n%s", text) } + m.picker = &commandPicker{kind: pickerModel, items: []pickerItem{{Group: "Models", Label: "only-row", Value: "only"}}} + for _, width := range []int{modelPickerOverlayMinWidth, 80} { + m.width = width + text := plainRender(t, m.modelPickerOverlay(width)) + if !strings.Contains(text, "Ctrl+R to retry") { + t.Fatalf("truncated notice at width %d hides the retry key:\n%s", width, text) + } + if !strings.Contains(text, "Esc close") { + t.Fatalf("picker footer missing at width %d:\n%s", width, text) + } + } } diff --git a/internal/tui/view.go b/internal/tui/view.go index 49da994855..d87c75efe6 100644 --- a/internal/tui/view.go +++ b/internal/tui/view.go @@ -1116,12 +1116,14 @@ func (m model) renderModelPickerOverlay(width, start, count int) string { // start. Rows are capped so several failing accounts cannot push the model // rows and footer out of the overlay. Hidden notices mostly belong to other // accounts, and /model list reports only the active profile, so the summary -// row states what was cut without pointing anywhere. +// row states what was cut without pointing there. Cutting a notice can remove +// its own retry text, so the summary row names the retry key itself. func (m model) modelPickerDiscoveryNoticeLines(innerWidth int) []string { + const retryHint = "Ctrl+R" width := maxInt(1, innerWidth-lipgloss.Width("❯ ")) var wrapped [][]string total := 0 - for _, status := range m.modelPickerDiscoveryNotices(m.modelPickerProviders(), "Ctrl+R") { + for _, status := range m.modelPickerDiscoveryNotices(m.modelPickerProviders(), retryHint) { rows := strings.Split(ansi.Wrap(status, width, ""), "\n") wrapped = append(wrapped, rows) total += len(rows) @@ -1141,9 +1143,14 @@ func (m model) modelPickerDiscoveryNoticeLines(innerWidth int) []string { lines = wrapped[0][:modelPickerMaxNoticeLines-1] shown = 1 } - more := "… notice truncated." + retry := retryHint + " to retry." + more := "… notice truncated. " + retry if hidden := len(wrapped) - shown; hidden > 0 { - more = fmt.Sprintf("+%d more discovery notices not shown.", hidden) + more = fmt.Sprintf("+%d more notices hidden. %s", hidden, retry) + } + if lipgloss.Width(more) > width { + // Keep the recovery action when a narrow overlay cannot fit the summary. + more = retry } return append(lines, ansi.Truncate(more, width, "…")) } From 3130f9bedd9b69881c1106402fa269e382a5dd8f Mon Sep 17 00:00:00 2001 From: oniisanlabs <1436535+oniisanlabs@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:01:55 +0100 Subject: [PATCH 11/13] fix(tui): register provider-switch discovery before the refresh guard Switching providers warmed discovery for the target through the raw command, which stamps the current generation without recording a request. After the picker had registered that provider and /model list had advanced the generation, the guard compared the result against the older registered request and discarded it. Route the switch through the registering helper, and only discard a result when its key has a registered request that differs, so the unregistered startup warm-up still lands. Co-Authored-By: Claude Fable 5.1 --- internal/tui/command_center.go | 8 +++-- internal/tui/model.go | 6 ++-- internal/tui/picker.go | 16 ++++++++-- internal/tui/picker_test.go | 58 ++++++++++++++++++++++++++++++++++ 4 files changed, 81 insertions(+), 7 deletions(-) diff --git a/internal/tui/command_center.go b/internal/tui/command_center.go index 0c727d1b09..454459a0d2 100644 --- a/internal/tui/command_center.go +++ b/internal/tui/command_center.go @@ -633,8 +633,12 @@ func (m model) switchProviderModel(providerName, modelID string) (model, string, // no window for this provider until /model happens to be opened separately. var cmds []tea.Cmd if hasDescriptor { - if cmd := m.modelPickerProviderDiscoveryCmd(descriptor, target); cmd != nil { - cmds = append(cmds, cmd) + // Register the request so the result passes the supersession guard even + // when a /model refresh has advanced the generation since this provider + // was last requested. + var discoveryCmd tea.Cmd + if m, discoveryCmd = m.requestProviderDiscoveryCmd(descriptor, target); discoveryCmd != nil { + cmds = append(cmds, discoveryCmd) } if cmd := m.ollamaContextWindowDiscoveryCmd(descriptor, target.BaseURL, target.Model); cmd != nil { cmds = append(cmds, cmd) diff --git a/internal/tui/model.go b/internal/tui/model.go index 9fdce0a1e4..4ac83043a0 100644 --- a/internal/tui/model.go +++ b/internal/tui/model.go @@ -3226,8 +3226,10 @@ func (m model) updateModel(msg tea.Msg) (tea.Model, tea.Cmd) { case setupOAuthDeviceMsg: return m.applySetupOAuthDeviceCode(msg) case modelPickerModelsDiscoveredMsg: - if msg.generation != 0 && msg.generation != m.modelPickerDiscoveryRequests[modelPickerDiscoveryKey(msg.endpointKey, msg.providerID)] { - // Only a newer request for the same account supersedes this result. + requested, tracked := m.modelPickerDiscoveryRequests[modelPickerDiscoveryKey(msg.endpointKey, msg.providerID)] + if msg.generation != 0 && tracked && msg.generation != requested { + // Only a newer registered request for the same account supersedes + // this result; an unregistered warm-up from Init stands until then. // Honor an explicit list request using current state without letting // an older response overwrite the newer discovery or its loading flag. if msg.showList { diff --git a/internal/tui/picker.go b/internal/tui/picker.go index 92772de6b5..13c64c3013 100644 --- a/internal/tui/picker.go +++ b/internal/tui/picker.go @@ -457,9 +457,20 @@ func (m model) modelPickerDiscoveryCmds() (model, tea.Cmd) { return m, tea.Batch(cmds...) } +// requestProviderDiscoveryCmd registers a fresh request for one provider and +// returns its discovery command. Every caller that can return the updated model +// must use this, or the result arrives stamped with a generation the guard in +// Update never saw and is dropped as stale. +func (m model) requestProviderDiscoveryCmd(descriptor providercatalog.Descriptor, profile config.ProviderProfile) (model, tea.Cmd) { + m = m.requestModelPickerDiscovery(modelPickerDiscoveryKey(providerEndpointKey(profile, descriptor), descriptor.ID)) + return m, m.modelPickerProviderDiscoveryCmd(descriptor, profile) +} + // modelPickerProviderDiscoveryCmd discovers one provider's live models, resolving // its credential the same way the wizard does: a stored/inline/env key, or a stored -// OAuth bearer for token-login providers (e.g. xAI). +// OAuth bearer for token-login providers (e.g. xAI). It stamps the current +// generation without registering a request; Init has no model to return, so its +// warm-up result is accepted until a registered request supersedes it. func (m model) modelPickerProviderDiscoveryCmd(descriptor providercatalog.Descriptor, profile config.ProviderProfile) tea.Cmd { authed := profile if store, err := m.providerKeyStore(); err == nil { @@ -511,8 +522,7 @@ func (m model) modelListDiscoveryCmd() (model, tea.Cmd) { if !ok || !config.HasProviderProfile(m.providerProfile) { return m, nil } - m = m.requestModelPickerDiscovery(modelPickerDiscoveryKey(providerEndpointKey(m.providerProfile, descriptor), descriptor.ID)) - cmd := m.modelPickerProviderDiscoveryCmd(descriptor, m.providerProfile) + m, cmd := m.requestProviderDiscoveryCmd(descriptor, m.providerProfile) if cmd == nil { return m, nil } diff --git a/internal/tui/picker_test.go b/internal/tui/picker_test.go index 291ce2f2e2..c954ad03a8 100644 --- a/internal/tui/picker_test.go +++ b/internal/tui/picker_test.go @@ -6,6 +6,8 @@ import ( "encoding/json" "errors" "fmt" + "net/http" + "net/http/httptest" "os" "path/filepath" "reflect" @@ -853,6 +855,62 @@ func TestSwitchProviderModelRecordsRecentHistory(t *testing.T) { } } +// Switching providers warms discovery for the target. The result must pass the +// supersession guard even when the picker registered that provider earlier and +// a /model list refresh of another provider has since advanced the generation. +func TestSwitchProviderModelDiscoveryPassesRefreshGuard(t *testing.T) { + probe := httptest.NewServer(http.NotFoundHandler()) + defer probe.Close() + configPath := filepath.Join(t.TempDir(), "zero", "config.json") + ollama := config.ProviderProfile{Name: "ollama", CatalogID: "ollama", ProviderKind: config.ProviderKindOpenAICompatible, BaseURL: probe.URL + "/v1", Model: "kimi-k2.7-code:cloud"} + if _, err := config.UpsertProvider(configPath, config.ProviderProfile{Name: "openai", CatalogID: "openai", Model: "gpt-5.1"}, true); err != nil { + t.Fatalf("seed openai provider: %v", err) + } + if _, err := config.UpsertProvider(configPath, ollama, false); err != nil { + t.Fatalf("seed ollama provider: %v", err) + } + m := newModel(context.Background(), Options{ + UserConfigPath: configPath, + ProviderName: "openai", + ModelName: "gpt-5.1", + Provider: &fakeProvider{}, + ProviderProfile: config.ProviderProfile{Name: "openai", CatalogID: "openai", Model: "gpt-5.1"}, + SavedProviders: []config.ProviderProfile{{Name: "openai", CatalogID: "openai", Model: "gpt-5.1"}, ollama}, + NewProvider: func(config.ProviderProfile) (zeroruntime.Provider, error) { + return &fakeProvider{}, nil + }, + }) + m.discoverProviderModels = func(context.Context, config.ProviderProfile) ([]providermodeldiscovery.Model, error) { + return []providermodeldiscovery.Model{{ID: "kimi-live"}}, nil + } + // Picker registers both providers, then /model list advances the generation + // for the active one only. + m, _ = m.openModelPicker() + m.picker = nil + m, _ = m.modelListDiscoveryCmd() + + next, status, switched, cmd, _ := m.switchProviderModel("ollama", "kimi-k2.7-code:cloud") + if !switched || cmd == nil { + t.Fatalf("switch failed or scheduled no discovery: %q", status) + } + var result tea.Msg + for _, sub := range cmd().(tea.BatchMsg) { + if msg, ok := sub().(modelPickerModelsDiscoveredMsg); ok { + result = msg + } + } + if result == nil { + t.Fatal("provider switch produced no discovery result") + } + updated, _ := next.Update(result) + for _, models := range updated.(model).modelPickerLiveByProvider { + if len(models) == 1 && models[0].ID == "kimi-live" { + return + } + } + t.Fatalf("provider switch discovery was discarded as stale; cache = %#v", updated.(model).modelPickerLiveByProvider) +} + func TestSwitchProviderModelReportsLockedConfigAsNotSavedWithoutPartialSelection(t *testing.T) { configPath := filepath.Join(t.TempDir(), "zero", "config.json") if _, err := config.UpsertProvider(configPath, config.ProviderProfile{Name: "openai", CatalogID: "openai", Model: "gpt-5.1"}, true); err != nil { From 8e68121cfbb4e11289ca30de3d21633cba2b960b Mon Sep 17 00:00:00 2001 From: oniisanlabs <1436535+oniisanlabs@users.noreply.github.com> Date: Fri, 13 Nov 2026 23:37:45 +0100 Subject: [PATCH 12/13] fix(tui): let registered refreshes supersede the startup warm-up Init warms discovery without registering a request, so its result carries generation 0. The guard let every generation-0 result through, so a slow startup response landing after a registered refresh reverted the account's models and status to stale startup data. Drop a result whenever its key has a registered request with a newer generation; generation 0 is older than any registered request. A key with no registered request still accepts its result. Co-Authored-By: Claude Fable 5.1 --- internal/tui/chatgpt_models_test.go | 30 +++++++++++++++++++++++++++++ internal/tui/model.go | 8 +++++--- internal/tui/picker.go | 3 ++- internal/tui/picker_test.go | 5 ++++- 4 files changed, 41 insertions(+), 5 deletions(-) diff --git a/internal/tui/chatgpt_models_test.go b/internal/tui/chatgpt_models_test.go index 659ff4a961..7dc376e1b5 100644 --- a/internal/tui/chatgpt_models_test.go +++ b/internal/tui/chatgpt_models_test.go @@ -374,6 +374,36 @@ func TestSubscriptionListRefreshKeepsOtherAccountResult(t *testing.T) { } } +// Init warms discovery without registering a request. When that slow startup +// result lands after a registered refresh already applied, it must not revert +// the account's models to stale startup data. +func TestSubscriptionLateStartupWarmupDoesNotOverrideRefresh(t *testing.T) { + m := subscriptionTestModel(t) + m.picker = m.newModelPicker() + m.discoverProviderModels = func(context.Context, config.ProviderProfile) ([]providermodeldiscovery.Model, error) { + return []providermodeldiscovery.Model{{ID: "gpt-refreshed"}}, nil + } + updated, cmd := m.Update(testKeyCtrl('r')) + if cmd == nil { + t.Fatal("Ctrl+R must register and start a refresh") + } + updated, _ = updated.(model).Update(cmd()) + updated, _ = updated.(model).Update(modelPickerModelsDiscoveredMsg{ + providerID: "chatgpt", endpointKey: "subscription", + models: []providermodeldiscovery.Model{{ID: "gpt-stale-startup"}}, + }) + next := updated.(model) + if models := next.modelPickerLiveByProvider["subscription"]; len(models) != 1 || models[0].ID != "gpt-refreshed" { + t.Fatalf("late startup warm-up overrode the registered refresh; cached = %#v", models) + } + updated, _ = next.Update(modelPickerModelsDiscoveredMsg{ + providerID: "chatgpt", endpointKey: "subscription", err: errors.New("startup discovery failed"), + }) + if strings.Contains(updated.(model).modelPickerOverlay(100), "startup discovery failed") { + t.Fatal("late startup warm-up failure replaced the registered refresh's status") + } +} + type subscriptionTransport func(*http.Request) (*http.Response, error) func (f subscriptionTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } diff --git a/internal/tui/model.go b/internal/tui/model.go index 4ac83043a0..77900a5e97 100644 --- a/internal/tui/model.go +++ b/internal/tui/model.go @@ -3227,9 +3227,11 @@ func (m model) updateModel(msg tea.Msg) (tea.Model, tea.Cmd) { return m.applySetupOAuthDeviceCode(msg) case modelPickerModelsDiscoveredMsg: requested, tracked := m.modelPickerDiscoveryRequests[modelPickerDiscoveryKey(msg.endpointKey, msg.providerID)] - if msg.generation != 0 && tracked && msg.generation != requested { - // Only a newer registered request for the same account supersedes - // this result; an unregistered warm-up from Init stands until then. + if tracked && msg.generation < requested { + // A registered request for the same account supersedes every older + // result for it, including the unregistered startup warm-up, whose + // generation 0 is older than any registered request. A key with no + // registered request accepts its result. // Honor an explicit list request using current state without letting // an older response overwrite the newer discovery or its loading flag. if msg.showList { diff --git a/internal/tui/picker.go b/internal/tui/picker.go index 13c64c3013..f2a6834f65 100644 --- a/internal/tui/picker.go +++ b/internal/tui/picker.go @@ -470,7 +470,8 @@ func (m model) requestProviderDiscoveryCmd(descriptor providercatalog.Descriptor // its credential the same way the wizard does: a stored/inline/env key, or a stored // OAuth bearer for token-login providers (e.g. xAI). It stamps the current // generation without registering a request; Init has no model to return, so its -// warm-up result is accepted until a registered request supersedes it. +// warm-up carries generation 0 and loses to any registered request for the same +// key, however late it finishes. func (m model) modelPickerProviderDiscoveryCmd(descriptor providercatalog.Descriptor, profile config.ProviderProfile) tea.Cmd { authed := profile if store, err := m.providerKeyStore(); err == nil { diff --git a/internal/tui/picker_test.go b/internal/tui/picker_test.go index c954ad03a8..66d595e11e 100644 --- a/internal/tui/picker_test.go +++ b/internal/tui/picker_test.go @@ -215,8 +215,11 @@ func TestModelPickerShowsLoadingUntilDiscoveryCompletes(t *testing.T) { } // When the provider's discovery returns, its section shows the live models. + // Opening the picker registered the request, so the result carries the + // generation it was stamped with. updated, _ = m.Update(modelPickerModelsDiscoveredMsg{ providerID: "ollama-cloud", + generation: m.modelPickerDiscoveryGeneration, models: []providermodeldiscovery.Model{{ID: "live-cloud-a", Description: "Live Cloud A"}}, }) m = updated.(model) @@ -290,7 +293,7 @@ func TestModelPickerFallsBackWhenDiscoveryFails(t *testing.T) { t.Fatal("expected opening the model picker to start discovery") } // A failed discovery leaves the static catalog list in place — no crash, no block. - updated, _ = m.Update(modelPickerModelsDiscoveredMsg{providerID: "ollama-cloud", models: nil, err: errors.New("offline")}) + updated, _ = m.Update(modelPickerModelsDiscoveredMsg{providerID: "ollama-cloud", generation: m.modelPickerDiscoveryGeneration, models: nil, err: errors.New("offline")}) m = updated.(model) view := plainRender(t, m.pickerOverlay(100)) assertNotContains(t, view, "Checking available models...") From 6fb6b47bd0175bbe1477a548cd52f3edef238e6b Mon Sep 17 00:00:00 2001 From: oniisanlabs <1436535+oniisanlabs@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:38:43 +0100 Subject: [PATCH 13/13] test(tui): make the provider-switch guard test depend on registration Since the guard only drops results older than the registered request, an unregistered switch stamps the current generation and its result is accepted either way, so the test passed without the registration it was added for. Deliver the picker's earlier ollama result after the switch and require the cache to keep the switch's models; without registration the older result is accepted and the assertion fails. Co-Authored-By: Claude Fable 5.1 --- internal/tui/picker_test.go | 43 +++++++++++++++++++++++++++---------- 1 file changed, 32 insertions(+), 11 deletions(-) diff --git a/internal/tui/picker_test.go b/internal/tui/picker_test.go index 66d595e11e..9a7f09339b 100644 --- a/internal/tui/picker_test.go +++ b/internal/tui/picker_test.go @@ -858,9 +858,11 @@ func TestSwitchProviderModelRecordsRecentHistory(t *testing.T) { } } -// Switching providers warms discovery for the target. The result must pass the -// supersession guard even when the picker registered that provider earlier and -// a /model list refresh of another provider has since advanced the generation. +// Switching providers warms discovery for the target and registers that request. +// The switch's result must land even though the picker registered the provider +// earlier and a /model list refresh of another provider advanced the generation, +// and a result from that earlier picker request arriving after the switch must +// not replace the switch's models. func TestSwitchProviderModelDiscoveryPassesRefreshGuard(t *testing.T) { probe := httptest.NewServer(http.NotFoundHandler()) defer probe.Close() @@ -891,27 +893,46 @@ func TestSwitchProviderModelDiscoveryPassesRefreshGuard(t *testing.T) { m, _ = m.openModelPicker() m.picker = nil m, _ = m.modelListDiscoveryCmd() + descriptor, ok := m.descriptorForProfile(ollama) + if !ok { + t.Fatal("ollama profile has no descriptor") + } + ollamaKey := modelPickerDiscoveryKey(providerEndpointKey(ollama, descriptor), descriptor.ID) + pickerRequest := m.modelPickerDiscoveryRequests[ollamaKey] + if pickerRequest == 0 { + t.Fatal("opening the picker did not register the ollama request") + } next, status, switched, cmd, _ := m.switchProviderModel("ollama", "kimi-k2.7-code:cloud") if !switched || cmd == nil { t.Fatalf("switch failed or scheduled no discovery: %q", status) } - var result tea.Msg + var result modelPickerModelsDiscoveredMsg + found := false for _, sub := range cmd().(tea.BatchMsg) { if msg, ok := sub().(modelPickerModelsDiscoveredMsg); ok { - result = msg + result, found = msg, true } } - if result == nil { + if !found { t.Fatal("provider switch produced no discovery result") } + if key := modelPickerDiscoveryKey(result.endpointKey, result.providerID); key != ollamaKey { + t.Fatalf("switch result keyed %q, want %q", key, ollamaKey) + } updated, _ := next.Update(result) - for _, models := range updated.(model).modelPickerLiveByProvider { - if len(models) == 1 && models[0].ID == "kimi-live" { - return - } + if models := updated.(model).modelPickerLiveByProvider[ollamaKey]; len(models) != 1 || models[0].ID != "kimi-live" { + t.Fatalf("provider switch discovery was discarded as stale; cache = %#v", updated.(model).modelPickerLiveByProvider) + } + // The picker's earlier request for ollama answers late: the switch registered + // a newer request, so this older result must be dropped. + updated, _ = updated.(model).Update(modelPickerModelsDiscoveredMsg{ + providerID: result.providerID, endpointKey: result.endpointKey, generation: pickerRequest, + models: []providermodeldiscovery.Model{{ID: "kimi-stale"}}, + }) + if models := updated.(model).modelPickerLiveByProvider[ollamaKey]; len(models) != 1 || models[0].ID != "kimi-live" { + t.Fatalf("older picker result replaced the switch's models; cache = %#v", models) } - t.Fatalf("provider switch discovery was discarded as stale; cache = %#v", updated.(model).modelPickerLiveByProvider) } func TestSwitchProviderModelReportsLockedConfigAsNotSavedWithoutPartialSelection(t *testing.T) {