Skip to content

feat: complete provider setup UX on unified configuration - #1441

Merged
jbeda merged 12 commits into
plan/mecatui-local-provider-setupfrom
impl/mecatui-local-provider-setup
Sep 17, 2026
Merged

jbeda merged 12 commits into
plan/mecatui-local-provider-setupfrom
impl/mecatui-local-provider-setup

Conversation

@JAORMX

@JAORMX JAORMX commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Draft implementation — rebuilt on unified configuration

This is the actual follow-up implementation on merged #1448 / ADR 0333, not the old prototype port. Existing Plan / Interface PR #1440 remains the base and human contract gate.

  • Implementation head: dc793b57b95eeb9c3823b2d8356d2bb65f3c96d2.
  • Revised plan head: 9b15e85b768cd55084c311c5611820b7c801228f (plan/mecatui-local-provider-setup).
  • Canonical implementation baseline: fdbd369c50c804ee391457a666d7471f53ec6069 (feat: unify provider configuration and Mecatui commands #1448). Remote main has since advanced to d25313767befc803277e38d658193844d6d150ab; no new main merge was performed.
  • The directing human explicitly authorized this stack before plan merge. That sequencing waiver is not merged-plan approval. Neither PR has been merged; implementation stays draft and its acceptance plan stays in-progress.
  • Normal fast-forward publication descends from the previous published head 31df424bfef87169f430b8bf710ebc06a597af55 through preserved merges. The reconciliation merge reset the implementation tree to the revised plan before residual work; obsolete prototype history is superseded, not replayed. Old tips remain archived/in ancestry. No rebase, force push, or cleanup.

Delivered scope

  • Passive status reports effective credential provenance, shadowed file presence, selected-default/recovery state, and explicitly unverified local facts; retains OIDC protected-store inspection and ToolHive external ownership.
  • Manual Codex status/reuse uses the configured-file runtime loader and existing local validator. Bare declared custom defaults reach shared composition-owned model validation; aliases, unknown/inherit/mismatched selectors retain their boundaries.
  • Shared key entry provides provider-specific API-console/consumer/billing/plaintext-custody guidance, bounded hidden accepted input, explicit reuse/replacement, separate save consent, and independently optional default consent. Custom setup follows add/login through the same paths. Missing configured-file first enrollment and unsupported-platform guidance are covered.
  • Linux/macOS shared private-file writer uses validated parent descriptors, rejects unsafe/special-file substitutions without FIFO blocking, retains snapshot comparison, and reports pre/post-replacement durability honestly. Real PTY tests exercise production input, signals, echo restoration, EOF/read failures, secret non-disclosure, and cancellation. The existing native macOS job now executes these PTY/provider regressions, not merely cross-compiles them.
  • Final AC4.2 repair handles replacement_applied_durability_unknown before generic API-key errors/cancellation: the key change may already be active and crash durability is uncertain; inspect named passive status and the configured credential file before manual retry. Direct login, stock/custom setup and add tests inject the actual write followed by unknown outcomes, including cancellation and secret-bearing faults. No blind deletion, retry, false rollback, leaked fault/path, or later default mutation; saved custom definitions remain. The already-correct ambiguous-default branch is unchanged.
  • Canonical guidance updated in user-docs/features/choose-models.md and user-docs/mecatui/getting-started.md.

No new command family, config schema, credential custody/store, public engine API, locks, cooperative retry protocol, or universal POSIX CAS guarantee. No automatic setup/startup, legacy llm/--auth-file forms, Codex enrollment/refresh/import, forced replacement-default selection, or changed selected-default removal policy. Add normally chains login; logout is credential-only; removal remains combined and does not select a replacement.

Eleven-AC trace

Own-plan strict trace reports 11 ACs / 11 test-verified / 0 missing. The current native macOS job also passed the real PTY/provider regressions and private-file writer suites; see the CI repair evidence below.

AC Actual named proof
1.1 TestProviderSetupFollowup_Scenario1_StatusProvenance
1.2 TestProviderSetupFollowup_Scenario1_RuntimeCredentialParity
1.3 TestProviderSetupFollowup_Scenario1_PassiveBoundaries
2.1 TestProviderSetupFollowup_Scenario2_ConsoleAndCustodyGuidance
2.2 TestProviderSetupFollowup_Scenario2_ReuseAndIndependentConsent
2.3 TestInvariant_ProviderSetupFollowup_TerminalCancellationAndSecretSafety
3.1 TestProviderSetupFollowup_Scenario3_CodexLoaderAndReuse
3.2 TestProviderSetupFollowup_Scenario3_SharedDefaultResolution
4.1 TestProviderSetupFollowup_Scenario4_PortablePrivateFileBoundary
4.2 TestProviderSetupFollowup_Scenario4_TruthfulWriteOutcomes; final real-route TestProviderReviewAPIKeyWriteOutcome
4.3 TestProviderSetupFollowup_Scenario4_UnifiedLifecyclePreserved

Verification before CI repair (65b6dd4a)

These are the previously recorded feature gates. The subsequent CI repair and current-head verification are recorded below; docs, schema and production code are unchanged by that repair.

Gate Result
Final regression TDD Red before the three-line production branch; green after. Four command routes cover secret-bearing fault, cancellation, nil-error unknown, and not-applied controls.
Focused go test -race ./cmd/mecatui provider review/follow-up/PTY/consent/add-cancellation selection Passed, uncached (-count=1).
task lint Passed, all modules.
task test Passed: root, engine, authn/oidc and all provider race suites plus standalone proofs. The earlier baseline lease-timing failure did not recur.
task docs / task site:build Both passed; no generated/lockfile drift.
task api:check Passed.
go run ./cmd/mecademo Passed: real offline turn/tool/permission-ask/approval/result sequence.
Acceptance-plan checker Passed, all eleven criteria and interface declarations.
Own-plan actrace --strict --plan docs/acceptance/mecatui-local-provider-setup.md Passed, 11/11 proofs.
Global task ac-trace-strict Still fails: pinned ac-trace v0.0.3 rejects unchanged docs/acceptance/callmcpwithquery-broker-support.md status proposed (tool exit 2). This unrelated baseline plan/tool mismatch was reproduced, not suppressed; neither old plan nor pin was changed.
git diff --no-ext-diff --no-textconv --check and ancestry Passed; revised plan, #1448 and prior published implementation are ancestors.
Native macOS PTY/writer runtime Pending post-push CI. Earlier Darwin cross-compilation is not runtime evidence.

task build and Darwin/FreeBSD compile-only checks also passed at independently reviewed parent a4fd6317f16c9c518e0c884757ac24b77f17b5b3; the final repair changes only the credential outcome branch and its route tests. No live provider calls were made. Local process-only signing/GOMAXPROCS/GOFLAGS settings were used, with no global host changes.

CI repair on the current head

The failures were investigated from the exact failed-job logs at 65b6dd4a, CI run 34832113603, not blindly rerun:

  • Draft coverage: TestGRPCConverseCancel returned end_turn. Its baseline blockingChunks fixture is a finite response, not a blocking stream; the transport can finish before the Cancel frame. The test now yields one delta then waits for context cancellation. The separate Test (non-race draft) failure was only the aggregate dependency check.
  • Native macOS: TestInvariant_ProviderSetupFollowup_TerminalCancellationAndSecretSafety failed with fstatat /dev/fd: bad file descriptor. Enumerate names without implicitly statting Darwin descriptor-directory entries, retaining explicit descriptor matching/leak assertions.
  • Native macOS: TestProviderReviewTerminalCommandErrors/oversized failed with EAGAIN. The fixture now preserves partial writes and polls under bounded PTY backpressure so the entire oversized input reaches the real reader.
  • Subsequent native diagnostics: the exact flag mismatch was 0x2 → 0x10002 (nonblocking: 0x6 → 0x10006), Darwin's kernel-maintained FWASWRITTEN bit—not failed O_NONBLOCK restoration. Prime and drain the fixture's shared output descriptor before its flag snapshot. Exact flag equality is retained; no masking, platform skips or production change. Native PTY/provider/writer execution passed at 79fb608aa in job 103947035526.
  • Subsequent draft coverage: TestSteer_PromotedRelaySequential timed out at steer_handoff_test.go:349. Its turn.end observation precedes steer-inbox closure; it now waits for the existing terminal outcome signal before sending the late steer. Its relay stays parked within the unchanged 20-second total test budget. All promotion, multimodal echo, ordered-stream and EOF assertions remain.
  • Local full race gate: TestHeadlessCredentialStorage_Scenario1_HelperFailuresFailClosed raced a race-instrumented helper's startup against a 100ms deadline in exit-status cases. Only those cases get startup allowance; the actual stall and explicit deadline tests retain their original 100ms budgets and every assertion. No production deadline or cancellation change.

These repairs change only four test files, with no new dependency/API/schema/CLI/lock protocol or workflow-gate changes. Normal pushes only; all commits have Co-Authored-By trailers. No agents were delegated during this repair.

Current-head checks: all applicable checks passed, monitored to completion, including CI run 34836108990, both draft test checks, native macOS PTY/provider/writer execution, perf, k8s e2e and Vercel. Existing draft race-shard/live-job skips are unchanged; they were not used to replace native execution.

Local final-head gates also passed: task lint, full task test (root + engine + OIDC + provider race suites and all standalone proofs), and the complete offline go run ./cmd/mecademo session. Focused cancellation and promoted-relay tests each passed x100 non-race + x100 race; provider review/PTY tests passed x10 non-race + x1 race; helper exit/deadline tests passed x20 race.

Local verification uses process-only signing overrides (a host tag.gpgsign=true otherwise launched an editor in an unrelated SDK release fixture), GOMAXPROCS=4, and GOFLAGS=-p=2; no global host setting was changed. Docs/site/plan trace were not rerun for this test-only repair; their prior evidence and the global strict-trace blocker above remain accurately attributed to the earlier feature head.

Independent review closure and remaining gates

The supplied independent panel has no open Spec, Standards, Test adequacy, Domain/security, Architecture, UX, or DevOps findings after the final AC4.2 red/green proof. One low duplication advisory is consciously retained: the two loader paths do not justify premature extraction. Positive informational reuse comments are not counted as findings. No additional panel was run during this final repair/publication step.

PANEL ship_blockers=0 important=0 advisory=1 reviewer_failures=0

CI monitoring is complete and green on the current head. Global strict trace and human plan/code merge gates remain outstanding, so this PR remains draft. No new panel was run for these test-only CI repairs. The implementation worktree is clean; no main merge, force push or cleanup was performed. Detailed local run evidence is retained under ignored .scratch/orchestrate/pr1441-ci-fix/final-publication.md.

Tracking: Plan / Interface PR #1440. No issue-closing relationship.

@jbeda

jbeda commented Sep 12, 2026

Copy link
Copy Markdown
Contributor

Feedback: converge provider configuration and the Mecatui provider CLI

The newly added mecatui llm surface combines three different concerns—provider selection, credential custody, and OIDC gateway enrollment—under terminology that does not explain the product to a user. In particular, "Native LLM" and "endpoint" are implementation terms. They should not be primary user-facing concepts.

This proposal standardizes on provider in both configuration and CLI. providers: predates llm: and is already the runtime registry abstraction; it should be the sole public configuration namespace.

Desired domain model

A provider is a named source of models used by a Mecatl deployment. Every provider has:

  • a stable provider name used by configuration and CLI;
  • a transport definition: built-in implementation or configured compatible service, plus URL/API flavor where applicable;
  • a default model and optional model discovery;
  • an authentication mode and credential custody;
  • lifecycle capabilities that determine the applicable actions.

The user should select a provider name, not decide whether it is a "native endpoint," an API endpoint, or an integration.

Provider classes

Class Examples Connection Selected authentication/custody
Stock provider OpenAI, Anthropic, OpenRouter, OpenCode Built-in transport API key today; a provider may additionally support OIDC if its integration defines it. The selected mode owns its credentials.
Custom provider A named OpenAI-compatible deployment gateway Configured URL/API flavor API key, OIDC, or no authentication; selected per provider definition.
External lifecycle provider ToolHive ToolHive-specific connection ToolHive-specific authentication and credential ownership.

Transport origin (stock or custom) and authentication are independent dimensions. A provider's integration advertises its supported authentication methods; its configuration selects exactly one active method. This permits a provider such as a corporate gateway to support both API-key and OIDC setups without inventing two user-facing provider types.

OIDC is an authentication mode, not a separate kind of user-facing LLM or endpoint.

ToolHive remains a provider/integration in status and selection, but Mecatui must clearly state when ToolHive owns the lifecycle rather than presenting unsupported generic credential actions.

Configuration direction

Standardize on the existing operator-owned providers: key. Do not add new user-facing configuration under llm:.

Conceptually, a custom OIDC provider should be expressible alongside an API-key provider:

providers:
  acme:
    base_url: https://llm-gateway.acme.example/v1/responses
    api_flavor: openai-responses
    default_model: acme-reasoning
    auth:
      method: oidc
      issuer: https://login.acme.example
      client_id: mecatui
      scopes: [openid, offline_access]
      resource_audience: https://llm-gateway.acme.example # optional
      issuer_trust:
        policy: public
      gateway_trust:
        policy: public

  local-proxy:
    base_url: http://127.0.0.1:8080/v1
    api_flavor: openai-chat
    default_model: local-model
    auth:
      method: none

The final field layout should respect existing validation and custody boundaries, but the configuration must describe one provider record rather than split a provider's transport data under providers: and its authentication data under llm.endpoints:.

Compatibility and migration

  1. Continue reading existing llm.endpoints as a deprecated compatibility input for at least one documented release.
  2. Normalize it into the equivalent provider record before registry assembly, as the implementation already does today.
  3. Emit a clear migration warning naming the provider and the replacement providers: form; never expose secrets or automatically rewrite configuration.
  4. Update generated configuration reference, examples, and user documentation to show only providers:.
  5. Remove llm.endpoints only in a separately announced breaking-change release, after the compatibility window.

Use provider name everywhere in CLI copy, help, errors, and documentation. Reserve URL for the configured network address. Do not call a provider name an "endpoint."

Proposed CLI

Rename the primary command group to mecatui providers. It owns local provider configuration and inspection.

mecatui providers
mecatui providers --help
mecatui providers list
mecatui providers status [PROVIDER]
mecatui providers setup [PROVIDER]
mecatui providers add PROVIDER [flags]
mecatui providers configure PROVIDER [flags]
mecatui providers login PROVIDER [--no-browser]
mecatui providers logout PROVIDER
mecatui providers set-default PROVIDER [MODEL]
mecatui providers remove PROVIDER

Exact verbs can be refined, but the action should be selected by provider capability:

Command Behavior
providers Comprehensive provider overview and next steps; no side effects.
providers list Lists stock and configured providers, supported authentication/lifecycle actions, default model, and configuration state. No credential values.
providers status [PROVIDER] Passive status. With no name, aggregate local state; with a name, reports that provider's local configuration/enrollment state. It never makes a paid inference or prints secrets.
providers setup [PROVIDER] Guided, interactive path. With no name, starts by selecting a provider. With a name, enters the provider-appropriate flow. It is a convenience command, not the only way to configure providers.
providers add PROVIDER [flags] Creates a custom provider definition. This is where a custom API-key, OIDC, or no-auth provider is defined. It should have explicit forms/options rather than an ambiguous catch-all prompt.
providers configure PROVIDER [flags] Changes a configured provider's non-secret connection/authentication metadata.
providers login PROVIDER Authenticates or replaces the local credential while preserving the provider definition: browser/headless OIDC enrollment for Mecatl-owned OIDC, or hidden API-key entry for an API-key provider. For ToolHive, give the exact ToolHive handoff rather than claiming generic login support.
providers logout PROVIDER Clears the provider's locally managed credential while preserving its definition: an API key from auth.yaml or an OIDC enrollment from protected storage. Describe the mode-specific consequence before confirmation, including that API-key logout does not revoke the key upstream.
providers set-default PROVIDER [MODEL] Sets the embedded-server default; validates provider/model with the same rules used at startup.
providers remove PROVIDER Removes a custom provider definition. It must not silently combine this with credential removal; refuse while a local credential exists and direct the user to providers logout PROVIDER first. Stock providers cannot be removed.

The existing mecatui llm ... forms should become documented deprecated aliases during a transition, with diagnostics that name the direct replacement. Top-level mecatui login ADDRESS and mecatui logout ADDRESS remain remote-server authentication commands and must not be conflated with provider authentication.

Help and guidance requirements

Every listed command and subcommand needs a real --help page. Help must be useful without reading source or external documentation.

mecatui providers --help

It should explain:

  1. the provider model above, including stock versus custom providers;
  2. API-key, OIDC, no-auth, and ToolHive lifecycle/custody distinctions;
  3. credential precedence (environment over auth.yaml where applicable);
  4. the difference between embedded mecatui configuration and mecatui connect ADDRESS, where the remote server remains authoritative;
  5. a command index with one-line descriptions and examples;
  6. the no-configured-provider recovery path: mecatui providers setup.

Child help

  • setup: Linux/macOS support, interactive behavior, numbered selection, cancellation, files touched, confirmation and partial-commit semantics.
  • list and status: exactly what is inspected, what is intentionally not verified, and confirmation that secrets are never printed.
  • add and configure: required fields by authentication mode, examples for API key/OIDC/no-auth, credential-home/keyring guidance, and TLS/private-CA guidance where relevant.
  • login: provider-appropriate credential replacement: hidden API-key entry or OIDC browser/--no-browser enrollment; protected credential storage and ToolHive handoff.
  • logout: mode-specific local credential removal, upstream-revocation limits, and environment shadowing.
  • set-default: provider/model validation, aliases, and the fact that it affects embedded startup rather than a remote server.
  • remove: custom-definition deletion only, the required prior logout, and the fact that stock providers cannot be removed.

The top-level mecatui --help should contain only a short entry such as:

providers    configure and inspect embedded LLM providers; run `mecatui providers --help`

It should not use "Native LLM." The detailed conceptual help belongs under mecatui providers.

Interactive setup UX

Keep providers setup as a shortcut, but make it structured and capability-aware:

  • Print a concise heading, current/default configuration summary, and clear next action.
  • List selectable providers with stable numbers and a short credential/lifecycle label; accept a number rather than requiring the user to retype a displayed name.
  • Use whitespace and explicit headings for information, input prompts, confirmation, success, warnings, and failure.
  • State the affected file/store before every write and show a concise committed/not-committed result afterward.
  • Treat Ctrl-C as cancellation at every input, including hidden API-key entry; restore terminal state and exit cleanly without a write.
  • If no provider is configured at ordinary Mecatui startup, show a direct recovery message: No provider is configured. Run 'mecatui providers setup' to configure one.

macOS support and write safety

providers setup should work on both Linux and macOS.

The current Linux-only restriction comes from the newly introduced descriptor-anchored, lock-heavy persistence implementation, not from any intrinsic limitation of an interactive provider setup flow. The product should not require macOS users to manually edit credential/configuration files for a mainstream setup path.

We should preserve the security properties that matter at a local secret boundary:

  • do not follow symlinks when writing sensitive credential/configuration files;
  • require the expected current-user ownership and private permissions before touching an existing credential file;
  • create new credential files with private permissions;
  • write through a same-directory temporary file and atomic rename;
  • never print secrets; preserve cancellation/error handling.

However, do not over-engineer around concurrent interactive invocations as though this were a multi-writer database. A simpler portable writer with atomic replacement, straightforward pre-write validation, and an honest error outcome is sufficient for this CLI. Cooperative lock protocols, complex descriptor state machines, and fine-grained crash-durability classifications should be retained only when they demonstrably protect a realistic user failure mode and can be implemented/tested consistently on Linux and macOS.

The implementation plan should explicitly define and test equivalent safe-write behavior on Darwin; it must not silently weaken filesystem safety simply to remove the platform gate.

Delivery plan

  1. Design/contract: finalize provider vocabulary, capability matrix, CLI grammar, configuration schema, compatibility window, and user documentation structure before a framework migration.
  2. Read compatibility: teach configuration loading to accept the standardized providers: OIDC form while retaining read-only compatibility for llm.endpoints.
  3. CLI/help: introduce mecatui providers and complete command/subcommand help; retain deprecated llm aliases with replacement messages.
  4. Setup UX: move the current three setup actions to direct commands, retain guided setup as a shortcut, add numbered selection, structured output, and correct Ctrl-C handling.
  5. Portable persistence: implement and test the required safe-write contract on Linux and macOS.
  6. Documentation and migration: update user docs and generated reference; add migration guidance and remove “Native LLM” terminology.
  7. Later cleanup: remove the legacy llm CLI/config compatibility only after the announced compatibility period.

Acceptance checks

  • A new user can run mecatui with no configured provider and receives one clear, accurate next command.
  • mecatui providers --help explains the model, credential modes, embedded-versus-remote boundary, and all subcommands.
  • Every providers subcommand has dedicated, successful --help output.
  • API-key, OIDC, no-auth, and ToolHive providers appear as one provider inventory with only valid actions offered.
  • A provider name is never described as an endpoint or URL in user-facing text.
  • mecatui providers setup is functional on Linux and macOS, supports clean Ctrl-C cancellation during secret entry, and offers numbered provider selection.
  • Existing llm.endpoints configurations and mecatui llm invocations remain usable through the documented migration period, with clear replacement guidance.
  • API-key files and protected OIDC credentials preserve their existing custody/security boundaries; no command or error output leaks credential values.

@JAORMX JAORMX changed the title feat: add guided local provider setup feat: provider setup follow-up on unified providers (preparing) Sep 14, 2026
@JAORMX JAORMX changed the title feat: provider setup follow-up on unified providers (preparing) feat: complete provider setup UX on unified configuration Sep 14, 2026

@jhrozek jhrozek left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Panel review complete (Spec, Standards, Test adequacy, Domain: secure-code-reviewer, go-architect, library-reuse-reviewer, code-duplication-reviewer). No ship-blockers.

Approving for velocity. The findings below (6 important, several advisory — inline comments to follow) are flagged for visibility; addressing them is at the author's discretion, not a condition of this approval.

🤖 Generated with Claude Code

@jhrozek jhrozek left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Panel review findings (Spec/Standards/Test-adequacy/Domain, 7 agents, no ship-blockers). Posted here for visibility per the panel review — addressing any of these is at the author's discretion, not a condition of the approval already given.

🤖 Generated with Claude Code

if err != nil {
return false
}
uid, ok := ownerUID(info)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[important] ownerUID (line 266, a few lines below sameParent — unchanged by this diff but exercised by the new re-verification path here) can nil-pointer-panic

func ownerUID(info os.FileInfo) (uint32, bool) {
	stat, ok := info.Sys().(*syscall.Stat_t)
	return stat.Uid, ok
}

stat.Uid is dereferenced regardless of ok. If the assertion fails, stat is a nil *syscall.Stat_t and this panics instead of returning false — both call sites (readTarget, and sameParent right here) rely on the ok bool and would otherwise fail closed safely. The sibling fileIdentity a few lines below guards this correctly. Suggested fix:

Suggested change
uid, ok := ownerUID(info)
func ownerUID(info os.FileInfo) (uint32, bool) {
stat, ok := info.Sys().(*syscall.Stat_t)
if !ok {
return 0, false
}
return stat.Uid, true
}

Pre-existing (not introduced by this diff), but this PR's new TOCTOU re-verification calls through sameParent more heavily, so flagging now.

(go-architect, domain axis)

"golang.org/x/sys/unix"
)

