fix(server): a changed provider key reaches threads that are already open #15915
main fromt3code/claude-session-picks-up-new-key·opened View on GitHubChanging a provider instance's API key, base URL, or environment rebuilt its adapter, but already-open threads kept a session bound to the old adapter. An eligible idle session now reopens through the current adapter on its next turn.
Keep active turns, pending background work, and sessions attached to another thread on their existing runtime. Recheck activity and attachments atomically before retiring a session so a concurrent attachment cannot lose its open-to-start handoff. Cache sign-in wrappers per instance build so ordinary lookups preserve adapter identity.
Maintainer takeover of #15915, preserving @shivamhwp's intent. Rebased onto current main as one commit; main had since converted removeLiveEntry to Effect.fn and removed some session-manager tests, and those changes are kept.
Verification#
- Focused manager, adapter-registry, and merge-back suites at
3aa64a1493: 52 passing tests across three existing files, 4 of them added by this PR. Before the rebase, idle replacement and wrapper identity both failed against main; removing the atomic attachment guard failed the extended shared-session regression; removing the release-error handler failed the idle-rebuild case. vp run check:changedpasses (format, lint, knip, server typecheck, focused tests). Current-head CI passes, with scope-dependent jobs skipped.- Independent full-diff reviews before the rebase: Codex gpt-6-sol and Claude claude-opus-5-5, two rounds, last round clean. After the rebase: Codex gpt-6.1-sol found no correctness, convention, or scope issues. No unresolved review threads remain.
- Live Linux server + web client before the rebase: an actual ACP subprocess reported harmless
TAKEOVER_KEY_MARKER=before-changefrom PID 221332. Changed that value through Settings, then sent another turn in the same open thread: PID 222574 reportedafter-change. A third turn without another settings edit reused PID 222574. The server stayed running throughout; completed prompts and session/load calls were recorded. These captures precede the rebase and the nonvisual release-error handler; the session-replacement logic itself is unchanged by the rebase, and the release-error branch has separate red/green coverage.
Before changing settings (rebuilt head, not a main-branch screenshot):

After changing settings, same thread:

