Repository navigation
fix(chatgpt): preserve account discovery and report fallback failures #1178
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
oniisanlabs
wants to merge
11
commits into
Twigpine:main
Choose a base branch
from
oniisanlabs:fix/chatgpt-discovery
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,325
−55
Open
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
9e83f6b
fix(chatgpt): preserve account discovery and report fallback failures
oniisanlabs 7f02517
fix(tui): use working retry hints in model list output
oniisanlabs 53cfc2f
fix(tui): scope discovery notices to refreshed accounts
oniisanlabs 233ee83
fix(chatgpt): normalize invisible error text before redaction
oniisanlabs ba16133
fix(chatgpt): withhold credentials damaged by escapes and cap notices
oniisanlabs 0591249
fix(cli): authenticate headless ChatGPT discovery with the stored login
oniisanlabs b37a504
fix(tui): stop pointing capped picker notices at /model list
oniisanlabs c29f425
fix(tui): size the context window from the active ChatGPT account
oniisanlabs 1c4f575
fix(tui): track model discovery requests per account
oniisanlabs 23dc04d
fix(tui): keep the retry key visible when picker notices are cut
oniisanlabs 1e326c4
fix(tui): register provider-switch discovery before the refresh guard
oniisanlabs File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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) | ||
| } | ||
| } |
141 changes: 141 additions & 0 deletions
141
internal/providermodeldiscovery/chatgpt_catalog_test.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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) | ||
| } | ||
| }) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.