-
-
Notifications
You must be signed in to change notification settings - Fork 549
feat(claude): support conversation rewind via native session truncation #1679
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
junmo-kim
wants to merge
7
commits into
tiann:main
Choose a base branch
from
junmo-kim:feat/claude-rewind
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 4 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
2acc783
feat(claude): expose resume-session-at rewind flags in sdk wrapper
junmo-kim e075dad
feat(claude): support conversation rewind via native session truncation
junmo-kim 2d3b4a8
feat(claude): gate rewind capability on native truncation support
junmo-kim 41c3e4e
fix(claude): harden rewind against /clear reset and restart races
junmo-kim d716dad
fix(claude): verify native truncation before reporting rewind success
junmo-kim f058e66
fix(claude): close rewind confirmation and locator gaps from review r…
junmo-kim 4db1605
fix(claude): filter injected user entries and canonicalize batch boun…
junmo-kim File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| import { describe, expect, it } from 'vitest' | ||
| import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs' | ||
| import { tmpdir } from 'node:os' | ||
| import { join } from 'node:path' | ||
| import { readNativeTurns, resolveRewindPlan, supportsNativeRewind } from './conversationHistory' | ||
|
|
||
| const CWD = '/tmp/rewind-fixture-project' | ||
|
|
||
| function line(entry: Record<string, unknown>): string { | ||
| return JSON.stringify(entry) | ||
| } | ||
|
|
||
| function prompt(uuid: string, text: string): string { | ||
| return line({ type: 'user', uuid, message: { role: 'user', content: [{ type: 'text', text }] } }) | ||
| } | ||
|
|
||
| function toolResult(uuid: string): string { | ||
| return line({ | ||
| type: 'user', | ||
| uuid, | ||
| message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'tool-1', content: 'ok' }] } | ||
| }) | ||
| } | ||
|
|
||
| function assistant(uuid: string, text: string): string { | ||
| return line({ type: 'assistant', uuid, message: { role: 'assistant', content: [{ type: 'text', text }] } }) | ||
| } | ||
|
|
||
| function attachment(uuid: string): string { | ||
| return line({ type: 'attachment', uuid }) | ||
| } | ||
|
|
||
| function sidechain(uuid: string): string { | ||
| return line({ type: 'assistant', uuid, isSidechain: true, message: { role: 'assistant', content: [] } }) | ||
| } | ||
|
|
||
| function writeTranscript(lines: string[]): string { | ||
| const projectDir = join(mkdtempSync(join(tmpdir(), 'hapi-rewind-')), 'projects') | ||
| mkdirSync(projectDir, { recursive: true }) | ||
| // getProjectPath encodes every non-alphanumeric char of the cwd as '-' | ||
| const projectId = CWD.replace(/[^a-zA-Z0-9]/g, '-') | ||
| const dir = join(projectDir, projectId) | ||
| mkdirSync(dir, { recursive: true }) | ||
| writeFileSync(join(dir, 'session-a.jsonl'), lines.join('\n') + '\n') | ||
| return projectDir | ||
| } | ||
|
|
||
| describe('readNativeTurns', () => { | ||
| it('collects ordered turns from prompts and assistant entries only', () => { | ||
| const root = writeTranscript([ | ||
| line({ type: 'queue-operation', uuid: 'q1' }), | ||
| attachment('a0'), | ||
| prompt('u1', 'Say ONE'), | ||
| assistant('as1', 'ONE'), | ||
| toolResult('tr1'), | ||
| prompt('u2', 'Say TWO'), | ||
| assistant('as2', 'TWO'), | ||
| sidechain('sc1'), | ||
| prompt('u3', 'Say THREE') | ||
| ]) | ||
| try { | ||
| process.env.CLAUDE_CONFIG_DIR = root.replace(/\/projects$/, '') | ||
| expect(readNativeTurns(CWD, 'session-a')).toEqual([ | ||
| { promptUuid: 'u1', endUuid: 'as1' }, | ||
| { promptUuid: 'u2', endUuid: 'as2' }, | ||
| { promptUuid: 'u3', endUuid: 'u3' } | ||
| ]) | ||
| } finally { | ||
| delete process.env.CLAUDE_CONFIG_DIR | ||
| rmSync(root, { recursive: true, force: true }) | ||
| } | ||
| }) | ||
|
|
||
| it('returns empty for a missing transcript', () => { | ||
| process.env.CLAUDE_CONFIG_DIR = join(tmpdir(), 'hapi-rewind-missing-config') | ||
| try { | ||
| expect(readNativeTurns('/nonexistent-cwd', 'nope')).toEqual([]) | ||
| } finally { | ||
| delete process.env.CLAUDE_CONFIG_DIR | ||
| } | ||
| }) | ||
| }) | ||
|
|
||
| describe('supportsNativeRewind', () => { | ||
| it('accepts versions at or above 2.1.223', () => { | ||
| expect(supportsNativeRewind('2.1.240 (Claude Code)')).toBe(true) | ||
| expect(supportsNativeRewind('2.2.0 (Claude Code)')).toBe(true) | ||
| expect(supportsNativeRewind('3.0.1')).toBe(true) | ||
| expect(supportsNativeRewind('2.1.223 (Claude Code)')).toBe(true) | ||
| }) | ||
|
|
||
| it('rejects older and undetectable binaries', () => { | ||
| expect(supportsNativeRewind('2.1.222 (Claude Code)')).toBe(false) | ||
| expect(supportsNativeRewind('2.0.55')).toBe(false) | ||
| expect(supportsNativeRewind(null)).toBe(false) | ||
| expect(supportsNativeRewind('Claude Code')).toBe(false) | ||
| }) | ||
| }) | ||
|
|
||
| describe('resolveRewindPlan', () => { | ||
| const turns = [ | ||
| { promptUuid: 'u1', endUuid: 'as1' }, | ||
| { promptUuid: 'u2', endUuid: 'as2' }, | ||
| { promptUuid: 'u3', endUuid: 'as3' } | ||
| ] | ||
|
|
||
| it('keeps the previous turn boundary and drops the selected turn onward', () => { | ||
| expect(resolveRewindPlan(turns, 1)).toEqual({ | ||
| resumeSessionAt: 'as1', | ||
| dropsTurns: ['u2', 'u3'] | ||
| }) | ||
| }) | ||
|
|
||
| it('rejects dropping the first turn and out-of-range indexes', () => { | ||
| expect(() => resolveRewindPlan(turns, 0)).toThrow('Cannot rewind the first message') | ||
| expect(() => resolveRewindPlan(turns, 3)).toThrow('no native history') | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,101 @@ | ||
| import { existsSync, readFileSync } from 'node:fs' | ||
| import { join } from 'node:path' | ||
| import { getProjectPath } from './utils/path' | ||
|
|
||
| export type NativeTurn = { | ||
| /** uuid of the user prompt entry that starts the turn. */ | ||
| promptUuid: string | ||
| /** uuid of the last user/assistant entry belonging to the turn. */ | ||
| endUuid: string | ||
| } | ||
|
|
||
| type TranscriptEntry = { | ||
| type?: string | ||
| uuid?: string | ||
| isSidechain?: boolean | ||
| message?: { content?: unknown } | ||
| } | ||
|
|
||
| function isPromptEntry(entry: TranscriptEntry): boolean { | ||
| const content = entry.message?.content | ||
| if (typeof content === 'string') return true | ||
|
junmo-kim marked this conversation as resolved.
Outdated
|
||
| return Array.isArray(content) && content.some((block) => (block as { type?: string } | null)?.type === 'text') | ||
| } | ||
|
|
||
| /** | ||
| * Parse the native Claude transcript for a session into ordered turns. | ||
| * The transcript is append-only; rewinds re-parent new turns, so dropped | ||
| * entries remain in the file. Only completed prompt turns are reported. | ||
| */ | ||
| export function readNativeTurns(workingDirectory: string, sessionId: string): NativeTurn[] { | ||
| const file = join(getProjectPath(workingDirectory), `${sessionId}.jsonl`) | ||
| if (!existsSync(file)) return [] | ||
| const turns: NativeTurn[] = [] | ||
| for (const line of readFileSync(file, 'utf-8').split('\n')) { | ||
| if (!line.trim()) continue | ||
| let entry: TranscriptEntry | ||
| try { | ||
| entry = JSON.parse(line) | ||
| } catch { | ||
| continue | ||
| } | ||
| if (entry.isSidechain) continue | ||
| if ((entry.type !== 'user' && entry.type !== 'assistant') || typeof entry.uuid !== 'string') continue | ||
| if (entry.type === 'user') { | ||
| if (!isPromptEntry(entry)) continue | ||
| turns.push({ promptUuid: entry.uuid, endUuid: entry.uuid }) | ||
| } else if (turns.length > 0) { | ||
| turns[turns.length - 1]!.endUuid = entry.uuid | ||
| } | ||
| } | ||
| return turns | ||
| } | ||
|
|
||
| export type RewindPlan = { | ||
| resumeSessionAt?: string | ||
| dropsTurns: string[] | ||
| } | ||
|
|
||
| /** Native `--resume-session-at` truncation landed in Claude Code v2.1.223. */ | ||
| export const NATIVE_REWIND_MIN_VERSION = [2, 1, 223] as const | ||
|
|
||
| export function parseClaudeVersion(versionOutput: string | null | undefined): number[] | null { | ||
| if (!versionOutput) return null | ||
| const match = /(\d+)\.(\d+)\.(\d+)/.exec(versionOutput) | ||
| if (!match) return null | ||
| return [Number(match[1]), Number(match[2]), Number(match[3])] | ||
| } | ||
|
|
||
| /** | ||
| * Whether the installed Claude Code supports resume-time truncation. | ||
| * `null`/unparseable output (detection failed) conservatively reports false so | ||
| * the rewind capability is not advertised against an unknown binary. | ||
| */ | ||
| export function supportsNativeRewind(versionOutput: string | null | undefined): boolean { | ||
| const version = parseClaudeVersion(versionOutput) | ||
| if (!version) return false | ||
| for (let i = 0; i < NATIVE_REWIND_MIN_VERSION.length; i++) { | ||
| const actual = version[i] ?? 0 | ||
| const min = NATIVE_REWIND_MIN_VERSION[i]! | ||
| if (actual !== min) return actual > min | ||
| } | ||
| return true | ||
| } | ||
|
|
||
| /** | ||
| * Build the resume flags to drop turns `[dropFromTurnIndex, turns.length)`. | ||
| * The kept boundary is the last entry of the previous turn; dropping every | ||
| * turn including the first is not representable and is rejected. | ||
| */ | ||
| export function resolveRewindPlan(turns: NativeTurn[], dropFromTurnIndex: number): RewindPlan { | ||
| if (dropFromTurnIndex < 0 || dropFromTurnIndex >= turns.length) { | ||
| throw new Error('Selected message has no native history to drop') | ||
| } | ||
| if (dropFromTurnIndex === 0) { | ||
| throw new Error('Cannot rewind the first message') | ||
| } | ||
| return { | ||
| resumeSessionAt: turns[dropFromTurnIndex - 1]!.endUuid, | ||
| dropsTurns: turns.slice(dropFromTurnIndex).map((turn) => turn.promptUuid) | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.