var testHook func(string) error

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[advisory] package-global mutable test hook

testHook is global state inside the commit path of a security-critical writer. Idiomatic-enough Go for fault injection, but it means tests touching this package can't run with independent hooks in parallel. Not blocking — just flagging the tradeoff.

(go-architect, domain axis)

@@ -202,12 +329,22 @@ func (c providerCommands) oidcStatus(ctx context.Context, definition permconfig.

func builtinProviderStatuses(keys cliconfig.ResolvedCredentials, shadowed map[string]bool) []providerStatus {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[important] builtin-provider facts duplicated across 6 sites

builtinProviderStatuses here, the known slice and shadowed/sources map construction in inspectLocalProviders, isBuiltinAPIKeyProvider in provider_credential.go, and the guidance switch in writeProviderKeyGuidance all separately encode "which providers are builtin." Adding a 6th builtin provider means 6 edits — miss the shadowed/sources one and the status output silently mis-reports provenance, which is exactly what this status flow exists to get right.

Suggested direction: one package-level table of {id, defaultModel, envKey func(ResolvedCredentials) string, guidance string} that the 5-6 call sites range over instead of re-enumerating the provider list. cliconfig's own known-provider list is unexported so it can't be reused directly across the package boundary — this would need its own local table.

(go-architect, domain axis)

Comment thread cmd/mecatui/provider_terminal_unix.go Outdated
invalid = true
continue
}
if len(line) == 8*1024 || tooLong {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[advisory] 8 KiB bound hardcoded in two places

Same literal (8*1024) appears here and in validateProviderAPIKey (provider_credential.go:180). Worth a shared const so the two never drift.

(go-architect, domain axis)

Comment thread cmd/mecatui/provider_terminal_unix.go Outdated
// cancellation. The duplicate shares flags with stdin, so restore those too.
//
//nolint:gocyclo // Keep terminal cleanup, bounded polling, and the small byte-editing state machine together.
func readProviderTerminalLine(ctx context.Context, input, output *os.File, prompt string, hidden bool) (value string, err error) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[advisory] hand-rolled raw-mode reader is justified, but undocumented as such

This reimplements a cancellable, size-bounded, UTF-8-validating line reader with backspace editing on top of x/term.MakeRaw/Restore plus manual unix.Poll/unix.Read. It's not gratuitous — x/term.ReadPassword has no ctx-cancellation, no size bound, and no non-hidden echo-with-editing mode, so there's no single stdlib/x/term call that replaces this. A short comment naming that ceiling (why ReadPassword doesn't suffice) would stop a future reader from "simplifying" this back into losing ctx cancellation or the 8 KiB bound.

(library-reuse-reviewer, domain axis)

Comment thread cmd/mecatui/provider_pty_darwin_test.go Outdated
"golang.org/x/sys/unix"
)

func providerPTYName(t *testing.T, fd int) string {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[important] hand-rolled PTY opener — github.com/creack/pty already does this

This file (and its Linux sibling) reimplements grantpt/unlockpt/ptsname via raw TIOCPTYGRANT/TIOCPTYUNLK/TIOCPTYGNAME (darwin) / TIOCSPTLCK/TIOCGPTN (linux) ioctls plus a manual /dev/ptmx open, purely for a test fixture. github.com/creack/pty (BSD-3, no CGo, de-facto standard for Go PTY test harnesses — used by Docker, gliderlabs/ssh, etc.) does the same thing via one pty.Open() call. Test-only dependency, no runtime surface added; would replace both platform files and net roughly -35 lines, and removes a per-OS raw-ioctl surface that's easy to get subtly wrong.

(library-reuse-reviewer, domain axis)

return sp, ap
}

func TestProviderSetupFollowup_Scenario1_StatusProvenance(t *testing.T) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[important, test adequacy] AC1.1's named test doesn't exercise malformed/unreadable credential input

TestProviderSetupFollowup_Scenario1_StatusProvenance only covers "present" vs. "removed" credential state, but AC1.1 explicitly requires that missing/malformed/unreadable input are "not conflated" — and provider_status.go (providerCredentialInputError) has three distinct branches for exactly that. The distinction is tested, but under a differently-named test (TestProviderFollowupStatusInputFailures in provider_followup_consent_test.go), so a regression collapsing those branches wouldn't fail the AC's own cited verify test. Given task ac-trace-strict traces by test name, worth either renaming/merging or adding the assertion here.

(test-adequacy axis)

}
}

