feat: message-level conversation fork and rewind (#1263)

* feat: add message-level conversation fork and rewind

Expose native Codex/Grok/Claude history controls through hub REST+RPC and web ConfirmDialog actions, without file rewind or composed forks. Also reconcile the duplicate hub V14→V15 migration so typecheck can pass.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: hydrate fork transcript and consume Claude --fork-session

Forked HAPI children now copy the source transcript prefix so navigation is not a blank thread, and Claude drops --fork-session after the first launch so relaunches do not branch again.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: harden fork/rewind concurrency and durable history points

Skip pending scheduled rows when hydrating fork transcripts, serialize fork/rewind per session, and persist conversation history points/indexes across existing-session bootstrap and Grok relaunches.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: close remaining fork/rewind races and UI anchoring

Block sends and scheduled maturation while history actions run, order fork prefixes by invocation time, inherit history locators into children, and only offer Fork current on the live tail boundary.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: address remaining fork/rewind bot findings

Materialize Claude --fork-session before the first child prompt, validate
HAPI history boundaries before native RPC, expose forkCurrent on a latest
user boundary, fully demote unsupported conversationHistory capabilities,
and fix the truncate test setup order.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: align fork-current ids and Claude fork bootstrap

Compare the latest fork boundary in assistant-ui threadMessageId space,
spawn Claude forks with the persisted session mode, and preserve
forkedFrom across existing-session bootstrap.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: close fork/rewind consistency holes at the contract layer

Hold the source history lock until Claude child binds a distinct native
id, persist Codex localId→turnId locators, and mark/block diverged
sessions when native rewind outruns HAPI truncate.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: use Codex stable lastTurnId for historical fork

Map HAPI's exclusive boundary to the previous turn's inclusive
lastTurnId so native fork context matches the hydrated transcript.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: require exact Grok native resume for fork children

Reject newSession fallback when forkedFrom is set, and keep the hub
history lock until the child binds the forked grokSessionId.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: kill active fork children before failed-fork cleanup

Bind/readiness failures can leave the child process running; deleteSession
rejects active rows, so terminate first then remove the HAPI session.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: close remaining fork lock, hydrate, and todos gaps

Reject mode switches during history actions, batch-copy fork
transcripts in one SQLite transaction, and rebuild todos after
fork hydrate / rewind truncate.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: allow Codex historical fork before the first turn

Use experimental beforeTurnId when there is no previous turn for the
stable inclusive lastTurnId boundary.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: mark Grok history busy immediately after dequeue

Hub idle checks clear once messages-consumed fires; hold the busy flag
across permission sync and rewind-points lookup before prompt starts.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: encode copied conversation history content

* fix(web): hide local conversation history actions

* style(codex): remove trailing whitespace

* fix(fork): preserve children when cleanup is unconfirmed

* fix(history): confirm cleanup and guard rewind divergence

* fix(history): probe capabilities before advertising

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
SSU-WEI HUANG
2026-08-03 09:28:01 +08:00
committed by GitHub
co-authored by Cursor
parent 3f03e8daa1
commit 3c3bffdfbd
59 changed files with 2829 additions and 122 deletions
+39
View File
@@ -427,6 +427,45 @@ export const SendMessageRequestSchema = z.object({
export type SendMessageRequest = z.infer<typeof SendMessageRequestSchema>
export const ForkConversationRequestSchema = z.object({
messageLocalId: z.string().min(1).optional()
})
export type ForkConversationRequest = z.infer<typeof ForkConversationRequestSchema>
export type ForkConversationResponse = {
sessionId: string
}
export const RewindConversationRequestSchema = z.object({
messageLocalId: z.string().min(1)
})
export type RewindConversationRequest = z.infer<typeof RewindConversationRequestSchema>
export type RewindConversationResponse = {
success: true
}
/** CLI → hub RPC result for native fork (before HAPI child binding). */
export type ForkConversationRpcResult = {
nativeSessionId: string
/** When true, hub must spawn with --fork-session (Claude). */
forkSession?: boolean
}
export type RewindConversationRpcResult = {
success: true
/** Truncate HAPI transcript at/after this localId, then accept rehydrated history. */
truncateFromLocalId: string
messages?: Array<{
content: unknown
localId?: string | null
createdAt?: number
invokedAt?: number | null
}>
}
export const QueuedStateRequestSchema = z.object({
localIds: z.array(z.string().min(1)).max(1000)
})
+25
View File
@@ -0,0 +1,25 @@
import { describe, expect, it } from 'bun:test'
import {
CLAUDE_CONVERSATION_HISTORY,
markUnsupported,
toConversationHistoryCapabilities
} from './conversationHistory'
describe('conversationHistory capabilities', () => {
it('only exposes supported flags', () => {
expect(toConversationHistoryCapabilities(CLAUDE_CONVERSATION_HISTORY)).toEqual({
forkCurrent: true
})
})
it('keeps unsupported sticky', () => {
const next = markUnsupported(
{ forkCurrent: 'supported', forkAtMessage: 'supported', rewindToMessage: 'supported' },
'rewindToMessage'
)
expect(toConversationHistoryCapabilities(next)).toEqual({
forkCurrent: true,
forkAtMessage: true
})
})
})
+64
View File
@@ -0,0 +1,64 @@
export type CapabilityState = 'unknown' | 'supported' | 'unsupported'
export type ConversationHistoryCapabilityStates = {
forkCurrent: CapabilityState
forkAtMessage: CapabilityState
rewindToMessage: CapabilityState
}
export type ConversationHistoryCapabilities = {
forkCurrent?: boolean
forkAtMessage?: boolean
rewindToMessage?: boolean
}
/** Only `supported` becomes true in session metadata; never optimistic. */
export function toConversationHistoryCapabilities(
states: ConversationHistoryCapabilityStates
): ConversationHistoryCapabilities | undefined {
const capabilities: ConversationHistoryCapabilities = {}
if (states.forkCurrent === 'supported') capabilities.forkCurrent = true
if (states.forkAtMessage === 'supported') capabilities.forkAtMessage = true
if (states.rewindToMessage === 'supported') capabilities.rewindToMessage = true
return Object.keys(capabilities).length > 0 ? capabilities : undefined
}
export function markUnsupported(
states: ConversationHistoryCapabilityStates,
key: keyof ConversationHistoryCapabilityStates
): ConversationHistoryCapabilityStates {
if (states[key] === 'unsupported') return states
return { ...states, [key]: 'unsupported' }
}
export function markSupported(
states: ConversationHistoryCapabilityStates,
key: keyof ConversationHistoryCapabilityStates
): ConversationHistoryCapabilityStates {
if (states[key] === 'unsupported') return states
return { ...states, [key]: 'supported' }
}
export const UNSUPPORTED_CONVERSATION_HISTORY: ConversationHistoryCapabilityStates = {
forkCurrent: 'unsupported',
forkAtMessage: 'unsupported',
rewindToMessage: 'unsupported'
}
export const CLAUDE_CONVERSATION_HISTORY: ConversationHistoryCapabilityStates = {
forkCurrent: 'supported',
forkAtMessage: 'unsupported',
rewindToMessage: 'unsupported'
}
export const CODEX_CONVERSATION_HISTORY_INITIAL: ConversationHistoryCapabilityStates = {
forkCurrent: 'unknown',
forkAtMessage: 'unknown',
rewindToMessage: 'unknown'
}
export const GROK_CONVERSATION_HISTORY_INITIAL: ConversationHistoryCapabilityStates = {
forkCurrent: 'unknown',
forkAtMessage: 'unknown',
rewindToMessage: 'unknown'
}
+1
View File
@@ -3,6 +3,7 @@ export * from './apiTypes'
export * from './cursorCliSku'
export * from './messages'
export * from './buildInfo'
export * from './conversationHistory'
export * from './effort'
export * from './flavors'
export * from './models'
+3 -1
View File
@@ -37,7 +37,9 @@ export const RPC_METHODS = {
ListGrokModelsForCwd: 'listGrokModelsForCwd',
ListGrokModels: 'listGrokModels',
ListGrokReasoningEffortOptions: 'listGrokReasoningEffortOptions',
ListOpencodeReasoningEffortOptions: 'listOpencodeReasoningEffortOptions'
ListOpencodeReasoningEffortOptions: 'listOpencodeReasoningEffortOptions',
ForkConversation: 'fork-conversation',
RewindConversation: 'rewind-conversation',
} as const
export type RpcMethod = typeof RPC_METHODS[keyof typeof RPC_METHODS]
+23 -2
View File
@@ -11,10 +11,19 @@ const MetadataSummarySchema = z.object({
updatedAt: z.number()
})
const SessionCapabilitiesSchema = z.object({
terminal: z.boolean().optional()
const ConversationHistoryCapabilitiesSchema = z.object({
forkCurrent: z.boolean().optional(),
forkAtMessage: z.boolean().optional(),
rewindToMessage: z.boolean().optional()
})
const SessionCapabilitiesSchema = z.object({
terminal: z.boolean().optional(),
conversationHistory: ConversationHistoryCapabilitiesSchema.optional()
})
export type ConversationHistoryCapabilities = z.infer<typeof ConversationHistoryCapabilitiesSchema>
export const WorktreeMetadataSchema = z.object({
basePath: z.string(),
branch: z.string(),
@@ -34,6 +43,10 @@ export const MetadataSchema = z.object({
summary: MetadataSummarySchema.optional(),
machineId: z.string().optional(),
claudeSessionId: z.string().optional(),
// Parent HAPI session id when this session was created by message-level fork
// (`claude --resume <id> --fork-session`). Lets the web list mark the new
// session as a branch of `<id>` instead of an unrelated duplicate.
forkedFrom: z.string().optional(),
codexSessionId: z.string().optional(),
// 原始 Codex thread id。导入 Codex 历史后,HAPI 会 fork 出自己的续写 thread
// codexSessionId 保存 fork 后的 threadcodexSourceSessionId 保留来源 thread 便于同步/展示。
@@ -81,6 +94,14 @@ export const MetadataSchema = z.object({
preferredPermissionMode: PermissionModeSchema.optional(),
flavor: z.string().nullish(),
capabilities: SessionCapabilitiesSchema.optional(),
conversationHistoryPoints: z.record(z.string(), z.literal(true)).optional(),
// Native locators for historical fork/rewind (e.g. Grok prompt indexes).
// Kept separately from the boolean UI markers above.
conversationHistoryIndexes: z.record(z.string(), z.number().int().nonnegative()).optional(),
// Codex localId → turnId mapping (durable across runner relaunches).
conversationHistoryTurns: z.record(z.string(), z.string().min(1)).optional(),
// Set when native rewind succeeded but HAPI truncate/hydrate failed.
conversationHistoryDiverged: z.boolean().optional(),
worktree: WorktreeMetadataSchema.optional(),
// Cached Pi model list — written by CLI, read by web (inactive session fallback).
// Minimal shape: each entry must have modelId; other fields (provider, name, etc.) pass through.