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
+143
View File
@@ -0,0 +1,143 @@
import { describe, expect, it, vi } from 'vitest'
import { CodexConversationHistory } from './conversationHistory'
function createClient(overrides?: {
fork?: (params: Record<string, unknown>) => Promise<{ thread: { id: string } }>
rollback?: (params: { threadId: string; numTurns: number }) => Promise<unknown>
read?: () => Promise<{ thread: { id: string; turns: Array<Record<string, unknown>> } }>
}) {
return {
supportsMethod: async () => true,
forkThread: overrides?.fork ?? (async () => ({ thread: { id: 'forked-1' } })),
rollbackThread: overrides?.rollback ?? (async () => ({ thread: { id: 'thread-1' } })),
readThread: overrides?.read ?? (async () => ({
thread: {
id: 'thread-1',
turns: [
{ id: 'turn-a', items: [{ type: 'userMessage', clientId: 'local-a' }] },
{ id: 'turn-b', items: [{ type: 'userMessage', clientId: 'local-b' }] },
{ id: 'turn-c', items: [{ type: 'userMessage', clientId: 'local-c' }] }
]
}
}))
}
}
describe('CodexConversationHistory', () => {
it('only publishes methods confirmed by the app server', async () => {
const supportsMethod = vi.fn(async (method: string) => method === 'thread/fork')
const history = new CodexConversationHistory(() => ({
...createClient(),
supportsMethod
}) as never)
history.setThreadId('thread-1')
await history.probeCapabilities()
expect(history.getCapabilitiesForMetadata()?.conversationHistory).toEqual({
forkCurrent: true,
forkAtMessage: true
})
})
it('forks current without a turn boundary', async () => {
const fork = vi.fn(async (params: Record<string, unknown>) => {
expect(params.beforeTurnId).toBeUndefined()
return { thread: { id: 'forked-current' } }
})
const history = new CodexConversationHistory(() => createClient({ fork }) as never)
history.setThreadId('thread-1')
const result = await history.fork()
expect(result).toEqual({ nativeSessionId: 'forked-current' })
expect(fork).toHaveBeenCalledTimes(1)
})
it('historical fork passes lastTurnId of the previous turn', async () => {
const fork = vi.fn(async (params: Record<string, unknown>) => {
expect(params.lastTurnId).toBe('turn-a')
expect(params.beforeTurnId).toBeUndefined()
return { thread: { id: 'forked-hist' } }
})
const history = new CodexConversationHistory(() => createClient({ fork }) as never)
history.setThreadId('thread-1')
const result = await history.fork('local-b')
expect(result.nativeSessionId).toBe('forked-hist')
})
it('historical fork of the first turn uses beforeTurnId', async () => {
const fork = vi.fn(async (params: Record<string, unknown>) => {
expect(params.beforeTurnId).toBe('turn-a')
expect(params.lastTurnId).toBeUndefined()
return { thread: { id: 'forked-first' } }
})
const history = new CodexConversationHistory(() => createClient({ fork }) as never)
history.setThreadId('thread-1')
const result = await history.fork('local-a')
expect(result.nativeSessionId).toBe('forked-first')
})
it('computes rewind numTurns from selected turn', async () => {
const rollback = vi.fn(async (params: { threadId: string; numTurns: number }) => {
expect(params).toEqual({ threadId: 'thread-1', numTurns: 2 })
return { thread: { id: 'thread-1' } }
})
const history = new CodexConversationHistory(() => createClient({ rollback }) as never)
history.setThreadId('thread-1')
const result = await history.rewind('local-b')
expect(result).toEqual({
success: true,
truncateFromLocalId: 'local-b',
messages: []
})
expect(rollback).toHaveBeenCalledTimes(1)
})
it('marks rewind unsupported on method-not-found without affecting fork', async () => {
const rollback = vi.fn(async () => {
throw new Error('thread/rollback is unsupported')
})
const fork = vi.fn(async () => ({ thread: { id: 'forked-ok' } }))
const history = new CodexConversationHistory(() => createClient({ rollback, fork }) as never)
history.setThreadId('thread-1')
await expect(history.rewind('local-a')).rejects.toThrow(/unsupported/)
const caps = history.getCapabilitiesForMetadata()?.conversationHistory
expect(caps?.rewindToMessage).toBeUndefined()
const forked = await history.fork()
expect(forked.nativeSessionId).toBe('forked-ok')
})
it('does not call native fork when selected turn is missing', async () => {
const fork = vi.fn(async () => ({ thread: { id: 'x' } }))
const history = new CodexConversationHistory(() => createClient({
fork,
read: async () => ({ thread: { id: 'thread-1', turns: [] } })
}) as never)
history.setThreadId('thread-1')
await expect(history.fork('missing-local')).rejects.toThrow(/No native history point/)
expect(fork).not.toHaveBeenCalled()
})
it('restores durable localId→turnId locators across relaunches', async () => {
const fork = vi.fn(async (params: Record<string, unknown>) => {
expect(params.lastTurnId).toBe('turn-a')
expect(params.beforeTurnId).toBeUndefined()
return { thread: { id: 'forked-restored' } }
})
const history = new CodexConversationHistory(() => createClient({
fork,
// Simulate a relaunch where thread/read no longer exposes clientIds.
read: async () => ({
thread: {
id: 'thread-1',
turns: [
{ id: 'turn-a', items: [] },
{ id: 'turn-b', items: [] }
]
}
})
}) as never)
history.setThreadId('thread-1')
history.restoreTurns({ 'local-b': 'turn-b' })
const result = await history.fork('local-b')
expect(result.nativeSessionId).toBe('forked-restored')
expect(history.getTurns()['local-b']).toBe('turn-b')
})
})