Summary
This is PR 2 of a 4-PR split of #725, following the review feedback that asked for the combined branch to be replaced by focused PRs in dependency order.
IMPORTANT
This PR is stacked on #892 and should be merged after it. I don't have push access to this repository, so the base branch of #892 can't exist here and GitHub forces this PR to target
main. That means the diff shown below includes #892's commit. Review only the second commit —feat(providers): resolve catalog ownership and credential candidates. Once #892 merges, this PR's diff will collapse to that commit alone.
What this PR establishes
Builds on #892's identity primitive to answer a question the old code answered by accident: which persisted provider row owns a given catalog identity, and which credential-store entries a provider command may touch.
Positive catalog ownership
EnsureCatalogProvider previously scanned rows with an EqualFold name-or-catalog match, so it could adopt a row by name alone that had nothing to do with the catalog entry being set up, or silently pick the first of several rows sharing one catalog ID.
providerOwnsCatalog/catalogProviderOwnerrequire positive ownership — a row must actually carry the catalog ID to be adopted for it.- Ambiguity is now an error rather than a file-order coin flip: several rows sharing a catalog ID is rejected instead of adopted.
PreflightCatalogProviderLoginapplies that check before a login burns a browser round trip.
One read-only credential-candidate resolver
ProviderCredentialCandidates is the single place that answers "which credential-store entries does this provider address resolve to." PersistedIdentityMatch / ResolvePersistedProviderIdentity give it exact-name precedence over catalog-ID matching, and CatalogIdentityExclusive reports whether a catalog ID is exclusively owned.
The OAuth surfaces are migrated onto it together, as the review requested — status, refresh, and logout. API-key cleanup remains row-name-scoped because stored API keys are read only by persisted profile name:
runAuthStatus/runAuthRefresh/runAuthRefreshWatch/filterAuthStatusesare candidate-list based rather than single-key based.runAuthLogoutexpands candidates only in the OAuth token store, deletes an API key only for the addressed persisted row name, clears markers viaClearProviderKeyStoredCaseVariants, and now: rejects an ambiguous catalog address, prefers an exactly-named profile, leaves shared catalog credentials alone, and fails closed before changing credentials when config validation fails.- The TUI wizard's key-removal branch (
applyManageKeyChoice) deletes only the persisted row-name entry from the credential store beside the config being edited.
Preflight before irreversible side effects
runAuthLogin, runAuthChatGPT, runAuthOpenRouter, and the TUI/onboarding OAuth and device-code paths now validate config before starting a flow. runAuthChatGPT re-checks immediately before token save to close the window between flow start and persistence — wired through a new BeforeSave hook on oauth.Manager (invoked in Login and CompleteDeviceLogin).
Since persistOAuthLoginProvider can now legitimately fail on an ambiguous or unowned catalog ID, applySetupOAuth turns a previously discarded _ = error into a real path that surfaces to the user instead of silently dropping a completed login.
Exit-code fix
zero auth openrouter previously returned 0 when it minted a key but failed to save it — reporting success for a command that left the provider unusable, which a script would happily carry on from. It now still prints the minted key (the user paid for it with a browser round trip) but exits non-zero with a clear error.
Deliberately out of scope
No locking, no CommitProviderProfile, no provider-selection presentation. saveOpenRouterProviderKey is byte-for-byte unchanged in this PR (verified) — its transaction fix is one of the two P1 findings and belongs to PR 3, so it stays reviewable there rather than being smuggled in here.
Remaining PRs:
3. #894 — Provider config/key transaction — one authoritative operation owning lock acquisition, config read/validation, credential capture, atomic publication, and conditional rollback across the full writer inventory. Carries both P1 fixes: lock acquisition must fail closed, and OpenRouter persistence must join the transaction.
4. #895 — Provider-selection UX and TUI synchronization — list/current/use source and selectability output, ZERO_PROVIDER override explanations, case-only live-session sync.
NOTE
#894 (3/4) is stacked on this PR and should merge after it.
Pre-existing tests adjusted
Both in internal/tui/provider_wizard_test.go, both required by the in-scope behavior change:
TestWizardProviderStoredKey—wizardProviderStoredKeynow returns an error and requires positive ownership, so the{Name: "nokey"}row gained aCatalogID, name-only-match assertions became ownership-rejection assertions, and exact-owner-wins / shared-owner-ambiguity cases were added.TestProviderWizardManageKeyRemove— the Remove branch deletes only the persisted row-name key; the fixture also stores a catalog-alias key and verifies that unrelated entry survives.
Validation
go build ./...go vet ./...gofmt -l .(clean)go test ./...(full suite green — 84 packages, 0 failures)
Refs #721. Split of #725. Stacked on #892.
🤖 Generated with Claude Code
Summary by CodeRabbit
-
New Features
- Added ChatGPT OAuth login support in the CLI and setup wizard.
- Added
providers repair-configto recover legacy provider configurations. - Added validation before OAuth authentication and credential storage.
- Improved provider recognition using catalog identities and normalized names.
-
Bug Fixes
- Prevented ambiguous or duplicate provider configurations from being selected.
- Improved provider use, rename, removal, logout, refresh, and status handling.
- Credential save failures now preserve existing credentials and display errors.
- Improved cleanup and retention of shared credentials across provider variants.
- Doctor reports now surface configuration resolution failures.
Activity
85Actionable comments posted: 6
CAUTION
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/tui/provider_wizard_test.go (1)
1159-1177: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick winAdd a shared-catalog-alias case to the manage-key removal test.
The fixture holds one row, so the test only proves that removal deletes the
acme-cloudalias. It cannot distinguish "always delete the catalog alias" from "delete the catalog alias only when no sibling profile claims it".CatalogIdentityExclusiveexists precisely for that distinction, and deleting a shared alias takes down another profile's login.Add a second case: two rows sharing one
catalogId, remove the key for one of them, then assert that the catalog-alias entry survives.The guideline "Every behavior or security-boundary change requires a regression test, including failure paths" applies here.
#!/bin/bash # Description: Inspect the manage-key removal path to confirm whether it checks # catalog-alias exclusivity before deleting the credential-store entry. set -euo pipefail rg -nP --type=go -C 15 'func \(m model\) applyManageKeyChoice' internal/tui rg -nP --type=go -C 6 'CatalogIdentityExclusive|ProviderCredentialCandidates' internal/tui🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/tui/provider_wizard_test.go` around lines 1159 - 1177, Extend the manage-key removal test around applyManageKeyChoice with a second fixture containing two provider rows that share the same catalogId, then remove one provider’s key and assert the shared catalog-alias entry remains in the credential store. Use CatalogIdentityExclusive to represent the sibling-profile condition, while preserving the existing single-provider assertion that an exclusive alias is deleted.Source: Coding guidelines
🧹 Nitpick comments (8)
internal/tui/onboarding.go (1)
540-564: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick winMake the config path a required parameter instead of a variadic option.
configPath ...stringmakes the preflight gate opt-in.preflightOAuthProviderConfigreturnsnilfor an empty path, so any call site that omits the argument silently skips catalog-ownership validation before an irreversible browser login. Every call site in this file now passesm.setup.configPath, so the variadic form only preserves the risk.Change
setupOAuthCmd,setupDevicePrepareCmd, andsetupDevicePollCmdto takeconfigPath string. The compiler then reports any future call site that forgets it.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/tui/onboarding.go` around lines 540 - 564, Change setupOAuthCmd, setupDevicePrepareCmd, and setupDevicePollCmd to accept a required configPath string instead of a variadic argument, and update their internal path handling to use that value directly. Ensure every call site passes m.setup.configPath so preflightOAuthProviderConfig always receives the configured path and cannot be skipped through omission.internal/config/writer.go (1)
326-365: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConfirm the read-error contract for
ProviderCredentialCandidates.The doc comment states that callers still receive the requested spelling on a config read error. The code satisfies that on lines 337 and 342, but returns
nilon the ambiguity path at line 351. That difference is intentional, so state it in the doc comment: an ambiguous catalog id yields no candidates at all, so no caller can delete a sibling's credential.📝 Suggested doc clarification
// The canonical name is returned separately for marker mutations. On a config // read error, callers still receive the requested spelling so logout can delete -// the credential it was explicitly asked to clear before reporting the error. +// the credential it was explicitly asked to clear before reporting the error. +// An ambiguous catalog id is different: it returns no candidates at all, so a +// destructive caller cannot act on a spelling several profiles could own.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/config/writer.go` around lines 326 - 365, Update the doc comment for ProviderCredentialCandidates to explicitly state that an ambiguous catalog ID returns no candidates, intentionally overriding the usual requested-spelling fallback so callers cannot delete a sibling profile’s credential. Leave the existing ambiguity return behavior unchanged.internal/tui/onboarding_test.go (1)
2186-2215: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winPreflight failure paths are provoked by
EISDIR, not by the identity rules. Each of these tests passes at.TempDir()directory as the config path, soos.ReadFilefails beforeValidatePersistedProviderNamesorcatalogProviderOwnerruns. Every one of them would still pass if the preflight were reduced to a file stat, so they do not protect the security boundary this PR adds. Seed a config file that violates the rule under test, then assert the specific error text.
internal/tui/onboarding_test.go#L2186-L2215: inTestApplySetupOAuthTokenPersistFailureStaysOnProviderandTestSetupDevicePreparePreflightsConfigBeforeRequestingCode, write a realconfig.jsoncontaining two rows whose names differ only by case, and assert the error containsdiffer only by case.internal/tui/provider_wizard_oauth_test.go#L453-L461: inTestProviderWizardDevicePreparePreflightsConfigBeforeRequestingCode, write a realconfig.jsonthe same way, keep theattemptIDassertion, and assert the specific error text.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/tui/onboarding_test.go` around lines 2186 - 2215, The onboarding tests in internal/tui/onboarding_test.go lines 2186-2215 must exercise the provider-name validation rather than EISDIR handling: update TestApplySetupOAuthTokenPersistFailureStaysOnProvider and TestSetupDevicePreparePreflightsConfigBeforeRequestingCode to write a real config.json containing two rows whose names differ only by case, then assert the error contains “differ only by case”; preserve the existing stage, command, and failure assertions. In internal/tui/provider_wizard_oauth_test.go lines 453-461, make the same config fixture change in TestProviderWizardDevicePreparePreflightsConfigBeforeRequestingCode, retain the attemptID assertion, and assert the specific “differ only by case” error text.Source: Coding guidelines
internal/config/credentials.go (1)
102-111: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider one helper with a match predicate.
ClearProviderKeyStoredandClearProviderKeyStoredCaseVariantsshare the whole read, parse, mutate, write sequence. They differ only in the name comparison. Extract a private helper that takes amatch func(string) booland keep both exported wrappers.♻️ Proposed refactor
+func clearProviderKeyStoredWhere(path string, match func(name string) bool) (bool, error) { + path = strings.TrimSpace(path) + if path == "" { + return false, nil + } + data, err := os.ReadFile(path) + if err != nil { + if os.IsNotExist(err) { + return false, nil + } + return false, fmt.Errorf("read config %s: %w", path, err) + } + var cfg FileConfig + if err := json.Unmarshal(data, &cfg); err != nil { + return false, fmt.Errorf("invalid config JSON %s: %w", path, err) + } + changed := false + for index := range cfg.Providers { + if match(cfg.Providers[index].Name) && cfg.Providers[index].APIKeyStored { + cfg.Providers[index].APIKeyStored = false + changed = true + } + } + if !changed { + return false, nil + } + return true, writeConfigFile(path, cfg) +}Also applies to: 119-148
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/config/credentials.go` around lines 102 - 111, Extract the shared read, parse, mutation, and write flow from ClearProviderKeyStored and ClearProviderKeyStoredCaseVariants into one private helper accepting a match func(string) bool. Keep both exported wrappers, passing predicates for their respective provider-name comparison behavior, and preserve the existing APIKeyStored and return-value semantics.internal/cli/auth_test.go (2)
837-851: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueThe
calls > 1trigger couples the test to the number ofuserConfigPathcalls.
TestRunAuthOpenRouterFailsWhenTheKeyCannotBeSavedassumes the preflight consumes exactly one call and the save consumes the second. A future extra lookup inrunAuthOpenRouterwould silently move the failure point. Consider failing on a call that follows the login instead, for example by flipping a flag insideopenRouterLogin.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/cli/auth_test.go` around lines 837 - 851, Update TestRunAuthOpenRouterFailsWhenTheKeyCannotBeSaved so the injected userConfigPath failure is triggered by state set in openRouterLogin, rather than by the calls > 1 counter. Keep preflight lookups successful, set the failure flag after login succeeds, and have subsequent config-path access return the save error.
317-328: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse one config-reading test helper.
This file now has
readCLIConfigFixture(line 317) and still callsreadFileConfig(line 993). Both decodeconfig.FileConfigfrom a path. Keep one helper so later tests do not have to choose.Also applies to: 993-993
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/cli/auth_test.go` around lines 317 - 328, Consolidate the duplicate config-reading helpers in internal/cli/auth_test.go: keep a single helper for reading and unmarshalling config.FileConfig, and update the call around readFileConfig to use readCLIConfigFixture or rename the retained helper consistently. Remove the redundant helper while preserving existing test behavior.internal/tui/provider_wizard.go (1)
216-228: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick winThe optional config path lets OAuth flows skip catalog-ownership validation.
preflightOAuthProviderConfigreturns nil when the path is empty, and theconfigPath ...stringsignatures let any caller omit the path. A call site that forgets the argument saves the token with no validation, and the compiler reports nothing.
internal/tui/provider_wizard.go#L216-L228: makepatha required parameter on the login and device helpers, and dropfirstString, so omission becomes a compile error.internal/tui/oauth_device.go#L62-L66: changeoauthDeviceCompleteto takeconfigPath stringand updateproviderWizardDevicePollCmdandsetupDevicePollCmdaccordingly.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/tui/provider_wizard.go` around lines 216 - 228, Make the OAuth config path mandatory throughout the provider wizard: in internal/tui/provider_wizard.go:216-228, remove firstString and require path in the login and device helper signatures, updating callers so omissions fail at compile time; in internal/tui/oauth_device.go:62-66, change oauthDeviceComplete to require configPath string and pass it through providerWizardDevicePollCmd and setupDevicePollCmd. Preserve catalog-ownership preflight validation for every OAuth flow.internal/oauth/manager.go (1)
152-156: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd
internal/oauthregression tests for theBeforeSavefailure path.When
BeforeSavereturns an error, assert that bothLoginandCompleteDeviceLoginreturn that error and leave the store unchanged.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/oauth/manager.go` around lines 152 - 156, Add regression tests in the internal/oauth test suite covering the beforeSave hook in the manager flow: configure BeforeSave to return a sentinel error, then assert both Login and CompleteDeviceLogin return that exact error and verify the backing store remains unchanged. Reuse existing manager/store test helpers and target the beforeSave invocation path shown in the diff.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/cli/auth.go`:
- Around line 653-679: Handle an empty credentialCandidates result immediately
after config.ProviderCredentialCandidates in the affected auth refresh flows,
before runAuthRefresh or runAuthRefreshWatch can iterate it. Return a crash
error through writeAppError using the existing redaction conventions, and
preserve the current behavior for non-empty candidate sets.
In `@internal/config/resolver.go`:
- Around line 962-985: Update active-provider selection around activeIndex to
compare against each provider’s effective name, applying normalizeProvider’s
empty-name default of "openai" before matching. Preserve exact-name precedence
and sameProviderIdentity ambiguity handling, and add regression coverage for
both ValidateBytes and LoadProviderCommand with activeProvider:"openai" and a
nameless OpenAI row.
In `@internal/config/writer_test.go`:
- Around line 1378-1388: Rename the subtest around
ResolvePersistedProviderIdentity from “a shared catalog id resolves to nothing”
to describe that the case-variant “XAI” resolves to the persisted identity name,
matching the PersistedIdentityName assertion and existing inline comment.
In `@internal/config/writer.go`:
- Around line 526-530: Update runProvidersUse, runProvidersRemove, and
runProvidersRename to resolve each raw CLI provider argument to its canonical
persisted Name before calling ProviderPersisted or other exact-match mutations,
supporting case variants and unique catalog IDs. Add tests covering both input
forms for all affected commands.
In `@internal/tui/provider_wizard_discovery.go`:
- Around line 156-159: Update aimlapiProfile to recognize legacy AIMLAPI
profiles by falling back to the profile name when CatalogID is empty, while
preserving the existing CatalogID identity check when present. Add a regression
test covering a saved profile named “aimlapi” without catalogID and verify
discovery does not re-onboard or overwrite its settings.
In `@internal/tui/provider_wizard.go`:
- Around line 1387-1421: After successful stored-key removal in the Remove path,
update the matching entry in m.savedProviders so its APIKeyStored state is
cleared, including the case-insensitive provider match used by the deletion
flow. Ensure reopening the provider wizard and selecting the same provider no
longer offers Keep/Replace/Remove, and add a regression test covering this
in-memory refresh.
---
Outside diff comments:
In `@internal/tui/provider_wizard_test.go`:
- Around line 1159-1177: Extend the manage-key removal test around
applyManageKeyChoice with a second fixture containing two provider rows that
share the same catalogId, then remove one provider’s key and assert the shared
catalog-alias entry remains in the credential store. Use
CatalogIdentityExclusive to represent the sibling-profile condition, while
preserving the existing single-provider assertion that an exclusive alias is
deleted.
---
Nitpick comments:
In `@internal/cli/auth_test.go`:
- Around line 837-851: Update TestRunAuthOpenRouterFailsWhenTheKeyCannotBeSaved
so the injected userConfigPath failure is triggered by state set in
openRouterLogin, rather than by the calls > 1 counter. Keep preflight lookups
successful, set the failure flag after login succeeds, and have subsequent
config-path access return the save error.
- Around line 317-328: Consolidate the duplicate config-reading helpers in
internal/cli/auth_test.go: keep a single helper for reading and unmarshalling
config.FileConfig, and update the call around readFileConfig to use
readCLIConfigFixture or rename the retained helper consistently. Remove the
redundant helper while preserving existing test behavior.
In `@internal/config/credentials.go`:
- Around line 102-111: Extract the shared read, parse, mutation, and write flow
from ClearProviderKeyStored and ClearProviderKeyStoredCaseVariants into one
private helper accepting a match func(string) bool. Keep both exported wrappers,
passing predicates for their respective provider-name comparison behavior, and
preserve the existing APIKeyStored and return-value semantics.
In `@internal/config/writer.go`:
- Around line 326-365: Update the doc comment for ProviderCredentialCandidates
to explicitly state that an ambiguous catalog ID returns no candidates,
intentionally overriding the usual requested-spelling fallback so callers cannot
delete a sibling profile’s credential. Leave the existing ambiguity return
behavior unchanged.
In `@internal/oauth/manager.go`:
- Around line 152-156: Add regression tests in the internal/oauth test suite
covering the beforeSave hook in the manager flow: configure BeforeSave to return
a sentinel error, then assert both Login and CompleteDeviceLogin return that
exact error and verify the backing store remains unchanged. Reuse existing
manager/store test helpers and target the beforeSave invocation path shown in
the diff.
In `@internal/tui/onboarding_test.go`:
- Around line 2186-2215: The onboarding tests in internal/tui/onboarding_test.go
lines 2186-2215 must exercise the provider-name validation rather than EISDIR
handling: update TestApplySetupOAuthTokenPersistFailureStaysOnProvider and
TestSetupDevicePreparePreflightsConfigBeforeRequestingCode to write a real
config.json containing two rows whose names differ only by case, then assert the
error contains “differ only by case”; preserve the existing stage, command, and
failure assertions. In internal/tui/provider_wizard_oauth_test.go lines 453-461,
make the same config fixture change in
TestProviderWizardDevicePreparePreflightsConfigBeforeRequestingCode, retain the
attemptID assertion, and assert the specific “differ only by case” error text.
In `@internal/tui/onboarding.go`:
- Around line 540-564: Change setupOAuthCmd, setupDevicePrepareCmd, and
setupDevicePollCmd to accept a required configPath string instead of a variadic
argument, and update their internal path handling to use that value directly.
Ensure every call site passes m.setup.configPath so preflightOAuthProviderConfig
always receives the configured path and cannot be skipped through omission.
In `@internal/tui/provider_wizard.go`:
- Around line 216-228: Make the OAuth config path mandatory throughout the
provider wizard: in internal/tui/provider_wizard.go:216-228, remove firstString
and require path in the login and device helper signatures, updating callers so
omissions fail at compile time; in internal/tui/oauth_device.go:62-66, change
oauthDeviceComplete to require configPath string and pass it through
providerWizardDevicePollCmd and setupDevicePollCmd. Preserve catalog-ownership
preflight validation for every OAuth flow.🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: f84481b6-bf87-4d4a-aedb-c309dccb4787
📥 Commits
Reviewing files that changed from the base of the PR and between cabfeefc4eb9d247d907d3dee0786fe2e745207d and 66936d432f99f07e107be882ce78e55872e704a6.
📒 Files selected for processing (18)
internal/cli/app.gointernal/cli/auth.gointernal/cli/auth_test.gointernal/config/credentials.gointernal/config/credentials_test.gointernal/config/resolver.gointernal/config/resolver_test.gointernal/config/writer.gointernal/config/writer_test.gointernal/credstore/credstore.gointernal/oauth/manager.gointernal/tui/oauth_device.gointernal/tui/onboarding.gointernal/tui/onboarding_test.gointernal/tui/provider_wizard.gointernal/tui/provider_wizard_discovery.gointernal/tui/provider_wizard_oauth_test.gointernal/tui/provider_wizard_test.go
Actionable comments posted: 4
🧹 Nitpick comments (1)
internal/config/validate_test.go (1)
37-40: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAssert the normalized profile name.
The test only checks
cfg.ActiveProvider, but the fixture already sets"activeProvider":"openai". A regression could leave the nameless profile'sNameempty and still satisfy these assertions. Also assert one provider withName == "openai"to protect the canonical identity consumed by provider mutations. The corresponding command test checks this atinternal/config/command_test.goLines 43-44.Proposed regression assertion
if cfg.ActiveProvider != "openai" { t.Fatalf("activeProvider = %q, want openai", cfg.ActiveProvider) } + if len(cfg.Providers) != 1 || cfg.Providers[0].Name != "openai" { + t.Fatalf("providers = %+v, want normalized nameless OpenAI provider", cfg.Providers) + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/config/validate_test.go` around lines 37 - 40, Extend the validation test’s assertions to verify that the normalized provider profile has Name equal to "openai", in addition to checking cfg.ActiveProvider. Locate the provider collection produced by the validation flow and assert the matching provider’s canonical Name, preserving the existing active-provider assertion.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/cli/provider_onboarding.go`:
- Around line 529-537: Reject ambiguous case-folded provider names before
removal: update resolvePersistedProviderName in
internal/cli/provider_onboarding.go:529-537 to return an ambiguity error when a
non-exact identity matches multiple profiles, while preserving exact-name
removal. Ensure RemoveProvider at internal/cli/provider_onboarding.go:403-419
propagates that error without deleting any profile or stored credential. Add a
regression test in internal/cli/provider_onboarding_test.go:46-94 using work,
WORK, and wOrK, asserting the command fails and both profiles and credentials
remain unchanged.
In `@internal/oauth/manager_test.go`:
- Around line 205-220: Update the test setup around test.run and BeforeSave to
seed ProviderKey("demo") with an old token before each run, then assert that the
same provider’s token remains unchanged when BeforeSave fails. Replace the
unrelated ProviderKey("existing") preservation check with a same-provider
assertion while retaining validation that the rejected token was not persisted.
In `@internal/tui/provider_wizard_test.go`:
- Around line 1888-1891: Extend the assertion in the
existingAimlapiConfiguration test to verify that profile.BaseURL matches the
legacy endpoint supplied by the test fixture, while preserving the current
checks for runtimeKey, profile name, model, and success status.
- Around line 1181-1185: The provider key-removal tests must verify persisted
configuration markers, not only in-memory or credential-store state. In
internal/tui/provider_wizard_test.go:1181-1185, reload configPath after
exclusive removal and assert acme.APIKeyStored is false; in
internal/tui/provider_wizard_test.go:1210-1212, reload it after shared-secret
removal and assert work-acme.APIKeyStored is false while
personal-acme.APIKeyStored remains true. Keep the existing
wizardProviderStoredKey assertions and failure diagnostics.
---
Nitpick comments:
In `@internal/config/validate_test.go`:
- Around line 37-40: Extend the validation test’s assertions to verify that the
normalized provider profile has Name equal to "openai", in addition to checking
cfg.ActiveProvider. Locate the provider collection produced by the validation
flow and assert the matching provider’s canonical Name, preserving the existing
active-provider assertion.🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 29501e79-8e02-4912-a635-72a7e22b5310
📥 Commits
Reviewing files that changed from the base of the PR and between 66936d432f99f07e107be882ce78e55872e704a6 and 296573e35b9cb1840fe87a2f84d74d462718e810.
📒 Files selected for processing (18)
internal/cli/auth.gointernal/cli/auth_test.gointernal/cli/provider_onboarding.gointernal/cli/provider_onboarding_test.gointernal/config/command_test.gointernal/config/credentials.gointernal/config/resolver.gointernal/config/validate_test.gointernal/config/writer.gointernal/config/writer_test.gointernal/oauth/manager_test.gointernal/tui/oauth_device.gointernal/tui/onboarding.gointernal/tui/onboarding_test.gointernal/tui/provider_wizard.gointernal/tui/provider_wizard_discovery.gointernal/tui/provider_wizard_oauth_test.gointernal/tui/provider_wizard_test.go
🚧 Files skipped from review as they are similar to previous changes (11)
- internal/config/credentials.go
- internal/config/resolver.go
- internal/tui/provider_wizard_oauth_test.go
- internal/tui/oauth_device.go
- internal/tui/onboarding_test.go
- internal/tui/provider_wizard_discovery.go
- internal/tui/onboarding.go
- internal/tui/provider_wizard.go
- internal/cli/auth.go
- internal/config/writer.go
- internal/config/writer_test.go
blocked until #892 lands
8ae2036Refreshed onto current main through the stack. Details and verification are in https://github.com/Twigpine/zero/pull/892#issuecomment-6169506807; summary: this PR only took the merge of the PR below it (one import-line conflict), with no changes of its own.
7778f9f9bdd076@Vasanthdev2004 Refreshed on the fixed #892 (df51fe4d). The only change of its own is a test fix: TestProviderIdentityMatrix now calls clearProviderEnv, because resolveProviderMutationName reads source names from the process environment, so an exported OPENAI_API_KEY made its case-variant use refuse, as it should. The full write-up is on #892.
Walkthrough
The PR centralizes provider identity and catalog ownership validation across configuration, credentials, CLI authentication, and TUI OAuth flows. Login paths preflight before authentication and saving. Status, refresh, logout, and provider mutations resolve canonical identities and credential candidates. It also adds legacy configuration repair and improved diagnostics.
Changes
Provider identity and OAuth authentication
internal/credstore/credstore.go,internal/config/credentials.go,internal/config/provider_ownership.go,internal/config/resolver.go,internal/config/writer.go,internal/config/*_test.gointernal/cli/app.go,internal/cli/auth.go,internal/cli/auth_test.gointernal/oauth/manager.go,internal/tui/oauth_device.go,internal/tui/onboarding.go,internal/tui/provider_wizard*.go,internal/tui/*_test.goBeforeSavevalidation. Onboarding and provider-wizard flows pass configuration paths, enforce catalog ownership, surface persistence errors, and prevent advancement after failed saves.internal/cli/provider_onboarding.go,internal/tui/provider_manager.go,internal/tui/command_center.go,internal/tui/model.go,internal/tui/picker.go,internal/cli/provider_onboarding_test.go,internal/tui/*_test.gointernal/cli/command_center.go,internal/cli/completions.go,internal/cli/observability.go,internal/doctor/doctor.go,internal/cli/setup.go,internal/cli/provider_setup.go,README.md,README_ZH.md,CHANGELOG.md,docs/oauth-subscriptions.mdproviders repair-configcommand repairs legacy unnamed profiles. Provider writes preflight configuration. Doctor reports configuration resolution failures. Command completion and documentation include the repair flow.Estimated code review effort: 4 (Complex) | ~60 minutes
Sequence Diagram(s)
Suggested reviewers:
kevincodex1,gnanam1990,anandh8x,vasanthdev2004Merge Risk: Moderate · up to
542c2This PR changes provider ownership resolution and credential cleanup. At the current head, credential removal may report success while leaving the secret stored, and provider setup or UI paths may reject valid profiles or create duplicates. The PR should not merge until these bounded correctness and credential-handling issues are addressed.
Pre-merge checks: 4 · 1
✨ Finishing Touches
🧪 Generate unit tests (beta)
Comment
@coderabbitai helpto get the list of available commands.