Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): a changed provider key reaches threads that are already open #15915

Closedshivamhwp(GitHub profile, opens in a new tab)wants to merge 1 commit intomain fromt3code/claude-session-picks-up-new-keyopened View on GitHub

Changing 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:changed passes (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-change from PID 221332. Changed that value through Settings, then sent another turn in the same open thread: PID 222574 reported after-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):

Existing thread uses the original environment marker

After changing settings, same thread:

The next turn uses the new environment marker and provider process

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

    2. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      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).
    3. juliusmarminge added labelsmacroscope-review

    4. github-actions[bot](GitHub profile, opens in a new tab)commented

      Thread transfer impact

      ✅ Thread transfer remains within every enforced ceiling.

      ProviderMetricMain baselineThis PRImpactPR ceiling
      CodexTotal thread wire5.0 KiB5.0 KiB0 B (0.0%)6.8 KiB✅
      CodexThread snapshot wire3.8 KiB3.8 KiB0 B (0.0%)4.9 KiB✅
      CodexLive turn WebSocket wire1.2 KiB1.2 KiB0 B (0.0%)2.0 KiB✅
      CodexLive turn WebSocket decoded20.9 KiB20.9 KiB0 B (0.0%)29.3 KiB✅
      CodexLive turn messages220 (0.0%)8✅
      ClaudeTotal thread wire5.0 KiB5.0 KiB−7 B (−0.1%)6.8 KiB✅
      ClaudeThread snapshot wire3.8 KiB3.8 KiB0 B (0.0%)4.9 KiB✅
      ClaudeLive turn WebSocket wire1.2 KiB1.2 KiB−7 B (−0.6%)2.0 KiB✅
      ClaudeLive turn WebSocket decoded21.2 KiB21.2 KiB0 B (0.0%)29.3 KiB✅
      ClaudeLive turn messages220 (0.0%)8✅

      Baseline: e075957 · PR result: 3aa64a1 · Source CI: success

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

    5. coderabbitai[bot](GitHub profile, opens in a new tab)commented
      Review in Change Stack →

      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.ts
      • apps/server/src/orchestration-v2/ProviderAdapterRegistry.ts
      • apps/server/src/orchestration-v2/ProviderSessionManager.test.ts
      • apps/server/src/orchestration-v2/ProviderSessionManager.ts
      • apps/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.ts
      The 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.ts
      Live 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 needed

      Suggested 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 f6f8a

      Updated 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: Passed 3 · Failed 1
      Failed Failed checks: 1 warning
      Check nameStatusExplanationResolution
      Description checkWarningThe 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 Passed checks: 3 passed
      Check nameStatusExplanation
      Title checkPassedThe title clearly and concisely describes the main change: updated provider settings now reach threads that are already open.
      Linked Issues checkPassedCheck skipped because no linked issues were found for this pull request.
      Out of Scope Changes checkPassedCheck 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
      Comment `@coderabbitai help` to get the list of available commands.
    6. 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.

    7. juliusmarminge assignedjuliusmarminge

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

    9. juliusmarminge closed this

Sign in to join this conversation.