#895

Clarify provider selection and synchronize live TUI state (4/4)

OpenPierrunoYTwants to merge intofrom

Summary

This is PR 4 of the 4-PR split of #725, completing the split requested during review of the combined provider-selection change.

IMPORTANT

This PR is stacked on #894, which is stacked on #893, and should be merged last. GitHub requires this cross-fork PR to target an upstream branch, so the displayed diff includes the predecessor commits. Review only the final commit: feat(providers): clarify selection source and live sync. Once the predecessors merge, this diff will collapse to that commit.

What changed

  • providers list and providers current text/JSON now expose exact selectable and source (user-config or resolved) metadata. Exact casing prevents project, provider-command, or environment case variants from being mislabeled as selectable through providers use.
  • providers use now explains ZERO_PROVIDER outcomes accurately: resolved and effective, unresolvable, deferred when ZERO_PROVIDER_COMMAND is configured without executing it, and unrelated configuration errors reported as config-error instead of blaming the override.
  • JSON output includes envProvider, envProviderResolves, and resolution metadata.
  • Case-only environment overrides are suppressed only when resolution proves they select the same persisted row; an exact case-variant project provider remains a real override.
  • TUI provider state uses exact live-profile identity. A case-only rename of the live persisted row synchronizes the session profile and ZERO_PROVIDER, while editing user profile work cannot retarget a live project profile WORK.
  • In-memory edit/upsert and picker lookup preserve exact-row precedence.

Scope

Locking, provider config/key transactions, credential rollback, and OpenRouter persistence are isolated in #894.

Validation

  • make fmt-check
  • go vet ./...
  • go test ./...
  • go test -race ./internal/config ./internal/cli ./internal/tui -count=1
  • go run ./cmd/zero-release build
  • go run ./cmd/zero-release smoke
  • make lint-static (0 issues.)
  • make vulncheck (No vulnerabilities found.)
  • git diff HEAD --check

Refs #721. Split of #725. Stacked on #894.

Summary by CodeRabbit

  • New Features

    • Added ChatGPT OAuth login support in CLI and setup flows.
    • Provider listings now show selection status and resolution source.
    • Provider management supports capitalization variants and catalog identifiers.
    • Environment overrides report resolved, deferred, or unresolved states.
    • Unnamed OpenAI configurations are handled automatically.
  • Bug Fixes

    • Improved validation before saving credentials.
    • Improved refresh, logout, and credential cleanup for API keys and OAuth tokens.
    • Provider changes now roll back safely when saving fails.
    • Plaintext migration and credential storage are more reliable and secure.
    • Lock contention now times out instead of blocking indefinitely.
    • Provider deletion preserves shared credentials while removing exclusive ones.

Activity

156
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: 5a947a3481cdf007b179c79d1fce890f039dd9e1
  • Latest commit, not reviewed: 38fe6386a3313ec4e43aca49841a8eca462668e4

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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: c368e4e3-a061-43b9-babf-b60a80750133

📥 Commits

Reviewing files that changed from the base of the PR and between fe32cab0c3e72dceec436db620ab693b4e51bf48 and 5a947a3481cdf007b179c79d1fce890f039dd9e1.

📒 Files selected for processing (3)
  • internal/credstore/filelock_timeout_test.go
  • internal/credstore/filelock_windows.go
  • internal/credstore/filelock_windows_test.go

Included review availability: Your plan provides up to 4 included reviews per hour; 0 remain after this review.

Walkthrough

Provider identity handling now distinguishes exact names, normalized case variants, and catalog IDs. Provider and credential writes use transactional persistence with rollback and bounded locking. CLI and TUI authentication flows validate configuration before authorization and credential storage.

Changes

Provider identity and credential management

