Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): respawn Claude sessions after re-login on expired credentials #9628

ClosedApexYash11(GitHub profile, opens in a new tab)wants to merge 2 commits intomain fromrefs/pull/9628/headopened View on GitHub

Closes #9607

Problem

T3 keeps one long-lived Claude CLI process per thread, and that process loads OAuth credentials once at startup. When a thread's OAuth session expires, the adapter's process reports authentication_failed ("Not logged in") on every subsequent turn. Because the adapter never treated that as a reason to end the session, the same poisoned process stayed in place even after the user logged in again via the CLI — until the idle-session reaper eventually reclaimed it (up to 30 minutes) or the thread was stopped.

Fix

The adapter now recognizes authentication failures and releases the stale process so the thread can recover as soon as the user re-logs-in:

  • In handleAssistantMessage, the CLI's error: "authentication_failed" stamp on the assistant snapshot flags the session (context.authenticationFailed).
  • In handleResultMessage, once the turn completes, an auth failure (from the snapshot flag or the result's error text) closes the runtime query. That ends the stream and drives the existing handleStreamExit -> stopSessionInternal teardown, which removes the session.
  • The next sendTurn on that thread then hits the existing resume-thread recovery path in ProviderService (the adapter reports hasSession() == false and the session is resumed from its persisted resumeCursor), spawning a fresh Claude process that reads the refreshed credentials.

No new recovery machinery is introduced — the fix is purely about detecting the failure and letting the existing lifecycle respawn. User-aborted/interrupted and cancelled turns are deliberately left alone.

This complements (and does not duplicate) #9612, which only exempts live Claude sessions from the idle reaper.

Verification

  • New ClaudeAdapter test: an auth-failure turn closes the query and leaves hasSession() == false (so the next turn resumes fresh).
  • New ClaudeAdapter test: a distinct non-auth failure (rate limit) keeps the session alive.
  • ClaudeAdapter.test.ts: 82/82 pass.
  • Server typecheck (tsgo --noEmit): clean for the edited files.

Done with Claude (Sonnet) in Cline.


Note

Medium Risk Changes Claude session lifecycle and hasSession semantics during async teardown; misclassification could close healthy sessions or leave stale processes, but scope is limited to auth-error detection and existing resume recovery.

Overview Fixes threads that stay stuck on "Not logged in" after re-login because the long-lived Claude CLI process only loads OAuth once and never picks up refreshed credentials.

ClaudeAdapter now treats CLI auth failures as fatal for the session process: assistant snapshots with error: "authentication_failed" set a context flag, and when the turn’s result finishes (unless interrupted/cancelled), matching error text triggers query.close(), logs claude.session.stopping-after-auth-failure, and immediately marks the session closed so hasSession is false and follow-up sendTurn calls fail with ProviderAdapterSessionNotFoundError instead of enqueueing on a dying runtime. The next successful turn is expected to go through the existing resume-thread path and spawn a fresh process.

Non-auth failures (e.g. rate limits) are unchanged—the session stays open and close() is not called.

Tests cover auth-failure teardown plus a negative case where other errors keep the session alive.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 862fdc9664314196f103c38c8090c3a058b1b3f6. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).

Note

Fix ClaudeAdapter to tear down sessions on authentication failure

  • Adds isClaudeAuthenticationErrorText to classify known auth failure strings, such as authentication_failed and /login.
  • handleAssistantMessage sets ClaudeSessionContext.authenticationFailed when an assistant snapshot's error matches the detector.
  • handleResultMessage closes the Claude query and marks the session closed on auth failure, unless the turn was interrupted or cancelled. Non-auth failures leave the session open.
  • hasSession now returns false for sessions marked closed, so follow-up sendTurn calls fail with ProviderAdapterSessionNotFoundError during teardown.
  • Risk: hasSession now requires sessionStatus to not be closed; if status is not updated correctly during teardown, follow-up turns will be rejected.
Macroscope summarized 862fdc9.
    1. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

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

      Approvability

      Verdict: Not approved

      Macroscope's review found this PR not approvable — This production change alters authentication-sensitive Claude session teardown and recovery behavior, including replacing long-lived processes after OAuth failures. An unresolved medium-severity concern also indicates that the session-level failure state can affect later turns, so the lifecycle behavior requires human review.

      Not approved because:

      • 1 blocking correctness issue found at or above your repo's Minimum Blocking Severity

      No code changes detected at 862fdc9. Prior analysis still applies.

      Adjust the Minimum Blocking Severity for this repo — including turning it Off — in [Settings](https://app.macroscope.com/pingdotgg/settings#Repos). You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    3. @@ -4499,3 +4580,4 @@
      44994580 lastAssistantUuid: resumeState?.resumeSessionAt,
      45004581 lastThreadStartedId: undefined,
      45014582 stopped: false,
      4583+ authenticationFailed: false,
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Layers/ClaudeAdapter.ts:4583

      An authentication failure from one turn can permanently close the session on a later successful turn. authenticationFailed is session-scoped and remains true when an interrupted or cancelled result deliberately keeps the query alive, so the next normal result takes the auth-failure branch despite having no authentication error. Clear the marker for exempt results or associate it with the turn that produced it.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/ClaudeAdapter.ts around line 4583:
      
      An authentication failure from one turn can permanently close the session on a later successful turn. `authenticationFailed` is session-scoped and remains `true` when an `interrupted` or `cancelled` result deliberately keeps the query alive, so the next normal result takes the auth-failure branch despite having no authentication error. Clear the marker for exempt results or associate it with the turn that produced it.
    4. @t3dotgg can you run the worflow for this!!

    5. robertnisipeanu(GitHub profile, opens in a new tab)commented

      Heads up that #9468 addresses the same issue (#9607) and was opened a day before this one, linked from the issue. Flagging it so the maintainers can triage the two together rather than review both.

      For what it's worth, a few differences that might help with that comparison:

      • #9468 keys off the exact error: "authentication_failed" code on the assistant message. This PR also substring-matches the result's errors text (not logged in, /login, oauth session expired). That only sees CLI error strings, not model output, so a false positive is unlikely and would just cost an extra respawn. The exact code already covers the stuck-process case, so the extra patterns mostly add surface without adding coverage.
      • #9468 stops the session through the existing stopSessionInternal path right after turn.completed, with a small guard so a stop issued from the stream fiber does not interrupt itself. This PR calls query.close() and then hand-sets the session status to closed and widens hasSession, relying on the async stream exit to finish the teardown.
      • The authenticationFailed flag here is session-scoped and never cleared, so an interrupted turn after an auth failure carries it into the next successful turn (Macroscope's open Medium finding). In #9468 the recorded error lives only as long as the session it ends.
      • #9468 uses the CLI's own message as the turn failure text and avoids emitting it a second time as a runtime error.
      • The negative test here waits on a few Effect.yieldNow calls to let the stream settle; AGENTS.md asks for receipt-driven tests rather than timing.

      Happy to fold anything from here into #9468 if the maintainers prefer parts of this approach.

    6. juliusmarminge added labelsmacroscope-review

    7. Thanks for working on this. We merged the orchestrator V2 rewrite in #2829, and we are closing this PR as part of that transition.

      This change touches ClaudeAdapter.ts, which the V2 merge removed. Claude execution now runs through ClaudeAdapterV2.

      Sorry for the extra work this creates. If the change is still needed on V2, please rebuild it on current main, verify it there, and open a new PR linking back here. We're closing the current implementation without assuming the underlying request is resolved.

    8. juliusmarminge closed this

Sign in to join this conversation.