claudecodeui icon indicating copy to clipboard operation
claudecodeui copied to clipboard

fix: auto-fallback to new session when resume fails with "No conversation found"

Open javamagong opened this issue 7 months ago • 2 comments

Summary

When CloudCLI UI has an old session ID in the sidebar that no longer exists in the CLI/SDK (e.g. session was cleaned up by
Claude/Codex), sending a message would fail with an error and give no response to the user.

This change adds automatic fallback for all SDK-based providers:

  • Claude SDK: Extract iteration loop into runSDKQueryLoop, catch "No conversation found" error → remove stale resume
    option → retry as new session with same prompt
  • OpenAI Codex SDK: Similar fix — if resumeThread(sessionId) fails with "not found" error → start a new thread

This is a common issue because:

  • CloudCLI persists session IDs in the project sidebar
  • The underlying CLI/SDK periodically cleans up old sessions
  • When users click an old session and send a message, it previously hung without any feedback

Testing

  • ✅ Reproduced the original bug for Claude (click stale session → send message → no response, server logs error)
  • ✅ Verified the fix works: same scenario → automatically creates new session → response appears correctly
  • ✅ Added the same fix for Codex for consistency
  • ✅ Gemini already had proper checking (if (session && session.cliSessionId) only)
  • ✅ Cursor already had shell fallback (... || cursor)

The change is minimal and isolated to the affected files: server/claude-sdk.js and server/openai-codex.js. Existing behavior unchanged for valid sessions.

Summary by CodeRabbit

  • Bug Fixes
    • Streaming is more resilient: when a prior session becomes stale or a resume fails, the system retries and recovers automatically with clearer warnings.
    • Missing or unavailable conversations now trigger creation of new sessions so streams continue without user action.
    • Session IDs and state are tracked more reliably across retries, improving continuity and reducing failed/duplicated responses.

javamagong avatar Apr 27 '26 04:04 javamagong

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 0af098df-2663-4883-a8b5-3b6a4c0c8645

📥 Commits

Reviewing files that changed from the base of the PR and between f2179c4cd88279d4794d83f600ae3ad25a0bec22 and 4b8c68c4e9bb5f77195e4c28547968011c7286e7.

📒 Files selected for processing (2)
  • server/claude-sdk.js
  • server/openai-codex.js
🚧 Files skipped from review as they are similar to previous changes (1)
  • server/openai-codex.js

📝 Walkthrough

Walkthrough

Refactors streaming resume/retry behavior: server/claude-sdk.js adds a streaming loop that retries on stale resume failures and propagates a mutable sessionRef.id; server/openai-codex.js catches failed thread resumes and falls back to creating new threads to avoid reusing stale session IDs.

Changes

Cohort / File(s) Summary
Claude SDK streaming & session handling
server/claude-sdk.js
Adds runSDKQueryLoop to wrap the SDK iterator and retry when resume fails with "no conversation found"; replaces capturedSessionId with a mutable sessionRef.id; moves session add/remove, session_created emits, message normalization/sending, and token-budget extraction into the loop; handles hook-init fallback and temporary close-timeout env override.
Codex resume fallback & session id selection
server/openai-codex.js
Guards codex.resumeThread with try/catch, detects stale/missing-thread resume errors and starts a fresh thread when necessary (sets resumeFailed), and ensures currentSessionId prefers the new thread id to avoid stale session reuse.

Sequence Diagram(s)

sequenceDiagram
    participant Client as WebSocket Client
    participant Server as App Server
    participant SDK as Claude SDK
    participant Store as SessionStore

    Client->>Server: start streaming query (may include resume id)
    Server->>Store: lookup resume mapping
    Server->>SDK: create or resume query iterator
    SDK-->>Server: returns iterator or throws "no conversation"
    alt resume failed ("no conversation" / stale)
        Server->>Store: remove stale session mapping
        Server->>Server: clear resume opts, set temp timeout, recreate query (retry)
        Server->>SDK: new iterator (fresh session)
        Server->>Store: add new session mapping (update sessionRef.id)
    end
    loop stream events
        SDK-->>Server: stream chunk / token-budget / completion / error
        Server->>Client: forward WS messages using sessionRef.id
        Server->>Store: update token-budget/status and dedupe metadata using sessionRef.id
    end

Possibly related PRs

  • siteboon/claudecodeui#462: Modifies server/claude-sdk.js session handling and session storage APIs — overlaps session add/remove lifecycle changes.
  • siteboon/claudecodeui#318: Adjusts sessionId propagation in streaming/WebSocket messages — closely related to sessionRef propagation changes.
  • siteboon/claudecodeui#208: Implements streaming/resume logic and session-id propagation similar to the retry/recreate flow introduced here.

Suggested reviewers

  • blackmammoth

Poem

🐰 I hopped through streams and nibbled stale threads,
Rebuilt fresh tunnels where old resumes bled.
sessionRef now guides each bouncing line,
Chunks hop home tidy, token counts align.
🥕✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically summarizes the main change: adding automatic fallback to a new session when resume fails with 'No conversation found'.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • [ ] Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar Apr 27 '26 04:04 coderabbitai[bot]

Only users with a collaborator, contributor, member, or owner role can interact with CodeRabbit.

coderabbitai[bot] avatar Apr 27 '26 06:04 coderabbitai[bot]

PR closed as there are no updates.

blackmammoth avatar Jun 25 '26 12:06 blackmammoth