Layer / File(s)Summary
Provider identity resolution and transactional persistence
internal/config/*.go, internal/credstore/credstore.go
Provider operations resolve exact names, normalized identities, and catalog ownership. Credential and profile mutations use transactional persistence, rollback checks, and bounded write locks.
OAuth validation and authentication flows
internal/cli/auth.go, internal/oauth/manager.go, internal/tui/oauth_device.go, internal/tui/onboarding.go, internal/tui/provider_wizard.go
OAuth flows preflight provider configuration and validate again before saving tokens. Status, refresh, and logout resolve matching credential candidates.
Provider CLI and TUI workflows
internal/cli/command_center.go, internal/cli/provider_onboarding.go, internal/cli/provider_setup.go, internal/cli/setup.go, internal/tui/*.go
Provider listing, selection, removal, renaming, editing, setup, and discovery use canonical identities and transactional APIs. Provider output includes source and selectability metadata.
Credential-store lock security
internal/credstore/filelock*.go, internal/credstore/*_test.go
Credential locks now use bounded acquisition and platform-specific path, ownership, permission, link, and trustee validation.
Validation and test integration
.github/workflows/ci.yml, internal/**/*_test.go
Tests cover identity ambiguity, rollback, OAuth preflight, provider cleanup, lock security, and updated test execution through make test.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related PRs

  • Gitlawb/zero#366: Related dependency wiring and provider authentication persistence changes.
  • Gitlawb/zero#560: Related OAuth provider-profile, credential handling, and provider-management changes.
Merge Risk: 🟡 Moderate · up to 5a947

The PR clarifies provider selection and synchronizes live TUI state, but the current head still permits an unrecognized write-capable trustee on Windows credential files by default unless strict ACL mode is enabled, and case-insensitive cleanup can remove a distinct case-variant profile after deletion. These could weaken credential protection or leave the session on the wrong provider, so merge should wait for fixes or explicit owner acceptance.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 38.43% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 216 functions across 39 files.Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title check✅ PassedThe title accurately describes the primary provider-selection and live TUI state changes, while the (4/4) suffix identifies the PR series.
Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

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

Actionable comments posted: 11

CAUTION

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
internal/config/writer.go (1)

411-431: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Trim the name before re-applying the APIKeyStored marker.

Line 412 compares strings.TrimSpace(existing.Name) against profile.Name, but line 426 compares cfg.Providers[index].Name raw. A persisted row saved as " work " therefore passes the collision check, merges, and then fails the marker loop. The result is the exact failure this comment block warns about: the secret sits in the credential store while apiKeyStored stays false, so every ApplyStoredAPIKey gate skips it.

ValidatePersistedProviderNames trims for comparison but does not reject untrimmed stored names, so such a row can exist on disk.