func TestProviderSetupFollowup_Scenario2_ReuseAndIndependentConsent(t *testing.T) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[important, test adequacy] AC2.2's named test never drives a successful replace-and-write

Both the "reuse" and "replace" sub-cases in TestProviderSetupFollowup_Scenario2_ReuseAndIndependentConsent answer "no" to the save confirmation — the test could pass even if the shared writer were broken or never invoked on a consented replace. Two other AC2.2 requirements (the "environment credential will still win" warning, and blank/oversized-key rejection) are also unasserted here, covered only by uncited sibling tests (TestProviderFollowupReplacementShadowWarning, TestProviderFollowupConsentStages). Same traceability gap as above.

(test-adequacy axis)

}
})
}
for _, args := range [][]string{{"llm", "status"}, {"providers", "login", "openai", "--api-key-file", "key"}, {"providers", "setup", "--auth-file", "key"}} {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[important, test adequacy] AC4.3 legacy-grammar rejection checked by 3 hardcoded invocations, not the registered command tree

This loop ({"llm","status"}, --api-key-file, --auth-file) proves those three specific spellings are rejected, but doesn't enumerate the actual registered flag/command surface — a legacy artifact surviving under an untested spelling wouldn't be caught. Lifecycle behavior itself (add/login chain, --no-login, logout, remove) in this same test is solid.

(test-adequacy axis)

@jbeda

jbeda commented Sep 17, 2026

Copy link
Copy Markdown
Contributor

Follow-up simplification pass

This update keeps the provider-setup scope but removes complexity that was not carrying its weight:

  • Replaced the bespoke Linux/macOS raw-terminal reader and PTY harness with standard x/term.ReadPassword for hidden API-key input. Ordinary setup prompts use conventional line input. The parent plan now reflects that the flow no longer promises cancellable secret reads, reader joining, or an 8 KiB input limit.
  • Centralized Mecatui's four stock API-key providers in a small local table for status, environment provenance, login eligibility, and guidance. Codex, ToolHive, custom providers, and OpenRouter's explicit fallback remain separate.
  • Made Mecatui status derive stock default-model display from the runtime internal/app default-model source rather than carrying a copy.
  • Fixed privatefile.ownerUID to fail closed instead of risking a nil type-assertion panic.
  • Removed generated empty YAML flow mappings such as providers: {} and credential_store: {}. Empty sections are omitted; blank settings now gain readable block-style models: output.
  • Simplified passive provider-status credential inspection: normal resolver/auth-file reads replace the custom captured/replayed ReadFile snapshot seam. Status remains value-free and retains distinct missing/malformed/unreadable diagnostics.
  • Tightened provider documentation, restored concrete direct-command examples in Mecatui getting-started guidance, and removed short-lived legacy llm: troubleshooting material.
  • Strengthened the named acceptance proofs for status input failures, consented key replacement, and command/flag grammar coverage.

Deferred deliberately: the broader settings-plus-auth provider snapshot design, the OpenRouter OPENAI_API_KEY fallback decision, the package-global writer fault-injection hook, and PTY fixture/dependency review.

Validation after the latest changes: task lint && task test passed; task docs, task site:build, and go run ./cmd/mecademo also passed earlier in this update.

@jbeda
jbeda force-pushed the impl/mecatui-local-provider-setup branch from 71e2637 to 6835ca6 Compare September 17, 2026 01:05
@jbeda
jbeda marked this pull request as ready for review September 17, 2026 03:45
@jbeda
jbeda force-pushed the impl/mecatui-local-provider-setup branch from 6835ca6 to 81161f9 Compare September 17, 2026 03:48
JAORMX and others added 2 commits September 17, 2026 09:01
Add cancellable Linux/macOS hidden terminal input, explicit credential reuse
and save/default consent, passive effective-source reporting, and manual
Codex reuse through shared validation. Preserve add/logout/remove lifecycle
semantics and repair flow-style settings writes and empty credential residue.

Cover the eleven follow-up acceptance criteria, including real PTY cleanup,
signal exit, oversized input, and command-route regression tests. Update the
owning user guidance; keep the plan in progress pending review.

Co-Authored-By: mecatl <[email protected]>
JAORMX and others added 6 commits September 17, 2026 09:02
Complete setup-only custom-provider default selection and preserve committed
state across cancellation and ambiguous default writes. Permit consented
first enrollment into an absent configured key file without weakening passive
status or malformed-input rejection. Keep OIDC cancellation truthful when its
credential directory or remote state may remain.

Preserve safe terminal diagnostics and EOF cancellation, publish actionable
manual-platform and Codex guidance, and cover real PTY echo and commit states.
Run provider PTY regressions in the existing native macOS CI gate.

Co-Authored-By: mecatl <[email protected]>
Handle replacement_applied_durability_unknown before generic errors or
cancellation. Direct users to passive status and configured-file inspection
before manual retry without exposing backend errors or claiming rollback.

Exercise direct login, stock/custom setup and add through the actual command
seams with applied writes, sync faults, cancellation and not-applied controls.
Keep possibly active keys and saved definitions; stop before optional defaults.

Co-Authored-By: mecatl <[email protected]>
Enumerate descriptor names without Darwin's failing directory-entry stat.
Handle partial PTY writes and EAGAIN under bounded polling so oversized
input reaches the real reader without weakening its acceptance assertions.

The draft coverage failure was an unrelated fixture race: blockingChunks
can emit its entire finite response before the client sends Cancel. Use a
provider that yields the first delta then waits for context cancellation.
Keep the wire-level cancelled-result assertion and production code intact.

CI evidence: run 34832113603 at 65b6dd4.
Focused Linux tests pass with and without race detection; lint passes.
Native macOS execution remains a required post-push check.

Co-Authored-By: mecatl <[email protected]>
Report only numeric before/after flags and syscall errors for the native Darwin restoration assertion uncovered after the PTY fixture repairs.

Co-Authored-By: mecatl <[email protected]>
Native diagnostics showed only FWASWRITTEN (0x10000) changed: 0x2 to 0x10002, or 0x6 to 0x10006 for nonblocking input. Prime and drain the shared output descriptor before taking the baseline, preserving exact flag equality and every restoration assertion without masking bits or changing production.

Co-Authored-By: mecatl <[email protected]>
CI run 34835086868 passed native Darwin but exposed the baseline promoted-relay fixture: turn.end precedes steer closure. Wait for the existing terminal outcome before sending the late steer, and keep its relay parked within the unchanged 20-second test budget.

Full local race suites also exposed the credential helper fixture racing process startup against its stall deadline. Keep the 100ms stall/deadline assertions; give only exit-status cases time to start. No production, cancellation, gate selection or assertion changes.

Co-Authored-By: mecatl <[email protected]>
@jbeda
jbeda force-pushed the impl/mecatui-local-provider-setup branch from 81161f9 to 9799536 Compare September 17, 2026 16:03
@jbeda
jbeda merged commit 9ccf838 into main Sep 17, 2026
36 checks passed
@jbeda
jbeda deleted the impl/mecatui-local-provider-setup branch September 17, 2026 16:20
@toolhive-release-app toolhive-release-app Bot mentioned this pull request Sep 21, 2026
2 tasks

This branch was successfully deployed

1 active deployment
Preview — 9799536f Deployed Sep 17, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants