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
+99 -1
View File
@@ -20,6 +20,8 @@ import {
import { GrokPermissionHandler } from './utils/permissionHandler'
import { RPC_METHODS } from '@hapi/protocol/rpcMethods'
import { GROK_TITLE_INSTRUCTION } from './utils/systemPrompt'
import { GrokConversationHistory } from './conversationHistory'
import { isObject } from '@hapi/protocol'
const PLAN_MODE_INSTRUCTION =
'Work in plan-only mode. Analyze and propose a plan, but do not execute commands or modify files.'
@@ -46,6 +48,7 @@ class GrokRemoteLauncher extends RemoteLauncherBase {
private defaultBackendEffort: string | null = null
private currentBackendPermissionMode: 'default' | 'auto' | null = null
private instructionsSent = false
private readonly conversationHistory = new GrokConversationHistory(() => this.backend)
constructor(
private readonly session: GrokSession,
@@ -102,6 +105,9 @@ class GrokRemoteLauncher extends RemoteLauncherBase {
await backend.initialize()
const acpMcpServers = toAcpMcpServers(mcpServers)
// Fork children must load the exact native id hub forked. Falling back to
// newSession() would leave hydrated HAPI history without matching model context.
const strictForkResume = session.client.getMetadata()?.forkedFrom != null
let acpSessionId: string
try {
if (session.sessionId) {
@@ -112,6 +118,9 @@ class GrokRemoteLauncher extends RemoteLauncherBase {
mcpServers: acpMcpServers
})
} catch (error) {
if (strictForkResume) {
throw error
}
logger.warn('[grok-remote] resume failed, starting new session', error)
session.sendSessionEvent({
type: 'message',
@@ -135,6 +144,53 @@ class GrokRemoteLauncher extends RemoteLauncherBase {
}
session.registerExistingNativeSession(acpSessionId)
this.conversationHistory.setSession(acpSessionId, session.path)
this.conversationHistory.setPublishCapabilities(async () => {
const conversationHistory = this.conversationHistory.getCapabilitiesForMetadata()?.conversationHistory
try {
session.client.updateMetadata((metadata) => {
const capabilities = { ...metadata?.capabilities }
delete capabilities.conversationHistory
if (conversationHistory) {
capabilities.conversationHistory = conversationHistory
}
return {
...metadata,
path: metadata?.path ?? session.path,
host: metadata?.host ?? 'unknown',
capabilities,
conversationHistoryPoints: {
...metadata?.conversationHistoryPoints,
...this.conversationHistory.getHistoryPoints()
},
conversationHistoryIndexes: {
...metadata?.conversationHistoryIndexes,
...this.conversationHistory.getHistoryIndexes()
}
}
})
} catch {
// best-effort; tests and transient hub disconnects must not crash the loop
}
})
this.conversationHistory.restorePromptIndexes(
typeof session.client.getMetadata === 'function'
? session.client.getMetadata()?.conversationHistoryIndexes
: undefined
)
session.client.rpcHandlerManager.registerHandler(RPC_METHODS.ForkConversation, async (payload: unknown) => {
const messageLocalId = isObject(payload) && typeof payload.messageLocalId === 'string'
? payload.messageLocalId
: undefined
return await this.conversationHistory.fork(messageLocalId)
})
session.client.rpcHandlerManager.registerHandler(RPC_METHODS.RewindConversation, async (payload: unknown) => {
if (!isObject(payload) || typeof payload.messageLocalId !== 'string') {
throw new Error('messageLocalId is required')
}
return await this.conversationHistory.rewind(payload.messageLocalId)
})
void this.conversationHistory.probeCapabilities().catch(() => {})
const modelMetadata = backend.getSessionModelsMetadata(acpSessionId)
const effortMetadata = backend.getThoughtLevelConfigOption(acpSessionId)
this.currentBackendModel = modelMetadata?.currentModelId ?? this.opts.model ?? null
@@ -186,6 +242,12 @@ class GrokRemoteLauncher extends RemoteLauncherBase {
break
}
// collectBatch already emitted messages-consumed; hub idle checks
// see an empty queue. Hold the history busy flag across the whole
// turn setup (model/permission sync, rewind-points, prompt).
this.conversationHistory.setBusy(true)
session.onThinkingChange(true)
try {
const requestedModel = batch.mode.model === null
? this.defaultBackendModel
: batch.mode.model
@@ -248,18 +310,54 @@ class GrokRemoteLauncher extends RemoteLauncherBase {
this.instructionsSent = true
}
const promptContent: PromptContent[] = [{ type: 'text', text }]
const localId = batch.items
?.map((item) => item.localId)
.find((id): id is string => typeof id === 'string' && id.length > 0)
// Official prompt index: count rewind points before the prompt; the new
// point lands at that index after a successful turn.
let nextPromptIndex: number | null = null
try {
const points = await backend.sendExtensionRequest<{ points?: unknown[] } | unknown[]>(
'_x.ai/rewind/points',
{ sessionId: acpSessionId }
)
const list = Array.isArray(points)
? points
: (isObject(points) && Array.isArray(points.points) ? points.points : null)
if (list) nextPromptIndex = list.length
} catch {
nextPromptIndex = null
}
session.onThinkingChange(true)
try {
await backend.prompt(acpSessionId, promptContent, (message: AgentMessage) => {
this.handleAgentMessage(message)
})
if (localId && nextPromptIndex != null) {
this.conversationHistory.rememberPromptIndex(localId, nextPromptIndex)
session.client.updateMetadata((metadata) => ({
...metadata,
path: metadata?.path ?? session.path,
host: metadata?.host ?? 'unknown',
conversationHistoryPoints: {
...metadata?.conversationHistoryPoints,
[localId]: true as const
},
conversationHistoryIndexes: {
...metadata?.conversationHistoryIndexes,
[localId]: nextPromptIndex
}
}))
}
} catch (error) {
const message = formatGrokError(error)
logger.warn('[grok-remote] prompt failed', error)
session.sendSessionEvent({ type: 'message', message: `Grok prompt failed: ${message}` })
this.messageBuffer.addMessage(`Grok prompt failed: ${message}`, 'status')
}
} finally {
this.conversationHistory.setBusy(false)
session.onThinkingChange(false)
await this.permissionHandler?.cancelAll('Prompt finished')
if (session.queue.size() === 0 && !this.shouldExit) {