diff --git a/docs/oauth-subscriptions.md b/docs/oauth-subscriptions.md index 6bb70c98d..ad81c81b0 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/cli/exec.go b/internal/cli/exec.go index 8369a90ad..498fef580 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 000000000..c373851ff --- /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) + } +} diff --git a/internal/providermodeldiscovery/chatgpt_catalog_test.go b/internal/providermodeldiscovery/chatgpt_catalog_test.go new file mode 100644 index 000000000..83dfd6cc5 --- /dev/null +++ b/internal/providermodeldiscovery/chatgpt_catalog_test.go @@ -0,0 +1,141 @@ +package providermodeldiscovery + +import ( + "context" + "errors" + "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" + // 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) { + 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 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/discovery.go b/internal/providermodeldiscovery/discovery.go index 9087ea6d7..9b1484bd3 100644 --- a/internal/providermodeldiscovery/discovery.go +++ b/internal/providermodeldiscovery/discovery.go @@ -16,7 +16,6 @@ import ( "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 ( @@ -55,6 +54,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 +286,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 +745,12 @@ 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, - }})) + secrets = append(secrets, profile.APIKey, profile.AuthHeaderValue) + 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 000000000..5fd7cf9c3 --- /dev/null +++ b/internal/providermodeldiscovery/redaction.go @@ -0,0 +1,108 @@ +package providermodeldiscovery + +import ( + "errors" + "fmt" + "strings" + "unicode" + + "github.com/Twigpine/zero/internal/redaction" + "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. +func RedactError(err error, secrets ...string) error { + if err == nil { + return nil + } + message := strings.Map(func(r rune) rune { + 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 + // 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]) + } + 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) || invisibleRune(r) { + return -1 + } + return r + }, s) +} diff --git a/internal/providermodeldiscovery/redaction_test.go b/internal/providermodeldiscovery/redaction_test.go new file mode 100644 index 000000000..c07c985e0 --- /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/chatgpt_models_test.go b/internal/tui/chatgpt_models_test.go new file mode 100644 index 000000000..7dc376e1b --- /dev/null +++ b/internal/tui/chatgpt_models_test.go @@ -0,0 +1,487 @@ +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", endpointKey: "subscription", 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", endpointKey: "subscription", 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", 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) + } +} + +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 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 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) { + 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") + } +} + +// 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() + 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", "\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 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) + } + }) + } +} + +func TestSubscriptionPickerIgnoresSupersededRefresh(t *testing.T) { + m := subscriptionTestModel(t) + m.modelPickerDiscoveryRequests = map[string]int{"subscription": 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") + } +} + +// /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") + } +} + +// 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) } + +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) + } + }) + } +} + +func TestSubscriptionSupersededModelListStillPrints(t *testing.T) { + m := subscriptionTestModel(t) + 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{ + 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/command_center.go b/internal/tui/command_center.go index 8a766e191..454459a0d 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) @@ -781,8 +785,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/image_attach_test.go b/internal/tui/image_attach_test.go index 2544c963d..906059cbb 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 2ac1fddde..77900a5e9 100644 --- a/internal/tui/model.go +++ b/internal/tui/model.go @@ -577,6 +577,14 @@ 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 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 @@ -2093,6 +2101,10 @@ 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 { + return m.modelPickerDiscoveryCmds() + } case keyCtrl(msg, 'f'): if m.picker != nil && m.picker.kind == pickerModel { if m.modelPickerIsLoading() { @@ -3214,7 +3226,24 @@ func (m model) updateModel(msg tea.Msg) (tea.Model, tea.Cmd) { case setupOAuthDeviceMsg: return m.applySetupOAuthDeviceCode(msg) case modelPickerModelsDiscoveredMsg: - return m.applyModelPickerModelsDiscovered(msg), nil + requested, tracked := m.modelPickerDiscoveryRequests[modelPickerDiscoveryKey(msg.endpointKey, msg.providerID)] + 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 { + m.transcript = reduceTranscript(m.transcript, transcriptAction{kind: actionAppendSystem, text: m.modelListText()}) + } + 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 +5153,11 @@ 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" { + if next, cmd := m.modelListDiscoveryCmd(); cmd != nil { + return next, 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 645cc1309..53821c5ef 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([]config.ProviderProfile{m.providerProfile}, "Run /model list"), "use /model to switch this TUI session; /model list refreshes availability"), }) } @@ -69,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 } } diff --git a/internal/tui/mouse.go b/internal/tui/mouse.go index 0a20636fc..50f5bb9c0 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 3539b60b3..33cb47b90 100644 --- a/internal/tui/mouse_test.go +++ b/internal/tui/mouse_test.go @@ -2,6 +2,7 @@ package tui import ( "context" + "fmt" "strings" "testing" @@ -1035,6 +1036,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() @@ -1129,3 +1160,84 @@ 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) + // 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 notices hidden. Ctrl+R to retry."} { + 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) + } + } + } +} + +// 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. 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 + 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) + } + 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/onboarding.go b/internal/tui/onboarding.go index 002987786..560c43aa2 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 0490ff751..f2a6834f6 100644 --- a/internal/tui/picker.go +++ b/internal/tui/picker.go @@ -2,6 +2,7 @@ package tui import ( "context" + "fmt" "os" "sort" "strings" @@ -303,7 +304,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] } @@ -389,41 +391,87 @@ func (m model) openModelPicker() (model, tea.Cmd) { // 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...) +} + +// 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 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 { @@ -452,16 +500,75 @@ 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. +// 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 m, nil + } + m, cmd := m.requestProviderDiscoveryCmd(descriptor, m.providerProfile) + if cmd == nil { + return m, nil + } + return m, func() tea.Msg { + msg := cmd().(modelPickerModelsDiscoveredMsg) + msg.showList = true + return msg + } +} + +// 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 profiles { + descriptor, ok := m.descriptorForProfile(profile) + if !ok { + continue + } + key := providerEndpointKey(profile, descriptor) + failure := m.modelPickerErrorsByProvider[key] + 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(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(discovered) == 0 { + notices = append(notices, label+": fallback suggestions (unverified). "+refreshAction+" to refresh.") + } + } + return notices +} + func (m model) modelPickerDiscoveryOptions(profile config.ProviderProfile) providermodeldiscovery.Options { oauthResolver, loginKey := providers.OAuthLoginForProfile(profile) return providermodeldiscovery.Options{ @@ -902,6 +1009,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) } @@ -941,6 +1053,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 +1142,19 @@ func profileMatchesProviderBaseURL(profile config.ProviderProfile, provider prov func (m model) applyModelPickerModelsDiscovered(msg modelPickerModelsDiscoveredMsg) model { m.modelPickerLoading = false m.modelPickerLoadingProviderID = "" + key := modelPickerDiscoveryKey(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 { + 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" + } + m.modelPickerErrorsByProvider = errorsByProvider if msg.err != nil || len(msg.models) == 0 { return m } @@ -1038,7 +1166,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/picker_test.go b/internal/tui/picker_test.go index 291ce2f2e..9a7f09339 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" @@ -213,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) @@ -288,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...") @@ -853,6 +858,83 @@ func TestSwitchProviderModelRecordsRecentHistory(t *testing.T) { } } +// 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() + 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() + 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 modelPickerModelsDiscoveredMsg + found := false + for _, sub := range cmd().(tea.BatchMsg) { + if msg, ok := sub().(modelPickerModelsDiscoveredMsg); ok { + result, found = msg, true + } + } + 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) + 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) + } +} + 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 { diff --git a/internal/tui/provider_wizard_discovery.go b/internal/tui/provider_wizard_discovery.go index 564735fd4..ea2f26f6d 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 71d7f941a..d87c75efe 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 @@ -1071,8 +1073,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)) - if status := strings.TrimSpace(m.modelPickerLoadError); status != "" { - lines = append(lines, fillPaletteLine(searchPrefix+zeroTheme.faint.Render(status), 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 := "" @@ -1110,6 +1112,49 @@ 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. 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 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(), retryHint) { + rows := strings.Split(ansi.Wrap(status, width, ""), "\n") + wrapped = append(wrapped, rows) + total += len(rows) + } + 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 + } + retry := retryHint + " to retry." + more := "… notice truncated. " + retry + if hidden := len(wrapped) - shown; hidden > 0 { + 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, "…")) +} + func (m model) modelPickerLoadingOverlay(width int) string { overlayWidth := modelPickerLoadingOverlayWidth(width) innerWidth := maxInt(1, overlayWidth-4)