Repository navigation
fix(agents): use each agent's configured environment for auth, MCP and hooks - #3562
Conversation
…n explicit provider env AgentPluginHost.checkAuthStatus (env in its dedup key), buildLoginCommand, readMcpServers, writeMcpServers and removeMcpServer take an optional env, merged over the allowlisted agent env with mergeAgentEnvLayers, the same layering buildAcpSpawn uses. MCP behaviours may resolve their config root from that env; Claude's .claude.json follows CLAUDE_CONFIG_DIR. The home root keeps the injected fs. AgentHookInstaller.hooksStatus takes the env too, and ACP sessions read MCP servers under the session env.
…3.1.0 The agent-config contract gains optional, additive fields: env on hooksStatus, startLogin, refreshAuthStatus, listMcpForAgent and removeMcpForAgent; providerEnvs on saveMcpServer and removeMcpServer; and a refreshMcpServers procedure that republishes the MCP list under the given envs. Auth status and its in-flight dedup are keyed by provider and env fingerprint, a login keeps the env it started with, and a refresh under a new env stops showing the previous account at once. A per-agent MCP removal refuses when the caller's listed root differs from the root the env resolves to now. Minor protocol bump: 13.0.0 -> 13.1.0.
…nvalidate on change The agents and MCP controllers read the provider env from Settings on every call (createProviderEnvSource, injected through controllers.ts) and pass it to the host's agent-config runtime: hooks status, auth refresh, login, the per-agent MCP list and removal, and Settings -> MCP list, save and removal. The renderer-facing agents and MCP contracts declare their inputs without env, and controllers rebuild upstream inputs field by field, so a renderer cannot supply one. When updateSettings changes a provider's env it re-probes auth and republishes the MCP list before returning; the renderer also refetches hooks status and the agent's MCP list. A per-agent removal sends back the root its list came from, which the host only compares.
main's #3559 took protocol 13.1.0 for git.repository.deletePrRef. The agent-config additions on this branch (optional provider env fields, refreshMcpServers, invalidateAuthStatus) move to their own minor, 13.2.0, so a 13.1 server built from main is told apart by the negotiated minor. Version tests and workspace-server.md list which minor introduced what.
Move the provider environment protocol change to 13.3.0; 13.2.0 is taken by the optional addRemote result.
Conflict in session-materializer.test.ts: both sides added a test at the same place (session MCP servers read under the session env; the agent's explanation of a failed load kept). Both tests are kept.
Confidence Score: 4/5
[Medium impact] The changes reach agent sign-in, hook status, and MCP settings for providers with saved environment overrides. The PR appears safe to merge, with a non-blocking auth cache cleanup issue. Findings
Fix with agent prompt### Issue 1
packages/core/src/runtimes/agent-config/node/runtime/auth.ts:130-133
`invalidateStatus` changes the cache key without removing old entries. Each later auth check creates another entry that retains its full `env`, including credentials. `createAsyncCache` has no size limit by default, and its TTL prevents reuse but does not remove expired entries. Repeated settings edits and auth checks therefore keep unreachable entries until the runtime exits. Remove the provider's old entries when invalidating, or bound this cache.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.SummaryPasses each agent's Settings environment through auth, login, hooks, and MCP calls. ACP sessions now read MCP servers with their session environment.
Acknowledged limits from Diagram%%{init: {'theme': 'neutral'}}%%
flowchart LR
Settings[Provider Settings] --> Main[Desktop main process]
Renderer[Renderer request] --> Main
Main --> Runtime[Host agent-config runtime]
Runtime --> Host[AgentPluginHost]
Ambient[Allowlisted host environment] --> Host
Host --> Auth[Auth and login]
Host --> Hooks[Hook status]
Host --> MCP[Environment-selected MCP root]
Session[ACP session environment] --> Host
Reviews (1) · Last reviewed commit: "Merge origin/main into fix/agent-config-..." · Reviewed by Greptile |
| invalidateStatus(providerId: string): void { | ||
| this.statusEpochs.set(providerId, (this.statusEpochs.get(providerId) ?? 0) + 1); | ||
| this.nextStatusGeneration(providerId); | ||
| this.publishedEnvs.delete(providerId); |
There was a problem hiding this comment.
Old auth environments accumulate
invalidateStatus changes the cache key without removing old entries. Each later auth check creates another entry that retains its full env, including credentials. createAsyncCache has no size limit by default, and its TTL prevents reuse but does not remove expired entries. Repeated settings edits and auth checks therefore keep unreachable entries until the runtime exits. Remove the provider's old entries when invalidating, or bound this cache.
Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/core/src/runtimes/agent-config/node/runtime/auth.ts
Line: 130-133
Comment:
**Old auth environments accumulate**
`invalidateStatus` changes the cache key without removing old entries. Each later auth check creates another entry that retains its full `env`, including credentials. `createAsyncCache` has no size limit by default, and its TTL prevents reuse but does not remove expired entries. Repeated settings edits and auth checks therefore keep unreachable entries until the runtime exits. Remove the provider's old entries when invalidating, or bound this cache.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.There was a problem hiding this comment.
Fixed in 2c56895: status cache keys now hold only the env fingerprint, the env is kept only while its probe is pending, and a provider's earlier entries are dropped when its status is invalidated or a newer read settles. A new test checks that one entry remains after repeated env changes and that earlier env objects are collectable.
…its environment changes The auth status cache keyed entries by provider, epoch and env fingerprint, but each entry kept the full StatusKey, env included, and invalidation only bumped the epoch. Entries for earlier envs became unreachable yet stayed in the cache, with their env values, until the runtime exited. The cache key now carries the fingerprint only; a probe reads its env from a map that holds it only while that read is pending. When a read settles or the status is invalidated, the provider's entries other than the newest request's are dropped (entries still being read are kept until they settle).
|
Merging with the review requirement overridden; evidence for the record, on head
|
Description
What users saw. Users can set environment variables for an agent in Settings → Agents →
Advanced settings, or for a project in Project Settings. If they set
CLAUDE_CONFIG_DIRthere,Claude was spawned with it and TUI hooks were installed under it. Everything else still used
~/.claudeand~/.claude.json:A server added for the configured account landed in the default account's file. A structured
(ACP) chat started under the configured directory was given the default account's MCP servers,
with their credentials.
Cause. These paths read the host's ambient environment. They never received the env that the
spawn path builds from Settings. Claude's MCP adapter also hard-coded
~/.claude.json, ignoringCLAUDE_CONFIG_DIRaltogether.Change.
the same source the spawn path uses. It passes the env explicitly to the host's
agent-configruntime. The host merges it over its allowlisted ambient env with
mergeAgentEnvLayers, thelayering
buildAcpSpawnuses. Nothing caches an env for a later call.AgentPluginHosttakes an optionalenvoncheckAuthStatus(env fingerprint in its dedupkey),
buildLoginCommand, and MCP read/write/remove..claude.jsonnow followsCLAUDE_CONFIG_DIR.AgentHookInstaller.hooksStatustakes the env too.unknownrather than the previous account's status, so the sign-in modalis not closed by it.
updateSettingschanges anagent's env, it only invalidates that provider's auth status (dropped from the cache, published
as
unknown). It never startsclaude auth statusor any other agent subprocess: the editorsaves half-typed entries, and the CLI writes its own files into whatever root it runs under. The
next reader that needs the status probes under the env current at that moment.
updateSettingsalso waits for the MCP list to be republished (file reads only) before returning. These
refreshes are queued and logged without values. The renderer refetches hooks status and the
agent's MCP lists.
The host only compares that root; a mismatch refuses the removal and never redirects it. The
removal also republishes the list under the same lock.
agentsandmcpcontracts have no env fields, and controllers rebuildinputs field by field.
other providers' Settings values are not sent to hosts for nothing.
Protocol.
PROTOCOL_VERSION13.2.0 → 13.3.0, a minor bump, asagents/architecture/workspace-server.mdprescribes for optional fields and new procedures.
mainalready took 13.1 forgit.repository.deletePrRef(#3559) and 13.2 for the optionaladdRemoteresult (#3558); theseadditions get their own minor, so an older server is told apart by the negotiated minor. The doc
and version tests list which minor introduced what. The
agent-configcontract gains, in 13.3:env?onhooksStatus,startLogin,refreshAuthStatusandlistMcpForAgent;providerEnvs?onsaveMcpServer,removeMcpServerandremoveMcpForAgent;expectedConfigRoot?onremoveMcpForAgent, andconfigRoot?in thelistMcpForAgentoutput;refreshMcpServersandinvalidateAuthStatusprocedures.Only the desktop main process fills these fields.
High-risk areas: provider environment handling (the auth probe and login PTY now get the
Settings env through the same merge as spawn; no allowlist widened;
terminal-env.tsuntouched),and the workspace protocol (minor bump, additive optional fields, two new procedures).
The analysis in #3207 identified the bug and the paths involved. This is a smaller replacement
for that PR, without its env cache or its ACP hook installation.
Related issues
Supersedes #3207.
Testing
nx run-many -t build --all --skip-nx-cache: pass.nx run-many -t typecheck lint format:checkfor core, plugins, desktop and workspace-server:pass. Lint includes the boundary-rule allowlist tests.
After merging
mainat33f0fe87a8(with the Claude ACP adapter 0.114 bump, chore(plugins): update the Claude Code ACP adapter to 0.114.0 #3570):@emdash/core: agent-plugins, agent-config, ACP and workspace-server tests, 838 passed. Anearlier full-suite run had 3109 passing and 9 failing; the 9 are the known process-group and
tmux tests that fail in this VM.
@emdash/pluginstests: 823 passed.@emdash/workspace-servertests: 121 passed.Desktop node tests for agents, MCP, conversations, settings and bootstrap: 60 files, 398 passed.
Desktop
browserproject, in 34 shards: 110 files, 698 passed.New tests (behaviour tests checked to fail without their change, plus read-only regression
guards):
plugin, with two config roots in temp directories. Spawn, hooks, auth, login, MCP list, save
and remove, and session MCP all agree on the configured root. With nothing configured they all
use the default root.
envorproviderEnvsis stripped by both contracts and neverreaches the host.
updateSettingsresolves, a save lands in the new root.updateSettingswith a changed env starts no auth subprocess and publishesunknown; thenext status read probes once, under the new env.
CLAUDE_CONFIG_DIR=""or a missing directory writes nothing ineither root or the working directory.
Manual run of the Electron app, current
mainagainst this branch merged with it, with twoClaude roots:
only that root's file. On
main, both land in the default file.there (structured chats install none). The chat's session gets the configured root's servers (
WHO=alt), and since chore(plugins): update the Claude Code ACP adapter to 0.114.0 #3570 theystill reach
claudeon its command line (--mcp-config);clauderuns with the configuredCLAUDE_CONFIG_DIR. Onmain,claudealso runs with the configured root but its--mcp-configcarries the default account's servers (WHO=personal).settings.jsonin the default root does not block a chat configured for another root (thechat answers normally), and an invalid one in the configured root stops the chat with the
error naming
/tmp/claude-alt/settings.json.mainbehaves the same here, since the agentprocess already got the configured
CLAUDE_CONFIG_DIRthere."Completed", also after restarting the app.
→ MCP back at once.
main.claudeprocess (checked with a logging wrapper), and bothroots' files stay byte-identical.
claude auth loginwithCLAUDE_CONFIG_DIR=/tmp/claude-alt, or with it unset when nothing is configured (as onmain). The modal stays open, and cancelling writes nothing to the other root. The promptitself had to be forced: in that VM a signed-out Claude chat fails its first prompt
(
prompt_failed, "Not logged in") instead of reportingauth_required, onmaintoo.Known limits.
CODEX_HOME, Copilot, Qwen, OpenCode, MiMoCode,Prime Agent) still read their MCP config from the home path; their hooks already follow the
override.
~/.claude.json), so Claude asks for foldertrust under a configured root; provider usage still ignores the env.
updateSettingsruns can still land in the newroot.
ignores the new fields and cannot serve the two 13.3 procedures, so the Settings → MCP list
fails to load against it.
login.
prompt_failedrather than a sign-in prompt(existing on
main).Screenshot/Recording (if applicable)
Not attached. The manual run's results and file checksums are in the report.
Checklist
messages and, when possible, the PR title