Recording of the Settings edit and next prompt.
This uses a protocol fixture, not vendor credentials. Real provider accounts, macOS, Windows, iOS, Android, and Electron desktop remain unverified. Shared sessions and sessions with background work intentionally defer adoption until safe release. Human review of the credential-sensitive lifecycle change remains appropriate.
Tests: Codex gpt-6-astra (high). Implementation: Codex gpt-6.1-sol (high). Reviews: Claude claude-opus-5-5 and Codex gpt-6-sol (high), via T3 Code delegation. Maintainer integration and live proof: Codex gpt-6.1-sol (high), Codex harness in T3 Code. Rebase onto main: Claude claude-opus-5-5, Claude Code in T3 Code; post-rebase review: Codex gpt-6.1-sol (high).
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:M
juliusmarminge added labelsmacroscope-review
Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Provider Metric Main baseline This PR Impact PR ceiling Codex Total thread wire 5.0 KiB 5.0 KiB 0 B (0.0%) 6.8 KiB ✅ Codex Thread snapshot wire 3.8 KiB 3.8 KiB 0 B (0.0%) 4.9 KiB ✅ Codex Live turn WebSocket wire 1.2 KiB 1.2 KiB 0 B (0.0%) 2.0 KiB ✅ Codex Live turn WebSocket decoded 20.9 KiB 20.9 KiB 0 B (0.0%) 29.3 KiB ✅ Codex Live turn messages 2 2 0 (0.0%) 8 ✅ Claude Total thread wire 5.0 KiB 5.0 KiB −7 B (−0.1%) 6.8 KiB ✅ Claude Thread snapshot wire 3.8 KiB 3.8 KiB 0 B (0.0%) 4.9 KiB ✅ Claude Live turn WebSocket wire 1.2 KiB 1.2 KiB −7 B (−0.6%) 2.0 KiB ✅ Claude Live turn WebSocket decoded 21.2 KiB 21.2 KiB 0 B (0.0%) 29.3 KiB ✅ Claude Live turn messages 2 2 0 (0.0%) 8 ✅ Baseline:
e075957· PR result:3aa64a1· Source CI: successScenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
- Codex decoded thread snapshot: 108.5 KiB
- Claude decoded thread snapshot: 108.8 KiB
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
-
⚙️ Run configuration
-
- Configuration used: Path: .coderabbit.config.ts
- Review profile: CHILL
- Plan: Advanced
- Run ID:
1923842e-41dd-4d01-8dfe-18ec71f692ba
📥 Commits
-
Reviewing files that changed from the base of the PR and between f6f8a62c7290dc6c453feae8237bb613b3b7b9f9 and 3aa64a1493841c9d47b83206aa19eda41dda9e16.
📒 Files selected for processing: 5
-
apps/server/src/orchestration-v2/ProviderAdapterRegistry.test.tsapps/server/src/orchestration-v2/ProviderAdapterRegistry.tsapps/server/src/orchestration-v2/ProviderSessionManager.test.tsapps/server/src/orchestration-v2/ProviderSessionManager.tsapps/server/src/orchestration-v2/testkit/ThreadMergeBack.integration.test.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review.
-
📝 Walkthrough
-
The provider adapter registry preserves authenticated adapter identity across lookups. The session manager detects adapter changes and replaces eligible idle sessions when no background work is pending. Tests cover adapter caching and session replacement conditions.
Changes: Adapter refresh and session lifecycle
Layer / File(s) Summary Cache authenticated adapter wrappers
apps/server/src/orchestration-v2/ProviderAdapterRegistry.ts,apps/server/src/orchestration-v2/ProviderAdapterRegistry.test.ts,apps/server/src/orchestration-v2/testkit/ThreadMergeBack.integration.test.tsThe registry caches authenticated wrappers by provider instance. Tests verify stable identity until the provider instance changes. The replay harness caches wrappers by adapter identity. Replace eligible sessions
apps/server/src/orchestration-v2/ProviderSessionManager.ts,apps/server/src/orchestration-v2/ProviderSessionManager.test.tsLive session entries record their opening adapter. On open, the manager checks for adapter changes and pending work before attempting a guarded release. Tests cover idle sessions, active turns, a rebuild-check race, shared sessions, and pending background work. Priority: ➖ Normal
Estimated code review effort: 3 (Moderate) | ~25 minutes
Change: Bug fix
Sequence Diagram(s)#
sequenceDiagram participant ProviderSessionManager participant ProviderAdapterRegistry participant SessionRuntime participant ProviderAdapter ProviderSessionManager->>ProviderAdapterRegistry: Get current adapter ProviderSessionManager->>SessionRuntime: Check pending background work ProviderSessionManager->>SessionRuntime: Release with manual_shutdown when eligible ProviderSessionManager->>ProviderAdapter: Open session when replacement is neededSuggested reviewers:
juliusmarminge
Merge Risk: ⚪ Minimal · up to
3aa64-
Idle threads now reopen through the current provider adapter after a settings change. Active turns, pending background work, and shared sessions stay on their existing runtime. No concrete merge-blocking issue was found in the reviewed changes.
Security Architecture Review
-
Security architecture risk: 🔵 Low · up to
f6f8aUpdated credentials can reach idle conversations while active work is preserved. A narrow concurrency uncertainty remains: work acquired just before a refresh may still reference the retired connection. No credential disclosure or authorization bypass was verified.
Retained concerns
- Low · architecture · inferred: A runtime returned by open can remain in another caller's possession while a subsequent open retires it after an adapter rebuild. The release guard protects already-busy turns, but not the interval between acquisition and startTurn. The exposed startTurn invokes its captured runtime while activity bookkeeping addresses only the session ID, allowing a stale caller to target a retired runtime or update replacement-session activity. The mechanism predates this PR's idle release, but settings-driven replacement adds a new immediate trigger. Provider-specific execution after retirement is not established.
Security review details
-
Security Blast Radius
- inferred — The immediate lifecycle boundary is one provider session and its attached threads. Sessions sharing an instance can each refresh on later opens; the changed code does not perform an unconditional instance-wide release.
Trust Boundaries and Controls
- observed — Caching does not cache an admission decision. Every wrapped openSession invocation reads credential-binding state, rejects credential changes in progress, and applies access controls for peers sharing the same binding owner and key.
Resilience and Maintainability Implications
- observed — Existing release cleanup avoids revoking credentials held by in-flight reservations or replacement sessions. Failed opens revoke only freshly issued credentials, and interruption drops the reservation. These controls remain in the replacement path.
Hardening Proposals
- proposed — Bind turn admission to runtime identity or an acquisition lease, so retirement cannot leave a previously returned runtime executable or allow its activity updates to affect a replacement. Validate the acquisition-to-start interval, not only turns already marked busy.
Pre-merge checks:
3 · 1-
Failed checks: 1 warningCheck name Status Explanation Resolution Description check The description clearly explains the problem, implementation, behavior constraints, verification results, limitations, and review context. However, it does not use the required Problem and Change sect… Add the required ## Problem, ## Change, and ## Scope and approval headings. Under Scope and approval, link the triaged issue or discussion and include the explicit maintainer approval comment, or explain why this focused fix qualifies for a… Passed checks: 3 passed-
Check name Status Explanation Title check The title clearly and concisely describes the main change: updated provider settings now reach threads that are already open. Linked Issues check Check skipped because no linked issues were found for this pull request. Out of Scope Changes check Check skipped because no linked issues were found for this pull request.
Full details: Description check
-
Explanation
The description clearly explains the problem, implementation, behavior constraints, verification results, limitations, and review context. However, it does not use the required Problem and Change section headings, and the Scope and approval section does not include an explicit maintainer approval comment or explain why prior approval was unnecessary.
Resolution
Add the required ## Problem, ## Change, and ## Scope and approval headings. Under Scope and approval, link the triaged issue or discussion and include the explicit maintainer approval comment, or explain why this focused fix qualifies for an exemption. Keep the existing verification details under ## Verification.
-
✨ Finishing Touches
-
📝 Generate docstrings
-
- Commit to this branch
- Create a new PR
🧪 Generate unit tests (beta)
-
- Commit to this branch
- Create a new PR
-
- Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
-
- apps/server/src/orchestration-v2/ProviderSessionManager.ts line 2147Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1705 +1708,20 @@1705- const existing = (yield* Ref.get(sessions)).get(key);1708+ const live = (yield* Ref.get(sessions)).get(key);1709+ // Editing a provider instance's settings rebuilds its adapter, and1710+ // a session keeps the environment (API key, base URL) of the1711+ // adapter that opened it. Replace a session from an older adapter1712+ // so the next turn uses the current settings, unless a turn or1713+ // background work is still running in it.1714+ const outdated =1715+ live !== undefined &&1716+ live.busyCount === 0 &&1717+ (yield* registry.get(live.runtime.instanceId).pipe(1718+ Effect.map((current) => current !== live.adapter),1719+ Effect.orElseSucceed(() => false),1720+ )) &&1721+ !(yield* (live.runtime.hasPendingBackgroundWork ?? Effect.succeed(false)).pipe(1722+ Effect.catchCause(() => Effect.succeed(false)),1723+ ));1724+ if (outdated) {1725+ // Another thread sharing the session can start a turn while the1726+ // checks above yield; the generation guard keeps it then.1727+ yield* releaseEntry({
🟠 High
orchestration-v2/ProviderSessionManager.ts:1727A settings edit can close the old runtime while a concurrent
providerSessions.opencaller is still loading its provider thread, causing the subsequentsession.startTurnto fail or run untracked.releaseEntryonly checksbusyCount/idleGeneration; the caller does not mark the entry busy until after this block, andmarkBusyno-ops once the entry has been removed. Add a reservation or equivalent handoff so an open runtime is protected before its turn starts, and release that reservation after registration.🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
In file @apps/server/src/orchestration-v2/ProviderSessionManager.ts around line 1727: A settings edit can close the old runtime while a concurrent `providerSessions.open` caller is still loading its provider thread, causing the subsequent `session.startTurn` to fail or run untracked. `releaseEntry` only checks `busyCount`/`idleGeneration`; the caller does not mark the entry busy until after this block, and `markBusy` no-ops once the entry has been removed. Add a reservation or equivalent handoff so an open runtime is protected before its turn starts, and release that reservation after registration.Fixed in 6a1dbe0. This only happens when another thread shares the session (Codex, OpenCode2). Effects for one thread run one at a time, so the opener's own earlier open has always finished. A session is now replaced only when the opening thread is the only one attached; a shared session keeps the old behavior and refreshes on idle release. New test: "keeps a session shared with another thread after a rebuild", which fails without the change.
Taking over this one. I’ll resolve it against current main, rebuild the idle-session replacement around the existing lifecycle guards, and push to this branch after focused tests and independent reviews.
juliusmarminge assignedjuliusmarminge
Thanks @shivamhwp for the earlier work on refreshing existing sessions after provider settings change. Closing this in favor of #31256 by @Kwan-Li, which addresses the same issue and is actively maintained. This PR’s head is from October 22, and main has since changed the affected session-manager files.
juliusmarminge closed this
Sign in to join this conversation.
Approvability#
Verdict: Needs Human Approval
Macroscope's review found this PR requires human approval — This targeted server fix detects rebuilt provider adapters and safely refreshes idle, single-thread sessions while preserving active or shared sessions. Because it changes credential-sensitive provider session teardown and recreation behavior, human review is warranted.
You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).