diff --git a/cli/src/api/apiMachine.test.ts b/cli/src/api/apiMachine.test.ts index 6a6e1ea6..a708e21a 100644 --- a/cli/src/api/apiMachine.test.ts +++ b/cli/src/api/apiMachine.test.ts @@ -115,6 +115,15 @@ async function callListCodexSessions(client: ApiMachineClient, machineId: string return JSON.parse(raw) as unknown } +async function callListPiSessions(client: ApiMachineClient, machineId: string, params: { cwd?: string | null; sessionIds?: string[] }): Promise { + const manager = (client as unknown as { rpcHandlerManager: { handleRequest: (req: { method: string; params: string }) => Promise } }).rpcHandlerManager + const raw = await manager.handleRequest({ + method: `${machineId}:listPiSessions`, + params: JSON.stringify(params) + }) + return JSON.parse(raw) as unknown +} + async function callArchiveCodexSession(client: ApiMachineClient, machineId: string, sessionId: string): Promise { const manager = (client as unknown as { rpcHandlerManager: { handleRequest: (req: { method: string; params: string }) => Promise } }).rpcHandlerManager const raw = await manager.handleRequest({ @@ -135,6 +144,17 @@ function writeCodexTranscript(codexHome: string, fileName: string, payload: Reco return file } +function writePiTranscript(sessionsRoot: string, fileName: string, sessionId: string, cwd: string, userText: string): string { + const sessionDir = join(sessionsRoot, '--project--') + mkdirSync(sessionDir, { recursive: true }) + const file = join(sessionDir, fileName) + writeFileSync(file, [ + JSON.stringify({ type: 'session', version: 3, id: sessionId, cwd }), + JSON.stringify({ type: 'message', id: `${sessionId}-user`, parentId: null, message: { role: 'user', content: userText } }) + ].join('\n')) + return file +} + describe('ApiMachineClient cursor-chat-store-status handler', () => { beforeEach(() => { inspectCursorChatStoreMock.mockReset() @@ -490,6 +510,49 @@ describe('ApiMachineClient Codex transcript handlers', () => { }) +describe('ApiMachineClient Pi transcript handlers', () => { + const originalPiSessions = process.env.PI_CODING_AGENT_SESSION_DIR + let workspaceRoot: string + let outsideRoot: string + let piSessions: string + + beforeEach(() => { + ioMock.mockReset() + workspaceRoot = mkdtempSync(join(tmpdir(), 'hapi-pi-allowed-')) + outsideRoot = mkdtempSync(join(tmpdir(), 'hapi-pi-outside-')) + piSessions = mkdtempSync(join(tmpdir(), 'hapi-pi-sessions-')) + process.env.PI_CODING_AGENT_SESSION_DIR = piSessions + }) + + afterEach(() => { + if (originalPiSessions === undefined) delete process.env.PI_CODING_AGENT_SESSION_DIR + else process.env.PI_CODING_AGENT_SESSION_DIR = originalPiSessions + rmSync(workspaceRoot, { recursive: true, force: true }) + rmSync(outsideRoot, { recursive: true, force: true }) + rmSync(piSessions, { recursive: true, force: true }) + }) + + it('filters Pi summaries and full transcripts to workspace roots', async () => { + writePiTranscript(piSessions, 'allowed.jsonl', 'allowed-pi-session', workspaceRoot, 'allowed') + writePiTranscript(piSessions, 'outside.jsonl', 'outside-pi-session', outsideRoot, 'outside') + const machine = makeMachine('pi-machine-1') + const client = new ApiMachineClient('cli-token', machine, [workspaceRoot]) + + try { + const summaries = await callListPiSessions(client, machine.id, {}) as { success: true; sessions: Array<{ id: string }> } + expect(summaries.sessions.map((session) => session.id)).toEqual(['allowed-pi-session']) + + const full = await callListPiSessions(client, machine.id, { + sessionIds: ['allowed-pi-session', 'outside-pi-session'] + }) as { success: true; sessions: Array<{ id: string; messages: unknown[] }> } + expect(full.sessions.map((session) => session.id)).toEqual(['allowed-pi-session']) + expect(full.sessions[0]?.messages).toHaveLength(1) + } finally { + client.shutdown() + } + }) +}) + describe('ApiMachineClient SpawnHappySession handler', () => { let workspaceRoot: string diff --git a/cli/src/api/apiMachine.ts b/cli/src/api/apiMachine.ts index 577d9b0d..c052f277 100644 --- a/cli/src/api/apiMachine.ts +++ b/cli/src/api/apiMachine.ts @@ -12,8 +12,10 @@ import type { ClientToServerEvents, ServerToClientEvents, Update, UpdateMachineB import { ArchiveCodexSessionRpcRequestSchema, ListCodexSessionsRpcRequestSchema, + ListPiSessionsRpcRequestSchema, type ArchiveCodexSessionRpcResponse, type ListCodexSessionsRpcResponse, + type ListPiSessionsRpcResponse, type MachineDirectoryEntry, type MachineListDirectoryResponse, type PathExistsResponse @@ -43,6 +45,7 @@ import { import type { SpawnSessionOptions, SpawnSessionResult } from '../modules/common/rpcTypes' import { applyVersionedAck } from './versionedUpdate' import { archiveLocalCodexSession, listLocalCodexSessionSummaries, listLocalCodexSessionsWithMessagesByIds } from '../modules/common/codexSessions' +import { listLocalPiSessionSummaries, listLocalPiSessionsWithMessagesByIds } from '../modules/common/piSessions' import { buildSocketIoExtraHeaderOptions } from './hubExtraHeaders' import { collectMachineHealth } from '@/utils/machineHealth' import { inspectCursorChatStore } from '@/cursor/cursorChatStoreStatus' @@ -310,7 +313,7 @@ export class ApiMachineClient { : listLocalCodexSessionSummaries() const sessions = [] for (const session of allSessions) { - if (await this.isCodexSessionWithinWorkspaceRoots(session)) { + if (await this.isLocalSessionWithinWorkspaceRoots(session)) { sessions.push(session) } } @@ -325,13 +328,37 @@ export class ApiMachineClient { 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) + canArchive: (session) => this.isLocalSessionWithinWorkspaceRoots(session) }) } ) + + this.rpcHandlerManager.registerHandler( + RPC_METHODS.ListPiSessions, + async (params) => { + const parsed = ListPiSessionsRpcRequestSchema.safeParse(params) + if (!parsed.success) return { success: false, error: 'Invalid Pi 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 + ? listLocalPiSessionsWithMessagesByIds(requestedIds) + : listLocalPiSessionSummaries() + const sessions = [] + for (const session of allSessions) { + if (await this.isLocalSessionWithinWorkspaceRoots(session)) sessions.push(session) + } + return { success: true, sessions } + } + ) } - private async isCodexSessionWithinWorkspaceRoots(session: { cwd?: string | null }): Promise { + private async isLocalSessionWithinWorkspaceRoots(session: { cwd?: string | null }): Promise { if (!this.normalizedWorkspaceRoots?.length) return true const cwd = session.cwd?.trim() if (!cwd) return false diff --git a/cli/src/modules/common/piSessions.test.ts b/cli/src/modules/common/piSessions.test.ts new file mode 100644 index 00000000..90aed461 --- /dev/null +++ b/cli/src/modules/common/piSessions.test.ts @@ -0,0 +1,134 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { mkdtempSync, mkdirSync, rmSync, utimesSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import { tmpdir } from 'node:os' +import { listLocalPiSessionSummaries, listLocalPiSessionsWithMessagesByIds } from './piSessions' + +describe('local Pi sessions', () => { + const originalSessionDir = process.env.PI_CODING_AGENT_SESSION_DIR + + afterEach(() => { + if (originalSessionDir === undefined) delete process.env.PI_CODING_AGENT_SESSION_DIR + else process.env.PI_CODING_AGENT_SESSION_DIR = originalSessionDir + }) + + it('keeps only the active leaf ancestry and converts Pi history blocks', () => { + const root = mkdtempSync(join(tmpdir(), 'pi-sessions-')) + process.env.PI_CODING_AGENT_SESSION_DIR = root + const bucket = join(root, '--tmp-project--') + mkdirSync(bucket, { recursive: true }) + const file = join(bucket, 'session.jsonl') + writeFileSync(file, [ + { type: 'session', version: 3, id: 'pi-session-1', timestamp: '2026-08-04T01:00:00Z', cwd: '/tmp/project' }, + { type: 'message', id: 'user-1', parentId: null, timestamp: '2026-08-04T01:00:01Z', message: { role: 'user', content: [{ type: 'text', text: 'first prompt' }] } }, + { type: 'message', id: 'old-branch', parentId: 'user-1', timestamp: '2026-08-04T01:00:02Z', message: { role: 'assistant', content: [{ type: 'text', text: 'old branch' }] } }, + { type: 'message', id: 'assistant-1', parentId: 'user-1', timestamp: '2026-08-04T01:00:03Z', message: { role: 'assistant', model: 'gpt-5.6', content: [ + { type: 'thinking', thinking: 'reasoning' }, + { type: 'text', text: 'answer' }, + { type: 'toolCall', id: 'tool-1', name: 'read', arguments: { path: 'a.ts' } } + ], usage: { input: 10, output: 5, cacheRead: 2, cacheWrite: 1, totalTokens: 18 } } }, + { type: 'message', id: 'tool-result-1', parentId: 'assistant-1', timestamp: '2026-08-04T01:00:04Z', message: { role: 'toolResult', toolCallId: 'tool-1', content: 'ok', isError: false } }, + { type: 'custom_message', id: 'custom-1', parentId: 'tool-result-1', timestamp: '2026-08-04T01:00:05Z', display: true, content: 'visible extension result' }, + { type: 'compaction', id: 'compact-1', parentId: 'custom-1', timestamp: '2026-08-04T01:00:06Z', summary: 'condensed context' }, + { type: 'session_info', id: 'info-1', parentId: 'compact-1', timestamp: '2026-08-04T01:00:07Z', name: 'Imported Pi session' } + ].map((line) => JSON.stringify(line)).join('\n')) + + const summaries = listLocalPiSessionSummaries() + expect(summaries).toEqual([expect.objectContaining({ + id: 'pi-session-1', + title: 'Imported Pi session', + cwd: '/tmp/project', + model: 'gpt-5.6', + leafEntryId: 'info-1', + messageCount: 8 + })]) + + const sessions = listLocalPiSessionsWithMessagesByIds(new Set(['pi-session-1'])) + expect(sessions).toHaveLength(1) + expect(sessions[0]?.messages.some((message) => JSON.stringify(message.content).includes('old branch'))).toBe(false) + expect(sessions[0]?.messages.map((message) => message.localId)).toEqual([ + 'pi:pi-session-1:user-1:user', + 'pi:pi-session-1:assistant-1:0', + 'pi:pi-session-1:assistant-1:1', + 'pi:pi-session-1:assistant-1:2', + 'pi:pi-session-1:assistant-1:usage', + 'pi:pi-session-1:tool-result-1:tool-result', + 'pi:pi-session-1:custom-1:custom_message', + 'pi:pi-session-1:compact-1:compaction' + ]) + expect(sessions[0]?.messages[0]).toMatchObject({ + entryId: 'user-1', + parentEntryId: null, + createdAt: Date.parse('2026-08-04T01:00:01Z'), + content: { role: 'user' } + }) + rmSync(root, { recursive: true, force: true }) + }) + + it('honors environment precedence, skips malformed lines, and deduplicates by newest file', () => { + const root = mkdtempSync(join(tmpdir(), 'pi-sessions-')) + process.env.PI_CODING_AGENT_SESSION_DIR = root + for (const [folder, title] of [['older', 'old'], ['newer', 'new']] as const) { + const bucket = join(root, folder) + mkdirSync(bucket, { recursive: true }) + const file = join(bucket, `${title}.jsonl`) + writeFileSync(file, [ + '{broken', + JSON.stringify({ type: 'session', id: 'same-session', cwd: '/tmp/project' }), + JSON.stringify({ type: 'message', id: `user-${title}`, parentId: null, message: { role: 'user', content: title } }) + ].join('\n')) + const time = title === 'new' ? new Date('2026-08-04T02:00:00Z') : new Date('2026-08-04T01:00:00Z') + utimesSync(file, time, time) + } + + expect(listLocalPiSessionSummaries()).toEqual([ + expect.objectContaining({ id: 'same-session', title: 'new', lastUserMessage: 'new' }) + ]) + rmSync(root, { recursive: true, force: true }) + }) + + it('keeps image-only user entries as explicit history placeholders', () => { + const root = mkdtempSync(join(tmpdir(), 'pi-sessions-')) + process.env.PI_CODING_AGENT_SESSION_DIR = root + mkdirSync(join(root, 'bucket'), { recursive: true }) + writeFileSync(join(root, 'bucket', 'image.jsonl'), [ + JSON.stringify({ type: 'session', id: 'image-session', cwd: '/tmp/project' }), + JSON.stringify({ + type: 'message', + id: 'image-user', + parentId: null, + message: { role: 'user', content: [{ type: 'image', mimeType: 'image/png', data: 'base64' }] } + }) + ].join('\n')) + + const session = listLocalPiSessionsWithMessagesByIds(new Set(['image-session']))[0] + expect(session?.messages[0]).toMatchObject({ + entryId: 'image-user', + content: { role: 'user', content: { text: '[Image attachment: image/png]' } } + }) + rmSync(root, { recursive: true, force: true }) + }) + + it('limits summary materialization while selected-id lookup can still reach older sessions', () => { + const root = mkdtempSync(join(tmpdir(), 'pi-sessions-')) + process.env.PI_CODING_AGENT_SESSION_DIR = root + mkdirSync(join(root, 'bucket'), { recursive: true }) + for (let index = 0; index < 205; index += 1) { + const file = join(root, 'bucket', `${index}.jsonl`) + writeFileSync(file, [ + JSON.stringify({ type: 'session', id: `session-${index}`, cwd: '/tmp/project' }), + JSON.stringify({ type: 'message', id: `user-${index}`, parentId: null, message: { role: 'user', content: `prompt-${index}` } }) + ].join('\n')) + const time = new Date(1_700_000_000_000 + index * 1_000) + utimesSync(file, time, time) + } + + const summaries = listLocalPiSessionSummaries(2) + expect(summaries.map((session) => session.id)).toEqual(['session-204', 'session-203']) + expect(listLocalPiSessionsWithMessagesByIds(new Set(['session-0']))[0]).toMatchObject({ + id: 'session-0', + lastUserMessage: 'prompt-0' + }) + rmSync(root, { recursive: true, force: true }) + }) +}) diff --git a/cli/src/modules/common/piSessions.ts b/cli/src/modules/common/piSessions.ts new file mode 100644 index 00000000..5666d806 --- /dev/null +++ b/cli/src/modules/common/piSessions.ts @@ -0,0 +1,451 @@ +import { closeSync, openSync, readdirSync, readFileSync, readSync, statSync } from 'node:fs' +import { basename, join } from 'node:path' +import { homedir } from 'node:os' +import { AGENT_MESSAGE_PAYLOAD_TYPE } from '@hapi/protocol' +import type { + PiImportedMessage, + PiImportedMessageContent, + PiLocalSessionSummary, + PiLocalSessionWithMessages +} from '@hapi/protocol/apiTypes' + +const DEFAULT_PI_SESSION_SCAN_LIMIT = 200 + +type JsonRecord = Record + +type ParsedPiSession = { + summary: PiLocalSessionSummary + messages: PiImportedMessage[] + activeEntryIds: string[] +} + +type PiSessionFileCandidate = { + file: string + modifiedAt: number + discoveryIndex: number +} + +type PiSessionHeader = { + id: string + cwd: string | null +} + +function asRecord(value: unknown): JsonRecord | null { + return value !== null && typeof value === 'object' && !Array.isArray(value) + ? value as JsonRecord + : null +} + +function asString(value: unknown): string | null { + return typeof value === 'string' && value.trim() ? value.trim() : null +} + +function asNumber(value: unknown): number | null { + return typeof value === 'number' && Number.isFinite(value) ? value : null +} + +function truncateText(value: string, maxLength: number): string { + return value.length > maxLength ? `${value.slice(0, maxLength - 1)}…` : value +} + +function parseTimestamp(value: unknown, fallback: number): number { + if (typeof value === 'number' && Number.isFinite(value)) { + return value < 1_000_000_000_000 ? value * 1000 : value + } + if (typeof value === 'string') { + const parsed = Date.parse(value) + if (Number.isFinite(parsed)) return parsed + } + return fallback +} + +function collectJsonlFiles(root: string, files: string[]): void { + let entries: import('node:fs').Dirent[] + try { + entries = readdirSync(root, { withFileTypes: true }) + } catch { + return + } + for (const entry of entries) { + const fullPath = join(root, entry.name) + if (entry.isDirectory()) collectJsonlFiles(fullPath, files) + else if (entry.isFile() && fullPath.toLowerCase().endsWith('.jsonl')) files.push(fullPath) + } +} + +function collectSortedPiSessionFiles(): PiSessionFileCandidate[] { + const files: string[] = [] + collectJsonlFiles(getPiSessionsRoot(), files) + return files.flatMap((file, discoveryIndex) => { + try { + return [{ file, modifiedAt: statSync(file).mtimeMs, discoveryIndex }] + } catch { + return [] + } + }).sort((a, b) => b.modifiedAt - a.modifiedAt || a.discoveryIndex - b.discoveryIndex) +} + +function readPiSessionHeader(filePath: string): PiSessionHeader | null { + const buffer = Buffer.alloc(64 * 1024) + let fd: number | null = null + try { + fd = openSync(filePath, 'r') + const bytesRead = readSync(fd, buffer, 0, buffer.length, 0) + const prefix = buffer.toString('utf-8', 0, bytesRead) + for (const line of prefix.split(/\r?\n/)) { + if (!line.trim()) continue + try { + const record = asRecord(JSON.parse(line)) + if (record?.type !== 'session') continue + const id = asString(record.id) + if (id) return { id, cwd: asString(record.cwd) } + } catch { + continue + } + } + } catch { + return null + } finally { + if (fd !== null) closeSync(fd) + } + return null +} + +export function getPiSessionsRoot(): string { + const direct = process.env.PI_CODING_AGENT_SESSION_DIR?.trim() + if (direct) return direct + const agentHome = process.env.PI_CODING_AGENT_DIR?.trim() + if (agentHome) return join(agentHome, 'sessions') + return join(homedir(), '.pi', 'agent', 'sessions') +} + +function extractText(value: unknown): string { + if (typeof value === 'string') return value + if (!Array.isArray(value)) return '' + return value.map((item) => { + if (typeof item === 'string') return item + const block = asRecord(item) + return block?.type === 'text' && typeof block.text === 'string' ? block.text : '' + }).filter(Boolean).join('\n') +} + +function extractUserText(value: unknown): string { + if (typeof value === 'string') return value + if (!Array.isArray(value)) return '' + return value.map((item) => { + if (typeof item === 'string') return item + const block = asRecord(item) + if (block?.type === 'text' && typeof block.text === 'string') return block.text + if (block?.type === 'image') { + const mimeType = asString(block.mimeType) ?? 'image' + return `[Image attachment: ${mimeType}]` + } + return '' + }).filter(Boolean).join('\n') +} + +function importedUser(text: string): PiImportedMessageContent { + return { + role: 'user', + content: { type: 'text', text }, + meta: { sentFrom: 'cli' } + } +} + +function importedAgent(data: unknown): PiImportedMessageContent { + return { + role: 'agent', + content: { type: AGENT_MESSAGE_PAYLOAD_TYPE, data }, + meta: { sentFrom: 'cli' } + } +} + +function messageLocalId(sessionId: string, entryId: string, suffix: string): string { + return `pi:${sessionId}:${entryId}:${suffix}` +} + +function pushImportedMessage( + target: PiImportedMessage[], + sessionId: string, + entryId: string, + parentEntryId: string | null, + createdAt: number, + suffix: string, + content: PiImportedMessageContent +): void { + target.push({ + localId: messageLocalId(sessionId, entryId, suffix), + entryId, + parentEntryId, + createdAt, + content + }) +} + +function convertMessageRecord( + record: JsonRecord, + sessionId: string, + entryId: string, + parentEntryId: string | null, + createdAt: number +): PiImportedMessage[] { + const message = asRecord(record.message) + const role = asString(message?.role) + if (!message || !role) return [] + const result: PiImportedMessage[] = [] + + if (role === 'user') { + const text = extractUserText(message.content).trim() + if (text) pushImportedMessage(result, sessionId, entryId, parentEntryId, createdAt, 'user', importedUser(text)) + return result + } + + if (role === 'toolResult') { + const callId = asString(message.toolCallId) ?? `pi-tool-${entryId}` + pushImportedMessage(result, sessionId, entryId, parentEntryId, createdAt, 'tool-result', importedAgent({ + type: 'tool-call-result', + callId, + output: message.content, + is_error: message.isError === true + })) + return result + } + + if (role !== 'assistant') return result + const blocks = Array.isArray(message.content) + ? message.content + : typeof message.content === 'string' + ? [{ type: 'text', text: message.content }] + : [] + let blockIndex = 0 + for (const rawBlock of blocks) { + const block = asRecord(rawBlock) + const type = asString(block?.type) + if (!block || !type) continue + const suffix = `${blockIndex++}` + if (type === 'text') { + const text = asString(block.text) + if (text) pushImportedMessage(result, sessionId, entryId, parentEntryId, createdAt, suffix, importedAgent({ type: 'message', message: text, id: messageLocalId(sessionId, entryId, suffix) })) + } else if (type === 'thinking') { + const text = asString(block.thinking) ?? asString(block.text) + if (text) pushImportedMessage(result, sessionId, entryId, parentEntryId, createdAt, suffix, importedAgent({ type: 'reasoning', message: text, id: messageLocalId(sessionId, entryId, suffix) })) + } else if (type === 'toolCall') { + const callId = asString(block.id) ?? asString(block.toolCallId) ?? `pi-tool-${entryId}-${suffix}` + const name = asString(block.name) ?? asString(block.toolName) ?? 'tool' + pushImportedMessage(result, sessionId, entryId, parentEntryId, createdAt, suffix, importedAgent({ + type: 'tool-call', + name, + callId, + input: block.arguments ?? block.args ?? block.input ?? {}, + status: 'completed' + })) + } + } + + const usage = asRecord(message.usage) + if (usage) { + const input = asNumber(usage.input) ?? 0 + const output = asNumber(usage.output) ?? 0 + const cacheRead = asNumber(usage.cacheRead) ?? 0 + const cacheWrite = asNumber(usage.cacheWrite) ?? 0 + const totalTokens = asNumber(usage.totalTokens) ?? input + output + cacheRead + cacheWrite + pushImportedMessage(result, sessionId, entryId, parentEntryId, createdAt, 'usage', importedAgent({ + type: 'token_count', + model: asString(message.model), + info: { + total: { + inputTokens: input + cacheRead + cacheWrite, + outputTokens: output, + totalTokens, + cachedInputTokens: cacheRead, + cacheWriteInputTokens: cacheWrite + } + } + })) + } + return result +} + +function convertBashRecord( + record: JsonRecord, + sessionId: string, + entryId: string, + parentEntryId: string | null, + createdAt: number +): PiImportedMessage[] { + const callId = `pi-bash-${entryId}` + const result: PiImportedMessage[] = [] + pushImportedMessage(result, sessionId, entryId, parentEntryId, createdAt, 'bash-call', importedAgent({ + type: 'tool-call', + name: 'bash', + callId, + input: { command: asString(record.command) ?? '' }, + status: 'completed' + })) + pushImportedMessage(result, sessionId, entryId, parentEntryId, createdAt, 'bash-result', importedAgent({ + type: 'tool-call-result', + callId, + output: record.output ?? '', + is_error: (asNumber(record.exitCode) ?? 0) !== 0 + })) + return result +} + +function convertVisibleMetadataRecord( + record: JsonRecord, + sessionId: string, + entryId: string, + parentEntryId: string | null, + createdAt: number +): PiImportedMessage[] { + let text: string | null = null + if (record.type === 'custom_message' && record.display === true) { + text = extractText(record.content).trim() || null + } else if (record.type === 'compaction') { + const summary = asString(record.summary) + if (summary) text = `[Compaction summary]\n\n${summary}` + } else if (record.type === 'branch_summary') { + const summary = asString(record.summary) + if (summary) text = `[Branch summary]\n\n${summary}` + } + if (!text) return [] + const result: PiImportedMessage[] = [] + pushImportedMessage(result, sessionId, entryId, parentEntryId, createdAt, String(record.type), importedAgent({ + type: 'message', + message: text, + id: messageLocalId(sessionId, entryId, String(record.type)) + })) + return result +} + +function parsePiLocalSession(filePath: string, knownModifiedAt?: number): ParsedPiSession | null { + let content: string + let modifiedAt: number + try { + content = readFileSync(filePath, 'utf-8') + modifiedAt = knownModifiedAt ?? statSync(filePath).mtimeMs + } catch { + return null + } + + const records: JsonRecord[] = [] + for (const line of content.split(/\r?\n/)) { + if (!line.trim()) continue + try { + const record = asRecord(JSON.parse(line)) + if (record) records.push(record) + } catch { + continue + } + } + + const header = records.find((record) => record.type === 'session') + const sessionId = asString(header?.id) + if (!sessionId) return null + const cwd = asString(header?.cwd) + + const nodes = new Map() + const orderedNodeIds: string[] = [] + for (const record of records) { + if (record.type === 'session') continue + const id = asString(record.id) + if (!id) continue + nodes.set(id, record) + orderedNodeIds.push(id) + } + const leafEntryId = orderedNodeIds.at(-1) ?? null + const activePath = new Set() + let cursor = leafEntryId + while (cursor && !activePath.has(cursor)) { + activePath.add(cursor) + cursor = asString(nodes.get(cursor)?.parentId) + } + + let title: string | null = null + let model: string | null = null + let thinkingLevel: string | null = null + + const messages: PiImportedMessage[] = [] + let firstUserMessage: string | null = null + let lastUserMessage: string | null = null + for (const id of orderedNodeIds) { + if (!activePath.has(id)) continue + const record = nodes.get(id) + if (!record) continue + if (record.type === 'session_info') title = asString(record.name) ?? title + if (record.type === 'model_change') model = asString(record.modelId) ?? model + if (record.type === 'thinking_level_change') thinkingLevel = asString(record.thinkingLevel) ?? thinkingLevel + const parentEntryId = asString(record.parentId) + const nestedMessage = asRecord(record.message) + const createdAt = parseTimestamp(nestedMessage?.timestamp ?? record.timestamp, modifiedAt) + const converted = record.type === 'message' + ? convertMessageRecord(record, sessionId, id, parentEntryId, createdAt) + : record.type === 'bashExecution' + ? convertBashRecord(record, sessionId, id, parentEntryId, createdAt) + : convertVisibleMetadataRecord(record, sessionId, id, parentEntryId, createdAt) + for (const message of converted) { + if (message.content.role === 'user') { + const text = message.content.content.text + firstUserMessage ??= text + lastUserMessage = text + } + messages.push(message) + } + if (record.type === 'message' && nestedMessage?.role === 'assistant') { + model = asString(nestedMessage.model) ?? model + } + } + + const displayTitle = title + ?? (firstUserMessage ? truncateText(firstUserMessage, 80) : null) + ?? (cwd ? basename(cwd) || cwd : null) + ?? sessionId.slice(0, 8) + return { + summary: { + id: sessionId, + title: displayTitle, + lastUserMessage: lastUserMessage ? truncateText(lastUserMessage, 140) : null, + cwd, + file: filePath, + modifiedAt, + model, + thinkingLevel, + leafEntryId, + messageCount: messages.length + }, + messages, + activeEntryIds: orderedNodeIds.filter((id) => activePath.has(id)) + } +} + +export function listLocalPiSessionSummaries(limit = DEFAULT_PI_SESSION_SCAN_LIMIT): PiLocalSessionSummary[] { + if (limit <= 0) return [] + const seenIds = new Set() + const summaries: PiLocalSessionSummary[] = [] + for (const candidate of collectSortedPiSessionFiles()) { + const header = readPiSessionHeader(candidate.file) + if (!header || seenIds.has(header.id)) continue + const parsed = parsePiLocalSession(candidate.file, candidate.modifiedAt) + if (!parsed) continue + seenIds.add(header.id) + summaries.push(parsed.summary) + if (summaries.length >= limit) break + } + return summaries +} + +export function listLocalPiSessionsWithMessagesByIds(ids: Set): PiLocalSessionWithMessages[] { + if (ids.size === 0) return [] + const unresolved = new Set(ids) + const sessions: PiLocalSessionWithMessages[] = [] + for (const candidate of collectSortedPiSessionFiles()) { + const header = readPiSessionHeader(candidate.file) + if (!header || !unresolved.has(header.id)) continue + const parsed = parsePiLocalSession(candidate.file, candidate.modifiedAt) + if (!parsed) continue + unresolved.delete(header.id) + sessions.push({ ...parsed.summary, messages: parsed.messages, activeEntryIds: parsed.activeEntryIds }) + if (unresolved.size === 0) break + } + return sessions +} diff --git a/cli/src/pi/conversationHistory.test.ts b/cli/src/pi/conversationHistory.test.ts index c9d1388c..6c22acb3 100644 --- a/cli/src/pi/conversationHistory.test.ts +++ b/cli/src/pi/conversationHistory.test.ts @@ -35,6 +35,16 @@ const source = { sessionId: 'source-id', sessionFile: '/tmp/source.jsonl' } const clone = { sessionId: 'clone-id', sessionFile: '/tmp/clone.jsonl' } describe('PiConversationHistory entry mapping', () => { + it('persists the append cursor for assistant entries without waiting for another user message', () => { + const { session, metadata, client } = createSession() + const history = new PiConversationHistory(session, vi.fn()) + + history.observeEntry({ type: 'message', id: 'assistant-leaf', message: { role: 'assistant', content: 'done' } }) + + expect(metadata.piHistoryLeafEntryId).toBe('assistant-leaf') + expect(client.updateMetadata).toHaveBeenCalledOnce() + }) + it('pairs duplicate prompts to native user entries strictly FIFO without reading text', () => { const { session, metadata } = createSession() const history = new PiConversationHistory(session, vi.fn()) @@ -75,6 +85,29 @@ describe('PiConversationHistory entry mapping', () => { await history.syncEntries() }) + it('persists one metadata snapshot for a multi-entry get_entries batch', async () => { + const { session, metadata, client } = createSession() + const rpc = vi.fn(async () => ({ + entries: [ + { type: 'message', id: 'user-1', message: { role: 'user' } }, + { type: 'message', id: 'assistant-1', message: { role: 'assistant' } }, + { type: 'message', id: 'assistant-2', message: { role: 'assistant' } } + ], + leafId: 'assistant-2' + })) + const history = new PiConversationHistory(session, rpc) + history.registerUserEntry('local-1') + + await history.syncEntries() + + expect(client.updateMetadata).toHaveBeenCalledOnce() + expect(metadata).toMatchObject({ + piHistoryLeafEntryId: 'assistant-2', + conversationHistoryEntryIds: { 'local-1': 'user-1' }, + conversationHistoryPoints: { 'local-1': true } + }) + }) + it('serializes concurrent syncs and ignores a duplicate entry_appended/get_entries user entry', async () => { const { session } = createSession() let resolveFirstRead!: (value: unknown) => void diff --git a/cli/src/pi/conversationHistory.ts b/cli/src/pi/conversationHistory.ts index 349b7a83..c3b7a9d6 100644 --- a/cli/src/pi/conversationHistory.ts +++ b/cli/src/pi/conversationHistory.ts @@ -270,11 +270,16 @@ export class PiConversationHistory { ) if (generation !== this.syncGeneration) return const result = readEntries(data) - for (const entry of result.entries) this.observeParsedEntry(entry) + for (const entry of result.entries) this.observeParsedEntry(entry, false) // `since` indexes the immutable append log, not the active branch. // A fork can move leafId backwards; advancing the cursor to it would // replay entries and break FIFO pairing. Empty increments keep cursor. - if (result.entries.length > 0) this.appendCursor = result.entries[result.entries.length - 1]!.id + if (result.entries.length > 0) { + this.appendCursor = result.entries[result.entries.length - 1]!.id + const entryIds = this.getEntryIds() + const points = this.getHistoryPoints() + this.session.updateMetadata((metadata) => this.metadataWithLocators(metadata, entryIds, points)) + } } async probeCapabilities(): Promise { @@ -726,7 +731,12 @@ export class PiConversationHistory { entryIds: Record, points: Record ): Metadata { - const next: Metadata = { ...metadata, conversationHistoryEntryIds: entryIds, conversationHistoryPoints: points } + const next: Metadata = { + ...metadata, + conversationHistoryEntryIds: entryIds, + conversationHistoryPoints: points, + ...(this.appendCursor ? { piHistoryLeafEntryId: this.appendCursor } : {}) + } if (Object.keys(entryIds).length === 0) delete next.conversationHistoryEntryIds if (Object.keys(points).length === 0) delete next.conversationHistoryPoints return next @@ -754,17 +764,29 @@ export class PiConversationHistory { : this.rpcWithinDeadline({ type: 'get_state' }, deadlineAt))) } - private observeParsedEntry(entry: PiEntry): void { + private observeParsedEntry(entry: PiEntry, persistMetadata: boolean = true): void { if (this.observedEntryIds.has(entry.id)) return this.observedEntryIds.add(entry.id) this.appendCursor = entry.id - if (!isUserEntry(entry)) return + if (!isUserEntry(entry)) { + if (persistMetadata) { + this.session.updateMetadata((metadata) => ({ ...metadata, piHistoryLeafEntryId: entry.id })) + } + return + } const pending = this.pendingUserEntries.shift() - if (!pending || this.entryIdByLocalId.has(pending.localId)) return + if (!pending || this.entryIdByLocalId.has(pending.localId)) { + if (persistMetadata) { + this.session.updateMetadata((metadata) => ({ ...metadata, piHistoryLeafEntryId: entry.id })) + } + return + } const localId = pending.localId this.entryIdByLocalId.set(localId, entry.id) + if (!persistMetadata) return this.session.updateMetadata((metadata) => ({ ...metadata, + piHistoryLeafEntryId: entry.id, conversationHistoryPoints: { ...metadata.conversationHistoryPoints, [localId]: true as const, diff --git a/hub/src/store/messageStore.ts b/hub/src/store/messageStore.ts index 0e82454f..079e8d49 100644 --- a/hub/src/store/messageStore.ts +++ b/hub/src/store/messageStore.ts @@ -3,6 +3,7 @@ import type { Database } from 'bun:sqlite' import type { StoredMessage } from './types' import { addMessage, + addImportedMessage, cancelQueuedMessage, deleteQueuedMessageById, lookupQueuedMessage, @@ -49,6 +50,10 @@ export class MessageStore { return addMessage(this.db, sessionId, content, localId, scheduledAt, createdAt) } + addImportedMessage(sessionId: string, content: unknown, localId: string, createdAt: number): { message: StoredMessage; inserted: boolean } { + return addImportedMessage(this.db, sessionId, content, localId, createdAt) + } + copyMessageToSession( sessionId: string, message: Pick diff --git a/hub/src/store/messages.ts b/hub/src/store/messages.ts index 7ae1daa7..dbf69dda 100644 --- a/hub/src/store/messages.ts +++ b/hub/src/store/messages.ts @@ -1,5 +1,6 @@ import type { Database } from 'bun:sqlite' import { randomUUID } from 'node:crypto' +import { isDeepStrictEqual } from 'node:util' import type { StoredMessage } from './types' import { decodeMessageContent, encodeMessageContent, truncateOversizedMessageContent } from './contentCodec' @@ -21,6 +22,60 @@ export type MessagePosition = { seq: number } +export class ImportedMessageConflictError extends Error { + constructor(readonly localId: string) { + super(`Imported message content changed for localId: ${localId}`) + this.name = 'ImportedMessageConflictError' + } +} + +export function addImportedMessage( + db: Database, + sessionId: string, + content: unknown, + localId: string, + createdAt: number +): { message: StoredMessage; inserted: boolean } { + const existing = db.prepare( + 'SELECT * FROM messages WHERE session_id = ? AND local_id = ? LIMIT 1' + ).get(sessionId, localId) as DbMessageRow | undefined + if (existing) { + const message = toStoredMessage(existing) + const canonicalContent = truncateOversizedMessageContent(content) + if (!isDeepStrictEqual(message.content, canonicalContent)) throw new ImportedMessageConflictError(localId) + return { message, inserted: false } + } + + const now = Date.now() + const stampedAt = Number.isFinite(createdAt) ? Math.min(createdAt, now) : now + return db.transaction(() => { + const previousHead = getNewestMessagePosition(db, sessionId) + const msgSeqRow = db.prepare( + 'SELECT COALESCE(MAX(seq), 0) + 1 AS nextSeq FROM messages WHERE session_id = ?' + ).get(sessionId) as { nextSeq: number } + const id = randomUUID() + db.prepare(` + INSERT INTO messages ( + id, session_id, content, created_at, seq, local_id, invoked_at, scheduled_at + ) VALUES ( + @id, @session_id, @content, @created_at, @seq, @local_id, @invoked_at, NULL + ) + `).run({ + id, + session_id: sessionId, + content: encodeMessageContent(truncateOversizedMessageContent(content)), + created_at: stampedAt, + seq: msgSeqRow.nextSeq, + local_id: localId, + invoked_at: stampedAt + }) + if (previousHead && stampedAt < previousHead.at) bumpMessageEpoch(db, sessionId) + const row = db.prepare('SELECT * FROM messages WHERE id = ?').get(id) as DbMessageRow | undefined + if (!row) throw new Error('Failed to create imported message') + return { message: toStoredMessage(row), inserted: true } + })() +} + function toStoredMessage(row: DbMessageRow): StoredMessage { return { id: row.id, diff --git a/hub/src/sync/rpcGateway.ts b/hub/src/sync/rpcGateway.ts index f495dae0..406bb784 100644 --- a/hub/src/sync/rpcGateway.ts +++ b/hub/src/sync/rpcGateway.ts @@ -3,7 +3,8 @@ import { RPC_METHODS } from '@hapi/protocol/rpcMethods' import { ArchiveCodexSessionRpcResponseSchema, CursorChatStoreStatusSchema, - ListCodexSessionsRpcResponseSchema + ListCodexSessionsRpcResponseSchema, + ListPiSessionsRpcResponseSchema } from '@hapi/protocol/apiTypes' import type { AgyModelsResponse, @@ -22,6 +23,7 @@ import type { GrokReasoningEffortResponse, ListDirectoryResponse, ListCodexSessionsRpcResponse, + ListPiSessionsRpcResponse, ArchiveCodexSessionRpcResponse, OpencodeModelsResponse, OpencodeModelSummary, @@ -70,6 +72,7 @@ export type RpcPathExistsResponse = PathExistsResponse export type RpcCodexModel = CodexModelSummary export type RpcListCodexModelsResponse = CodexModelsResponse export type RpcListCodexSessionsResponse = ListCodexSessionsRpcResponse +export type RpcListPiSessionsResponse = ListPiSessionsRpcResponse export type RpcArchiveCodexSessionResponse = ArchiveCodexSessionRpcResponse export type RpcCursorModel = CursorModelSummary export type RpcListCursorModelsResponse = CursorModelsResponse @@ -341,6 +344,11 @@ export class RpcGateway { return ListCodexSessionsRpcResponseSchema.parse(result) } + async listPiSessionsForMachine(machineId: string, cwd?: string | null, sessionIds?: string[]): Promise { + const result = await this.machineRpc(machineId, RPC_METHODS.ListPiSessions, { cwd: cwd ?? null, sessionIds }, MODEL_LIST_RPC_TIMEOUT_MS) + return ListPiSessionsRpcResponseSchema.parse(result) + } + async archiveCodexSessionForMachine(machineId: string, sessionId: string): Promise { const result = await this.machineRpc(machineId, RPC_METHODS.ArchiveCodexSession, { sessionId }, MODEL_LIST_RPC_TIMEOUT_MS) return ArchiveCodexSessionRpcResponseSchema.parse(result) diff --git a/hub/src/sync/sessionCache.ts b/hub/src/sync/sessionCache.ts index 117435d1..cf364467 100644 --- a/hub/src/sync/sessionCache.ts +++ b/hub/src/sync/sessionCache.ts @@ -1401,16 +1401,22 @@ export class SessionCache { private extractAgentSessionId( metadata: NonNullable - ): { field: 'codexSessionId' | 'claudeSessionId' | 'geminiSessionId' | 'opencodeSessionId' | 'grokSessionId' | 'cursorSessionId' | 'piSessionId' | 'agySessionId' | 'copilotSessionId'; value: string } | null { - if (metadata.codexSessionId) return { field: 'codexSessionId', value: metadata.codexSessionId } - if (metadata.claudeSessionId) return { field: 'claudeSessionId', value: metadata.claudeSessionId } - if (metadata.geminiSessionId) return { field: 'geminiSessionId', value: metadata.geminiSessionId } - if (metadata.opencodeSessionId) return { field: 'opencodeSessionId', value: metadata.opencodeSessionId } - if (metadata.grokSessionId) return { field: 'grokSessionId', value: metadata.grokSessionId } - if (metadata.cursorSessionId) return { field: 'cursorSessionId', value: metadata.cursorSessionId } - if (metadata.piSessionId) return { field: 'piSessionId', value: metadata.piSessionId } - if (metadata.agySessionId) return { field: 'agySessionId', value: metadata.agySessionId } - if (metadata.copilotSessionId) return { field: 'copilotSessionId', value: metadata.copilotSessionId } + ): { field: 'codexSessionId' | 'claudeSessionId' | 'geminiSessionId' | 'opencodeSessionId' | 'grokSessionId' | 'cursorSessionId' | 'piSessionId' | 'agySessionId' | 'copilotSessionId'; value: string; dedupeKey: string; machineId?: string } | null { + const scoped = (field: 'codexSessionId' | 'claudeSessionId' | 'geminiSessionId' | 'opencodeSessionId' | 'grokSessionId' | 'cursorSessionId' | 'piSessionId' | 'agySessionId' | 'copilotSessionId', value: string) => ({ + field, + value, + dedupeKey: field === 'piSessionId' ? `${field}:${metadata.machineId ?? 'unscoped'}:${value}` : `${field}:${value}`, + ...(field === 'piSessionId' && metadata.machineId ? { machineId: metadata.machineId } : {}) + }) + if (metadata.codexSessionId) return scoped('codexSessionId', metadata.codexSessionId) + if (metadata.claudeSessionId) return scoped('claudeSessionId', metadata.claudeSessionId) + if (metadata.geminiSessionId) return scoped('geminiSessionId', metadata.geminiSessionId) + if (metadata.opencodeSessionId) return scoped('opencodeSessionId', metadata.opencodeSessionId) + if (metadata.grokSessionId) return scoped('grokSessionId', metadata.grokSessionId) + if (metadata.cursorSessionId) return scoped('cursorSessionId', metadata.cursorSessionId) + if (metadata.piSessionId) return scoped('piSessionId', metadata.piSessionId) + if (metadata.agySessionId) return scoped('agySessionId', metadata.agySessionId) + if (metadata.copilotSessionId) return scoped('copilotSessionId', metadata.copilotSessionId) return null } @@ -1426,26 +1432,29 @@ export class SessionCache { // for active duplicates: a session can become inactive while the first // pass is only allowed to move history, and the follow-up pass should // then be allowed to delete the inactive duplicate record. - if (this.deduplicateInProgress.has(agentId.value)) { - this.deduplicatePending.add(agentId.value) + if (this.deduplicateInProgress.has(agentId.dedupeKey)) { + this.deduplicatePending.add(agentId.dedupeKey) return } - this.deduplicateInProgress.add(agentId.value) + this.deduplicateInProgress.add(agentId.dedupeKey) try { do { - this.deduplicatePending.delete(agentId.value) + this.deduplicatePending.delete(agentId.dedupeKey) const currentSession = this.sessions.get(sessionId) const candidates: { id: string; session: Session }[] = [] if (currentSession?.metadata && currentSession.metadata[agentId.field] === agentId.value) { - candidates.push({ id: sessionId, session: currentSession }) + if (agentId.field !== 'piSessionId' || currentSession.metadata.machineId === agentId.machineId) { + candidates.push({ id: sessionId, session: currentSession }) + } } for (const [existingId, existing] of this.sessions) { if (existingId === sessionId) continue if (existing.namespace !== session.namespace) continue if (!existing.metadata) continue if (existing.metadata[agentId.field] !== agentId.value) continue + if (agentId.field === 'piSessionId' && existing.metadata.machineId !== agentId.machineId) continue candidates.push({ id: existingId, session: existing }) } @@ -1493,10 +1502,10 @@ export class SessionCache { // best-effort: duplicate remains if merge fails } } - } while (this.deduplicatePending.has(agentId.value)) + } while (this.deduplicatePending.has(agentId.dedupeKey)) } finally { - this.deduplicateInProgress.delete(agentId.value) - this.deduplicatePending.delete(agentId.value) + this.deduplicateInProgress.delete(agentId.dedupeKey) + this.deduplicatePending.delete(agentId.dedupeKey) } } } diff --git a/hub/src/sync/sessionModel.test.ts b/hub/src/sync/sessionModel.test.ts index 4b885b12..8ba8bc38 100644 --- a/hub/src/sync/sessionModel.test.ts +++ b/hub/src/sync/sessionModel.test.ts @@ -3214,6 +3214,61 @@ describe('session model', () => { } }) + it('does not resume a native Pi session on a same-host machine when its recorded machine is offline', async () => { + const store = new Store(':memory:') + const engine = new SyncEngine( + store, + {} as never, + new RpcRegistry(), + { broadcast() {} } as never + ) + + try { + const session = engine.getOrCreateSession( + 'pi-offline-recorded-machine-resume', + { + path: '/remote/project', + host: 'shared-host-label', + machineId: 'recorded-machine-offline', + flavor: 'pi', + piSessionId: 'pi-native-offline', + lifecycleState: 'archived' + }, + null, + 'default' + ) + engine.getOrCreateMachine( + 'recorded-machine-offline', + { host: 'shared-host-label', platform: 'linux', happyCliVersion: '0.1.0' }, + null, + 'default' + ) + engine.getOrCreateMachine( + 'wrong-same-host-machine', + { host: 'shared-host-label', platform: 'linux', happyCliVersion: '0.1.0' }, + { status: 'running', capabilities: { piExistingSessionResume: true } }, + 'default' + ) + engine.handleMachineAlive({ machineId: 'wrong-same-host-machine', time: Date.now() }) + + let spawnCalled = false + ;(engine as any).rpcGateway.spawnSession = async () => { + spawnCalled = true + return { type: 'success', sessionId: session.id } + } + + expect(await engine.reopenSession(session.id, 'default')).toEqual({ + type: 'error', + message: 'No machine online', + code: 'no_machine_online' + }) + expect(spawnCalled).toBe(false) + expect(engine.getSession(session.id)?.metadata?.lifecycleState).toBe('archived') + } finally { + engine.stop() + } + }) + it('resumeSession fresh-spawns when inactive cursor session has no agent id and no user messages', async () => { const store = new Store(':memory:') const engine = new SyncEngine( @@ -3508,6 +3563,30 @@ describe('session model', () => { expect(cache.getSession(s2.id)).toBeDefined() }) + it('does not merge the same Pi session id across different machines', async () => { + const store = new Store(':memory:') + const events: SyncEvent[] = [] + const cache = new SessionCache(store, createPublisher(events)) + const s1 = cache.getOrCreateSession( + 'pi-tag-1', + { path: '/tmp/project', host: 'one', machineId: 'machine-1', flavor: 'pi', piSessionId: 'native-pi-id' }, + null, + 'default' + ) + const s2 = cache.getOrCreateSession( + 'pi-tag-2', + { path: '/tmp/project', host: 'two', machineId: 'machine-2', flavor: 'pi', piSessionId: 'native-pi-id' }, + null, + 'default' + ) + + await cache.deduplicateByAgentSessionId(s2.id) + + expect(cache.getSession(s1.id)).toBeDefined() + expect(cache.getSession(s2.id)).toBeDefined() + store.close() + }) + it('does not merge across namespaces', async () => { const store = new Store(':memory:') const events: SyncEvent[] = [] diff --git a/hub/src/sync/syncEngine.ts b/hub/src/sync/syncEngine.ts index baa526ac..a4b08a12 100644 --- a/hub/src/sync/syncEngine.ts +++ b/hub/src/sync/syncEngine.ts @@ -35,6 +35,7 @@ import { type RpcStatFilesResponse, type RpcListAgyModelsResponse, type RpcListCodexModelsResponse, + type RpcListPiSessionsResponse, type RpcArchiveCodexSessionResponse, type RpcListCursorModelsResponse, type RpcListOpencodeModelsResponse, @@ -66,6 +67,7 @@ export type { RpcStatFilesResponse, RpcListAgyModelsResponse, RpcListCodexModelsResponse, + RpcListPiSessionsResponse, RpcListCursorModelsResponse, RpcListOpencodeModelsResponse, RpcListGrokModelsResponse, @@ -2690,7 +2692,7 @@ async uploadScratchlistAttachment( const targetMachine = this.resolveOnlineMachineForSession( session, namespace, - { strictMachineId: flavor === 'cursor' } + { strictMachineId: flavor === 'cursor' || (flavor === 'pi' && resumeToken !== undefined) } ) if (!targetMachine) { return { type: 'error', message: 'No machine online', code: 'no_machine_online' } @@ -3730,6 +3732,10 @@ async uploadScratchlistAttachment( return await this.rpcGateway.listCodexSessionsForMachine(machineId, cwd, sessionIds) } + async listPiSessionsForMachine(machineId: string, cwd?: string | null, sessionIds?: string[]): Promise { + return await this.rpcGateway.listPiSessionsForMachine(machineId, cwd, sessionIds) + } + async archiveCodexSessionForMachine(machineId: string, sessionId: string): Promise { return await this.rpcGateway.archiveCodexSessionForMachine(machineId, sessionId) } diff --git a/hub/src/web/routes/piSessions.test.ts b/hub/src/web/routes/piSessions.test.ts new file mode 100644 index 00000000..2d356134 --- /dev/null +++ b/hub/src/web/routes/piSessions.test.ts @@ -0,0 +1,338 @@ +import { afterEach, describe, expect, it, spyOn } from 'bun:test' +import { Hono } from 'hono' +import type { PiLocalSessionSummary, PiLocalSessionWithMessages } from '@hapi/protocol/apiTypes' +import { Store } from '../../store' +import type { Machine, SyncEngine } from '../../sync/syncEngine' +import type { WebAppEnv } from '../middleware/auth' +import { createPiSessionRoutes, importPiSession } from './piSessions' + +function machine(id: string): Machine { + return { + id, + namespace: 'default', + seq: 1, + createdAt: 1, + updatedAt: 1, + active: true, + activeAt: 1, + metadata: { + host: `${id}.local`, + platform: 'darwin', + happyCliVersion: 'test' + }, + metadataVersion: 1, + runnerState: null, + runnerStateVersion: 1, + health: null + } +} + +function userMessage(sessionId: string, entryId: string, parentEntryId: string | null, text: string, createdAt: number) { + return { + localId: `pi:${sessionId}:${entryId}:user`, + entryId, + parentEntryId, + createdAt, + content: { + role: 'user' as const, + content: { type: 'text' as const, text }, + meta: { sentFrom: 'cli' as const } + } + } +} + +function toolResultMessage(sessionId: string, entryId: string, parentEntryId: string | null, output: string, createdAt: number) { + return { + localId: `pi:${sessionId}:${entryId}:tool-result`, + entryId, + parentEntryId, + createdAt, + content: { + role: 'agent' as const, + content: { + type: 'codex' as const, + data: { type: 'tool-call-result', callId: 'tool-1', output, is_error: false } + }, + meta: { sentFrom: 'cli' as const } + } + } +} + +function transcript( + sessionId: string, + entries: Array | ReturnType>, + activeEntryIds = entries.map((entry) => entry.entryId) +): PiLocalSessionWithMessages { + const lastUser = [...entries].reverse().find((entry) => entry.content.role === 'user') + return { + id: sessionId, + title: `Session ${sessionId}`, + lastUserMessage: lastUser?.content.role === 'user' ? lastUser.content.content.text : null, + cwd: '/tmp/project', + file: `/tmp/${sessionId}.jsonl`, + modifiedAt: entries.at(-1)?.createdAt ?? 1, + model: 'gpt-5.6', + thinkingLevel: 'high', + leafEntryId: activeEntryIds.at(-1) ?? null, + messageCount: entries.length, + messages: entries, + activeEntryIds + } +} + +describe('Pi session import', () => { + const stores: Store[] = [] + + afterEach(() => { + for (const store of stores.splice(0)) store.close() + }) + + function setup() { + const store = new Store(':memory:') + stores.push(store) + const events: unknown[] = [] + const engine = { + recordSessionActivity: (sessionId: string, updatedAt: number) => { + store.sessions.touchSessionUpdatedAt(sessionId, updatedAt, 'default') + }, + handleRealtimeEvent: (event: unknown) => events.push(event) + } as unknown as SyncEngine + return { store, engine, events } + } + + it('loads imported sessions once when listing multiple Pi summaries', async () => { + const { store } = setup() + const selectedMachine = machine('machine-1') + const imported = store.sessions.getOrCreateSession('imported-native-1', { + flavor: 'pi', + machineId: selectedMachine.id, + piSessionId: 'native-1', + piImportState: { state: 'complete' } + }, {}, 'default') + const summaries: PiLocalSessionSummary[] = [ + transcript('native-1', []), + transcript('native-2', []) + ] + const engine = { + getOnlineMachinesByNamespace: () => [selectedMachine], + listPiSessionsForMachine: async () => ({ success: true, sessions: summaries }) + } as unknown as SyncEngine + const getSessionsSpy = spyOn(store.sessions, 'getSessionsByNamespace') + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + app.route('/api', createPiSessionRoutes({ store, getSyncEngine: () => engine })) + + const response = await app.request('/api/pi/sessions?machineId=machine-1') + + expect(response.status).toBe(200) + expect(await response.json()).toMatchObject({ + success: true, + sessions: [ + { id: 'native-1', hapiSessionId: imported.id, importState: 'complete' }, + { id: 'native-2' } + ] + }) + expect(getSessionsSpy).toHaveBeenCalledTimes(1) + }) + + it('loads imported sessions once for a deduplicated batch import', async () => { + const { store } = setup() + const selectedMachine = machine('machine-1') + const transcripts = [ + transcript('native-batch-1', [userMessage('native-batch-1', 'entry-1', null, 'one', 1_000)]), + transcript('native-batch-2', [userMessage('native-batch-2', 'entry-1', null, 'two', 2_000)]) + ] + let requestedIds: string[] | undefined + const engine = { + getOnlineMachinesByNamespace: () => [selectedMachine], + listPiSessionsForMachine: async (_machineId: string, _cwd: string | null, sessionIds?: string[]) => { + requestedIds = sessionIds + return { success: true, sessions: transcripts } + }, + recordSessionActivity: (sessionId: string, updatedAt: number) => { + store.sessions.touchSessionUpdatedAt(sessionId, updatedAt, 'default') + }, + handleRealtimeEvent: () => {} + } as unknown as SyncEngine + const getSessionsSpy = spyOn(store.sessions, 'getSessionsByNamespace') + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + app.route('/api', createPiSessionRoutes({ store, getSyncEngine: () => engine })) + + const response = await app.request('/api/pi/import-sessions', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + machineId: selectedMachine.id, + sessionIds: ['native-batch-1', 'native-batch-2', 'native-batch-1'] + }) + }) + + expect(response.status).toBe(200) + expect(requestedIds).toEqual(['native-batch-1', 'native-batch-2']) + expect(await response.json()).toMatchObject({ + success: true, + results: [ + { piSessionId: 'native-batch-1', action: 'created' }, + { piSessionId: 'native-batch-2', action: 'created' } + ] + }) + expect(getSessionsSpy).toHaveBeenCalledTimes(1) + }) + + it('imports idempotently and appends only entries after the persisted native leaf', () => { + const { store, engine } = setup() + const first = transcript('native-1', [ + userMessage('native-1', 'entry-1', null, 'one', 1_000) + ]) + const initial = importPiSession({ store, engine, namespace: 'default', machine: machine('machine-1'), transcript: first }) + expect(initial).toMatchObject({ action: 'created', appended: 1 }) + expect(store.messages.getAllMessages(initial.hapiSessionId!)[0]).toMatchObject({ + localId: 'pi:native-1:entry-1:user', + invokedAt: 1_000 + }) + + const unchanged = importPiSession({ store, engine, namespace: 'default', machine: machine('machine-1'), transcript: first }) + expect(unchanged).toMatchObject({ hapiSessionId: initial.hapiSessionId, action: 'unchanged', appended: 0 }) + + const extended = transcript('native-1', [ + userMessage('native-1', 'entry-1', null, 'one', 1_000), + userMessage('native-1', 'entry-2', 'entry-1', 'two', 2_000) + ]) + const updated = importPiSession({ store, engine, namespace: 'default', machine: machine('machine-1'), transcript: extended }) + expect(updated).toMatchObject({ hapiSessionId: initial.hapiSessionId, action: 'updated', appended: 1 }) + expect(store.messages.getAllMessages(initial.hapiSessionId!)).toHaveLength(2) + const metadata = store.sessions.getSession(initial.hapiSessionId!)?.metadata as Record + expect(metadata.piHistoryLeafEntryId).toBe('entry-2') + expect(metadata.conversationHistoryEntryIds).toMatchObject({ + 'pi:native-1:entry-1:user': 'entry-1', + 'pi:native-1:entry-2:user': 'entry-2' + }) + }) + + it('keeps the same native Pi id separate on different machines', () => { + const { store, engine } = setup() + const source = transcript('same-native-id', [userMessage('same-native-id', 'entry-1', null, 'one', 1_000)]) + const first = importPiSession({ store, engine, namespace: 'default', machine: machine('machine-1'), transcript: source }) + const second = importPiSession({ store, engine, namespace: 'default', machine: machine('machine-2'), transcript: source }) + + expect(first.hapiSessionId).not.toBe(second.hapiSessionId) + expect(store.sessions.getSessionsByNamespace('default')).toHaveLength(2) + }) + + it('preserves a custom HAPI session name during later Pi reconciliation', () => { + const { store, engine } = setup() + const source = transcript('native-renamed', [userMessage('native-renamed', 'entry-1', null, 'one', 1_000)]) + const first = importPiSession({ store, engine, namespace: 'default', machine: machine('machine-1'), transcript: source }) + const stored = store.sessions.getSession(first.hapiSessionId!)! + store.sessions.updateSessionMetadata( + stored.id, + { ...(stored.metadata as Record), name: 'My custom HAPI title' }, + stored.metadataVersion, + 'default' + ) + + const extended = transcript('native-renamed', [ + userMessage('native-renamed', 'entry-1', null, 'one', 1_000), + userMessage('native-renamed', 'entry-2', 'entry-1', 'two', 2_000) + ]) + const result = importPiSession({ store, engine, namespace: 'default', machine: machine('machine-1'), transcript: extended }) + + expect(result.error).toBeUndefined() + expect((store.sessions.getSession(stored.id)?.metadata as { name?: string }).name).toBe('My custom HAPI title') + }) + + it('keeps a mid-transcript incremental import idempotent and rebuilds missing user locators', () => { + const { store, engine } = setup() + const source = transcript('native-mid', [ + userMessage('native-mid', 'entry-1', null, 'one', 1_000), + userMessage('native-mid', 'entry-2', 'entry-1', 'two', 2_000) + ]) + const existing = store.sessions.getOrCreateSession('existing-mid', { + path: '/tmp/project', + host: 'machine-1.local', + machineId: 'machine-1', + flavor: 'pi', + piSessionId: 'native-mid', + piHistoryLeafEntryId: 'entry-1' + }, {}, 'default') + + const first = importPiSession({ store, engine, namespace: 'default', machine: machine('machine-1'), transcript: source }) + expect(first).toMatchObject({ hapiSessionId: existing.id, action: 'updated', appended: 1 }) + const second = importPiSession({ store, engine, namespace: 'default', machine: machine('machine-1'), transcript: source }) + expect(second).toMatchObject({ hapiSessionId: existing.id, action: 'unchanged', appended: 0 }) + expect(second.error).toBeUndefined() + expect((store.sessions.getSession(existing.id)?.metadata as { conversationHistoryEntryIds?: Record }).conversationHistoryEntryIds).toMatchObject({ + 'pi:native-mid:entry-2:user': 'entry-2' + }) + }) + + it('rebuilds locators for messages persisted before a failed metadata finalize', () => { + const { store, engine } = setup() + const source = transcript('native-retry', [ + userMessage('native-retry', 'entry-1', null, 'one', 1_000), + userMessage('native-retry', 'entry-2', 'entry-1', 'two', 2_000) + ]) + const existing = store.sessions.getOrCreateSession('existing-retry', { + path: '/tmp/project', host: 'machine-1.local', machineId: 'machine-1', flavor: 'pi', piSessionId: 'native-retry' + }, {}, 'default') + store.messages.addImportedMessage(existing.id, source.messages[0]!.content, source.messages[0]!.localId, 1_000) + + const result = importPiSession({ store, engine, namespace: 'default', machine: machine('machine-1'), transcript: source }) + expect(result).toMatchObject({ action: 'updated', appended: 1 }) + expect((store.sessions.getSession(existing.id)?.metadata as { conversationHistoryEntryIds?: Record }).conversationHistoryEntryIds).toMatchObject({ + 'pi:native-retry:entry-1:user': 'entry-1', + 'pi:native-retry:entry-2:user': 'entry-2' + }) + }) + + it('compares oversized imported content using the persisted truncation form', () => { + const { store, engine } = setup() + const source = transcript('native-large', [toolResultMessage('native-large', 'entry-1', null, 'x'.repeat(70_000), 1_000)]) + const first = importPiSession({ store, engine, namespace: 'default', machine: machine('machine-1'), transcript: source }) + const second = importPiSession({ store, engine, namespace: 'default', machine: machine('machine-1'), transcript: source }) + + expect(first).toMatchObject({ action: 'created', appended: 1 }) + expect(second).toMatchObject({ action: 'unchanged', appended: 0 }) + expect(second.error).toBeUndefined() + }) + + it('marks the import diverged when the active branch drops or rewrites imported history', () => { + const { store, engine } = setup() + const source = transcript('native-diverged', [userMessage('native-diverged', 'entry-1', null, 'one', 1_000)]) + const first = importPiSession({ store, engine, namespace: 'default', machine: machine('machine-1'), transcript: source }) + + const rewritten = transcript('native-diverged', [ + userMessage('native-diverged', 'entry-1', null, 'changed', 1_000) + ]) + const result = importPiSession({ store, engine, namespace: 'default', machine: machine('machine-1'), transcript: rewritten }) + expect(result.error?.code).toBe('transcript_diverged') + expect((store.sessions.getSession(first.hapiSessionId!)?.metadata as { piImportState?: { state?: string } }).piImportState?.state).toBe('diverged') + }) + + it('does not interleave new imported entries into an active HAPI session', () => { + const { store, engine } = setup() + const first = importPiSession({ + store, + engine, + namespace: 'default', + machine: machine('machine-1'), + transcript: transcript('native-active', [userMessage('native-active', 'entry-1', null, 'one', 1_000)]) + }) + store.sessions.setSessionActive(first.hapiSessionId!, true, 2_000, 'default') + const extended = transcript('native-active', [ + userMessage('native-active', 'entry-1', null, 'one', 1_000), + userMessage('native-active', 'entry-2', 'entry-1', 'two', 2_000) + ]) + + const result = importPiSession({ store, engine, namespace: 'default', machine: machine('machine-1'), transcript: extended }) + expect(result.error?.code).toBe('session_active') + expect(store.messages.getAllMessages(first.hapiSessionId!)).toHaveLength(1) + }) +}) diff --git a/hub/src/web/routes/piSessions.ts b/hub/src/web/routes/piSessions.ts new file mode 100644 index 00000000..a622f5e6 --- /dev/null +++ b/hub/src/web/routes/piSessions.ts @@ -0,0 +1,419 @@ +import { dirname } from 'node:path' +import { isDeepStrictEqual } from 'node:util' +import { Hono } from 'hono' +import type { PiLocalSessionSummary, PiLocalSessionWithMessages } from '@hapi/protocol/apiTypes' +import type { Metadata } from '@hapi/protocol/types' +import type { Store, StoredMessage, StoredSession } from '../../store' +import { ImportedMessageConflictError } from '../../store/messages' +import { truncateOversizedMessageContent } from '../../store/contentCodec' +import type { Machine, SyncEngine } from '../../sync/syncEngine' +import type { WebAppEnv } from '../middleware/auth' + +const importLocks = new Map>() + +export type PiSessionListItem = PiLocalSessionSummary & { + hapiSessionId?: string + importState?: 'importing' | 'complete' | 'failed' | 'diverged' +} + +export type PiImportResult = { + piSessionId: string + hapiSessionId?: string + action?: 'created' | 'updated' | 'unchanged' + appended?: number + error?: { code: string; message: string } +} + +function asRecord(value: unknown): Record | null { + return value !== null && typeof value === 'object' && !Array.isArray(value) + ? value as Record + : null +} + +function storedMetadata(session: StoredSession): Record { + return asRecord(session.metadata) ?? {} +} + +function resolvePiMachine( + engine: SyncEngine | null, + namespace: string, + requestedMachineId?: string | null +): Machine | null { + if (!engine) return null + const online = engine.getOnlineMachinesByNamespace(namespace) + if (requestedMachineId) return online.find((machine) => machine.id === requestedMachineId) ?? null + return online[0] ?? null +} + +function findImportedPiSession( + store: Store, + namespace: string, + machineId: string, + piSessionId: string +): StoredSession | null { + return importedPiSessionsById(store, namespace, machineId).get(piSessionId) ?? null +} + +function importedPiSessionsById( + store: Store, + namespace: string, + machineId: string +): Map { + const importedByPiId = new Map() + for (const session of store.sessions.getSessionsByNamespace(namespace)) { + const metadata = storedMetadata(session) + const piSessionId = metadata.piSessionId + if (metadata.flavor !== 'pi' + || metadata.machineId !== machineId + || typeof piSessionId !== 'string' + || importedByPiId.has(piSessionId)) continue + importedByPiId.set(piSessionId, session) + } + return importedByPiId +} + +function buildPiMetadata( + transcript: PiLocalSessionWithMessages, + machine: Machine, + existing: Record, + state: NonNullable +): Metadata { + const summaryText = transcript.lastUserMessage ?? transcript.title + const entryIds = asRecord(existing.conversationHistoryEntryIds) ?? {} + const points = asRecord(existing.conversationHistoryPoints) ?? {} + return { + ...existing, + path: transcript.cwd ?? (typeof existing.path === 'string' ? existing.path : dirname(transcript.file)), + host: typeof existing.host === 'string' ? existing.host : (machine.metadata?.host ?? machine.id), + os: typeof existing.os === 'string' ? existing.os : (machine.metadata?.platform ?? process.platform), + name: typeof existing.name === 'string' ? existing.name : transcript.title, + summary: summaryText ? { text: summaryText, updatedAt: Date.now() } : undefined, + machineId: machine.id, + flavor: 'pi', + piSessionId: transcript.id, + lifecycleState: typeof existing.lifecycleState === 'string' ? existing.lifecycleState : 'archived', + lifecycleStateSince: typeof existing.lifecycleStateSince === 'number' ? existing.lifecycleStateSince : Date.now(), + archivedBy: typeof existing.archivedBy === 'string' ? existing.archivedBy : 'pi-import', + archiveReason: typeof existing.archiveReason === 'string' ? existing.archiveReason : 'Imported from local Pi history', + conversationHistoryEntryIds: entryIds as Record, + conversationHistoryPoints: points as Record, + piImportState: state + } +} + +function updateMetadataWithRetry( + store: Store, + sessionId: string, + namespace: string, + transform: (metadata: Record) => Metadata +): Metadata { + for (let attempt = 0; attempt < 5; attempt += 1) { + const current = store.sessions.getSessionByNamespace(sessionId, namespace) + if (!current) throw new Error('Imported HAPI session disappeared') + const next = transform(storedMetadata(current)) + const result = store.sessions.updateSessionMetadata( + sessionId, + next, + current.metadataVersion, + namespace, + { touchUpdatedAt: false } + ) + if (result.result === 'success') return next + if (result.result === 'error') throw new Error('Failed to persist Pi import metadata') + } + throw new Error('Pi import metadata changed concurrently') +} + +function emitImportedMessages(engine: SyncEngine, sessionId: string, messages: StoredMessage[]): void { + for (const message of messages) { + engine.handleRealtimeEvent({ + type: 'message-received', + sessionId, + message: { + id: message.id, + seq: message.seq, + localId: message.localId, + content: message.content, + createdAt: message.createdAt, + invokedAt: message.invokedAt + } + }) + } +} + +function importedPrefix(sessionId: string): string { + return `pi:${sessionId}:` +} + +function classifyImportDelta( + existing: StoredMessage[], + transcript: PiLocalSessionWithMessages, + observedLeafId: string | null +): { messages: PiLocalSessionWithMessages['messages']; error?: string } { + const sourceLocalIds = transcript.messages.map((message) => message.localId) + const sourceIndexByLocalId = new Map(sourceLocalIds.map((localId, index) => [localId, index])) + const storedImported = existing + .filter((message) => message.localId?.startsWith(importedPrefix(transcript.id))) + let priorSourceIndex = -1 + for (const message of storedImported) { + const sourceIndex = sourceIndexByLocalId.get(message.localId!) + if (sourceIndex === undefined || sourceIndex <= priorSourceIndex) { + return { messages: [], error: 'Local Pi transcript no longer extends the previously imported history' } + } + priorSourceIndex = sourceIndex + } + const sourceByLocalId = new Map(transcript.messages.map((message) => [ + message.localId, + truncateOversizedMessageContent(message.content) + ])) + const changed = storedImported.find((message) => !isDeepStrictEqual(sourceByLocalId.get(message.localId!), message.content)) + if (changed?.localId) { + return { messages: [], error: `Local Pi transcript changed imported entry ${changed.localId}` } + } + if (!observedLeafId) { + const imported = new Set(storedImported.map((message) => message.localId!)) + return { messages: transcript.messages.filter((message) => !imported.has(message.localId)) } + } + const leafIndex = transcript.activeEntryIds.indexOf(observedLeafId) + if (leafIndex === -1) { + return { messages: [], error: 'The active Pi branch no longer contains the last imported entry' } + } + const newEntryIds = new Set(transcript.activeEntryIds.slice(leafIndex + 1)) + return { messages: transcript.messages.filter((message) => newEntryIds.has(message.entryId)) } +} + +function markImportState( + store: Store, + engine: SyncEngine, + sessionId: string, + namespace: string, + transcript: PiLocalSessionWithMessages, + machineId: string, + state: 'failed' | 'diverged', + error: string +): void { + const current = store.sessions.getSessionByNamespace(sessionId, namespace) + const currentImportState = asRecord(asRecord(current?.metadata)?.piImportState) + const startedAt = typeof currentImportState?.startedAt === 'number' ? currentImportState.startedAt : Date.now() + updateMetadataWithRetry(store, sessionId, namespace, (metadata) => ({ + ...metadata, + path: typeof metadata.path === 'string' ? metadata.path : (transcript.cwd ?? dirname(transcript.file)), + host: typeof metadata.host === 'string' ? metadata.host : machineId, + piImportState: { + state, + machineId, + piSessionId: transcript.id, + sourceFile: transcript.file, + startedAt, + updatedAt: Date.now(), + leafEntryId: transcript.leafEntryId ?? null, + error + } + } as Metadata)) + engine.handleRealtimeEvent({ type: 'session-updated', sessionId }) +} + +export function importPiSession(options: { + store: Store + engine: SyncEngine + namespace: string + machine: Machine + transcript: PiLocalSessionWithMessages + existingSession?: StoredSession | null +}): PiImportResult { + const { store, engine, namespace, machine, transcript, existingSession } = options + const startedAt = Date.now() + let stored = existingSession === undefined + ? findImportedPiSession(store, namespace, machine.id, transcript.id) + : existingSession + const created = !stored + if (!stored) { + const metadata = buildPiMetadata(transcript, machine, {}, { + state: 'importing', + machineId: machine.id, + piSessionId: transcript.id, + sourceFile: transcript.file, + startedAt, + updatedAt: startedAt, + leafEntryId: transcript.leafEntryId ?? null + }) + stored = store.sessions.getOrCreateSession( + `pi-import:${machine.id}:${transcript.id}`, + metadata, + {}, + namespace, + transcript.model ?? undefined, + transcript.thinkingLevel ?? undefined + ) + } else { + updateMetadataWithRetry(store, stored.id, namespace, (metadata) => buildPiMetadata(transcript, machine, metadata, { + state: 'importing', + machineId: machine.id, + piSessionId: transcript.id, + sourceFile: transcript.file, + startedAt, + updatedAt: startedAt, + leafEntryId: transcript.leafEntryId ?? null + })) + } + + const currentMetadata = storedMetadata(store.sessions.getSessionByNamespace(stored.id, namespace) ?? stored) + const observedLeafId = typeof currentMetadata.piHistoryLeafEntryId === 'string' + ? currentMetadata.piHistoryLeafEntryId + : null + const delta = classifyImportDelta(store.messages.getAllMessages(stored.id), transcript, observedLeafId) + if (delta.error) { + markImportState(store, engine, stored.id, namespace, transcript, machine.id, 'diverged', delta.error) + return { piSessionId: transcript.id, hapiSessionId: stored.id, error: { code: 'transcript_diverged', message: delta.error } } + } + if (stored.active && delta.messages.length > 0) { + const message = 'The HAPI Pi session is active; stop it before importing native history changes' + markImportState(store, engine, stored.id, namespace, transcript, machine.id, 'failed', message) + return { piSessionId: transcript.id, hapiSessionId: stored.id, error: { code: 'session_active', message } } + } + + const appended: StoredMessage[] = [] + try { + for (const source of delta.messages) { + const result = store.messages.addImportedMessage(stored.id, source.content, source.localId, source.createdAt) + if (result.inserted) appended.push(result.message) + } + } catch (error) { + const message = error instanceof Error ? error.message : 'Failed to persist imported Pi history' + const state = error instanceof ImportedMessageConflictError ? 'diverged' : 'failed' + markImportState(store, engine, stored.id, namespace, transcript, machine.id, state, message) + return { + piSessionId: transcript.id, + hapiSessionId: stored.id, + error: { code: state === 'diverged' ? 'transcript_diverged' : 'import_failed', message } + } + } + + const persistedLocalIds = new Set(store.messages.getAllMessages(stored.id) + .map((message) => message.localId) + .filter((localId): localId is string => Boolean(localId))) + try { + updateMetadataWithRetry(store, stored.id, namespace, (metadata) => { + const entryIds = { ...(asRecord(metadata.conversationHistoryEntryIds) ?? {}) } as Record + const points = { ...(asRecord(metadata.conversationHistoryPoints) ?? {}) } as Record + for (const source of transcript.messages) { + if (source.content.role !== 'user' || !persistedLocalIds.has(source.localId)) continue + entryIds[source.localId] = source.entryId + points[source.localId] = true + } + return { + ...buildPiMetadata(transcript, machine, metadata, { + state: 'complete', + machineId: machine.id, + piSessionId: transcript.id, + sourceFile: transcript.file, + startedAt, + updatedAt: Date.now(), + leafEntryId: transcript.leafEntryId ?? null + }), + conversationHistoryEntryIds: entryIds, + conversationHistoryPoints: points, + ...(transcript.leafEntryId ? { piHistoryLeafEntryId: transcript.leafEntryId } : {}) + } + }) + } catch (error) { + const message = error instanceof Error ? error.message : 'Failed to finalize imported Pi history' + try { markImportState(store, engine, stored.id, namespace, transcript, machine.id, 'failed', message) } catch {} + return { piSessionId: transcript.id, hapiSessionId: stored.id, error: { code: 'import_failed', message } } + } + if (transcript.model !== undefined) store.sessions.setSessionModel(stored.id, transcript.model ?? null, namespace, { touchUpdatedAt: false }) + if (transcript.thinkingLevel !== undefined) store.sessions.setSessionEffort(stored.id, transcript.thinkingLevel ?? null, namespace, { touchUpdatedAt: false }) + const activityAt = appended.at(-1)?.createdAt ?? transcript.modifiedAt + engine.recordSessionActivity(stored.id, activityAt) + emitImportedMessages(engine, stored.id, appended) + engine.handleRealtimeEvent({ type: 'session-updated', sessionId: stored.id }) + return { + piSessionId: transcript.id, + hapiSessionId: stored.id, + action: created ? 'created' : appended.length > 0 ? 'updated' : 'unchanged', + appended: appended.length + } +} + +async function importWithLock(key: string, work: () => PiImportResult): Promise { + const prior = importLocks.get(key) + if (prior) return prior + const current = Promise.resolve().then(work) + importLocks.set(key, current) + try { + return await current + } finally { + if (importLocks.get(key) === current) importLocks.delete(key) + } +} + +export function createPiSessionRoutes(options: { + store: Store + getSyncEngine: () => SyncEngine | null +}): Hono { + const app = new Hono() + + app.get('/pi/sessions', async (c) => { + const namespace = c.get('namespace') + const machine = resolvePiMachine(options.getSyncEngine(), namespace, c.req.query('machineId')?.trim() || null) + if (!machine) return c.json({ success: false, error: 'No online machine available for Pi history import', sessions: [] }, 503) + const result = await options.getSyncEngine()!.listPiSessionsForMachine(machine.id, c.req.query('cwd')?.trim() || null) + if (!result.success) return c.json({ success: false, error: result.error, sessions: [], machineId: machine.id }, 503) + const importedByPiId = importedPiSessionsById(options.store, namespace, machine.id) + const sessions: PiSessionListItem[] = result.sessions.map((summary) => { + const imported = importedByPiId.get(summary.id) + const metadata = imported ? storedMetadata(imported) : null + const importState = asRecord(metadata?.piImportState)?.state + return { + ...summary, + ...(imported ? { hapiSessionId: imported.id } : {}), + ...(importState === 'importing' || importState === 'complete' || importState === 'failed' || importState === 'diverged' + ? { importState } + : {}) + } + }) + return c.json({ success: true, sessions, machineId: machine.id }) + }) + + app.post('/pi/import-sessions', async (c) => { + const body = asRecord(await c.req.json().catch(() => null)) + const sessionIds = Array.isArray(body?.sessionIds) + ? body.sessionIds.filter((id): id is string => typeof id === 'string' && id.trim().length > 0).map((id) => id.trim()) + : [] + if (sessionIds.length === 0) return c.json({ success: false, error: 'No Pi sessions selected', results: [] }, 400) + const uniqueSessionIds = [...new Set(sessionIds)] + const namespace = c.get('namespace') + const engine = options.getSyncEngine() + const machine = resolvePiMachine(engine, namespace, typeof body?.machineId === 'string' ? body.machineId.trim() : null) + if (!engine || !machine) return c.json({ success: false, error: 'No online machine available for Pi history import', results: [] }, 503) + const remote = await engine.listPiSessionsForMachine( + machine.id, + typeof body?.cwd === 'string' ? body.cwd.trim() : null, + uniqueSessionIds + ) + if (!remote.success) return c.json({ success: false, error: remote.error, results: [], machineId: machine.id }, 503) + const byId = new Map(remote.sessions + .filter((session): session is PiLocalSessionWithMessages => 'messages' in session) + .map((session) => [session.id, session])) + const importedByPiId = importedPiSessionsById(options.store, namespace, machine.id) + const results: PiImportResult[] = [] + for (const sessionId of uniqueSessionIds) { + const transcript = byId.get(sessionId) + if (!transcript) { + results.push({ piSessionId: sessionId, error: { code: 'not_found', message: 'Pi session transcript not found' } }) + continue + } + results.push(await importWithLock(`${namespace}:${machine.id}:${sessionId}`, () => importPiSession({ + store: options.store, + engine, + namespace, + machine, + transcript, + existingSession: importedByPiId.get(sessionId) ?? null + }))) + } + return c.json({ success: results.every((result) => !result.error), results, machineId: machine.id }) + }) + + return app +} diff --git a/hub/src/web/server.ts b/hub/src/web/server.ts index 79a629c4..e838ec17 100644 --- a/hub/src/web/server.ts +++ b/hub/src/web/server.ts @@ -24,6 +24,7 @@ import { createUsageRoutes } from './routes/usage' import { createGitRoutes } from './routes/git' import { createCliRoutes } from './routes/cli' import { createCodexDesktopRoutes } from './routes/codexDesktop' +import { createPiSessionRoutes } from './routes/piSessions' import { createPushRoutes } from './routes/push' import { createDevicesRoutes } from './routes/devices' import { createVoiceRoutes } from './routes/voice' @@ -284,6 +285,10 @@ function createWebApp(options: { store: options.store, getSyncEngine: options.getSyncEngine })) + app.route('/api', createPiSessionRoutes({ + store: options.store, + getSyncEngine: options.getSyncEngine + })) app.route('/api', createPushRoutes(options.store, options.vapidPublicKey)) app.route('/api', createDevicesRoutes(options.store)) app.route('/api', createVoiceRoutes()) diff --git a/shared/src/apiTypes.test.ts b/shared/src/apiTypes.test.ts index 8abd5933..95eaca2e 100644 --- a/shared/src/apiTypes.test.ts +++ b/shared/src/apiTypes.test.ts @@ -3,6 +3,7 @@ import { ClearOpencodeSessionCallbackRequestSchema, ClearOpencodeSessionResponseSchema, ListCodexSessionsRpcResponseSchema, + ListPiSessionsRpcResponseSchema, MessagesQuerySchema, SendMessageRequestSchema } from './apiTypes' @@ -36,6 +37,36 @@ describe('ListCodexSessionsRpcResponseSchema', () => { }) }) +describe('ListPiSessionsRpcResponseSchema', () => { + it('preserves stable Pi entry and local ids', () => { + const parsed = ListPiSessionsRpcResponseSchema.parse({ + success: true, + sessions: [{ + id: 'pi-session-id', + title: 'Pi Session', + file: '/home/user/.pi/agent/sessions/session.jsonl', + modifiedAt: 1_000, + messageCount: 1, + activeEntryIds: ['entry-1'], + messages: [{ + localId: 'pi:pi-session-id:entry-1:user', + entryId: 'entry-1', + parentEntryId: null, + createdAt: 900, + content: { + role: 'user', + content: { type: 'text', text: 'hello' }, + meta: { sentFrom: 'cli' } + } + }] + }] + }) + + expect(parsed.success).toBe(true) + if (parsed.success) expect(parsed.sessions[0]?.messages?.[0]?.entryId).toBe('entry-1') + }) +}) + describe('ClearOpencodeSessionResponseSchema', () => { it('requires the new HAPI session identity', () => { expect(ClearOpencodeSessionResponseSchema.parse({ ok: true, sessionId: 'fresh-session' })).toEqual({ diff --git a/shared/src/apiTypes.ts b/shared/src/apiTypes.ts index 9f2e42d6..f53a86d7 100644 --- a/shared/src/apiTypes.ts +++ b/shared/src/apiTypes.ts @@ -197,6 +197,51 @@ export type ListCodexSessionsRpcResponse = z.infer export type ArchiveCodexSessionRpcResponse = z.infer +export const PiImportedMessageContentSchema = CodexImportedMessageSchema + +export const PiImportedMessageSchema = z.object({ + localId: z.string().min(1), + entryId: z.string().min(1), + parentEntryId: z.string().nullable().optional(), + createdAt: z.number(), + content: PiImportedMessageContentSchema +}) + +export const PiLocalSessionSummarySchema = z.object({ + id: z.string().min(1), + title: z.string(), + lastUserMessage: z.string().nullable().optional(), + cwd: z.string().nullable().optional(), + file: z.string().min(1), + modifiedAt: z.number(), + model: z.string().nullable().optional(), + thinkingLevel: z.string().nullable().optional(), + leafEntryId: z.string().nullable().optional(), + messageCount: z.number().int().nonnegative() +}) + +export const PiLocalSessionWithMessagesSchema = PiLocalSessionSummarySchema.extend({ + messages: z.array(PiImportedMessageSchema), + activeEntryIds: z.array(z.string().min(1)) +}) + +export const ListPiSessionsRpcRequestSchema = z.object({ + cwd: z.string().nullable().optional(), + sessionIds: z.array(z.string().min(1)).optional() +}) + +export const ListPiSessionsRpcResponseSchema = z.union([ + z.object({ success: z.literal(true), sessions: z.array(z.union([PiLocalSessionWithMessagesSchema, PiLocalSessionSummarySchema])) }), + z.object({ success: z.literal(false), error: z.string() }) +]) + +export type PiImportedMessageContent = z.infer +export type PiImportedMessage = z.infer +export type PiLocalSessionSummary = z.infer +export type PiLocalSessionWithMessages = z.infer +export type ListPiSessionsRpcRequest = z.infer +export type ListPiSessionsRpcResponse = z.infer + export const SessionCollaborationModeRequestSchema = z.object({ mode: CodexCollaborationModeSchema }) diff --git a/shared/src/rpcMethods.ts b/shared/src/rpcMethods.ts index 456ba281..120eddce 100644 --- a/shared/src/rpcMethods.ts +++ b/shared/src/rpcMethods.ts @@ -32,6 +32,7 @@ export const RPC_METHODS = { ArchiveCodexSession: 'archiveCodexSession', ListCursorModels: 'listCursorModels', ListPiModels: 'listPiModels', + ListPiSessions: 'listPiSessions', ListOpencodeModels: 'listOpencodeModels', ListOpencodeModelsForCwd: 'listOpencodeModelsForCwd', ListGrokModelsForCwd: 'listGrokModelsForCwd', diff --git a/shared/src/schemas.ts b/shared/src/schemas.ts index 4f1596f7..ace0208a 100644 --- a/shared/src/schemas.ts +++ b/shared/src/schemas.ts @@ -135,6 +135,19 @@ export const MetadataSchema = z.object({ // Pi localId → append-only session entry id mapping. Pi entry ids are the // only stable native boundary accepted by its fork API. conversationHistoryEntryIds: z.record(z.string(), z.string().min(1)).optional(), + // Latest Pi append-log entry observed by HAPI. Import uses it as the + // incremental cursor so native history already streamed live is not copied twice. + piHistoryLeafEntryId: z.string().optional(), + piImportState: z.object({ + state: z.enum(['importing', 'complete', 'failed', 'diverged']), + machineId: z.string(), + piSessionId: z.string(), + sourceFile: z.string(), + startedAt: z.number(), + updatedAt: z.number(), + leafEntryId: z.string().nullable().optional(), + error: z.string().optional() + }).optional(), // Set when native rewind succeeded but HAPI truncate/hydrate failed. conversationHistoryDiverged: z.boolean().optional(), worktree: WorktreeMetadataSchema.optional(), diff --git a/web/src/api/client.test.ts b/web/src/api/client.test.ts index 35d798aa..576770e1 100644 --- a/web/src/api/client.test.ts +++ b/web/src/api/client.test.ts @@ -93,6 +93,23 @@ describe('ApiClient error mapping', () => { expect(fetchMock.mock.calls[0]?.[0]).toBe('/api/sessions/session%20cursor/cursor-chat-store') }) + it('lists and imports Pi sessions through the selected machine', async () => { + fetchMock + .mockResolvedValueOnce(new Response(JSON.stringify({ success: true, sessions: [], machineId: 'machine-1' }), { status: 200 })) + .mockResolvedValueOnce(new Response(JSON.stringify({ success: true, results: [], machineId: 'machine-1' }), { status: 200 })) + const api = new ApiClient('test-token') + + await api.getPiSessions('/tmp/project', 'machine-1') + await api.importPiSessions({ sessionIds: ['pi-1'], cwd: '/tmp/project', machineId: 'machine-1' }) + + expect(fetchMock.mock.calls[0]?.[0]).toBe('/api/pi/sessions?cwd=%2Ftmp%2Fproject&machineId=machine-1') + expect(fetchMock.mock.calls[1]?.[0]).toBe('/api/pi/import-sessions') + expect(fetchMock.mock.calls[1]?.[1]).toMatchObject({ + method: 'POST', + body: JSON.stringify({ sessionIds: ['pi-1'], cwd: '/tmp/project', machineId: 'machine-1' }) + }) + }) + it('loads the authoritative queued state for encoded session IDs', async () => { fetchMock.mockResolvedValueOnce( new Response(JSON.stringify({ diff --git a/web/src/api/client.ts b/web/src/api/client.ts index ec3e5706..23a59874 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -14,6 +14,8 @@ import type { MachinesResponse, MessagesResponse, PermissionMode, + PiImportSessionsResponse, + PiLocalSessionsResponse, PushSubscriptionPayload, PushUnsubscribePayload, PushVapidPublicKeyResponse, @@ -226,6 +228,21 @@ export class ApiClient { return await this.request(`/api/codex/sessions${query}`) } + async getPiSessions(cwd?: string | null, machineId?: string | null): Promise { + const params = new URLSearchParams() + if (cwd?.trim()) params.set('cwd', cwd.trim()) + if (machineId?.trim()) params.set('machineId', machineId.trim()) + const query = params.size ? `?${params.toString()}` : '' + return await this.request(`/api/pi/sessions${query}`) + } + + async importPiSessions(payload: { sessionIds: string[]; cwd?: string | null; machineId?: string | null }): Promise { + return await this.request('/api/pi/import-sessions', { + method: 'POST', + body: JSON.stringify(payload) + }) + } + async archiveCodexSession(sessionId: string, machineId?: string | null): Promise { return await this.request('/api/codex/archive-session', { method: 'POST', diff --git a/web/src/components/NewSession/PiImportActions.test.tsx b/web/src/components/NewSession/PiImportActions.test.tsx new file mode 100644 index 00000000..aeff1f68 --- /dev/null +++ b/web/src/components/NewSession/PiImportActions.test.tsx @@ -0,0 +1,26 @@ +import { fireEvent, render, screen } from '@testing-library/react' +import { describe, expect, it, vi } from 'vitest' +import { PiImportActions } from './PiImportActions' + +vi.mock('@/lib/use-translation', () => ({ + useTranslation: () => ({ t: (key: string) => key }) +})) + +describe('PiImportActions', () => { + it('opens the local Pi history picker', () => { + const onChooseHistory = vi.fn() + render( + + ) + + fireEvent.click(screen.getByRole('button', { name: 'piImport.inline.choose' })) + expect(onChooseHistory).toHaveBeenCalledOnce() + }) +}) diff --git a/web/src/components/NewSession/PiImportActions.tsx b/web/src/components/NewSession/PiImportActions.tsx new file mode 100644 index 00000000..d5927edb --- /dev/null +++ b/web/src/components/NewSession/PiImportActions.tsx @@ -0,0 +1,41 @@ +import type { PiLocalSessionSummary } from '@/types/api' +import { useTranslation } from '@/lib/use-translation' + +export function PiImportActions(props: { + selectedSession: PiLocalSessionSummary | null + isLoading: boolean + isDisabled: boolean + error: string | null + onChooseHistory: () => void + onClear: () => void +}) { + const { t } = useTranslation() + return ( +
+
+
+
{t('piImport.inline.title')}
+
+ {props.selectedSession ? props.selectedSession.title : t('piImport.inline.description')} +
+
+
+ {props.selectedSession ? ( + + ) : null} + +
+
+ {props.error ?
{props.error}
: null} +
+ ) +} diff --git a/web/src/components/NewSession/index.test.tsx b/web/src/components/NewSession/index.test.tsx index 880cc86b..c8ab6ed2 100644 --- a/web/src/components/NewSession/index.test.tsx +++ b/web/src/components/NewSession/index.test.tsx @@ -1,5 +1,5 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import { fireEvent, render, screen, waitFor } from '@testing-library/react' +import { act, fireEvent, render, screen, waitFor } from '@testing-library/react' import type { ApiClient } from '@/api/client' import type { Machine } from '@/types/api' import { saveNewSessionFormDraft } from './newSessionFormDraft' @@ -19,14 +19,17 @@ const mocks = vi.hoisted(() => ({ agyModels: [{ modelId: 'gemini-3.6-flash-low', name: 'Gemini 3.6 Flash (Low)' }], directoryExists: undefined as boolean | undefined, copilotModels: [] as Array<{ modelId: string; name?: string }>, - copilotModelsLoading: false + copilotModelsLoading: false, + piDialogSelection: ['pi-native-1'] as string[], + refetchSessions: vi.fn(), + addToast: vi.fn() })) vi.mock('@/lib/use-translation', () => ({ useTranslation: () => ({ t: (key: string) => key }) })) vi.mock('@/lib/toast-context', () => ({ - useToast: () => ({ addToast: vi.fn() }) + useToast: () => ({ addToast: mocks.addToast }) })) vi.mock('@/hooks/usePlatform', () => ({ usePlatform: () => ({ haptic: { notification: mocks.notification } }) @@ -39,7 +42,7 @@ vi.mock('@/hooks/mutations/useSpawnSession', () => ({ }) })) vi.mock('@/hooks/queries/useSessions', () => ({ - useSessions: () => ({ sessions: [] }) + useSessions: () => ({ sessions: [], refetch: mocks.refetchSessions }) })) vi.mock('@/hooks/useRecentPaths', () => ({ useRecentPaths: () => ({ @@ -132,8 +135,30 @@ vi.mock('../../utils/formatRunnerSpawnError', () => ({ vi.mock('@/components/CodexSessionSyncDialog', () => ({ CodexSessionSyncDialog: () => null })) +vi.mock('@/components/PiSessionImportDialog', () => ({ + PiSessionImportDialog: (props: { isOpen: boolean; sessions: Array<{ id: string }>; onClose: () => void; onConfirm: (ids: string[]) => Promise }) => props.isOpen ? ( + <> +
{props.sessions.map((session) => session.id).join(',')}
+ + + + ) : null +})) vi.mock('./DirectorySection', () => ({ DirectorySection: () => null })) -vi.mock('./MachineSelector', () => ({ MachineSelector: () => null })) +vi.mock('./MachineSelector', () => ({ + MachineSelector: (props: { machines: Machine[]; machineId: string | null; isDisabled: boolean; onChange: (machineId: string) => void }) => ( + + ) +})) vi.mock('./SessionTypeSelector', () => ({ SessionTypeSelector: () => null })) vi.mock('./GrokPermissionModeSelector', () => ({ GrokPermissionModeSelector: () => null })) vi.mock('./CodexFamilyPermissionModeSelector', () => ({ CodexFamilyPermissionModeSelector: () => null })) @@ -202,6 +227,10 @@ describe('NewSession launch preferences', () => { mocks.directoryExists = true mocks.copilotModels = [] mocks.copilotModelsLoading = false + mocks.piDialogSelection = ['pi-native-1'] + mocks.refetchSessions.mockReset() + mocks.refetchSessions.mockResolvedValue(undefined) + mocks.addToast.mockReset() savePreferredAgent('codex') }) @@ -466,6 +495,176 @@ describe('NewSession launch preferences', () => { expect(mocks.spawnSession).toHaveBeenCalledTimes(1) }) + it('imports the selected Pi history and resumes the canonical HAPI session', async () => { + savePreferredAgent('pi') + const piApi = { + getPiSessions: vi.fn().mockResolvedValue({ + success: true, + machineId: 'machine-1', + sessions: [{ + id: 'pi-native-1', + title: 'Existing Pi session', + cwd: 'C:\\repo', + file: 'C:\\pi-native-1.jsonl', + modifiedAt: 1, + messageCount: 2 + }] + }), + importPiSessions: vi.fn().mockResolvedValue({ + success: true, + machineId: 'machine-1', + results: [{ piSessionId: 'pi-native-1', hapiSessionId: 'hapi-imported-1', action: 'created', appended: 2 }] + }), + reopenSession: vi.fn().mockResolvedValue({ ok: true, sessionId: 'hapi-imported-1', resumed: true }) + } as unknown as ApiClient + + render( + {}} + /> + ) + + fireEvent.click(screen.getByRole('button', { name: 'piImport.inline.choose' })) + await waitFor(() => expect(screen.getByTestId('select-pi-history')).toBeEnabled()) + fireEvent.click(screen.getByTestId('select-pi-history')) + fireEvent.click(screen.getByTestId('create')) + + await waitFor(() => expect(mocks.onSuccess).toHaveBeenCalledWith('hapi-imported-1')) + expect(piApi.importPiSessions).toHaveBeenCalledWith({ + sessionIds: ['pi-native-1'], + cwd: 'C:\\repo', + machineId: 'machine-1' + }) + expect(piApi.reopenSession).toHaveBeenCalledWith('hapi-imported-1') + expect(mocks.spawnSession).not.toHaveBeenCalled() + }) + + it('discards a stale Pi scan after switching machines', async () => { + savePreferredAgent('pi') + mocks.piDialogSelection = ['pi-machine-b'] + const machineA = { id: 'machine-a' } as Machine + const machineB = { id: 'machine-b' } as Machine + let resolveMachineA!: (value: Awaited>) => void + let resolveMachineB!: (value: Awaited>) => void + const machineAScan = new Promise>>((resolve) => { + resolveMachineA = resolve + }) + const machineBScan = new Promise>>((resolve) => { + resolveMachineB = resolve + }) + const piApi = { + getPiSessions: vi.fn((_cwd: string | null, selectedMachineId: string) => ( + selectedMachineId === machineA.id ? machineAScan : machineBScan + )), + importPiSessions: vi.fn().mockResolvedValue({ + success: true, + machineId: machineB.id, + results: [{ piSessionId: 'pi-machine-b', hapiSessionId: 'hapi-machine-b', action: 'created', appended: 1 }] + }), + reopenSession: vi.fn().mockResolvedValue({ ok: true, sessionId: 'hapi-machine-b', resumed: true }) + } as unknown as ApiClient + + render( + {}} + /> + ) + + fireEvent.click(screen.getByRole('button', { name: 'piImport.inline.choose' })) + fireEvent.click(screen.getByTestId('close-pi-history')) + fireEvent.change(screen.getByLabelText('machine-selector'), { target: { value: machineB.id } }) + fireEvent.click(screen.getByRole('button', { name: 'piImport.inline.choose' })) + await act(async () => { + resolveMachineB({ + success: true, + machineId: machineB.id, + sessions: [{ id: 'pi-machine-b', title: 'Machine B', cwd: 'C:\\repo', file: 'B.jsonl', modifiedAt: 2, messageCount: 1 }] + }) + await machineBScan + }) + await waitFor(() => expect(screen.getByTestId('pi-session-ids')).toHaveTextContent('pi-machine-b')) + + await act(async () => { + resolveMachineA({ + success: true, + machineId: machineA.id, + sessions: [{ id: 'pi-machine-a', title: 'Machine A', cwd: 'C:\\repo', file: 'A.jsonl', modifiedAt: 1, messageCount: 1 }] + }) + await machineAScan + }) + expect(screen.getByTestId('pi-session-ids')).toHaveTextContent('pi-machine-b') + expect(screen.getByTestId('pi-session-ids')).not.toHaveTextContent('pi-machine-a') + + fireEvent.click(screen.getByTestId('select-pi-history')) + fireEvent.click(screen.getByTestId('create')) + await waitFor(() => expect(mocks.onSuccess).toHaveBeenCalledWith('hapi-machine-b')) + expect(piApi.importPiSessions).toHaveBeenCalledWith({ + sessionIds: ['pi-machine-b'], + cwd: 'C:\\repo', + machineId: machineB.id + }) + }) + + it('refreshes successful Pi imports even when another batch item fails', async () => { + savePreferredAgent('pi') + mocks.piDialogSelection = ['pi-native-1', 'pi-native-2'] + const piApi = { + getPiSessions: vi.fn().mockResolvedValue({ + success: true, + machineId: 'machine-1', + sessions: [1, 2].map((index) => ({ + id: `pi-native-${index}`, + title: `Pi ${index}`, + cwd: 'C:\\repo', + file: `C:\\pi-${index}.jsonl`, + modifiedAt: index, + messageCount: 1 + })) + }), + importPiSessions: vi.fn().mockResolvedValue({ + success: false, + machineId: 'machine-1', + results: [ + { piSessionId: 'pi-native-1', hapiSessionId: 'hapi-1', action: 'created', appended: 1 }, + { piSessionId: 'pi-native-2', hapiSessionId: 'hapi-2', error: { code: 'session_active', message: 'active' } } + ] + }) + } as unknown as ApiClient + + render( + {}} + /> + ) + + fireEvent.click(screen.getByRole('button', { name: 'piImport.inline.choose' })) + await waitFor(() => expect(screen.getByTestId('select-pi-history')).toBeEnabled()) + fireEvent.click(screen.getByTestId('select-pi-history')) + + await waitFor(() => expect(mocks.refetchSessions).toHaveBeenCalled()) + expect(piApi.getPiSessions).toHaveBeenCalledTimes(2) + expect(mocks.addToast).toHaveBeenCalledWith(expect.objectContaining({ + title: 'piImport.success.title', + body: 'piImport.success.body' + })) + expect(mocks.addToast).toHaveBeenCalledWith(expect.objectContaining({ title: 'piImport.failed.title' })) + }) + it('does not save changed launch settings when creation fails', async () => { mocks.spawnSession.mockResolvedValue({ type: 'error', message: 'spawn failed' }) diff --git a/web/src/components/NewSession/index.tsx b/web/src/components/NewSession/index.tsx index a6500215..f73b17e2 100644 --- a/web/src/components/NewSession/index.tsx +++ b/web/src/components/NewSession/index.tsx @@ -1,6 +1,6 @@ import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react' import type { ApiClient } from '@/api/client' -import type { CodexDuplicateSessionGroup, CodexLocalSessionSummary, Machine } from '@/types/api' +import type { CodexDuplicateSessionGroup, CodexLocalSessionSummary, Machine, PiLocalSessionSummary } from '@/types/api' import type { CodexCollaborationMode, GrokPermissionMode, PermissionMode, CopilotAgentMode } from '@hapi/protocol' import { codexModelAdvertisesFastTier } from '@/components/AssistantChat/codexFastMode' import { usePlatform } from '@/hooks/usePlatform' @@ -41,6 +41,7 @@ import { ActionButtons } from './ActionButtons' import { AgentSelector } from './AgentSelector' import { CollaborationModeSelector } from './CollaborationModeSelector' import { CodexImportActions } from './CodexImportActions' +import { PiImportActions } from './PiImportActions' import { clearBatchImportedCodexSelection, resolveCodexImportRedirectSessionId } from './codexImportMerge' import { AgyModelSelector } from './AgyModelSelector' import { DirectorySection } from './DirectorySection' @@ -68,6 +69,7 @@ import { SessionTypeSelector } from './SessionTypeSelector' import { YoloToggle } from './YoloToggle' import { usesCodexFamilyPermissionModes } from '@/lib/codexFamilyPermissionAgents' import { CodexSessionSyncDialog } from '@/components/CodexSessionSyncDialog' +import { PiSessionImportDialog } from '@/components/PiSessionImportDialog' import { ConfirmDialog } from '@/components/ui/ConfirmDialog' import { formatRunnerSpawnError } from '../../utils/formatRunnerSpawnError' import { markCodexSessionsImported } from '@/lib/codexImportedSessions' @@ -121,6 +123,15 @@ export function NewSession(props: { const [codexImportError, setCodexImportError] = useState(null) const [isImportingCodexSession, setIsImportingCodexSession] = useState(false) const [isCodexImportDialogOpen, setIsCodexImportDialogOpen] = useState(false) + const [piImportSessions, setPiImportSessions] = useState([]) + const [selectedPiImportSessionId, setSelectedPiImportSessionId] = useState(null) + const [piImportMachineId, setPiImportMachineId] = useState(null) + const [isLoadingPiImportSessions, setIsLoadingPiImportSessions] = useState(false) + const [piImportError, setPiImportError] = useState(null) + const [isImportingPiSession, setIsImportingPiSession] = useState(false) + const [isBulkImportingPiSessions, setIsBulkImportingPiSessions] = useState(false) + const [isPiImportDialogOpen, setIsPiImportDialogOpen] = useState(false) + const piLoadGenerationRef = useRef(0) const [isCreating, setIsCreating] = useState(false) const createInFlightRef = useRef(false) const [isBulkImportingCodexSessions, setIsBulkImportingCodexSessions] = useState(false) @@ -130,7 +141,15 @@ export function NewSession(props: { const [duplicateSessionGroups, setDuplicateSessionGroups] = useState([]) const [isDuplicateMergeConfirmOpen, setIsDuplicateMergeConfirmOpen] = useState(false) const [isMergingDuplicateSessions, setIsMergingDuplicateSessions] = useState(false) - const isFormDisabled = Boolean(isCreating || isPending || props.isLoading || isImportingCodexSession || isBulkImportingCodexSessions) + const isFormDisabled = Boolean( + isCreating + || isPending + || props.isLoading + || isImportingCodexSession + || isBulkImportingCodexSessions + || isImportingPiSession + || isBulkImportingPiSessions + ) const worktreeInputRef = useRef(null) const preserveRestoredDraftRef = useRef(false) @@ -791,6 +810,44 @@ export function NewSession(props: { } }, [agent, machineId, props.api, trimmedDirectory, t]) + useEffect(() => { + piLoadGenerationRef.current += 1 + setIsLoadingPiImportSessions(false) + }, [agent, machineId, trimmedDirectory]) + + useEffect(() => () => { + piLoadGenerationRef.current += 1 + }, []) + + const loadPiImportSessions = useCallback(async () => { + if (agent !== 'pi' || !machineId) return + const generation = ++piLoadGenerationRef.current + setIsLoadingPiImportSessions(true) + setPiImportError(null) + try { + const result = await props.api.getPiSessions(trimmedDirectory || null, machineId) + if (generation !== piLoadGenerationRef.current) return + if (!result.success) throw new Error(result.error) + setPiImportSessions(result.sessions) + setPiImportMachineId(result.machineId ?? machineId) + setSelectedPiImportSessionId((current) => current && result.sessions.some((session) => session.id === current) ? current : null) + } catch (loadError) { + if (generation !== piLoadGenerationRef.current) return + setPiImportSessions([]) + setPiImportMachineId(null) + setSelectedPiImportSessionId(null) + setPiImportError(loadError instanceof Error ? loadError.message : t('piImport.failed.body')) + } finally { + if (generation === piLoadGenerationRef.current) setIsLoadingPiImportSessions(false) + } + }, [agent, machineId, props.api, trimmedDirectory, t]) + + const formatPiImportError = useCallback((code?: string, message?: string): string => { + if (code === 'transcript_diverged') return t('piImport.error.diverged') + if (code === 'session_active') return t('piImport.error.active') + return message?.trim() || t('piImport.failed.body') + }, [t]) + const normalizeCodexScriptError = useCallback((message: string | null | undefined, fallback: string): string => { const raw = (message ?? '').trim() if (!raw) return fallback @@ -985,10 +1042,74 @@ export function NewSession(props: { t ]) + const handleBulkImportPiSessions = useCallback(async (sessionIds: string[]) => { + if (isBulkImportingPiSessions || isLoadingPiImportSessions) return + setIsBulkImportingPiSessions(true) + try { + const result = await props.api.importPiSessions({ + sessionIds, + cwd: trimmedDirectory || null, + machineId: piImportMachineId ?? machineId + }) + const importedCount = result.results.filter((item) => item.hapiSessionId && !item.error).length + const failed = result.results.filter((item) => item.error) + if (importedCount > 0) { + addToast({ + title: t('piImport.success.title'), + body: t('piImport.success.body', { n: importedCount }), + sessionId: '', + url: '' + }) + await refetchSessions() + await loadPiImportSessions() + } + if (failed.length > 0) { + const first = failed[0]!.error! + addToast({ + title: t('piImport.failed.title'), + body: t('piImport.failed.partial', { + failed: failed.length, + reason: formatPiImportError(first.code, first.message) + }), + sessionId: '', + url: '' + }) + return + } + setIsPiImportDialogOpen(false) + setSelectedPiImportSessionId(null) + } catch (importError) { + addToast({ + title: t('piImport.failed.title'), + body: importError instanceof Error ? importError.message : t('piImport.failed.body'), + sessionId: '', + url: '' + }) + } finally { + setIsBulkImportingPiSessions(false) + } + }, [ + addToast, + formatPiImportError, + isBulkImportingPiSessions, + isLoadingPiImportSessions, + loadPiImportSessions, + machineId, + piImportMachineId, + props.api, + refetchSessions, + t, + trimmedDirectory + ]) + const selectedCodexImportSession = useMemo( () => codexImportSessions.find((session) => session.id === selectedCodexImportSessionId) ?? null, [codexImportSessions, selectedCodexImportSessionId] ) + const selectedPiImportSession = useMemo( + () => piImportSessions.find((session) => session.id === selectedPiImportSessionId) ?? null, + [piImportSessions, selectedPiImportSessionId] + ) const handleAgentChange = useCallback((newAgent: AgentType) => { preserveRestoredDraftRef.current = false @@ -1003,6 +1124,9 @@ export function NewSession(props: { setSelectedCodexImportSessionId(null) setCodexImportSessions([]) setCodexImportMachineId(null) + setSelectedPiImportSessionId(null) + setPiImportSessions([]) + setPiImportMachineId(null) const paths = getRecentPaths(newMachineId) if (paths[0]) { setDirectory(paths[0]) @@ -1094,6 +1218,11 @@ export function NewSession(props: { } }, []) + const handleSelectPiImportSession = useCallback((session: PiLocalSessionSummary) => { + setSelectedPiImportSessionId(session.id) + if (session.cwd?.trim()) setDirectory(session.cwd.trim()) + }, []) + const handlePathClick = useCallback((path: string) => { setDirectory(path) }, []) @@ -1249,6 +1378,31 @@ export function NewSession(props: { return } + if (agent === 'pi' && selectedPiImportSession) { + setIsImportingPiSession(true) + const result = await props.api.importPiSessions({ + sessionIds: [selectedPiImportSession.id], + cwd: selectedPiImportSession.cwd ?? trimmedDirectory, + machineId: piImportMachineId ?? machineId + }) + const imported = result.results.find((item) => item.piSessionId === selectedPiImportSession.id) + if (imported?.error) { + setIsImportingPiSession(false) + haptic.notification('error') + setError(formatPiImportError(imported.error.code, imported.error.message)) + return + } + if (!imported?.hapiSessionId) throw new Error(result.error || t('piImport.failed.body')) + const reopened = await props.api.reopenSession(imported.hapiSessionId) + haptic.notification('success') + savePreferredLaunchSettings(machineId, agent, preferredLaunchSettings) + clearNewSessionFormDraft() + setLastUsedMachineId(machineId) + addRecentPath(machineId, trimmedDirectory) + props.onSuccess(reopened.sessionId) + return + } + const result = await spawnSession({ machineId, directory: trimmedDirectory, @@ -1285,6 +1439,7 @@ export function NewSession(props: { setError(result.message) } catch (e) { setIsImportingCodexSession(false) + setIsImportingPiSession(false) haptic.notification('error') setError(e instanceof Error ? e.message : 'Failed to create session') } finally { @@ -1391,6 +1546,19 @@ export function NewSession(props: { onClear={() => setSelectedCodexImportSessionId(null)} /> ) : null} + {agent === 'pi' ? ( + { + setIsPiImportDialogOpen(true) + void loadPiImportSessions() + }} + onClear={() => setSelectedPiImportSessionId(null)} + /> + ) : null} {agent === 'agy' ? ( + setIsPiImportDialogOpen(false)} + sessions={piImportSessions} + currentSessionId={selectedPiImportSessionId} + currentWorkDirectory={trimmedDirectory} + onConfirm={async (sessionIds) => { + if (sessionIds.length === 1) { + const session = piImportSessions.find((candidate) => candidate.id === sessionIds[0]) + if (session) { + handleSelectPiImportSession(session) + setIsPiImportDialogOpen(false) + } + return + } + await handleBulkImportPiSessions(sessionIds) + }} + isPending={isBulkImportingPiSessions} + isLoading={isLoadingPiImportSessions} + /> 0} onClose={closeDuplicateMergeDialog} diff --git a/web/src/components/PiSessionImportDialog.tsx b/web/src/components/PiSessionImportDialog.tsx new file mode 100644 index 00000000..7da06e41 --- /dev/null +++ b/web/src/components/PiSessionImportDialog.tsx @@ -0,0 +1,127 @@ +import { useEffect, useMemo, useState } from 'react' +import type { PiLocalSessionSummary } from '@/types/api' +import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog' +import { Button } from '@/components/ui/button' +import { SelectControl } from '@/components/ui/select-control' +import { useTranslation } from '@/lib/use-translation' + +const ALL_DIRECTORIES = '__all__' + +export function PiSessionImportDialog(props: { + isOpen: boolean + onClose: () => void + sessions: PiLocalSessionSummary[] + currentSessionId: string | null + currentWorkDirectory?: string | null + onConfirm: (sessionIds: string[]) => Promise + isPending: boolean + isLoading: boolean +}) { + const { t } = useTranslation() + const [selectedIds, setSelectedIds] = useState([]) + const [directory, setDirectory] = useState(ALL_DIRECTORIES) + const [query, setQuery] = useState('') + + const directories = useMemo(() => Array.from(new Set(props.sessions + .map((session) => session.cwd?.trim()) + .filter((value): value is string => Boolean(value)))).sort(), [props.sessions]) + const filtered = useMemo(() => { + const normalized = query.trim().toLowerCase() + return props.sessions.filter((session) => { + if (directory !== ALL_DIRECTORIES && session.cwd !== directory) return false + if (!normalized) return true + return [session.title, session.lastUserMessage, session.cwd, session.id, session.model] + .filter((value): value is string => typeof value === 'string') + .some((value) => value.toLowerCase().includes(normalized)) + }) + }, [directory, props.sessions, query]) + + useEffect(() => { + if (!props.isOpen) return + setSelectedIds(props.currentSessionId ? [props.currentSessionId] : []) + const cwd = props.currentWorkDirectory?.trim() + setDirectory(cwd && directories.includes(cwd) ? cwd : ALL_DIRECTORIES) + setQuery('') + }, [directories, props.currentSessionId, props.currentWorkDirectory, props.isOpen]) + + const toggle = (id: string) => { + if (props.isPending || props.isLoading) return + setSelectedIds((current) => current.includes(id) ? current.filter((value) => value !== id) : [...current, id]) + } + + return ( + !open && props.onClose()}> + + + {t('piImport.dialog.title')} + {t('piImport.dialog.description')} + +
+
+ {t('piImport.dialog.concurrentWarning')} +
+
+ {t('piImport.selectedCount', { n: selectedIds.length })} +
+ + +
+
+ {props.sessions.length > 0 ? ( +
+ setDirectory(event.target.value)}> + + {directories.map((value) => )} + + setQuery(event.target.value)} + /> +
+ ) : null} +
+ {props.isLoading ? ( +
{t('piImport.loading')}
+ ) : filtered.length === 0 ? ( +
{t('piImport.empty')}
+ ) : ( +
+ {filtered.map((session) => { + const checked = selectedIds.includes(session.id) + return ( + + ) + })} +
+ )} +
+
+ + +
+
+
+
+ ) +} diff --git a/web/src/components/SessionActionMenu.test.tsx b/web/src/components/SessionActionMenu.test.tsx index af392353..14d192c9 100644 --- a/web/src/components/SessionActionMenu.test.tsx +++ b/web/src/components/SessionActionMenu.test.tsx @@ -139,6 +139,24 @@ describe('SessionActionMenu - Codex sync action', () => { }) }) +describe('SessionActionMenu - Pi sync action', () => { + it('renders, fires, and closes Sync Pi history when a handler is provided', () => { + const onSyncPi = vi.fn() + const onClose = vi.fn() + renderMenu({ onSyncPi, onClose }) + + fireEvent.click(screen.getByRole('menuitem', { name: /Sync Pi history/ })) + + expect(onSyncPi).toHaveBeenCalledOnce() + expect(onClose).toHaveBeenCalledOnce() + }) + + it('hides Sync Pi history when no handler is provided', () => { + renderMenu({ onSyncPi: undefined }) + expect(screen.queryByRole('menuitem', { name: /Sync Pi history/ })).toBeNull() + }) +}) + describe('SessionActionMenu - Copy reference action', () => { it('renders the Copy reference item', () => { renderMenu() diff --git a/web/src/components/SessionActionMenu.tsx b/web/src/components/SessionActionMenu.tsx index 8e438c70..1d0adaac 100644 --- a/web/src/components/SessionActionMenu.tsx +++ b/web/src/components/SessionActionMenu.tsx @@ -23,6 +23,7 @@ type SessionActionMenuProps = { onRename: () => void onExport?: () => void onSyncCodex?: () => void + onSyncPi?: () => void onArchive: () => void onReopen?: () => void reopenDisabledReason?: string @@ -176,6 +177,7 @@ export function SessionActionMenu(props: SessionActionMenuProps) { onRename, onExport, onSyncCodex, + onSyncPi, onArchive, onReopen, reopenDisabledReason, @@ -224,6 +226,11 @@ export function SessionActionMenu(props: SessionActionMenuProps) { onSyncCodex?.() } + const handleSyncPi = () => { + onClose() + onSyncPi?.() + } + const handleDelete = () => { onClose() onDelete() @@ -379,6 +386,18 @@ export function SessionActionMenu(props: SessionActionMenuProps) { ) : null} + {onSyncPi ? ( + + ) : null} + {sessionActive ? (