Files
hapi/cli/src/grok/grokRemoteLauncher.test.ts
T
3c3bffdfbd 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>
2026-08-03 09:28:01 +08:00

248 lines
10 KiB
TypeScript

import { afterEach, describe, expect, it, vi } from 'vitest'
import { MessageQueue2 } from '@/utils/MessageQueue2'
import type { GrokMode } from './types'
const harness = vi.hoisted(() => ({
setModels: [] as Array<{ sessionId: string; modelId: string; flavor?: string }>,
setModes: [] as Array<{ sessionId: string; modeId: string }>,
prompts: [] as unknown[][],
autoCommandAvailable: true,
stderrHandler: null as null | ((error: { message: string; raw: string }) => void),
sessionInfoUpdateHandler: null as null | ((update: { title?: string | null }) => void),
nativeTitle: null as string | null,
nativeTitleSent: false,
loadSessionCalls: [] as string[],
loadSessionError: null as Error | null,
newSessionCalls: 0,
}))
vi.mock('./utils/grokBackend', () => ({
createGrokBackend: vi.fn(() => ({
initialize: vi.fn(async () => {}),
newSession: vi.fn(async () => {
harness.newSessionCalls += 1
return 'grok-new-session'
}),
loadSession: vi.fn(async (params: { sessionId: string }) => {
harness.loadSessionCalls.push(params.sessionId)
if (harness.loadSessionError) {
throw harness.loadSessionError
}
return params.sessionId
}),
setModel: vi.fn(async (sessionId: string, modelId: string, opts?: { flavor?: string }) => {
harness.setModels.push({ sessionId, modelId, flavor: opts?.flavor })
}),
setMode: vi.fn(async (sessionId: string, modeId: string) => {
harness.setModes.push({ sessionId, modeId })
}),
prompt: vi.fn(async (_sessionId: string, content: unknown[]) => {
harness.prompts.push(content)
if (harness.nativeTitle !== null && !harness.nativeTitleSent) {
harness.nativeTitleSent = true
harness.sessionInfoUpdateHandler?.({ title: harness.nativeTitle })
}
if (harness.prompts.length === 1) {
harness.stderrHandler?.({
message: 'status=402 Payment Required model_id=grok-build spending-limit',
raw: 'status=402 Payment Required model_id=grok-build spending-limit'
})
}
}),
cancelPrompt: vi.fn(async () => {}),
respondToPermission: vi.fn(async () => {}),
onStderrError: vi.fn((handler) => { harness.stderrHandler = handler }),
setSessionInfoUpdateListener: vi.fn((handler) => { harness.sessionInfoUpdateHandler = handler }),
onPermissionRequest: vi.fn(),
disconnect: vi.fn(async () => {}),
getSessionModelsMetadata: vi.fn(() => ({
availableModels: [{ modelId: 'grok-a' }, { modelId: 'grok-b' }],
currentModelId: 'grok-a'
})),
getThoughtLevelConfigOption: vi.fn(() => ({
id: 'x.ai/reasoning-effort',
currentValue: 'low',
options: [{ value: 'low' }, { value: 'medium' }, { value: 'high' }]
})),
hasAvailableCommand: vi.fn((_sessionId: string, command: string) => (
command === 'auto' && harness.autoCommandAvailable
))
})),
formatGrokError: (error: unknown) => error instanceof Error ? error.message : String(error),
isGrokBuildAuxiliaryQuotaError: (value: string, activeModel?: string | null) => (
activeModel !== 'grok-build'
&& value.includes('402 Payment Required')
&& value.includes('model_id=grok-build')
)
}))
vi.mock('@/codex/utils/buildHapiMcpBridge', () => ({
buildHapiMcpBridge: async () => ({ server: { stop: () => {} }, mcpServers: {} })
}))
vi.mock('./utils/permissionHandler', () => ({
GrokPermissionHandler: class { async cancelAll(): Promise<void> {} }
}))
vi.mock('@/ui/ink/GrokDisplay', () => ({ GrokDisplay: () => null }))
vi.mock('@/ui/logger', () => ({
logger: { debug: vi.fn(), warn: vi.fn(), info: vi.fn() }
}))
import { grokRemoteLauncher } from './grokRemoteLauncher'
function createSession() {
const queue = new MessageQueue2<GrokMode>((mode) => JSON.stringify(mode))
queue.pushIsolateAndClear('first', { permissionMode: 'default', model: 'grok-a', effort: 'low' })
queue.push('second', { permissionMode: 'default', model: 'grok-b', effort: 'medium' })
queue.close()
const rpcHandlers = new Map<string, () => unknown>()
const session = {
path: '/tmp/grok-test',
logPath: '/tmp/grok-test/test.log',
client: {
rpcHandlerManager: {
registerHandler(method: string, handler: () => unknown) { rpcHandlers.set(method, handler) }
},
updateMetadata: vi.fn(),
getMetadata: vi.fn(() => null),
sendAgentMessage: vi.fn(),
sendSessionEvent: vi.fn(),
sendClaudeSessionMessage: vi.fn()
},
queue,
sessionId: null as string | null,
thinking: false,
getPermissionMode: () => 'default' as const,
registerExistingNativeSession(id: string) { session.sessionId = id },
setModel: vi.fn(),
setEffort: vi.fn(),
setPermissionMode: vi.fn(),
pushKeepAlive: vi.fn(),
onThinkingChange(thinking: boolean) { session.thinking = thinking },
sendAgentMessage: vi.fn(),
sendSessionEvent: vi.fn()
}
return { session, rpcHandlers }
}
function createPermissionSession(modes: GrokMode['permissionMode'][]) {
const { session, rpcHandlers } = createSession()
session.queue.reset()
modes.forEach((permissionMode, index) => {
session.queue.push(`permission-${index + 1}`, {
permissionMode,
model: 'grok-a',
effort: 'low'
})
})
session.queue.close()
return { session, rpcHandlers }
}
describe('grokRemoteLauncher runtime config', () => {
afterEach(() => {
harness.setModels = []
harness.setModes = []
harness.prompts = []
harness.stderrHandler = null
harness.sessionInfoUpdateHandler = null
harness.nativeTitle = null
harness.nativeTitleSent = false
harness.autoCommandAvailable = true
harness.loadSessionCalls = []
harness.loadSessionError = null
harness.newSessionCalls = 0
})
it('switches model and effort between turns and exposes session catalogs', async () => {
const { session, rpcHandlers } = createSession()
const discovered: unknown[] = []
await grokRemoteLauncher(session as never, {
model: 'grok-a',
effort: 'low',
onConfigDiscovered: (config) => discovered.push(config)
})
expect(discovered).toEqual([{ model: 'grok-a', effort: 'low' }])
expect(harness.setModels).toEqual([
{ sessionId: 'grok-new-session', modelId: 'grok-b', flavor: 'grok' }
])
expect(harness.setModes).toEqual([
{ sessionId: 'grok-new-session', modeId: 'medium' }
])
expect(harness.prompts).toHaveLength(3)
expect(session.sendSessionEvent).not.toHaveBeenCalledWith(expect.objectContaining({
message: expect.stringContaining('402 Payment Required')
}))
expect(JSON.stringify(harness.prompts[0])).toContain('/always-approve off')
expect(JSON.stringify(harness.prompts[1])).toContain('hapi_change_title')
expect(JSON.stringify(harness.prompts[1])).toContain('$name')
expect(JSON.stringify(harness.prompts[1])).toContain('skill_lookup')
expect(JSON.stringify(harness.prompts[2])).not.toContain('hapi_change_title')
expect(JSON.stringify(harness.prompts[2])).not.toContain('skill_lookup')
expect(await rpcHandlers.get('listGrokModels')?.()).toMatchObject({ success: true, currentModelId: 'grok-a' })
expect(await rpcHandlers.get('listGrokReasoningEffortOptions')?.()).toMatchObject({ success: true, currentValue: 'low' })
})
it('does not fall back to newSession when a fork child cannot load its native id', async () => {
const { session } = createSession()
session.sessionId = 'grok-forked-native'
vi.mocked(session.client.getMetadata).mockReturnValue({ forkedFrom: 'parent-session' } as never)
harness.loadSessionError = new Error('session/load rejected')
await expect(grokRemoteLauncher(session as never, {
model: 'grok-a',
effort: 'low'
})).rejects.toThrow(/session\/load rejected/)
expect(harness.loadSessionCalls).toEqual(['grok-forked-native'])
expect(harness.newSessionCalls).toBe(0)
})
it('uses Grok slash commands to enter and leave Auto permission mode without model turns', async () => {
const { session } = createPermissionSession(['auto', 'default'])
await grokRemoteLauncher(session as never, { model: 'grok-a', effort: 'low' })
expect(harness.prompts.map((prompt) => JSON.stringify(prompt))).toEqual([
expect.stringContaining('/auto'),
expect.stringContaining('permission-1'),
expect.stringContaining('/always-approve off'),
expect.stringContaining('permission-2')
])
})
it('forwards ACP native titles while retaining the prompt fallback', async () => {
harness.nativeTitle = 'Native Grok title'
const { session } = createSession()
await grokRemoteLauncher(session as never, { model: 'grok-a', effort: 'low' })
expect(session.client.sendClaudeSessionMessage).toHaveBeenCalledWith({
type: 'summary',
summary: 'Native Grok title',
leafUuid: expect.any(String)
})
expect(JSON.stringify(harness.prompts[1])).toContain('hapi_change_title')
})
it('rolls Auto back to Default when Grok does not advertise the feature', async () => {
harness.autoCommandAvailable = false
const { session } = createPermissionSession(['auto'])
const rollbacks: string[] = []
await grokRemoteLauncher(session as never, {
model: 'grok-a',
effort: 'low',
onPermissionModeRollback: (mode) => rollbacks.push(mode)
})
expect(rollbacks).toEqual(['default'])
expect(harness.prompts).toHaveLength(2)
expect(JSON.stringify(harness.prompts[0])).toContain('/always-approve off')
expect(session.sendSessionEvent).toHaveBeenCalledWith(expect.objectContaining({
message: expect.stringContaining('not enabled')
}))
})
})