Repository navigation
fix(daemon): only resume Claude turn when a real transcript exists - #22
Conversation
Defense-in-depth guard in runClaudeJob. Previously the SDK `resume` option was set unconditionally from request.sessionId. When a card switches provider (e.g. codex/gpt-5.5 turns then a claude turn), the daemon was handed a foreign codex-format UUIDv7 thread id with no Claude transcript on disk. The Claude Agent SDK then returned num_turns:0 with zero assistant content — the user saw an empty reply. Now findClaudeResumeTranscript() scans <CLAUDE_CONFIG_DIR|~/.claude>/projects/*/<sessionId>.jsonl for a non-empty transcript before setting `resume`. Scan-all (rather than reconstructing the encoded-cwd project key) sidesteps the SDK's realpath + NFC + 200-char hash-suffix encoding. Foreign/stale ids match nothing → start fresh so the model runs normally; valid same-provider Claude ids keep resuming unchanged. Also covers the symmetric case (a Claude id handed to a codex/omnigent resume path elsewhere). Adds regression test: a sessionId with no transcript must NOT pass `resume` (and still runs the turn); one with a transcript must pass it.
📝 WalkthroughWalkthroughAdds a ChangesClaude Resume Guard
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Pull request overview
This PR hardens the daemon’s Claude job execution to avoid attempting to resume Claude sessions when the provided sessionId doesn’t correspond to a real on-disk Claude transcript (e.g., after switching providers and receiving a non-Claude thread id). This prevents “empty reply” turns caused by the Claude Agent SDK resuming a session with zero turns.
Changes:
- Add a transcript-existence guard (
findClaudeResumeTranscript) and only set the Claude SDKresumeoption when a real transcript file exists. - Emit a warning and start a fresh Claude turn when the
sessionIdis foreign/stale. - Add a node test covering both “missing transcript” and “transcript present” cases by injecting
claudeQuery.
Reviewed changes
Copilot reviewed 1 out of 2 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
packages/codesurf-daemon/bin/chat-jobs.mjs |
Adds transcript-based resume guard and updates Claude job options to only resume when a transcript exists. |
test/daemon/chat-jobs-claude-resume-guard.test.mjs |
Adds regression tests validating resume is omitted for foreign ids and preserved for valid Claude transcripts. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| @@ -0,0 +1,126 @@ | |||
| import test from 'node:test' | |||
| import assert from 'node:assert/strict' | |||
| import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises' | |||
There was a problem hiding this comment.
🧹 Nitpick comments (1)
test/daemon/chat-jobs-claude-resume-guard.test.mjs (1)
26-32: 💤 Low valueTest helper should also wait for
'queued'status.The daemon can start jobs in
'queued'status when concurrency slots are full. The current check only waits whilestatus === 'running', so a queued job would be treated as complete. This doesn't affect current tests (single job, 4 slots), but would cause flaky failures if tests ever run concurrent jobs.♻️ Suggested fix
async function waitForCompletedJob(manager, jobId) { return await waitFor(async () => { const state = await manager.getJobState(jobId) - if (!state || state.status === 'running') return null + if (!state || state.status === 'running' || state.status === 'queued') return null return state }) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@test/daemon/chat-jobs-claude-resume-guard.test.mjs` around lines 26 - 32, The waitForCompletedJob helper function only waits while status === 'running', but jobs can also be in 'queued' status when concurrency slots are full. Modify the condition in the waitFor callback to also check for 'queued' status, so the function returns null (continues waiting) for both 'running' and 'queued' statuses instead of treating queued jobs as complete.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@test/daemon/chat-jobs-claude-resume-guard.test.mjs`:
- Around line 26-32: The waitForCompletedJob helper function only waits while
status === 'running', but jobs can also be in 'queued' status when concurrency
slots are full. Modify the condition in the waitFor callback to also check for
'queued' status, so the function returns null (continues waiting) for both
'running' and 'queued' statuses instead of treating queued jobs as complete.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 801583e4-0fe4-4868-b76c-67900e9c2b0f
📒 Files selected for processing (2)
packages/codesurf-daemon/bin/chat-jobs.mjstest/daemon/chat-jobs-claude-resume-guard.test.mjs
Problem (proven from on-disk evidence)
In
packages/codesurf-daemon/bin/chat-jobs.mjs,runClaudeJobset the Claude Agent SDKresumeoption unconditionally fromrequest.sessionIdwith no check that the id refers to a real, resumable Claude session.When a card switches provider (e.g. 6 codex/gpt-5.5 turns then a claude turn), the daemon is handed a codex-format UUIDv7 thread id (e.g.
019ecd2c-…-7580-…). The Claude SDK tries to resume a session with no transcript on disk and returnsnum_turns:0,cost:0, zero assistant content — the user sees an empty reply.Fix — defense-in-depth guard
findClaudeResumeTranscript(sessionId)confirms a real transcript exists beforeresumeis set. Only then doesrunClaudeJobpassresume: request.sessionId; otherwise it omitsresumeand starts a fresh turn so the model runs normally (and logs a warn).Confirmed transcript path layout (from installed
@anthropic-ai/claude-agent-sdk)where
<encoded-cwd>= realpath(cwd) → NFC-normalized →replace(/[^a-zA-Z0-9]/g, '-')(paths > 200 chars get a hash suffix).The guard scans every project dir for
<sessionId>.jsonlinstead of reconstructing the encoded key — this deliberately sidesteps the SDK's realpath + NFC + hash-suffix encoding (replicating it is the brittle part). A foreign/stale id has no transcript anywhere → returns null → fresh start. A valid same-provider Claude id always has its transcript on disk → resume preserved unchanged. Includes a path-traversal guard on the id and the SDK's ownsize > 0check.Test
test/daemon/chat-jobs-claude-resume-guard.test.mjs(drivesrunClaudeJobvia injectedclaudeQuery, setsCLAUDE_CONFIG_DIRto a temp dir):options.resume === undefined, turn still runs, job completes.options.resume === sessionId.Gates
node --test test/daemon/chat-jobs-claude-resume-guard.test.mjs→ 2/2 passnpm run test:daemon→ 220 pass / 3 fail. All 3 failures pre-existing and unrelated: two assert an outdated error string (…OpenCode, and Hermes) the recent Omnigent provider work changed to…Hermes, and Omnigent; one is a renderer ChatTileComposer pills test.npm run typecheck→ 16 errors, all pre-existing baseline, none in the changed file (chat-jobs.mjsis.mjs, outside the tsc program).Scope: 2 files, +188/-3.
Summary by CodeRabbit
Bug Fixes
Tests