mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-25 05:07:05 +00:00
feat(codex): import and resume sessions from runners (#1088)
* fix codex import resume flow * fix hub restart session active state * fix codex transcript workspace scoping * Address Codex import review findings * Fix Codex import machine selection * Update Codex sessions error test * Address Codex import review findings * Preserve forked Codex session id on sync * Make Codex duplicate cleanup source-aware * Handle Codex archive failures * Limit existing session flag to Codex * Preserve Codex import machine binding * fix: rebase runner Codex import onto current main * fix: preserve runner-scoped Codex import behavior --------- Co-authored-by: syy <815728149@qq.com>
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { mkdtempSync, rmSync, mkdirSync, realpathSync } from 'node:fs'
|
||||
import { existsSync, mkdtempSync, rmSync, mkdirSync, realpathSync, writeFileSync } from 'node:fs'
|
||||
import { homedir, tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
|
||||
@@ -92,6 +92,35 @@ async function callCursorChatStoreStatus(
|
||||
return JSON.parse(raw) as unknown
|
||||
}
|
||||
|
||||
async function callListCodexSessions(client: ApiMachineClient, machineId: string, params: { cwd?: string | null; sessionIds?: string[] }): Promise<unknown> {
|
||||
const manager = (client as unknown as { rpcHandlerManager: { handleRequest: (req: { method: string; params: string }) => Promise<string> } }).rpcHandlerManager
|
||||
const raw = await manager.handleRequest({
|
||||
method: `${machineId}:listCodexSessions`,
|
||||
params: JSON.stringify(params)
|
||||
})
|
||||
return JSON.parse(raw) as unknown
|
||||
}
|
||||
|
||||
async function callArchiveCodexSession(client: ApiMachineClient, machineId: string, sessionId: string): Promise<unknown> {
|
||||
const manager = (client as unknown as { rpcHandlerManager: { handleRequest: (req: { method: string; params: string }) => Promise<string> } }).rpcHandlerManager
|
||||
const raw = await manager.handleRequest({
|
||||
method: `${machineId}:archiveCodexSession`,
|
||||
params: JSON.stringify({ sessionId })
|
||||
})
|
||||
return JSON.parse(raw) as unknown
|
||||
}
|
||||
|
||||
function writeCodexTranscript(codexHome: string, fileName: string, payload: Record<string, unknown>, userText: string): string {
|
||||
const sessionDir = join(codexHome, 'sessions', '2026', '06', '29')
|
||||
mkdirSync(sessionDir, { recursive: true })
|
||||
const file = join(sessionDir, fileName)
|
||||
writeFileSync(file, [
|
||||
JSON.stringify({ type: 'session_meta', payload }),
|
||||
JSON.stringify({ type: 'response_item', payload: { type: 'message', role: 'user', content: [{ type: 'input_text', text: userText }] } })
|
||||
].join('\n'))
|
||||
return file
|
||||
}
|
||||
|
||||
describe('ApiMachineClient cursor-chat-store-status handler', () => {
|
||||
beforeEach(() => {
|
||||
inspectCursorChatStoreMock.mockReset()
|
||||
@@ -300,6 +329,100 @@ describe('ApiMachineClient listGrokModelsForCwd handler', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('ApiMachineClient Codex transcript handlers', () => {
|
||||
const originalCodexHome = process.env.CODEX_HOME
|
||||
let workspaceRoot: string
|
||||
let outsideRoot: string
|
||||
let codexHome: string
|
||||
|
||||
beforeEach(() => {
|
||||
ioMock.mockReset()
|
||||
listOpencodeModelsForCwdMock.mockReset()
|
||||
workspaceRoot = mkdtempSync(join(tmpdir(), 'hapi-codex-allowed-'))
|
||||
outsideRoot = mkdtempSync(join(tmpdir(), 'hapi-codex-outside-'))
|
||||
codexHome = mkdtempSync(join(tmpdir(), 'hapi-codex-home-'))
|
||||
process.env.CODEX_HOME = codexHome
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
if (originalCodexHome === undefined) delete process.env.CODEX_HOME
|
||||
else process.env.CODEX_HOME = originalCodexHome
|
||||
rmSync(workspaceRoot, { recursive: true, force: true })
|
||||
rmSync(outsideRoot, { recursive: true, force: true })
|
||||
rmSync(codexHome, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
it('filters listed Codex sessions to workspace roots', async () => {
|
||||
writeCodexTranscript(codexHome, 'allowed.jsonl', {
|
||||
id: 'allowed-session-id',
|
||||
cwd: workspaceRoot
|
||||
}, 'allowed prompt')
|
||||
writeCodexTranscript(codexHome, 'outside.jsonl', {
|
||||
id: 'outside-session-id',
|
||||
cwd: outsideRoot
|
||||
}, 'outside prompt')
|
||||
|
||||
const machine = makeMachine('codex-machine-1')
|
||||
const client = new ApiMachineClient('cli-token', machine, [workspaceRoot])
|
||||
|
||||
try {
|
||||
const result = await callListCodexSessions(client, machine.id, {})
|
||||
|
||||
expect(result).toMatchObject({ success: true })
|
||||
const sessions = (result as { sessions: Array<{ id: string }> }).sessions
|
||||
expect(sessions.map((session) => session.id)).toEqual(['allowed-session-id'])
|
||||
} finally {
|
||||
client.shutdown()
|
||||
}
|
||||
})
|
||||
|
||||
it('filters import-by-sessionId Codex sessions to workspace roots before returning message bodies', async () => {
|
||||
writeCodexTranscript(codexHome, 'allowed.jsonl', {
|
||||
id: 'allowed-session-id',
|
||||
cwd: workspaceRoot
|
||||
}, 'allowed prompt')
|
||||
writeCodexTranscript(codexHome, 'outside.jsonl', {
|
||||
id: 'outside-session-id',
|
||||
cwd: outsideRoot
|
||||
}, 'outside prompt')
|
||||
|
||||
const machine = makeMachine('codex-machine-2')
|
||||
const client = new ApiMachineClient('cli-token', machine, [workspaceRoot])
|
||||
|
||||
try {
|
||||
const result = await callListCodexSessions(client, machine.id, {
|
||||
sessionIds: ['allowed-session-id', 'outside-session-id']
|
||||
})
|
||||
|
||||
expect(result).toMatchObject({ success: true })
|
||||
const sessions = (result as { sessions: Array<{ id: string; messages?: unknown[] }> }).sessions
|
||||
expect(sessions.map((session) => session.id)).toEqual(['allowed-session-id'])
|
||||
expect(sessions[0]?.messages).toHaveLength(1)
|
||||
} finally {
|
||||
client.shutdown()
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects archive for Codex sessions outside workspace roots', async () => {
|
||||
const outsideFile = writeCodexTranscript(codexHome, 'outside.jsonl', {
|
||||
id: 'outside-session-id',
|
||||
cwd: outsideRoot
|
||||
}, 'outside prompt')
|
||||
|
||||
const machine = makeMachine('codex-machine-3')
|
||||
const client = new ApiMachineClient('cli-token', machine, [workspaceRoot])
|
||||
|
||||
try {
|
||||
const result = await callArchiveCodexSession(client, machine.id, 'outside-session-id')
|
||||
|
||||
expect(result).toEqual({ success: false, error: 'Codex session is outside workspace roots' })
|
||||
expect(existsSync(outsideFile)).toBe(true)
|
||||
} finally {
|
||||
client.shutdown()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('ApiMachineClient keepAlive lifecycle', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
|
||||
@@ -9,7 +9,15 @@ import { basename, dirname, isAbsolute, join, relative, resolve as resolvePath }
|
||||
import { logger } from '@/ui/logger'
|
||||
import { configuration } from '@/configuration'
|
||||
import type { ClientToServerEvents, ServerToClientEvents, Update, UpdateMachineBody } from '@hapi/protocol'
|
||||
import type { MachineDirectoryEntry, MachineListDirectoryResponse, PathExistsResponse } from '@hapi/protocol/apiTypes'
|
||||
import {
|
||||
ArchiveCodexSessionRpcRequestSchema,
|
||||
ListCodexSessionsRpcRequestSchema,
|
||||
type ArchiveCodexSessionRpcResponse,
|
||||
type ListCodexSessionsRpcResponse,
|
||||
type MachineDirectoryEntry,
|
||||
type MachineListDirectoryResponse,
|
||||
type PathExistsResponse
|
||||
} from '@hapi/protocol/apiTypes'
|
||||
import { RPC_METHODS } from '@hapi/protocol/rpcMethods'
|
||||
import type { RunnerState, Machine, MachineMetadata } from './types'
|
||||
import { RunnerStateSchema, MachineMetadataSchema } from './types'
|
||||
@@ -29,6 +37,7 @@ import {
|
||||
} from '../modules/common/grokModels'
|
||||
import type { SpawnSessionOptions, SpawnSessionResult } from '../modules/common/rpcTypes'
|
||||
import { applyVersionedAck } from './versionedUpdate'
|
||||
import { archiveLocalCodexSession, listLocalCodexSessionSummaries, listLocalCodexSessionsWithMessagesByIds } from '../modules/common/codexSessions'
|
||||
import { buildSocketIoExtraHeaderOptions } from './hubExtraHeaders'
|
||||
import { collectMachineHealth } from '@/utils/machineHealth'
|
||||
import { inspectCursorChatStore } from '@/cursor/cursorChatStoreStatus'
|
||||
@@ -257,6 +266,54 @@ export class ApiMachineClient {
|
||||
return await listGrokModelsForCwd(resolvedCwd)
|
||||
}
|
||||
)
|
||||
|
||||
this.rpcHandlerManager.registerHandler<unknown, ListCodexSessionsRpcResponse>(
|
||||
RPC_METHODS.ListCodexSessions,
|
||||
async (params) => {
|
||||
const parsed = ListCodexSessionsRpcRequestSchema.safeParse(params)
|
||||
if (!parsed.success) return { success: false, error: 'Invalid Codex sessions request' }
|
||||
const rawCwd = typeof parsed.data.cwd === 'string' ? parsed.data.cwd.trim() : ''
|
||||
if (rawCwd) {
|
||||
const resolvedCwd = await this.resolveForWorkspaceCheck(rawCwd)
|
||||
if (!this.isWithinWorkspaceRoots(resolvedCwd)) {
|
||||
return { success: false, error: 'Path is outside workspace roots' }
|
||||
}
|
||||
}
|
||||
const requestedIds = parsed.data.sessionIds
|
||||
? new Set(parsed.data.sessionIds)
|
||||
: null
|
||||
const allSessions = requestedIds
|
||||
? listLocalCodexSessionsWithMessagesByIds(requestedIds)
|
||||
: listLocalCodexSessionSummaries()
|
||||
const sessions = []
|
||||
for (const session of allSessions) {
|
||||
if (await this.isCodexSessionWithinWorkspaceRoots(session)) {
|
||||
sessions.push(session)
|
||||
}
|
||||
}
|
||||
return { success: true, sessions }
|
||||
}
|
||||
)
|
||||
|
||||
this.rpcHandlerManager.registerHandler<unknown, ArchiveCodexSessionRpcResponse>(
|
||||
RPC_METHODS.ArchiveCodexSession,
|
||||
async (params) => {
|
||||
const parsed = ArchiveCodexSessionRpcRequestSchema.safeParse(params)
|
||||
if (!parsed.success) return { success: false, error: 'Invalid Codex archive request' }
|
||||
const sessionId = parsed.data.sessionId.trim()
|
||||
return await archiveLocalCodexSession(sessionId, {
|
||||
canArchive: (session) => this.isCodexSessionWithinWorkspaceRoots(session)
|
||||
})
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
private async isCodexSessionWithinWorkspaceRoots(session: { cwd?: string | null }): Promise<boolean> {
|
||||
if (!this.normalizedWorkspaceRoots?.length) return true
|
||||
const cwd = session.cwd?.trim()
|
||||
if (!cwd) return false
|
||||
const resolvedCwd = await this.resolveForWorkspaceCheck(cwd)
|
||||
return this.isWithinWorkspaceRoots(resolvedCwd)
|
||||
}
|
||||
|
||||
private isWithinWorkspaceRoots(absolutePath: string): boolean {
|
||||
@@ -300,7 +357,7 @@ export class ApiMachineClient {
|
||||
|
||||
setRPCHandlers({ spawnSession, stopSession, requestShutdown }: MachineRpcHandlers): void {
|
||||
this.rpcHandlerManager.registerHandler(RPC_METHODS.SpawnHappySession, async (params: any) => {
|
||||
const { directory, sessionId, resumeSessionId, machineId, approvedNewDirectoryCreation, agent, model, effort, modelReasoningEffort, yolo, permissionMode, serviceTier, token, sessionType, worktreeName } = params || {}
|
||||
const { directory, sessionId, existingSessionId, resumeSessionId, machineId, approvedNewDirectoryCreation, agent, model, effort, modelReasoningEffort, yolo, permissionMode, serviceTier, token, sessionType, worktreeName } = params || {}
|
||||
|
||||
if (!directory) {
|
||||
throw new Error('Directory is required')
|
||||
@@ -314,6 +371,7 @@ export class ApiMachineClient {
|
||||
const result = await spawnSession({
|
||||
directory,
|
||||
sessionId,
|
||||
existingSessionId,
|
||||
resumeSessionId,
|
||||
machineId,
|
||||
approvedNewDirectoryCreation,
|
||||
|
||||
Reference in New Issue
Block a user