🐛 Proposed fix
 	if profile.APIKeyStored {
 		for index := range cfg.Providers {
-			if cfg.Providers[index].Name == profile.Name {
+			if strings.TrimSpace(cfg.Providers[index].Name) == profile.Name {
 				cfg.Providers[index].APIKeyStored = true
 				break
 			}
 		}
 	}
🤖 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 411 - 431, Update the APIKeyStored
reapplication loop after mergeProvider to compare provider names using
strings.TrimSpace on cfg.Providers[index].Name, matching the collision check and
supporting persisted names with surrounding whitespace. Keep the existing
exact-name assignment and break behavior unchanged.
internal/cli/app.go (1)

656-660: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Interactive startup can now stall on the provider write lock. Update the comment or move the migration off the startup path.

MigratePlaintextProviderKeysTransactional acquires the cross-process lock from internal/config/provider_commit.go. That lock waits up to providerWriteLockTimeout, which is 5 seconds (provider_commit.go line 215). If another zero process holds it — a concurrent provider add, auth login, or a second TUI — this line blocks the interactive TUI for up to 5 seconds before the launch continues, and the failure is discarded.

The comment above still describes only the previous failure modes: "a missing keyring or write error leaves the inline key in place." It no longer describes the lock wait.

Two options:

  • Run the migration in a goroutine, as this function already does for the models.dev cache refresh at line 616, and keep it fail-soft.
  • Keep it synchronous and state the bounded lock wait in the comment.

A one-line warning on stderr for a repeated failure would also make a stuck migration visible; right now every failure is silent.

The repository rule that comments must match shipped behavior applies here.

🤖 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/app.go` around lines 656 - 660, The synchronous call to
MigratePlaintextProviderKeysTransactional can block interactive startup on the
provider write lock, while the comment omits this bounded wait and all failures
are silent. Move the migration off the startup path using the existing
asynchronous pattern, preserving its fail-soft behavior, and ensure any repeated
migration failure is surfaced with a one-line stderr warning if supported by the
surrounding startup flow; update the comment to match the shipped behavior.

Source: Coding guidelines

🧹 Nitpick comments (10)
internal/oauth/manager.go (1)

63-66: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Narrow the BeforeSave doc comment to the login paths.

The comment says BeforeSave runs "immediately before credential mutation". The hook is invoked only in Login and CompleteDeviceLogin. Refresh paths that persist rotated tokens do not call it. A caller could read this comment as a guarantee that every store write is gated.

📝 Proposed wording
-	// BeforeSave runs after interactive authorization succeeds and immediately
-	// before credential mutation. Interactive callers use it to revalidate
-	// state that may have changed while a browser or device flow was pending.
+	// BeforeSave runs after interactive authorization succeeds and immediately
+	// before the login token is stored (Login and CompleteDeviceLogin only; it
+	// does not gate token-refresh writes). Interactive callers use it to
+	// revalidate state that may have changed while a browser or device flow
+	// was pending.
 	BeforeSave func() error

Also applies to: 152-156, 213-217

🤖 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 63 - 66, Update the BeforeSave
documentation to state that it runs only during the Login and
CompleteDeviceLogin authorization paths before their credential persistence, and
remove wording implying that every credential mutation or store write is gated
by the hook.
internal/cli/command_center.go (1)

196-206: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Prefer the existing config loader over an ad-hoc read and unmarshal.

This block re-implements user-config loading: raw os.ReadFile plus json.Unmarshal into config.FileConfig. Any normalization, defaulting, or tolerance the config package applies is bypassed, so this reader can disagree with the resolver about which rows exist. Use the package's file-config loader if one is exported.

Run the following script to find a reusable loader:

#!/bin/bash
# Description: Look for an exported user/file config loader in internal/config.
set -euo pipefail

fd -e go . internal/config | xargs rg -n 'func (Load|Read)[A-Za-z]*Config'
🤖 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/command_center.go` around lines 196 - 206, Replace the manual
os.ReadFile and json.Unmarshal flow with the exported file-config loader from
the config package, preserving the existing not-found and error behavior around
the caller. Reuse the loader’s returned config in the surrounding resolver logic
so normalization and defaults are applied consistently.
internal/cli/auth.go (1)

148-152: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use config.SameProviderIdentity here too.

Line 42 now compares provider identity with config.SameProviderIdentity, but this function still uses strings.EqualFold for the same active-provider comparison. EqualFold folds Unicode pairs that the credential store treats as distinct identities, which is the exact mismatch the rest of this PR removes. The impact is limited to which message is printed, so this is a consistency fix.

♻️ Proposed change
-	active := strings.EqualFold(strings.TrimSpace(ensured.Active), strings.TrimSpace(ensured.Name))
+	active := config.SameProviderIdentity(ensured.Active, ensured.Name)
🤖 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.go` around lines 148 - 152, Replace the
strings.EqualFold-based comparison assigned to active in the surrounding
authentication function with config.SameProviderIdentity, matching the provider
identity semantics already used at line 42. Preserve the existing trimming
behavior and downstream message selection.
internal/cli/provider_onboarding.go (1)

85-93: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Two full config resolutions run for one override check.

When an override is present and case-only, activeProviderEnvOverrideSelectsSaved calls resolveActiveProviderWithoutProviderCommand, and activeProviderEnvOverrideResolution calls it again. Each call re-reads the user config, the project config, and the workspace root. activeProviderEnvOverrideResolution also repeats the providerCommandEnv check that the helper already performs.

Resolve once and reuse the result and error. This removes the duplicate disk work and keeps both decisions on the same snapshot, so a concurrent config edit cannot make the suppression decision and the reported resolution disagree.

Also applies to: 177-222

🤖 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/provider_onboarding.go` around lines 85 - 93, Update the
override handling around activeProviderEnvOverrideSelectsSaved and
activeProviderEnvOverrideResolution to resolve the active provider configuration
once, capturing and reusing its result and error for both suppression and
override resolution. Refactor the helpers or surrounding flow so the shared
snapshot also supplies the providerCommandEnv decision, eliminating repeated
config reads while preserving existing absent, suppressed, and resolved
outcomes.
internal/cli/provider_onboarding_test.go (1)

260-285: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert the JSON shape for the config-error resolution.

This test covers the human-readable branch only. The new JSON contract adds envProviderResolution: "config-error", envProviderResolutionError, and a null envProviderResolves for the same state (internal/cli/provider_onboarding.go Line 108-111). Add a --json run here so a future change to that payload fails a test.

As per coding guidelines: "Every behavior or security-boundary change requires a regression test, including failure paths".

🤖 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/provider_onboarding_test.go` around lines 260 - 285, Extend
TestRunProvidersUseReportsUnrelatedConfigError to execute the same
invalid-configuration scenario with --json, then assert the payload includes
envProviderResolution set to "config-error", a populated
envProviderResolutionError describing the configuration failure, and
envProviderResolves set to null. Keep the existing human-readable assertions and
ensure the JSON run does not attribute the error to the unrelated provider
override.

Source: Coding guidelines

internal/tui/oauth_device.go (1)

62-66: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Use configPath directly. path := configPath is redundant. Blank paths are intentionally accepted by preflightOAuthProviderConfig.

🤖 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/oauth_device.go` around lines 62 - 66, Remove the redundant path
alias in oauthDeviceComplete and pass configPath directly to
preflightOAuthProviderConfig. Preserve the existing behavior that allows blank
configuration paths.
internal/config/writer.go (1)

62-81: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Collapse the three copies of read-and-unmarshal.

PreflightUserConfig (lines 69-79), persistedProviders (lines 182-192), and PreflightProviderWrite (lines 375-385) each repeat os.ReadFile plus json.Unmarshal plus the same two error strings. Have the two preflight functions call persistedProviders, so the missing-file and invalid-JSON behavior stays defined in one place.

♻️ Suggested consolidation
 func PreflightProviderWrite(path, name string) error {
 	if err := PreflightUserConfig(path); err != nil {
 		return err
 	}
-	data, err := os.ReadFile(path)
-	if os.IsNotExist(err) {
-		return nil
-	}
-	if err != nil {
-		return fmt.Errorf("read config %s: %w", path, err)
-	}
-	var cfg FileConfig
-	if err := json.Unmarshal(data, &cfg); err != nil {
-		return fmt.Errorf("invalid config JSON %s: %w", path, err)
-	}
+	providers, err := persistedProviders(path)
+	if err != nil {
+		return err
+	}
 	name = strings.TrimSpace(name)
-	for _, provider := range cfg.Providers {
+	for _, provider := range providers {
 		existing := strings.TrimSpace(provider.Name)
 		if sameProviderIdentity(existing, name) && existing != name {
 			return fmt.Errorf("provider %q already exists as %q; provider names must be unique case-insensitively", name, existing)
 		}
 	}
 	return nil
 }

Also applies to: 181-194, 369-394

🤖 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 62 - 81, Consolidate config loading
in persistedProviders: move or retain the shared os.ReadFile/json.Unmarshal
handling and its existing missing-file and invalid-JSON behavior there. Update
PreflightUserConfig and PreflightProviderWrite to call persistedProviders and
then perform their respective validation/write logic, removing their duplicated
read-and-unmarshal code and error strings.
internal/config/credentials.go (1)

211-233: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Return a truthful migrated count when the transaction fails.

op.setKey writes credentials, then runProviderProfileOperation rolls those writes back if publication fails. In that case this function still returns the pre-failure migrated count together with the error. A caller that logs "migrated N keys" on error would report work that was undone. Return 0 with the error.

Also, the old implementation documented why a failed Set is skipped. That reasoning is worth keeping here, because a silent continue now hides every per-provider credential-store failure.

♻️ Proposed change
 func MigratePlaintextProviderKeysTransactional(path string) (int, error) {
 	migrated := 0
 	_, err := runProviderProfileOperation(path, true, false, func(op *providerProfileOperation) error {
 		for index := range op.config.Providers {
 			profile := &op.config.Providers[index]
 			key := strings.TrimSpace(profile.APIKey)
 			if key == "" || strings.TrimSpace(profile.Name) == "" {
 				continue
 			}
 			if err := op.setKey(profile.Name, key); err != nil {
+				// Leave the plaintext key in place; a failed capture must not strand it.
 				continue
 			}
 			profile.APIKey = ""
 			profile.APIKeyStored = true
 			migrated++
 		}
 		op.publish = migrated > 0
 		return nil
 	})
+	if err != nil {
+		// Publication failure rolls the credential writes back, so nothing migrated.
+		return 0, err
+	}
 	return migrated, err
 }
🤖 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 211 - 233, Update
MigratePlaintextProviderKeysTransactional to return 0 whenever
runProviderProfileOperation returns an error, while preserving the error, so the
count reflects only committed migrations. Add a concise comment at the op.setKey
failure branch explaining that failed credential-store writes are intentionally
skipped, retaining the existing per-provider continuation behavior.
internal/config/provider_commit_test.go (1)

290-292: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Note the serial-execution requirement for these package-variable overrides.

Both tests replace package-level variables (providerWriteLockTimeout, publishProviderConfig) and restore them with t.Cleanup. That is safe only while no test in this package calls t.Parallel(). A future parallel test in package config would see a 20 ms lock timeout or a failing publisher. A short comment on each override records the constraint.

Also applies to: 334-336

🤖 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/provider_commit_test.go` around lines 290 - 292, The
package-level overrides in the tests must document that they require serial
execution. Add a concise comment beside each override of
providerWriteLockTimeout and publishProviderConfig stating that these tests must
not run in parallel, while preserving the existing t.Cleanup restoration.
internal/config/provider_commit.go (1)

117-146: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Propagate the credentialStore error in setKey and deleteKey.

Line 123 and line 138 discard the error from op.credentialStore(). Today this is safe: snapshotCredential populates op.store before any snapshot is cached, so store is never nil here. The safety depends on that ordering, and nothing in the code states it. A future change to snapshot caching turns both lines into a nil dereference on a credential write path.

♻️ Proposed change
-	store, _ := op.credentialStore()
+	store, err := op.credentialStore()
+	if err != nil {
+		return err
+	}
 	if err := store.Set(name, value); err != nil {

Apply the same change in deleteKey, returning (false, err).

🤖 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/provider_commit.go` around lines 117 - 146, Propagate errors
from op.credentialStore() in both providerProfileOperation.setKey and deleteKey
instead of discarding them. Return the error immediately, using nil for setKey’s
error result and false for deleteKey’s boolean result, before calling store.Set
or store.Delete.
🤖 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 489-536: Update the final configErr error handling in the auth
logout flow to append the stale apiKeyStored marker advice only when OAuth or
API-key deletion actually removed a credential. Use the existing removed and
keyRemoved results from manager.Logout and config.DeleteProviderCredentials;
preserve the plain configErr error when both are false.

In `@internal/config/credentials_test.go`:
- Around line 331-349: Add a failure-path test for DeleteProviderCredentials
using an invalid or case-duplicate provider configuration. Assert that the
candidate credential is deleted, removed is true, and the persisted apiKeyStored
markers remain unchanged when publication is suppressed by validation failure or
a missing config.

In `@internal/config/provider_commit_test.go`:
- Around line 230-238: Add t.Setenv("ZERO_CRED_STORAGE", "encrypted-file") at
the start of TestCommitProviderProfileCrossProcessCaseVariantsKeepOneKey,
TestCommitProviderProfileFailsClosedWhenLockIsBusy, and
TestCommitProviderProfileFailsClosedWhenLockCannotBeCreated, ensuring the parent
process and all store interactions use the temporary encrypted-file backend.
- Around line 177-193: Update the CI/test invocation for this concurrent
CommitProviderProfile test to run the race detector with uncached execution,
using the existing make test target or equivalent go test -race -count=1
command; preserve the test’s current behavior and coverage.

In `@internal/config/provider_commit.go`:
- Around line 265-275: Update the busy-transaction error returned in the
deadline branch of the provider lock acquisition loop to include the lock file
path, using the existing lock-path variable from the surrounding function, so
users can locate and remove a stranded lock.
- Around line 148-163: Update internal/config/provider_commit.go:148-163 so
providerProfileOperation.rollbackCredentials returns rollback errors, including
snapshot verification skips and Set/Delete failures, then join that error into
runProviderProfileOperation’s returned error at both rollback call sites while
reporting provider names only. Update internal/config/credentials.go:211-233 so
MigratePlaintextProviderKeysTransactional returns 0 alongside its publication
error after rollback.
- Around line 227-263: Update lockProviderWrite to release the lock through an
ownership-safe atomic primitive that verifies the token while removing the file,
replacing the separate os.ReadFile and lockutil.RemoveLockFile sequence. Use the
same ownership-safe primitive when cleaning up after write or close failures,
and add a test covering replacement of the lock between acquisition and release
to ensure a newer holder’s lock is preserved.

In `@internal/config/resolver.go`:
- Around line 958-960: The single-provider fallback in the active provider
selection branch must assign "openai" when the sole provider name is empty, so
Resolve does not return ErrNoActiveProvider. Update the logic around activeName
and providers to apply this default during selection, and add a regression test
covering an unnamed sole provider.

In `@internal/config/writer.go`:
- Around line 1134-1137: Remove the unconditional ValidatePersistedProviderNames
call from writeConfigFile so generic updates can persist despite duplicate
provider identities. Apply that validation only in provider-row mutation paths,
preserving its repair hint, while allowing SetFavoriteModels, SetRecentModels,
SetRecapsEnabled, SetTheme, and all STT setters to save without validating
provider rows.

In `@internal/tui/provider_manager.go`:
- Around line 364-372: Update the delete flow around RemoveProviderAndKey and
providerManagerCleanupCmd to resolve the profile’s provider name and catalog-ID
credential candidates, then transactionally delete every matching credential
before clearing row.profile.APIKeyStored. Pass the resolved candidates through
cleanup rather than only name, preserve failure handling, and add a
provider-manager regression test covering an alias such as “acme” with
credentials stored under “acme-cloud,” including the relevant failure path.

In `@internal/tui/provider_wizard.go`:
- Around line 1336-1354: Update the saved-provider scan around the ownership
logic to record name-only conflicts instead of returning immediately. Continue
scanning so an exact profile name with a matching CatalogID is returned first;
only report the existing ownership error when no positive exact owner is found.
Add a regression test covering a conflicting case-variant name before the valid
exact owner.

---

Outside diff comments:
In `@internal/cli/app.go`:
- Around line 656-660: The synchronous call to
MigratePlaintextProviderKeysTransactional can block interactive startup on the
provider write lock, while the comment omits this bounded wait and all failures
are silent. Move the migration off the startup path using the existing
asynchronous pattern, preserving its fail-soft behavior, and ensure any repeated
migration failure is surfaced with a one-line stderr warning if supported by the
surrounding startup flow; update the comment to match the shipped behavior.

In `@internal/config/writer.go`:
- Around line 411-431: Update the APIKeyStored reapplication loop after
mergeProvider to compare provider names using strings.TrimSpace on
cfg.Providers[index].Name, matching the collision check and supporting persisted
names with surrounding whitespace. Keep the existing exact-name assignment and
break behavior unchanged.

---

Nitpick comments:
In `@internal/cli/auth.go`:
- Around line 148-152: Replace the strings.EqualFold-based comparison assigned
to active in the surrounding authentication function with
config.SameProviderIdentity, matching the provider identity semantics already
used at line 42. Preserve the existing trimming behavior and downstream message
selection.

In `@internal/cli/command_center.go`:
- Around line 196-206: Replace the manual os.ReadFile and json.Unmarshal flow
with the exported file-config loader from the config package, preserving the
existing not-found and error behavior around the caller. Reuse the loader’s
returned config in the surrounding resolver logic so normalization and defaults
are applied consistently.

In `@internal/cli/provider_onboarding_test.go`:
- Around line 260-285: Extend TestRunProvidersUseReportsUnrelatedConfigError to
execute the same invalid-configuration scenario with --json, then assert the
payload includes envProviderResolution set to "config-error", a populated
envProviderResolutionError describing the configuration failure, and
envProviderResolves set to null. Keep the existing human-readable assertions and
ensure the JSON run does not attribute the error to the unrelated provider
override.

In `@internal/cli/provider_onboarding.go`:
- Around line 85-93: Update the override handling around
activeProviderEnvOverrideSelectsSaved and activeProviderEnvOverrideResolution to
resolve the active provider configuration once, capturing and reusing its result
and error for both suppression and override resolution. Refactor the helpers or
surrounding flow so the shared snapshot also supplies the providerCommandEnv
decision, eliminating repeated config reads while preserving existing absent,
suppressed, and resolved outcomes.

In `@internal/config/credentials.go`:
- Around line 211-233: Update MigratePlaintextProviderKeysTransactional to
return 0 whenever runProviderProfileOperation returns an error, while preserving
the error, so the count reflects only committed migrations. Add a concise
comment at the op.setKey failure branch explaining that failed credential-store
writes are intentionally skipped, retaining the existing per-provider
continuation behavior.

In `@internal/config/provider_commit_test.go`:
- Around line 290-292: The package-level overrides in the tests must document
that they require serial execution. Add a concise comment beside each override
of providerWriteLockTimeout and publishProviderConfig stating that these tests
must not run in parallel, while preserving the existing t.Cleanup restoration.

In `@internal/config/provider_commit.go`:
- Around line 117-146: Propagate errors from op.credentialStore() in both
providerProfileOperation.setKey and deleteKey instead of discarding them. Return
the error immediately, using nil for setKey’s error result and false for
deleteKey’s boolean result, before calling store.Set or store.Delete.

In `@internal/config/writer.go`:
- Around line 62-81: Consolidate config loading in persistedProviders: move or
retain the shared os.ReadFile/json.Unmarshal handling and its existing
missing-file and invalid-JSON behavior there. Update PreflightUserConfig and
PreflightProviderWrite to call persistedProviders and then perform their
respective validation/write logic, removing their duplicated read-and-unmarshal
code and error strings.

In `@internal/oauth/manager.go`:
- Around line 63-66: Update the BeforeSave documentation to state that it runs
only during the Login and CompleteDeviceLogin authorization paths before their
credential persistence, and remove wording implying that every credential
mutation or store write is gated by the hook.

In `@internal/tui/oauth_device.go`:
- Around line 62-66: Remove the redundant path alias in oauthDeviceComplete and
pass configPath directly to preflightOAuthProviderConfig. Preserve the existing
behavior that allows blank configuration paths.
🪄 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: 1ea9a67e-ffb5-470f-943d-17657241f3e0

📥 Commits

Reviewing files that changed from the base of the PR and between cabfeefc4eb9d247d907d3dee0786fe2e745207d and 9198e95ad4c95064749be1dee2a4517a9ea542ac.

📒 Files selected for processing (33)
  • internal/cli/app.go
  • internal/cli/auth.go
  • internal/cli/auth_test.go
  • internal/cli/command_center.go
  • internal/cli/command_center_test.go
  • internal/cli/dictation.go
  • internal/cli/provider_onboarding.go
  • internal/cli/provider_onboarding_test.go
  • internal/cli/provider_setup.go
  • internal/cli/setup.go
  • internal/config/command_test.go
  • internal/config/credentials.go
  • internal/config/credentials_test.go
  • internal/config/provider_commit.go
  • internal/config/provider_commit_test.go
  • internal/config/resolver.go
  • internal/config/resolver_test.go
  • internal/config/validate_test.go
  • internal/config/writer.go
  • internal/config/writer_test.go
  • internal/credstore/credstore.go
  • internal/oauth/manager.go
  • internal/oauth/manager_test.go
  • internal/tui/command_center.go
  • internal/tui/oauth_device.go
  • internal/tui/onboarding.go
  • internal/tui/onboarding_test.go
  • internal/tui/provider_manager.go
  • internal/tui/provider_manager_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
jatmn3mo ago

blocked until #894 lands

PierrunoYT1mo ago

@Vasanthdev2004 Fixed in d7996e43; refreshed as 38fe6386. The JSON effectiveProvider is now resolvedOverride. TestRunProvidersUseJSONReportsResolvedEffectiveProvider sets ZERO_PROVIDER=WORK against a saved work row and expects envProvider WORK and effectiveProvider work. Before the fix it reported effectiveProvider:"WORK". The only conflict from the merge was the import block in command_center.go. Verification for the whole stack is on #892.