#893

Resolve catalog ownership and credential candidates (2/4)

OpenPierrunoYTwants to merge intofrom

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 / catalogProviderOwner require 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.
  • PreflightCatalogProviderLogin applies 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 / filterAuthStatuses are candidate-list based rather than single-key based.
  • runAuthLogout expands candidates only in the OAuth token store, deletes an API key only for the addressed persisted row name, clears markers via ClearProviderKeyStoredCaseVariants, 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 — wizardProviderStoredKey now returns an error and requires positive ownership, so the {Name: "nokey"} row gained a CatalogID, 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-config to 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

85
coderabbitai[bot]3mo ago

NOTE

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

  • Last reviewed commit: 542c2231c4d1a393b59321af9f99593cb532c146
  • Latest commit, not reviewed: df51fe4d39264794384bc42e7b12fa0469acaf0b

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

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

Layer / File(s)Summary
Provider identity and configuration contracts
internal/credstore/credstore.go, internal/config/credentials.go, internal/config/provider_ownership.go, internal/config/resolver.go, internal/config/writer.go, internal/config/*_test.go
Provider normalization, duplicate validation, catalog ownership checks, exact mutations, credential candidates, active-provider resolution, repair, and marker cleanup now use explicit identity rules.
CLI authentication and credential lifecycle
internal/cli/app.go, internal/cli/auth.go, internal/cli/auth_test.go
CLI login flows preflight configuration before authentication and saving. Status and refresh resolve candidate credentials. Logout removes matching credentials and reports cleanup failures.
TUI OAuth and device authentication
internal/oauth/manager.go, internal/tui/oauth_device.go, internal/tui/onboarding.go, internal/tui/provider_wizard*.go, internal/tui/*_test.go
OAuth managers support BeforeSave validation. Onboarding and provider-wizard flows pass configuration paths, enforce catalog ownership, surface persistence errors, and prevent advancement after failed saves.
Provider mutation identity resolution
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.go
Provider use, remove, rename, model switching, and key cleanup resolve persisted identities and preserve credentials that remain owned by surviving profiles.
Repair, diagnostics, wiring, and documentation
internal/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.md
The providers repair-config command 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)

sequenceDiagram
  participant User
  participant CLI_or_TUI
  participant Config
  participant OAuthManager
  participant CredentialStore
  User->>CLI_or_TUI: start provider login
  CLI_or_TUI->>Config: preflight provider configuration
  CLI_or_TUI->>OAuthManager: authorize provider
  OAuthManager->>Config: revalidate before save
  OAuthManager->>CredentialStore: persist token
  CredentialStore-->>CLI_or_TUI: return save result
  CLI_or_TUI-->>User: report success or error

Suggested reviewers: kevincodex1, gnanam1990, anandh8x, vasanthdev2004

Merge Risk: Moderate · up to 542c2

This 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

Failed checks: 1 warning

Check nameStatusExplanationResolution
Docstring CoverageDocstring coverage is 45.96% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 285 functions across 46 files.Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed checks: 4 passed
Check nameStatusExplanation
Linked Issues checkCheck skipped because no linked issues were found for this pull request.
Out of Scope Changes checkCheck skipped because no linked issues were found for this pull request.
Title checkThe title clearly summarizes the main changes: catalog ownership resolution and shared credential-candidate handling. The “(2/4)” suffix identifies the stacked PR sequence without obscuring the scope.
Description CheckCheck skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

coderabbitai[bot]requested changes3mo ago
coderabbitai[bot]3mo ago

Actionable 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 win

Add 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-cloud alias. It cannot distinguish "always delete the catalog alias" from "delete the catalog alias only when no sibling profile claims it". CatalogIdentityExclusive exists 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 win

Make the config path a required parameter instead of a variadic option.

configPath ...string makes the preflight gate opt-in. preflightOAuthProviderConfig returns nil for 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 passes m.setup.configPath, so the variadic form only preserves the risk.

Change setupOAuthCmd, setupDevicePrepareCmd, and setupDevicePollCmd to take configPath 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 value

Confirm 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 nil on 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 win

Preflight failure paths are provoked by EISDIR, not by the identity rules. Each of these tests passes a t.TempDir() directory as the config path, so os.ReadFile fails before ValidatePersistedProviderNames or catalogProviderOwner runs. 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: in TestApplySetupOAuthTokenPersistFailureStaysOnProvider and TestSetupDevicePreparePreflightsConfigBeforeRequestingCode, write a real config.json containing two rows whose names differ only by case, and assert the error contains differ only by case.
  • internal/tui/provider_wizard_oauth_test.go#L453-L461: in TestProviderWizardDevicePreparePreflightsConfigBeforeRequestingCode, write a real config.json the same way, keep the attemptID assertion, 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 value

Consider one helper with a match predicate.

ClearProviderKeyStored and ClearProviderKeyStoredCaseVariants share the whole read, parse, mutate, write sequence. They differ only in the name comparison. Extract a private helper that takes a match func(string) bool and 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 value

The calls > 1 trigger couples the test to the number of userConfigPath calls.

TestRunAuthOpenRouterFailsWhenTheKeyCannotBeSaved assumes the preflight consumes exactly one call and the save consumes the second. A future extra lookup in runAuthOpenRouter would silently move the failure point. Consider failing on a call that follows the login instead, for example by flipping a flag inside openRouterLogin.

🤖 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 value

Use one config-reading test helper.

This file now has readCLIConfigFixture (line 317) and still calls readFileConfig (line 993). Both decode config.FileConfig from 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 win

The optional config path lets OAuth flows skip catalog-ownership validation. preflightOAuthProviderConfig returns nil when the path is empty, and the configPath ...string signatures 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: make path a required parameter on the login and device helpers, and drop firstString, so omission becomes a compile error.
  • internal/tui/oauth_device.go#L62-L66: change oauthDeviceComplete to take configPath string and update providerWizardDevicePollCmd and setupDevicePollCmd accordingly.
🤖 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 win

Add internal/oauth regression tests for the BeforeSave failure path.

When BeforeSave returns an error, assert that both Login and CompleteDeviceLogin return 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.go
  • internal/cli/auth.go
  • internal/cli/auth_test.go
  • internal/config/credentials.go
  • internal/config/credentials_test.go
  • internal/config/resolver.go
  • internal/config/resolver_test.go
  • internal/config/writer.go
  • internal/config/writer_test.go
  • internal/credstore/credstore.go
  • internal/oauth/manager.go
  • internal/tui/oauth_device.go
  • internal/tui/onboarding.go
  • internal/tui/onboarding_test.go
  • internal/tui/provider_wizard.go
  • internal/tui/provider_wizard_discovery.go
  • internal/tui/provider_wizard_oauth_test.go
  • internal/tui/provider_wizard_test.go
coderabbitai[bot]requested changes3mo ago
coderabbitai[bot]3mo ago

Actionable comments posted: 4

🧹 Nitpick comments (1)
internal/config/validate_test.go (1)

37-40: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Assert the normalized profile name.

The test only checks cfg.ActiveProvider, but the fixture already sets "activeProvider":"openai". A regression could leave the nameless profile's Name empty and still satisfy these assertions. Also assert one provider with Name == "openai" to protect the canonical identity consumed by provider mutations. The corresponding command test checks this at internal/config/command_test.go Lines 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.go
  • internal/cli/auth_test.go
  • internal/cli/provider_onboarding.go
  • internal/cli/provider_onboarding_test.go
  • internal/config/command_test.go
  • internal/config/credentials.go
  • internal/config/resolver.go
  • internal/config/validate_test.go
  • internal/config/writer.go
  • internal/config/writer_test.go
  • internal/oauth/manager_test.go
  • internal/tui/oauth_device.go
  • internal/tui/onboarding.go
  • internal/tui/onboarding_test.go
  • internal/tui/provider_wizard.go
  • internal/tui/provider_wizard_discovery.go
  • internal/tui/provider_wizard_oauth_test.go
  • internal/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
jatmn3mo ago

blocked until #892 lands

PierrunoYT1mo ago

Refreshed 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.

PierrunoYT1mo ago

@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.