diff --git a/cli/src/api/apiMachine.test.ts b/cli/src/api/apiMachine.test.ts index df38584a..650293bb 100644 --- a/cli/src/api/apiMachine.test.ts +++ b/cli/src/api/apiMachine.test.ts @@ -43,7 +43,16 @@ vi.mock('@/cursor/cursorChatStoreStatus', () => ({ inspectCursorChatStore: inspectCursorChatStoreMock })) +vi.mock('../modules/common/opencodeSessions', () => ({ + listLocalOpencodeSessionSummaries: vi.fn().mockResolvedValue([ + { id: 'opencode-wired', title: 'Wired opencode session', lastUserMessage: null, cwd: '/tmp/wired', file: '/tmp/wired.db', modifiedAt: 1 } + ]), + listLocalOpencodeSessionsWithMessagesByIds: vi.fn().mockResolvedValue([]) +})) + import { ApiMachineClient, normalizeWindowsDriveRoot } from './apiMachine' +import { registerLocalSessionSource } from '../modules/common/localSessions/registry' +import { codexLocalSessionSource } from '../modules/common/localSessions/sources/codex' import type { Machine } from './types' function makeMachine(id: string): Machine { @@ -62,6 +71,84 @@ function makeMachine(id: string): Machine { } } +function callListLocalSessions(client: ApiMachineClient, machineId: string, params: { flavor: string; cwd?: string | null; sessionIds?: string[] }): Promise { + const manager = (client as unknown as { rpcHandlerManager: { handleRequest: (req: { method: string; params: string }) => Promise } }).rpcHandlerManager + return manager.handleRequest({ + method: `${machineId}:listLocalSessions`, + params: JSON.stringify(params) + }).then((raw) => JSON.parse(raw) as unknown) +} + +describe('ApiMachineClient ListLocalSessions wiring', () => { + it('routes every flavor through the registry handler', async () => { + const codexHome = mkdtempSync(join(tmpdir(), 'hapi-lls-codex-')) + const piSessions = mkdtempSync(join(tmpdir(), 'hapi-lls-pi-')) + const claudeHome = mkdtempSync(join(tmpdir(), 'hapi-lls-claude-')) + const original = { + CODEX_HOME: process.env.CODEX_HOME, + PI_CODING_AGENT_SESSION_DIR: process.env.PI_CODING_AGENT_SESSION_DIR, + CLAUDE_CONFIG_DIR: process.env.CLAUDE_CONFIG_DIR + } + process.env.CODEX_HOME = codexHome + process.env.PI_CODING_AGENT_SESSION_DIR = piSessions + process.env.CLAUDE_CONFIG_DIR = claudeHome + writeCodexTranscript(codexHome, 'wired.jsonl', { id: 'codex-wired', cwd: '/tmp/wired' }, 'wired prompt') + writePiTranscript(piSessions, 'wired.jsonl', 'pi-wired', '/tmp/wired', 'wired pi') + const projectDir = join(claudeHome, 'projects', '-tmp-wired') + mkdirSync(projectDir, { recursive: true }) + writeFileSync(join(projectDir, 'claude-wired.jsonl'), [ + JSON.stringify({ type: 'user', uuid: 'u1', timestamp: '2026-11-13T00:00:00.000Z', cwd: '/tmp/wired', message: { role: 'user', content: 'wired claude' } }) + ].join('\n')) + + const machine = makeMachine('wiring-machine') + const client = new ApiMachineClient('cli-token', machine) + try { + const codex = await callListLocalSessions(client, machine.id, { flavor: 'codex' }) as { success: boolean; sessions: Array> } + expect(codex.success).toBe(true) + expect(codex.sessions[0]).toMatchObject({ id: 'codex-wired', flavor: 'codex' }) + + const pi = await callListLocalSessions(client, machine.id, { flavor: 'pi' }) as { success: boolean; sessions: Array> } + expect(pi.success).toBe(true) + expect(pi.sessions[0]).toMatchObject({ id: 'pi-wired', flavor: 'pi' }) + + const claude = await callListLocalSessions(client, machine.id, { flavor: 'claude' }) as { success: boolean; sessions: Array> } + expect(claude.success).toBe(true) + expect(claude.sessions[0]).toMatchObject({ id: 'claude-wired', flavor: 'claude' }) + + const opencode = await callListLocalSessions(client, machine.id, { flavor: 'opencode' }) as { success: boolean; sessions: Array> } + expect(opencode.success).toBe(true) + expect(opencode.sessions[0]).toMatchObject({ id: 'opencode-wired', flavor: 'opencode' }) + } finally { + client.shutdown() + if (original.CODEX_HOME === undefined) delete process.env.CODEX_HOME + else process.env.CODEX_HOME = original.CODEX_HOME + if (original.PI_CODING_AGENT_SESSION_DIR === undefined) delete process.env.PI_CODING_AGENT_SESSION_DIR + else process.env.PI_CODING_AGENT_SESSION_DIR = original.PI_CODING_AGENT_SESSION_DIR + if (original.CLAUDE_CONFIG_DIR === undefined) delete process.env.CLAUDE_CONFIG_DIR + else process.env.CLAUDE_CONFIG_DIR = original.CLAUDE_CONFIG_DIR + rmSync(codexHome, { recursive: true, force: true }) + rmSync(piSessions, { recursive: true, force: true }) + rmSync(claudeHome, { recursive: true, force: true }) + } + }) + + it('maps a thrown source error to a failed ListLocalSessions response', async () => { + const machine = makeMachine('throwing-machine') + const client = new ApiMachineClient('cli-token', machine) + registerLocalSessionSource({ + flavor: 'codex', + list: async () => { throw new Error('disk on fire') } + } as typeof codexLocalSessionSource) + try { + const result = await callListLocalSessions(client, machine.id, { flavor: 'codex' }) as { success?: boolean; error?: string } + expect(result).toMatchObject({ success: false, error: 'disk on fire' }) + } finally { + registerLocalSessionSource(codexLocalSessionSource) + client.shutdown() + } + }) +}) + describe('normalizeWindowsDriveRoot', () => { it('restores the trailing separator when Windows realpath returns a bare drive', () => { expect(normalizeWindowsDriveRoot('C:')).toBe('C:\\') diff --git a/cli/src/api/apiMachine.ts b/cli/src/api/apiMachine.ts index 666adfd0..0e5bf855 100644 --- a/cli/src/api/apiMachine.ts +++ b/cli/src/api/apiMachine.ts @@ -41,10 +41,6 @@ import { type ListOpencodeModelsForCwdRequest, type ListOpencodeModelsForCwdResponse } from '../modules/common/opencodeModels' -import { - listLocalOpencodeSessionSummaries, - listLocalOpencodeSessionsWithMessagesByIds -} from '../modules/common/opencodeSessions' import { listOpencodeModelVariants, type ListOpencodeModelVariantsResponse @@ -70,8 +66,19 @@ import { } from '../modules/common/kimiModels' import type { SpawnSessionOptions, SpawnSessionResult } from '../modules/common/rpcTypes' import { applyVersionedAck } from './versionedUpdate' -import { archiveLocalCodexSession, listLocalCodexSessionSummaries, listLocalCodexSessionsWithMessagesByIds } from '../modules/common/codexSessions' +import { + archiveLocalCodexSession, + listLocalCodexSessionSummaries, + listLocalCodexSessionsWithMessagesByIds +} from '../modules/common/codexSessions' import { listLocalPiSessionSummaries, listLocalPiSessionsWithMessagesByIds } from '../modules/common/piSessions' +import { listLocalOpencodeSessionSummaries, listLocalOpencodeSessionsWithMessagesByIds } from '../modules/common/opencodeSessions' +import { registerLocalSessionHandlers } from '../modules/common/localSessions/rpcHandlers' +import { registerLocalSessionSource } from '../modules/common/localSessions/registry' +import { codexLocalSessionSource } from '../modules/common/localSessions/sources/codex' +import { piLocalSessionSource } from '../modules/common/localSessions/sources/pi' +import { opencodeLocalSessionSource } from '../modules/common/localSessions/sources/opencode' +import { claudeLocalSessionSource } from '../modules/common/localSessions/sources/claude' import { buildSocketIoExtraHeaderOptions } from './hubExtraHeaders' import { collectMachineHealth } from '@/utils/machineHealth' import { inspectCursorChatStore } from '@/cursor/cursorChatStoreStatus' @@ -543,6 +550,16 @@ export class ApiMachineClient { return { success: true, sessions } } ) + + for (const source of [codexLocalSessionSource, piLocalSessionSource, opencodeLocalSessionSource, claudeLocalSessionSource]) { + registerLocalSessionSource(source) + } + registerLocalSessionHandlers({ + registerHandler: (method, handler) => this.rpcHandlerManager.registerHandler(method, handler), + resolveForCheck: (path) => this.pathPolicy.resolveForCheck(path), + isWithinSpawnRoots: (path) => this.pathPolicy.isWithinSpawnRoots(path), + isSessionWithinWorkspaceRoots: (session) => this.isLocalSessionWithinWorkspaceRoots(session) + }) } private async isLocalSessionWithinWorkspaceRoots(session: { cwd?: string | null }): Promise { diff --git a/cli/src/api/apiSession.ts b/cli/src/api/apiSession.ts index d2ddd879..fd92b0cc 100644 --- a/cli/src/api/apiSession.ts +++ b/cli/src/api/apiSession.ts @@ -40,72 +40,16 @@ import { cleanupUploadDir, preserveUploadDirOnExit } from '../modules/common/han import { TerminalManager } from '@/terminal/TerminalManager' import { applyVersionedAck } from './versionedUpdate' import { buildHubRequestHeaders, buildSocketIoExtraHeaderOptions } from './hubExtraHeaders' +import { extractRawUserTextContent, isExternalUserMessage } from '@/claude/utils/transcriptEntry' -/** - * XML tags that Claude Code injects as `type:'user'` messages. - * These are internal bookkeeping, not text the human actually typed. - */ -const SYSTEM_INJECTION_PREFIXES = [ - '', - '', - '', - '', -] +// Transcript entry classification moved to @/claude/utils/transcriptEntry; +// re-exported here so existing importers of the old name keep working. +export { isExternalUserMessage } from '@/claude/utils/transcriptEntry' // Cap for the runner-side in-memory agent-terminal screen buffer (matches the // hub's scrollback ring). The tail always holds the latest full-screen redraw. const AGENT_TERMINAL_LOCAL_BUFFER_BYTES = 256 * 1024 -function extractRawUserTextContent(content: unknown): string | null { - if (typeof content === 'string') { - return content - } - - if (!Array.isArray(content)) { - return null - } - - const parts = content - .map((block) => { - if (!block || typeof block !== 'object' || Array.isArray(block)) return null - const record = block as Record - return record.type === 'text' && typeof record.text === 'string' - ? record.text - : null - }) - .filter((text): text is string => text !== null) - - return parts.length > 0 ? parts.join('\n') : null -} - -/** - * Returns true if a JSONL message should be classified as a user-role message - * (i.e., text typed by a real human) rather than an agent-role message. - * - * Claude Code injects system messages (task notifications, command caveats, …) - * into the JSONL log as `type:'user'` entries so the model sees them in - * context. All metadata fields (`userType`, `isMeta`, …) are identical to - * genuine user messages, so the only reliable signal is the message content - * itself: injected messages always start with a well-known XML tag. - */ -export function isExternalUserMessage(body: RawJSONLines): body is Extract { - if (body.type !== 'user') return false - // Defensive: a malformed/minimal user line may lack `.message`. Treat it as - // a non-external (forwardable) message rather than throwing. - const message = (body as { message?: { content?: unknown } }).message - if (!message || typeof message !== 'object') return false - const text = extractRawUserTextContent(message.content) - if (text === null) return false - if (body.isSidechain === true) return false - if (body.isMeta === true) return false - - const trimmed = text.trimStart() - for (const prefix of SYSTEM_INJECTION_PREFIXES) { - if (trimmed.startsWith(prefix)) return false - } - return true -} - /** * Dedup filter for messages arriving on the realtime socket and via reconnect * backfill. Keyed by message id (with a bounded LRU) and falls back to the diff --git a/cli/src/claude/claudeLocalLauncher.ts b/cli/src/claude/claudeLocalLauncher.ts index cf16de07..0f74e3af 100644 --- a/cli/src/claude/claudeLocalLauncher.ts +++ b/cli/src/claude/claudeLocalLauncher.ts @@ -1,7 +1,7 @@ import { claudeLocal } from "./claudeLocal"; import { Session } from "./session"; import { createSessionScanner } from "./utils/sessionScanner"; -import { isClaudeChatVisibleMessage } from "./utils/chatVisibility"; +import { isImportableClaudeEntry } from "./utils/transcriptEntry"; import { BaseLocalLauncher } from "@/modules/common/launcher/BaseLocalLauncher"; import { applySessionTitleFallback } from './utils/sessionTitleFallback'; import { resolveClaudeLaunchModel } from './utils/claudeSettings'; @@ -56,14 +56,10 @@ export async function claudeLocalLauncher(session: Session): Promise<'switch' | applySessionTitleFallback(session.client, message.summary) return } - // Filter out internal meta messages (e.g. skill injections) and - // compact summaries to avoid them appearing in the web UI - if (message.isMeta || message.isCompactSummary) { - return - } - // Filter out invisible system messages (e.g. init, stop_hook_summary) - // to avoid them showing as raw JSON in the web UI - if (!isClaudeChatVisibleMessage(message)) { + // Filter out internal meta messages (e.g. skill injections), compact + // summaries, and invisible system messages (e.g. init, + // stop_hook_summary) to avoid them appearing in the web UI + if (!isImportableClaudeEntry(message)) { return } stampContextWindow(message, session.localContextModel) diff --git a/cli/src/claude/utils/sessionScanner.ts b/cli/src/claude/utils/sessionScanner.ts index d4c6c016..f77b4b52 100644 --- a/cli/src/claude/utils/sessionScanner.ts +++ b/cli/src/claude/utils/sessionScanner.ts @@ -1,9 +1,10 @@ import { RawJSONLines, RawJSONLinesSchema } from "../types"; -import { basename, dirname, join } from "node:path"; -import { open, readdir, readFile, stat } from "node:fs/promises"; +import { basename, dirname } from "node:path"; +import { open, stat } from "node:fs/promises"; import { logger } from "@/ui/logger"; -import { getClaudeProjectsDir, getProjectPath } from "./path"; +import { getProjectPath } from "./path"; import { BaseSessionScanner, SessionFileScanEntry, SessionFileScanResult, SessionFileScanStats } from "@/modules/common/session/BaseSessionScanner"; +import { findClaudeSessionFile, listClaudeSubagentFiles, readSubagentParentToolUseId } from "./transcriptEntry"; /** * Known internal Claude Code event types that should be silently skipped. @@ -175,61 +176,28 @@ class ClaudeSessionScanner extends BaseSessionScanner { // the session enters or leaves a git worktree, so look for it by session id // across all project dirs once the known path is gone. private async resolveSessionFile(sessionId: string): Promise { - const known = this.sessionFiles.get(sessionId) ?? join(this.projectDir, `${sessionId}.jsonl`); - if (await isFile(known)) { - return known; - } - const projectsDir = getClaudeProjectsDir(); - let newest: { path: string; mtimeMs: number } | null = null; - for (const dir of await readdir(projectsDir).catch(() => [])) { - const candidate = join(projectsDir, dir, `${sessionId}.jsonl`); - const mtimeMs = await stat(candidate).then((s) => s.mtimeMs, () => null); - if (mtimeMs !== null && (!newest || mtimeMs > newest.mtimeMs)) { - newest = { path: candidate, mtimeMs }; + return findClaudeSessionFile(sessionId, { + projectDir: this.projectDir, + sessionFiles: this.sessionFiles, + onFileMoved: (newPath, knownPath) => { + // Re-read the moved file from the top; processed event keys drop what was already sent. + this.setCursor(newPath, 0); + this.pruneWatchers(this.getWatchedFiles().filter((file) => file !== knownPath)); } - } - if (!newest || newest.path === known) { - return known; - } - logger.debug(`[SESSION_SCANNER] Session ${sessionId} transcript moved to ${newest.path}`); - this.sessionFiles.set(sessionId, newest.path); - // Re-read the moved file from the top; processed event keys drop what was already sent. - this.setCursor(newest.path, 0); - this.pruneWatchers(this.getWatchedFiles().filter((file) => file !== known)); - return newest.path; + }); } // Claude Code 2.x writes each subagent to /subagents/agent-*.jsonl // instead of the main session log. private async subagentFilePaths(sessionFile: string): Promise { - const dir = join(sessionFile.slice(0, -'.jsonl'.length), 'subagents'); - try { - return (await readdir(dir)) - .filter((name) => name.startsWith('agent-') && name.endsWith('.jsonl')) - .map((name) => join(dir, name)); - } catch { - return []; - } + return listClaudeSubagentFiles(sessionFile); } // The transcript lines carry no parent tool_use id; the sibling meta.json // records it as `toolUseId`. Without it the web tracer can only fall back // to matching the subagent prompt against the Agent tool input. private async subagentParentToolUseId(filePath: string): Promise { - const cached = this.subagentParents.get(filePath); - if (cached) { - return cached; - } - try { - const meta = JSON.parse(await readFile(filePath.slice(0, -'.jsonl'.length) + '.meta.json', 'utf-8')); - if (typeof meta?.toolUseId === 'string') { - this.subagentParents.set(filePath, meta.toolUseId); - return meta.toolUseId; - } - } catch { - // meta.json not written yet - } - return undefined; + return readSubagentParentToolUseId(filePath, this.subagentParents); } } @@ -369,10 +337,6 @@ export async function readSessionLog(filePath: string, startByte: number): Promi return { events: messages, nextCursor }; } -async function isFile(filePath: string): Promise { - return stat(filePath).then((s) => s.isFile(), () => false); -} - function isSubagentFile(filePath: string): boolean { return basename(dirname(filePath)) === 'subagents'; } diff --git a/cli/src/claude/utils/transcriptEntry.test.ts b/cli/src/claude/utils/transcriptEntry.test.ts new file mode 100644 index 00000000..74f18094 --- /dev/null +++ b/cli/src/claude/utils/transcriptEntry.test.ts @@ -0,0 +1,231 @@ +import { describe, it, expect, beforeEach, afterEach } from 'vitest' +import { mkdir, rm, writeFile, unlink, utimes } from 'node:fs/promises' +import { join } from 'node:path' +import { tmpdir } from 'node:os' +import { existsSync } from 'node:fs' +import { + findClaudeSessionFile, + isExternalUserMessage, + isImportableClaudeEntry, + listClaudeSubagentFiles, + readSubagentParentToolUseId +} from './transcriptEntry' +import type { RawJSONLines } from '../types' + +function userLine(text: string, extra: Partial = {}): RawJSONLines { + return { + type: 'user', + uuid: 'user-uuid-1', + message: { role: 'user', content: text }, + ...extra + } as RawJSONLines +} + +describe('isExternalUserMessage', () => { + it('classifies a genuine user message as external', () => { + expect(isExternalUserMessage(userLine('say lol'))).toBe(true) + }) + + it('rejects non-user transcript entries', () => { + expect(isExternalUserMessage({ type: 'assistant', uuid: 'a' } as RawJSONLines)).toBe(false) + }) + + it('rejects meta and sidechain entries', () => { + expect(isExternalUserMessage(userLine('hi', { isMeta: true }))).toBe(false) + expect(isExternalUserMessage(userLine('hi', { isSidechain: true }))).toBe(false) + }) + + it('rejects system-injected prefixes', () => { + for (const prefix of ['', '', '', '']) { + expect(isExternalUserMessage(userLine(`${prefix} internal`))).toBe(false) + } + }) + + it('rejects malformed user lines without a message', () => { + expect(isExternalUserMessage({ type: 'user', uuid: 'x' } as unknown as RawJSONLines)).toBe(false) + }) +}) + +describe('isImportableClaudeEntry', () => { + it('keeps visible conversation messages', () => { + expect(isImportableClaudeEntry(userLine('say lol'))).toBe(true) + expect(isImportableClaudeEntry({ type: 'assistant', uuid: 'a' } as RawJSONLines)).toBe(true) + }) + + it('drops meta and compact summary entries', () => { + expect(isImportableClaudeEntry(userLine('hi', { isMeta: true }))).toBe(false) + expect(isImportableClaudeEntry(userLine('hi', { isCompactSummary: true }))).toBe(false) + }) + + it('drops invisible system messages', () => { + expect(isImportableClaudeEntry({ + type: 'system', + uuid: 's', + subtype: 'stop_hook_summary' + } as RawJSONLines)).toBe(false) + expect(isImportableClaudeEntry({ + type: 'system', + uuid: 's', + subtype: 'init' + } as RawJSONLines)).toBe(false) + }) +}) + +describe('findClaudeSessionFile', () => { + let configDir: string + let projectsDir: string + let originalConfigDir: string | undefined + const sessionFiles = new Map() + + beforeEach(() => { + configDir = join(tmpdir(), `transcript-entry-test-${Date.now()}-${Math.random().toString(36).slice(2)}`) + projectsDir = join(configDir, 'projects') + originalConfigDir = process.env.CLAUDE_CONFIG_DIR + process.env.CLAUDE_CONFIG_DIR = configDir + sessionFiles.clear() + }) + + afterEach(async () => { + if (originalConfigDir === undefined) delete process.env.CLAUDE_CONFIG_DIR + else process.env.CLAUDE_CONFIG_DIR = originalConfigDir + if (existsSync(configDir)) await rm(configDir, { recursive: true, force: true }) + }) + + it('returns the known session file when it exists', async () => { + const projectDir = join(projectsDir, 'proj-a') + await mkdir(projectDir, { recursive: true }) + const known = join(projectDir, 'session-1.jsonl') + await writeFile(known, '') + + const resolved = await findClaudeSessionFile('session-1', { + projectDir, + sessionFiles + }) + + expect(resolved).toBe(known) + expect([...sessionFiles.entries()]).toEqual([]) + }) + + it('finds the newest copy across project dirs when the known file is gone', async () => { + const projectDir = join(projectsDir, 'proj-a') + await mkdir(join(projectsDir, 'proj-old'), { recursive: true }) + await mkdir(join(projectsDir, 'proj-new'), { recursive: true }) + const known = join(projectDir, 'session-1.jsonl') + const oldCopy = join(projectsDir, 'proj-old', 'session-1.jsonl') + const newCopy = join(projectsDir, 'proj-new', 'session-1.jsonl') + await writeFile(oldCopy, '') + await writeFile(newCopy, '') + // Deterministic mtimes: proj-new is strictly newer. + await utimes(oldCopy, new Date(1000), new Date(1000)) + await utimes(newCopy, new Date(2000), new Date(2000)) + const moved: Array<{ newPath: string; knownPath: string }> = [] + + const resolved = await findClaudeSessionFile('session-1', { + projectDir, + sessionFiles, + onFileMoved: (newPath, knownPath) => moved.push({ newPath, knownPath }) + }) + + expect(resolved).toBe(newCopy) + expect(moved).toEqual([{ newPath: newCopy, knownPath: known }]) + expect(sessionFiles.get('session-1')).toBe(newCopy) + }) + + it('falls back to the known path when nothing exists', async () => { + const projectDir = join(projectsDir, 'proj-a') + await mkdir(projectDir, { recursive: true }) + + const resolved = await findClaudeSessionFile('missing-session', { + projectDir, + sessionFiles + }) + + expect(resolved).toBe(join(projectDir, 'missing-session.jsonl')) + }) +}) + +describe('listClaudeSubagentFiles', () => { + let testDir: string + + beforeEach(() => { + testDir = join(tmpdir(), `subagent-list-test-${Date.now()}-${Math.random().toString(36).slice(2)}`) + }) + + afterEach(async () => { + if (existsSync(testDir)) await rm(testDir, { recursive: true, force: true }) + }) + + it('lists only agent-*.jsonl files in the subagents dir', async () => { + const sessionFile = join(testDir, 'session-1.jsonl') + const subagentsDir = join(testDir, 'session-1', 'subagents') + await mkdir(subagentsDir, { recursive: true }) + const agentA = join(subagentsDir, 'agent-a.jsonl') + const agentB = join(subagentsDir, 'agent-b.jsonl') + await writeFile(agentA, '') + await writeFile(agentB, '') + await writeFile(join(subagentsDir, 'agent-c.txt'), '') + await writeFile(join(subagentsDir, 'other.jsonl'), '') + + const listed = await listClaudeSubagentFiles(sessionFile) + expect(listed.sort()).toEqual([agentA, agentB].sort()) + }) + + it('lists subagent files in deterministic name order regardless of readdir order', async () => { + const sessionFile = join(testDir, 'session-1.jsonl') + const subagentsDir = join(testDir, 'session-1', 'subagents') + await mkdir(subagentsDir, { recursive: true }) + // Creation order differs from name order: the OS directory order must + // not leak into the assembled transcript. + await writeFile(join(subagentsDir, 'agent-b.jsonl'), '') + await writeFile(join(subagentsDir, 'agent-a.jsonl'), '') + + const listed = await listClaudeSubagentFiles(sessionFile) + expect(listed).toEqual([join(subagentsDir, 'agent-a.jsonl'), join(subagentsDir, 'agent-b.jsonl')]) + }) + + it('returns an empty list when the subagents dir does not exist', async () => { + expect(await listClaudeSubagentFiles(join(testDir, 'none.jsonl'))).toEqual([]) + }) +}) + +describe('readSubagentParentToolUseId', () => { + let testDir: string + const cache = new Map() + + beforeEach(() => { + testDir = join(tmpdir(), `subagent-meta-test-${Date.now()}-${Math.random().toString(36).slice(2)}`) + cache.clear() + }) + + afterEach(async () => { + if (existsSync(testDir)) await rm(testDir, { recursive: true, force: true }) + }) + + it('reads toolUseId from the sibling meta file and caches it', async () => { + const subagentFile = join(testDir, 'agent-a.jsonl') + await mkdir(testDir, { recursive: true }) + await writeFile(subagentFile.slice(0, -'.jsonl'.length) + '.meta.json', JSON.stringify({ toolUseId: 'toolu-1' })) + + expect(await readSubagentParentToolUseId(subagentFile, cache)).toBe('toolu-1') + expect(cache.get(subagentFile)).toBe('toolu-1') + }) + + it('returns undefined when the meta file is not written yet', async () => { + const subagentFile = join(testDir, 'agent-a.jsonl') + await mkdir(testDir, { recursive: true }) + + expect(await readSubagentParentToolUseId(subagentFile, cache)).toBeUndefined() + }) + + it('serves subsequent reads from the cache', async () => { + const subagentFile = join(testDir, 'agent-a.jsonl') + await mkdir(testDir, { recursive: true }) + const metaFile = subagentFile.slice(0, -'.jsonl'.length) + '.meta.json' + await writeFile(metaFile, JSON.stringify({ toolUseId: 'toolu-2' })) + expect(await readSubagentParentToolUseId(subagentFile, cache)).toBe('toolu-2') + // The real scanner never re-reads a cached path; deleting the meta file + // simulates that and proves the second read comes from the cache. + await unlink(metaFile) + expect(await readSubagentParentToolUseId(subagentFile, cache)).toBe('toolu-2') + }) +}) diff --git a/cli/src/claude/utils/transcriptEntry.ts b/cli/src/claude/utils/transcriptEntry.ts new file mode 100644 index 00000000..cf431ccd --- /dev/null +++ b/cli/src/claude/utils/transcriptEntry.ts @@ -0,0 +1,169 @@ +import { join } from 'node:path' +import { readdir, readFile, stat } from 'node:fs/promises' +import { logger } from '@/ui/logger' +import { getClaudeProjectsDir } from './path' +import { isClaudeChatVisibleMessage } from './chatVisibility' +import type { RawJSONLines } from '../types' + +/** + * XML tags that Claude Code injects as `type:'user'` messages. + * These are internal bookkeeping, not text the human actually typed. + */ +const SYSTEM_INJECTION_PREFIXES = [ + '', + '', + '', + '', +] + +export function extractRawUserTextContent(content: unknown): string | null { + if (typeof content === 'string') { + return content + } + + if (!Array.isArray(content)) { + return null + } + + const parts = content + .map((block) => { + if (!block || typeof block !== 'object' || Array.isArray(block)) return null + const record = block as Record + return record.type === 'text' && typeof record.text === 'string' + ? record.text + : null + }) + .filter((text): text is string => text !== null) + + return parts.length > 0 ? parts.join('\n') : null +} + +/** + * Returns true if a JSONL message should be classified as a user-role message + * (i.e., text typed by a real human) rather than an agent-role message. + * + * Claude Code injects system messages (task notifications, command caveats, …) + * into the JSONL log as `type:'user'` entries so the model sees them in + * context. All metadata fields (`userType`, `isMeta`, …) are identical to + * genuine user messages, so the only reliable signal is the message content + * itself: injected messages always start with a well-known XML tag. + */ +export function isExternalUserMessage(body: RawJSONLines): body is Extract { + if (body.type !== 'user') return false + // Defensive: a malformed/minimal user line may lack `.message`. Treat it as + // a non-external (forwardable) message rather than throwing. + const message = (body as { message?: { content?: unknown } }).message + if (!message || typeof message !== 'object') return false + const text = extractRawUserTextContent(message.content) + if (text === null) return false + if (body.isSidechain === true) return false + if (body.isMeta === true) return false + + const trimmed = text.trimStart() + for (const prefix of SYSTEM_INJECTION_PREFIXES) { + if (trimmed.startsWith(prefix)) return false + } + return true +} + +/** + * Transcript entry filter used when relaying Claude Code transcript entries + * into the web UI: internal meta messages (e.g. skill injections), compact + * summaries, and invisible system messages (e.g. init, stop_hook_summary) + * must not appear in the chat. + */ +export function isImportableClaudeEntry(message: RawJSONLines): boolean { + if (message.isMeta || message.isCompactSummary) { + return false + } + return isClaudeChatVisibleMessage(message) +} + +async function isFile(filePath: string): Promise { + return stat(filePath).then((s) => s.isFile(), () => false); +} + +/** + * Resolve a session's transcript file. Claude Code moves the transcript to the + * project dir of the new cwd when the session enters or leaves a git worktree, + * so look for it by session id across all project dirs once the known path is + * gone. + * + * `sessionFiles` is the caller's session id → transcript path cache; it is + * updated in place when the transcript has moved. `onFileMoved` lets the + * caller react to a move (e.g. re-read from the top and re-point watchers). + */ +export async function findClaudeSessionFile( + sessionId: string, + opts: { + projectDir: string; + sessionFiles: Map; + onFileMoved?: (newPath: string, knownPath: string) => void; + } +): Promise { + const known = opts.sessionFiles.get(sessionId) ?? join(opts.projectDir, `${sessionId}.jsonl`); + if (await isFile(known)) { + return known; + } + const projectsDir = getClaudeProjectsDir(); + let newest: { path: string; mtimeMs: number } | null = null; + for (const dir of await readdir(projectsDir).catch(() => [])) { + const candidate = join(projectsDir, dir, `${sessionId}.jsonl`); + const mtimeMs = await stat(candidate).then((s) => s.mtimeMs, () => null); + if (mtimeMs !== null && (!newest || mtimeMs > newest.mtimeMs)) { + newest = { path: candidate, mtimeMs }; + } + } + if (!newest || newest.path === known) { + return known; + } + logger.debug(`[SESSION_SCANNER] Session ${sessionId} transcript moved to ${newest.path}`); + opts.sessionFiles.set(sessionId, newest.path); + // Re-read the moved file from the top; processed event keys drop what was already sent. + opts.onFileMoved?.(newest.path, known); + return newest.path; +} + +/** + * Claude Code 2.x writes each subagent to /subagents/agent-*.jsonl + * instead of the main session log. + */ +export async function listClaudeSubagentFiles(sessionFile: string): Promise { + const dir = join(sessionFile.slice(0, -'.jsonl'.length), 'subagents'); + try { + // Deterministic name order: the OS directory order is not stable and + // would reshuffle assembled transcripts between imports. Chronology + // comes from the entries' timestamps at assembly time. + return (await readdir(dir)) + .filter((name) => name.startsWith('agent-') && name.endsWith('.jsonl')) + .sort() + .map((name) => join(dir, name)); + } catch { + return []; + } +} + +/** + * The transcript lines carry no parent tool_use id; the sibling meta.json + * records it as `toolUseId`. Without it the web tracer can only fall back + * to matching the subagent prompt against the Agent tool input. + * + * `cache` is the caller's subagent transcript path → parent tool_use id cache, + * populated on first successful read. + */ +export async function readSubagentParentToolUseId(filePath: string, cache?: Map): Promise { + const cached = cache?.get(filePath); + if (cached) { + return cached; + } + try { + const meta = JSON.parse(await readFile(filePath.slice(0, -'.jsonl'.length) + '.meta.json', 'utf-8')); + if (typeof meta?.toolUseId === 'string') { + cache?.set(filePath, meta.toolUseId); + return meta.toolUseId; + } + } catch { + // meta.json not written yet + } + return undefined; +} diff --git a/cli/src/modules/common/claudeSessions.test.ts b/cli/src/modules/common/claudeSessions.test.ts new file mode 100644 index 00000000..8fc561ae --- /dev/null +++ b/cli/src/modules/common/claudeSessions.test.ts @@ -0,0 +1,303 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import { tmpdir } from 'node:os' +import { + listLocalClaudeSessionSummaries, + listLocalClaudeSessionsWithMessagesByIds, + readClaudeSessionEntries +} from './claudeSessions' + +const SESSION_ID = '06992c9a-1234-5678-9abc-def012345678' + +function writeSubagent(projectDir: string, sessionId: string, name: string, toolUseId: string, lines: unknown[]): void { + const subagentsDir = join(projectDir, sessionId, 'subagents') + mkdirSync(subagentsDir, { recursive: true }) + writeFileSync(join(subagentsDir, `${name}.jsonl`), lines.map((line) => JSON.stringify(line)).join('\n')) + writeFileSync(join(subagentsDir, `${name}.meta.json`), JSON.stringify({ toolUseId })) +} + +function writeMainTranscript(projectDir: string, sessionId: string, lines: unknown[]): void { + writeFileSync(join(projectDir, `${sessionId}.jsonl`), lines.map((line) => JSON.stringify(line)).join('\n')) +} + +function userEntry(uuid: string, text: string, extra: Record = {}): Record { + return { + type: 'user', + uuid, + timestamp: '2026-11-13T00:00:00.000Z', + cwd: '/tmp/project', + message: { role: 'user', content: text }, + ...extra + } +} + +function assistantEntry(uuid: string, text: string, extra: Record = {}): Record { + return { + type: 'assistant', + uuid, + timestamp: '2026-11-13T00:00:05.000Z', + cwd: '/tmp/project', + message: { role: 'assistant', content: [{ type: 'text', text }] }, + ...extra + } +} + +describe('local Claude session reader', () => { + const originalClaudeConfigDir = process.env.CLAUDE_CONFIG_DIR + let root = '' + + afterEach(() => { + if (root) rmSync(root, { recursive: true, force: true }) + root = '' + if (originalClaudeConfigDir === undefined) delete process.env.CLAUDE_CONFIG_DIR + else process.env.CLAUDE_CONFIG_DIR = originalClaudeConfigDir + }) + + function makeProject(): string { + root = mkdtempSync(join(tmpdir(), 'claude-home-')) + process.env.CLAUDE_CONFIG_DIR = root + const projectDir = join(root, 'projects', '-tmp-project') + mkdirSync(projectDir, { recursive: true }) + return projectDir + } + + it('splices subagent batches before their tool_result and filters meta and injected rows', async () => { + const projectDir = makeProject() + writeMainTranscript(projectDir, SESSION_ID, [ + { type: 'summary', summary: 'Continued from an earlier conversation', leafUuid: 'u4' }, + { type: 'ai-title', aiTitle: 'E2E run title' }, + userEntry('u1', 'hello there'), + assistantEntry('u2', 'Starting the search'), + // Subagent transcript (matched through meta.json toolUseId). + { type: 'user', uuid: 'u3', timestamp: '2026-11-13T00:00:10.000Z', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'tool-1', content: 'done' }] } }, + assistantEntry('u4', 'All done'), + // Filtered rows: meta injection, system-reminder injection. + userEntry('u5', 'meta noise', { isMeta: true }), + userEntry('u6', 'background task'), + // Visible system subtype stays importable. + { type: 'system', uuid: 'u7', subtype: 'api_error', timestamp: '2026-11-13T00:00:20.000Z', error: 'rate limited' } + ]) + writeSubagent(projectDir, SESSION_ID, 'agent-a', 'tool-1', [ + { type: 'user', uuid: 's1', isSidechain: true, timestamp: '2026-11-13T00:00:07.000Z', message: { role: 'user', content: 'scanning files' } }, + { type: 'assistant', uuid: 's2', isSidechain: true, timestamp: '2026-11-13T00:00:08.000Z', message: { role: 'assistant', content: [{ type: 'text', text: 'found matches' }] } } + ]) + // No main entry carries this tool_use id: batch lands at the end. + writeSubagent(projectDir, SESSION_ID, 'agent-b', 'tool-missing', [ + { type: 'user', uuid: 'b1', isSidechain: true, timestamp: '2026-11-13T00:00:09.000Z', message: { role: 'user', content: 'orphan scan' } }, + assistantEntry('b2', 'orphan result', { isSidechain: true }) + ]) + // Non-agent files in the subagents dir are ignored. + mkdirSync(join(projectDir, SESSION_ID, 'subagents'), { recursive: true }) + writeFileSync(join(projectDir, SESSION_ID, 'subagents', 'notes.txt'), 'ignore me') + + const entries = await readClaudeSessionEntries(join(projectDir, `${SESSION_ID}.jsonl`)) + // u5 (isMeta) drops; u6 (system-reminder user row) stays, matching the + // live replay where non-external user rows go out as agent payloads. + expect(entries.map((entry) => ('uuid' in entry ? entry.uuid : ''))).toEqual([ + 'u1', 'u2', 's1', 's2', 'u3', 'u4', 'u6', 'u7', 'b1', 'b2' + ]) + // Subagent sidechain rows are marked sidechain and carry the parent + // tool_use id from meta.json so the web tracer can group them. + const spliced = entries[2]! + expect(spliced.isSidechain).toBe(true) + expect(spliced.parentToolUseId).toBe('tool-1') + + const summaries = await listLocalClaudeSessionSummaries() + expect(summaries).toHaveLength(1) + expect(summaries[0]!.id).toBe(SESSION_ID) + expect(summaries[0]!.title).toBe('E2E run title') + // Only genuinely typed user text counts: meta and injected rows are + // not user prompts. + expect(summaries[0]!.lastUserMessage).toBe('hello there') + expect(summaries[0]!.cwd).toBe('/tmp/project') + expect(summaries[0]!.messageCount).toBe(10) + + const sessions = await listLocalClaudeSessionsWithMessagesByIds(new Set([SESSION_ID])) + expect(sessions).toHaveLength(1) + const messages = sessions[0]!.messages + expect(messages).toHaveLength(10) + expect(messages.map((message) => message.uuid)).toEqual([ + 'u1', 'u2', 's1', 's2', 'u3', 'u4', 'u6', 'u7', 'b1', 'b2' + ]) + // External user text keeps the live replay shape... + expect(messages[0]!.content).toEqual({ + role: 'user', + content: { type: 'text', text: 'hello there' }, + meta: { sentFrom: 'cli' } + }) + expect(messages[0]!.createdAt).toBe(Date.parse('2026-11-13T00:00:00.000Z')) + // ...everything else is the raw entry as the agent 'output' payload. + expect(messages[1]!.content.role).toBe('agent') + expect(messages[1]!.content.content).toMatchObject({ type: 'output', data: { type: 'assistant', uuid: 'u2' } }) + // Sidechain user rows are agent payload, not user input. + expect(messages[2]!.content.role).toBe('agent') + // tool_result rows are agent payload too (they carry no user text). + expect(messages[4]!.content.role).toBe('agent') + expect(messages[4]!.content.content).toMatchObject({ type: 'output', data: { uuid: 'u3' } }) + }) + + it('falls back to first user text for the title and skips sessions without importable rows', async () => { + const projectDir = makeProject() + writeMainTranscript(projectDir, SESSION_ID, [ + userEntry('u1', 'Fix the flaky e2e test'), + assistantEntry('u2', 'On it') + ]) + const otherId = '11111111-2222-3333-4444-555555555555' + writeMainTranscript(projectDir, otherId, [ + { type: 'summary', summary: 'nothing importable', leafUuid: 'x' } + ]) + + const summaries = await listLocalClaudeSessionSummaries() + expect(summaries).toHaveLength(1) + expect(summaries[0]!.id).toBe(SESSION_ID) + expect(summaries[0]!.title).toBe('Fix the flaky e2e test') + expect(summaries[0]!.messageCount).toBe(2) + + const sessions = await listLocalClaudeSessionsWithMessagesByIds(new Set([SESSION_ID, otherId])) + expect(sessions).toHaveLength(1) + expect(sessions[0]!.id).toBe(SESSION_ID) + }) + + it('returns empty lists when no Claude config dir exists', async () => { + makeProject() + rmSync(join(root, 'projects'), { recursive: true, force: true }) + expect(await listLocalClaudeSessionSummaries()).toEqual([]) + expect(await listLocalClaudeSessionsWithMessagesByIds(new Set([SESSION_ID]))).toEqual([]) + }) + + it('deduplicates a session id kept in two project dirs, scanning only the newest file', async () => { + const projectDir = makeProject() + writeMainTranscript(projectDir, SESSION_ID, [userEntry('u1', 'newest copy')]) + // Claude Code keeps a stale copy behind when a session moves between + // project dirs (worktree enter/leave). + const olderDir = join(root, 'projects', '-tmp-project-old') + mkdirSync(olderDir, { recursive: true }) + writeMainTranscript(olderDir, SESSION_ID, [userEntry('u1', 'oldest copy')]) + utimesSync(join(olderDir, `${SESSION_ID}.jsonl`), new Date(1000), new Date(1000)) + utimesSync(join(projectDir, `${SESSION_ID}.jsonl`), new Date(2000), new Date(2000)) + + const summaries = await listLocalClaudeSessionSummaries() + expect(summaries).toHaveLength(1) + expect(summaries[0]!.file).toBe(join(projectDir, `${SESSION_ID}.jsonl`)) + expect(summaries[0]!.lastUserMessage).toBe('newest copy') + + const sessions = await listLocalClaudeSessionsWithMessagesByIds(new Set([SESSION_ID])) + expect(sessions).toHaveLength(1) + expect(sessions[0]!.messages[0]!.content).toMatchObject({ content: { text: 'newest copy' } }) + }) + + it('drops entries with an empty uuid from the imported messages', async () => { + const projectDir = makeProject() + writeMainTranscript(projectDir, SESSION_ID, [ + userEntry('u1', 'kept'), + { type: 'user', uuid: '', timestamp: '2026-11-13T00:00:02.000Z', message: { role: 'user', content: 'empty uuid row' } }, + assistantEntry('u2', 'also kept') + ]) + + const sessions = await listLocalClaudeSessionsWithMessagesByIds(new Set([SESSION_ID])) + // An empty uuid would fail the hub's anchor validation for the whole + // machine import: the row is dropped instead. + expect(sessions[0]!.messages.map((message) => message.uuid)).toEqual(['u1', 'u2']) + }) + + it('counts and lists only rows that import, so empty-uuid sessions are not offered', async () => { + const projectDir = makeProject() + writeMainTranscript(projectDir, SESSION_ID, [ + userEntry('u1', 'kept'), + { type: 'user', uuid: '', timestamp: '2026-11-13T00:00:02.000Z', message: { role: 'user', content: 'empty uuid row' } }, + assistantEntry('u2', 'also kept') + ]) + const emptyOnly = '16992c9a-1234-5678-9abc-def012345678' + writeMainTranscript(projectDir, emptyOnly, [ + { type: 'user', uuid: ' ', timestamp: '2026-11-13T00:00:02.000Z', message: { role: 'user', content: 'no usable uuid' } } + ]) + + const summaries = await listLocalClaudeSessionSummaries() + expect(summaries.map((summary) => summary.id)).toEqual([SESSION_ID]) + expect(summaries[0]!.messageCount).toBe(2) + }) + + it('lists at most the 200 newest sessions, like the other local sources', async () => { + const projectDir = makeProject() + // One more session than an import request may carry. + for (let index = 0; index < 201; index += 1) { + const sessionId = `${String(index).padStart(8, '0')}-1234-5678-9abc-def012345678` + writeMainTranscript(projectDir, sessionId, [userEntry(`u-${index}`, `session ${index}`)]) + utimesSync(join(projectDir, `${sessionId}.jsonl`), 1_000 + index, 1_000 + index) + } + + const summaries = await listLocalClaudeSessionSummaries() + expect(summaries).toHaveLength(200) + // Newest first; the oldest session is the one left out. + expect(summaries[0]!.lastUserMessage).toBe('session 200') + expect(summaries.map((summary) => summary.lastUserMessage)).not.toContain('session 0') + }) + + it('picks the same copy of a duplicated session id on every scan when mtimes tie', async () => { + makeProject() + const firstDir = join(root, 'projects', '-tmp-a') + const secondDir = join(root, 'projects', '-tmp-b') + mkdirSync(firstDir, { recursive: true }) + mkdirSync(secondDir, { recursive: true }) + writeMainTranscript(firstDir, SESSION_ID, [userEntry('u1', 'copy a')]) + writeMainTranscript(secondDir, SESSION_ID, [userEntry('u1', 'copy b')]) + utimesSync(join(firstDir, `${SESSION_ID}.jsonl`), 1_000, 1_000) + utimesSync(join(secondDir, `${SESSION_ID}.jsonl`), 1_000, 1_000) + + const summaries = await listLocalClaudeSessionSummaries() + expect(summaries.map((summary) => summary.file)).toEqual([join(firstDir, `${SESSION_ID}.jsonl`)]) + }) + + it('compares raw mtimes so a sub-millisecond newer copy still wins', async () => { + makeProject() + // The newer copy sits in the dir that sorts last, so neither path + // order nor directory listing order can pick it by accident. + const olderDir = join(root, 'projects', '-tmp-a') + const newerDir = join(root, 'projects', '-tmp-b') + mkdirSync(newerDir, { recursive: true }) + mkdirSync(olderDir, { recursive: true }) + writeMainTranscript(newerDir, SESSION_ID, [userEntry('u1', 'newer copy')]) + writeMainTranscript(olderDir, SESSION_ID, [userEntry('u1', 'older copy')]) + // Both round to the same millisecond. + utimesSync(join(olderDir, `${SESSION_ID}.jsonl`), 1_000.0002, 1_000.0002) + utimesSync(join(newerDir, `${SESSION_ID}.jsonl`), 1_000.0004, 1_000.0004) + + const summaries = await listLocalClaudeSessionSummaries() + expect(summaries.map((summary) => summary.lastUserMessage)).toEqual(['newer copy']) + }) + + it('splices subagent batches through their native parentToolUseId without meta.json', async () => { + const projectDir = makeProject() + writeMainTranscript(projectDir, SESSION_ID, [ + userEntry('u1', 'hello there'), + { type: 'user', uuid: 'u2', timestamp: '2026-11-13T00:00:10.000Z', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'tool-1', content: 'done' }] } } + ]) + // No sibling meta.json: newer Claude Code writes the parent tool_use + // id on every sidechain entry itself. + const subagentsDir = join(projectDir, SESSION_ID, 'subagents') + mkdirSync(subagentsDir, { recursive: true }) + writeFileSync(join(subagentsDir, 'agent-a.jsonl'), [ + JSON.stringify({ type: 'user', uuid: 's1', isSidechain: true, parentToolUseId: 'tool-1', timestamp: '2026-11-13T00:00:07.000Z', message: { role: 'user', content: 'scanning files' } }), + JSON.stringify({ type: 'assistant', uuid: 's2', isSidechain: true, parentToolUseId: 'tool-1', timestamp: '2026-11-13T00:00:08.000Z', message: { role: 'assistant', content: [{ type: 'text', text: 'found matches' }] } }) + ].join('\n')) + + const entries = await readClaudeSessionEntries(join(projectDir, `${SESSION_ID}.jsonl`)) + expect(entries.map((entry) => ('uuid' in entry ? entry.uuid : ''))).toEqual(['u1', 's1', 's2', 'u2']) + expect((entries[1] as { parentToolUseId?: string }).parentToolUseId).toBe('tool-1') + }) + + it('orders unmatched subagent batches by first-entry timestamp, not readdir order', async () => { + const projectDir = makeProject() + writeMainTranscript(projectDir, SESSION_ID, [userEntry('u1', 'solo')]) + const subagentsDir = join(projectDir, SESSION_ID, 'subagents') + mkdirSync(subagentsDir, { recursive: true }) + // Written first but stamped later: timestamp order must beat the OS + // directory order so re-imports stay position-stable. + writeFileSync(join(subagentsDir, 'agent-a.jsonl'), JSON.stringify({ type: 'user', uuid: 'late-1', isSidechain: true, timestamp: '2026-11-13T00:00:20.000Z', message: { role: 'user', content: 'late batch' } })) + writeFileSync(join(subagentsDir, 'agent-z.jsonl'), JSON.stringify({ type: 'user', uuid: 'early-1', isSidechain: true, timestamp: '2026-11-13T00:00:10.000Z', message: { role: 'user', content: 'early batch' } })) + + const entries = await readClaudeSessionEntries(join(projectDir, `${SESSION_ID}.jsonl`)) + expect(entries.map((entry) => ('uuid' in entry ? entry.uuid : ''))).toEqual(['u1', 'early-1', 'late-1']) + }) +}) \ No newline at end of file diff --git a/cli/src/modules/common/claudeSessions.ts b/cli/src/modules/common/claudeSessions.ts new file mode 100644 index 00000000..3606ad38 --- /dev/null +++ b/cli/src/modules/common/claudeSessions.ts @@ -0,0 +1,283 @@ +import { readdir, readFile, stat } from 'node:fs/promises' +import { basename, join } from 'node:path' +import { RawJSONLinesSchema, type RawJSONLines } from '@/claude/types' +import { + extractRawUserTextContent, + isExternalUserMessage, + isImportableClaudeEntry, + listClaudeSubagentFiles, + readSubagentParentToolUseId +} from '@/claude/utils/transcriptEntry' +import { getClaudeProjectsDir } from '@/claude/utils/path' +import type { ClaudeLocalSessionSummary, ClaudeLocalSessionWithMessages } from '@hapi/protocol/apiTypes' + +/** + * Local Claude Code transcript reader for history import. + * Conversations live in ~/.claude/projects//.jsonl with + * per-session subagent transcripts in /subagents/agent-*.jsonl. + */ + +const DEFAULT_CLAUDE_SESSION_SCAN_LIMIT = 200 + +type ClaudeSessionFile = { + sessionId: string + filePath: string + modifiedAt: number + mtimeMs: number +} + +async function listSessionFiles(): Promise { + const projectsDir = getClaudeProjectsDir() + const projectDirs = await readdir(projectsDir, { withFileTypes: true }).catch(() => []) + const files: ClaudeSessionFile[] = [] + for (const project of projectDirs) { + if (!project.isDirectory()) continue + const entries = await readdir(join(projectsDir, project.name), { withFileTypes: true }).catch(() => []) + for (const entry of entries) { + if (!entry.isFile() || !entry.name.endsWith('.jsonl')) continue + const filePath = join(projectsDir, project.name, entry.name) + const stats = await stat(filePath).catch(() => null) + if (!stats) continue + files.push({ + sessionId: basename(entry.name, '.jsonl'), + filePath, + modifiedAt: Math.round(stats.mtimeMs), + mtimeMs: stats.mtimeMs + }) + } + } + // Newest file wins per session id: Claude Code leaves a stale copy behind + // when a session moves between project dirs (worktree enter/leave), and + // both list output and import must see exactly one, newest transcript. + // Raw mtimes order sub-millisecond writes; the path breaks exact ties so + // every scan picks the same copy whatever the directory listing order. + const seen = new Set() + return files + .sort((a, b) => (b.mtimeMs - a.mtimeMs) || a.filePath.localeCompare(b.filePath)) + .filter((file) => { + if (seen.has(file.sessionId)) return false + seen.add(file.sessionId) + return true + }) +} + +function parseLine(line: string): RawJSONLines | null { + try { + const parsed = JSON.parse(line) + const result = RawJSONLinesSchema.safeParse(parsed) + return result.success ? result.data : null + } catch { + return null + } +} + +async function readTranscriptEntries(filePath: string): Promise { + const content = await readFile(filePath, 'utf-8').catch(() => '') + const entries: RawJSONLines[] = [] + for (const line of content.split('\n')) { + if (!line.trim()) continue + const parsed = parseLine(line) + if (parsed) entries.push(parsed) + } + return entries +} + +/** Importable entries keep the chat-visible filter the live replay uses. */ +function isImportableEntry(entry: RawJSONLines): boolean { + if (entry.type === 'summary' || entry.type === 'ai-title') return false + return isImportableClaudeEntry(entry) +} + +/** + * Assemble one session's ordered entries: main transcript entries with each + * subagent transcript's entries spliced in right before the main entry that + * carries the matching tool_result. The parent tool_use id comes from the + * sidechain rows themselves when present, falling back to the sibling + * meta.json; batches are ordered by their first entry's timestamp so a + * re-import stays position-stable regardless of directory listing order. + * Subagent batches without a matching tool_result land at the end of the + * conversation (in timestamp order): a later import that finds them a + * matching tool_result would move them earlier, which the anchored matcher + * deliberately rejects as diverged (matchAnchored pins insert-ahead) instead + * of rewriting already-imported history. Unfiltered: summary/ai-title + * bookkeeping rows stay in so the title can be derived from them. + */ +async function readAssembledEntries(sessionFile: string): Promise { + const mainEntries = await readTranscriptEntries(sessionFile) + const subagentFiles = await listClaudeSubagentFiles(sessionFile) + if (subagentFiles.length === 0) return mainEntries + + const parentCache = new Map() + const batches: Array<{ parentToolUseId: string; entries: RawJSONLines[] }> = [] + for (const subagentFile of subagentFiles) { + const entries = await readTranscriptEntries(subagentFile) + // Claude Code 2.x stamps the spawning tool_use id on every sidechain + // entry; older logs only record it in the sibling meta.json. + const nativeParentToolUseId = entries.find((entry) => typeof entry.parentToolUseId === 'string' && entry.parentToolUseId)?.parentToolUseId + const parentToolUseId = nativeParentToolUseId ?? await readSubagentParentToolUseId(subagentFile, parentCache) + const stamped = parentToolUseId + ? entries.map((entry) => ( + entry.isSidechain && !entry.parentToolUseId + ? { ...entry, parentToolUseId } as RawJSONLines + : entry + )) + : entries + if (stamped.length > 0) { + batches.push({ parentToolUseId: parentToolUseId ?? '', entries: stamped }) + } + } + if (batches.length === 0) return mainEntries + + // Chronological batch order: the splice target fixes the position, and + // this keeps same-target batches (and unmatched tails) deterministic + // across directory listing orders. + const firstTimestamp = (batch: { entries: RawJSONLines[] }): number => { + const parsed = batch.entries[0]?.timestamp ? Date.parse(batch.entries[0].timestamp) : NaN + return Number.isFinite(parsed) ? parsed : 0 + } + batches.sort((a, b) => firstTimestamp(a) - firstTimestamp(b)) + + const toolResultIndex = new Map() + mainEntries.forEach((entry, index) => { + if (entry.type !== 'user') return + const blocks = entry.message?.content + if (!Array.isArray(blocks)) return + for (const block of blocks) { + const record = block as { type?: unknown; tool_use_id?: unknown } + if (record?.type === 'tool_result' && typeof record.tool_use_id === 'string') { + if (!toolResultIndex.has(record.tool_use_id)) { + toolResultIndex.set(record.tool_use_id, index) + } + } + } + }) + + const insertions = new Map() + const unmatched: RawJSONLines[] = [] + for (const batch of batches) { + const targetIndex = batch.parentToolUseId ? toolResultIndex.get(batch.parentToolUseId) : undefined + if (targetIndex === undefined) { + unmatched.push(...batch.entries) + continue + } + const existing = insertions.get(targetIndex) ?? [] + existing.push(...batch.entries) + insertions.set(targetIndex, existing) + } + + const ordered: RawJSONLines[] = [] + mainEntries.forEach((entry, index) => { + ordered.push(...(insertions.get(index) ?? [])) + ordered.push(entry) + }) + ordered.push(...unmatched) + return ordered +} + +/** Importable entries in conversation order, chat-visible like the live replay. */ +export async function readClaudeSessionEntries(sessionFile: string): Promise { + return (await readAssembledEntries(sessionFile)).filter(isImportableEntry) +} + +function toImportedMessage(entry: RawJSONLines): ClaudeLocalSessionWithMessages['messages'][number] | null { + // An empty uuid would fail the hub's anchor validation (z.string().min(1)) + // for the whole machine import: drop the row instead. + if (typeof entry.uuid !== 'string' || entry.uuid.trim().length === 0) return null + const createdAt = entry.timestamp ? Date.parse(entry.timestamp) : undefined + if (entry.type !== 'assistant' && entry.type !== 'user' && entry.type !== 'system') { + return null + } + if (isExternalUserMessage(entry)) { + const text = extractRawUserTextContent(entry.message.content) ?? '' + return { + uuid: entry.uuid, + ...(Number.isFinite(createdAt) ? { createdAt } : {}), + content: { + role: 'user', + content: { type: 'text', text }, + meta: { sentFrom: 'cli' } + } + } + } + return { + uuid: entry.uuid, + ...(Number.isFinite(createdAt) ? { createdAt } : {}), + content: { + role: 'agent', + content: { type: 'output', data: entry }, + meta: { sentFrom: 'cli' } + } + } +} + +/** The messages an import of these entries stores; summaries count the same rows. */ +function toImportedMessages(rawEntries: RawJSONLines[]): ClaudeLocalSessionWithMessages['messages'] { + return rawEntries + .filter(isImportableEntry) + .map(toImportedMessage) + .filter((message): message is NonNullable => message !== null) +} + +function toSummary( + sessionFile: ClaudeSessionFile, + rawEntries: RawJSONLines[], + messages: ClaudeLocalSessionWithMessages['messages'] +): ClaudeLocalSessionSummary { + const userTexts: string[] = [] + let cwd: string | undefined + for (const entry of rawEntries) { + if (!cwd && typeof entry.cwd === 'string' && entry.cwd.trim()) cwd = entry.cwd + if (isExternalUserMessage(entry)) { + userTexts.push(extractRawUserTextContent(entry.message.content) ?? '') + } + } + // The native interactive-CLI title beats the compaction summary line + // (summaries narrate a continuation, they do not name the conversation). + const aiTitle = rawEntries.find((entry): entry is Extract => entry.type === 'ai-title')?.aiTitle + const summaryTitle = rawEntries.find((entry): entry is Extract => entry.type === 'summary')?.summary + const title = aiTitle ?? summaryTitle ?? '' + return { + id: sessionFile.sessionId, + title: title || userTexts[0]?.trim().slice(0, 80) || `Claude session ${sessionFile.sessionId.slice(0, 8)}`, + lastUserMessage: userTexts.at(-1) ?? null, + cwd: cwd ?? null, + file: sessionFile.filePath, + modifiedAt: sessionFile.modifiedAt, + messageCount: messages.length + } +} + +/** + * Summaries of the most recent local Claude conversations, newest first. + * Bounded like the Pi, OpenCode and Codex lists: a "Select all" over the + * list must stay within the hub's per-request import limit (200). + */ +export async function listLocalClaudeSessionSummaries(limit = DEFAULT_CLAUDE_SESSION_SCAN_LIMIT): Promise { + if (limit <= 0) return [] + const files = await listSessionFiles() + const summaries: ClaudeLocalSessionSummary[] = [] + for (const sessionFile of files) { + const rawEntries = await readAssembledEntries(sessionFile.filePath) + const messages = toImportedMessages(rawEntries) + if (messages.length === 0) continue + summaries.push(toSummary(sessionFile, rawEntries, messages)) + if (summaries.length >= limit) break + } + return summaries +} + +/** Full transcripts for exactly the requested session ids. */ +export async function listLocalClaudeSessionsWithMessagesByIds(sessionIds: Set): Promise { + const files = (await listSessionFiles()).filter((sessionFile) => sessionIds.has(sessionFile.sessionId)) + const sessions: ClaudeLocalSessionWithMessages[] = [] + for (const sessionFile of files) { + const rawEntries = await readAssembledEntries(sessionFile.filePath) + const messages = toImportedMessages(rawEntries) + if (messages.length === 0) continue + sessions.push({ + ...toSummary(sessionFile, rawEntries, messages), + messages + }) + } + return sessions +} \ No newline at end of file diff --git a/cli/src/modules/common/codexSessions.test.ts b/cli/src/modules/common/codexSessions.test.ts index 8d3c98b5..55b501ed 100644 --- a/cli/src/modules/common/codexSessions.test.ts +++ b/cli/src/modules/common/codexSessions.test.ts @@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync, existsSync, utimesSync } from 'node:fs' import { join } from 'node:path' import { tmpdir } from 'node:os' +import { AGENT_MESSAGE_PAYLOAD_TYPE } from '@hapi/protocol' import { archiveLocalCodexSession, listLocalCodexSessionSummaries, listLocalCodexSessionsWithMessagesByIds } from './codexSessions' vi.mock('node:fs', async (importOriginal) => { @@ -229,3 +230,297 @@ describe('listLocalCodexSessionSummaries', () => { } }) }) + +type CodexTranscriptLine = Record + +function sessionMetaLine(sessionId: string): CodexTranscriptLine { + return { + type: 'session_meta', + payload: { + id: sessionId, + cwd: '/tmp/project', + originator: 'codex_cli_rs', + cli_version: '0.0.0-test' + } + } +} + +function responseUserLine(text: string): CodexTranscriptLine { + return { + type: 'response_item', + payload: { type: 'message', role: 'user', content: [{ type: 'input_text', text }] } + } +} + +function responseAssistantLine(text: string): CodexTranscriptLine { + return { + type: 'response_item', + payload: { type: 'message', role: 'assistant', content: [{ type: 'output_text', text }] } + } +} + +function eventUserLine(text: string): CodexTranscriptLine { + return { type: 'event_msg', payload: { type: 'user_message', message: text } } +} + +function eventAgentLine(text: string): CodexTranscriptLine { + return { type: 'event_msg', payload: { type: 'agent_message', message: text } } +} + +describe('Codex transcript import parity', () => { + const originalCodexHome = process.env.CODEX_HOME + let codexHome = '' + + afterEach(() => { + if (originalCodexHome === undefined) delete process.env.CODEX_HOME + else process.env.CODEX_HOME = originalCodexHome + if (codexHome) rmSync(codexHome, { recursive: true, force: true }) + codexHome = '' + }) + + function writeTranscript(name: string, sessionId: string, lines: CodexTranscriptLine[]): void { + const dir = join(codexHome, 'sessions', '2026', '06', '04') + mkdirSync(dir, { recursive: true }) + writeFileSync(join(dir, name), `${lines.map((line) => JSON.stringify(line)).join('\n')}\n`, 'utf-8') + } + + function importMessages(sessionId: string) { + const sessions = listLocalCodexSessionsWithMessagesByIds(new Set([sessionId])) + const session = sessions.find((item) => item.id === sessionId) + if (!session) throw new Error(`Codex session ${sessionId} was not found`) + return session.messages + } + + function useCodexHome(): string { + codexHome = mkdtempSync(join(tmpdir(), 'codex-home-')) + process.env.CODEX_HOME = codexHome + return codexHome + } + + it('imports normal response_item chat messages', () => { + useCodexHome() + writeTranscript('normal.jsonl', 'normal-session-id', [ + sessionMetaLine('normal-session-id'), + responseUserLine('normal user message'), + responseAssistantLine('normal assistant message') + ]) + + const messages = importMessages('normal-session-id') + + expect(messages).toHaveLength(2) + expect(messages[0]).toEqual({ + role: 'user', + content: { type: 'text', text: 'normal user message' }, + meta: { sentFrom: 'cli' } + }) + expect(messages[1]).toEqual({ + role: 'agent', + content: { + type: AGENT_MESSAGE_PAYLOAD_TYPE, + data: { type: 'message', message: 'normal assistant message', id: expect.any(String) } + }, + meta: { sentFrom: 'cli' } + }) + }) + + it('deduplicates mirrored event_msg and response_item user messages', () => { + useCodexHome() + writeTranscript('mirrored.jsonl', 'mirrored-session-id', [ + sessionMetaLine('mirrored-session-id'), + eventUserLine('mirrored user message'), + responseUserLine('mirrored user message\n') + ]) + + const messages = importMessages('mirrored-session-id') + + expect(messages).toHaveLength(1) + expect(messages[0]).toEqual({ + role: 'user', + content: { type: 'text', text: 'mirrored user message' }, + meta: { sentFrom: 'cli' } + }) + }) + + it('deduplicates adjacent mirrored agent messages with different ids', () => { + useCodexHome() + writeTranscript('mirrored-agent.jsonl', 'mirrored-agent-session-id', [ + sessionMetaLine('mirrored-agent-session-id'), + eventAgentLine('duplicated assistant message'), + responseAssistantLine('duplicated assistant message') + ]) + + const messages = importMessages('mirrored-agent-session-id') + + expect(messages).toHaveLength(1) + expect(messages[0]).toEqual({ + role: 'agent', + content: { + type: AGENT_MESSAGE_PAYLOAD_TYPE, + data: { type: 'message', message: 'duplicated assistant message', id: expect.any(String) } + }, + meta: { sentFrom: 'cli' } + }) + }) + + it('skips injected response_item user context messages', () => { + useCodexHome() + writeTranscript('injected.jsonl', 'injected-session-id', [ + sessionMetaLine('injected-session-id'), + responseUserLine('# AGENTS.md instructions for /repo\nignore'), + responseUserLine('\n2026-07-07\nworkspace\n'), + eventUserLine('real event user message') + ]) + + const messages = importMessages('injected-session-id') + + expect(messages).toHaveLength(1) + expect(messages[0]).toEqual({ + role: 'user', + content: { type: 'text', text: 'real event user message' }, + meta: { sentFrom: 'cli' } + }) + }) + + it('preserves a real response_item user prompt containing embedded environment_context text', () => { + useCodexHome() + writeTranscript('embedded-env.jsonl', 'embedded-env-session-id', [ + sessionMetaLine('embedded-env-session-id'), + responseUserLine('Please inspect this transcript block:\n\n2026-07-07\n\nThis is part of my prompt.') + ]) + + const messages = importMessages('embedded-env-session-id') + + expect(messages).toHaveLength(1) + expect(messages[0]).toMatchObject({ + role: 'user', + content: { type: 'text', text: expect.stringContaining('') } + }) + }) + + it('preserves adjacent duplicate messages from the same transcript source', () => { + useCodexHome() + writeTranscript('same-source.jsonl', 'same-source-session-id', [ + sessionMetaLine('same-source-session-id'), + responseUserLine('same source user message'), + responseUserLine('same source user message'), + responseAssistantLine('same source assistant message'), + responseAssistantLine('same source assistant message') + ]) + + const messages = importMessages('same-source-session-id') + + expect(messages).toHaveLength(4) + expect(messages.map((message) => message.role)).toEqual(['user', 'user', 'agent', 'agent']) + }) + + it('keeps a later response_item-only user turn with the same text', () => { + useCodexHome() + writeTranscript('repeat-user.jsonl', 'repeat-user-session-id', [ + sessionMetaLine('repeat-user-session-id'), + eventUserLine('repeat user message'), + responseUserLine('repeat user message'), + responseAssistantLine('assistant answer'), + responseUserLine('repeat user message') + ]) + + const messages = importMessages('repeat-user-session-id') + + expect(messages.map((message) => message.role)).toEqual(['user', 'agent', 'user']) + expect(messages[0]).toMatchObject({ + role: 'user', + content: { type: 'text', text: 'repeat user message' } + }) + expect(messages[2]).toMatchObject({ + role: 'user', + content: { type: 'text', text: 'repeat user message' } + }) + }) + + it('keeps distinct user turns while deduplicating mirrored user events', () => { + useCodexHome() + writeTranscript('distinct-user.jsonl', 'distinct-user-session-id', [ + sessionMetaLine('distinct-user-session-id'), + eventUserLine('first user message'), + responseUserLine('first user message'), + eventUserLine('second user message') + ]) + + const messages = importMessages('distinct-user-session-id') + + expect(messages).toHaveLength(2) + expect(messages.map((message) => message.content)).toEqual([ + { type: 'text', text: 'first user message' }, + { type: 'text', text: 'second user message' } + ]) + }) + + it('uses the latest session_index thread_name for the session title', () => { + useCodexHome() + writeTranscript('index-title.jsonl', 'index-title-session-id', [ + sessionMetaLine('index-title-session-id'), + responseUserLine('normal user message') + ]) + writeFileSync(join(codexHome, 'session_index.jsonl'), [ + JSON.stringify({ id: 'index-title-session-id', thread_name: 'old thread title', updated_at: '2026-07-07T01:00:00.000000000Z' }), + JSON.stringify({ id: 'index-title-session-id', thread_name: 'new thread title', updated_at: '2026-07-07T02:00:00.000000000Z' }) + ].join('\n')) + + expect(listLocalCodexSessionSummaries()[0]?.title).toBe('new thread title') + }) + + it('falls back to the transcript title when session_index is missing', () => { + useCodexHome() + writeTranscript('no-index-title.jsonl', 'no-index-title-session-id', [ + sessionMetaLine('no-index-title-session-id'), + responseUserLine('normal user message') + ]) + + expect(listLocalCodexSessionSummaries()[0]?.title).toBe('normal user message') + }) + + it('falls back to the transcript title when session_index has no matching id', () => { + useCodexHome() + writeTranscript('index-miss-title.jsonl', 'index-miss-title-session-id', [ + sessionMetaLine('index-miss-title-session-id'), + responseUserLine('normal user message') + ]) + writeFileSync(join(codexHome, 'session_index.jsonl'), [ + JSON.stringify({ id: 'other-session-id', thread_name: 'unrelated title', updated_at: '2026-07-07T03:00:00.000000000Z' }) + ].join('\n')) + + expect(listLocalCodexSessionSummaries()[0]?.title).toBe('normal user message') + }) + + it('keeps event_msg user messages that only look like injected context', () => { + useCodexHome() + writeTranscript('event-injected.jsonl', 'event-injected-session-id', [ + sessionMetaLine('event-injected-session-id'), + eventUserLine('# AGENTS.md instructions for /repo') + ]) + + const messages = importMessages('event-injected-session-id') + + expect(messages).toHaveLength(1) + expect(messages[0]).toEqual({ + role: 'user', + content: { type: 'text', text: '# AGENTS.md instructions for /repo' }, + meta: { sentFrom: 'cli' } + }) + }) + + it('keeps a response_item user prompt with an unclosed environment_context block', () => { + useCodexHome() + writeTranscript('unclosed-env.jsonl', 'unclosed-env-session-id', [ + sessionMetaLine('unclosed-env-session-id'), + responseUserLine('\n2026-07-07') + ]) + + const messages = importMessages('unclosed-env-session-id') + + expect(messages).toHaveLength(1) + expect(messages[0]).toMatchObject({ + role: 'user', + content: { type: 'text', text: expect.stringContaining('') } + }) + }) +}) diff --git a/cli/src/modules/common/codexSessions.ts b/cli/src/modules/common/codexSessions.ts index 02f8a7ae..89ae78f4 100644 --- a/cli/src/modules/common/codexSessions.ts +++ b/cli/src/modules/common/codexSessions.ts @@ -2,7 +2,14 @@ import { closeSync, existsSync, mkdirSync, openSync, readSync, readdirSync, read import { randomUUID } from 'node:crypto' import { basename, dirname, join, relative } from 'node:path' import { homedir } from 'node:os' -import { AGENT_MESSAGE_PAYLOAD_TYPE } from '@hapi/protocol' +import { + AGENT_MESSAGE_PAYLOAD_TYPE, + deduplicateCodexTranscriptMessages, + shouldIgnoreInjectedResponseUserMessage, + type CodexImportedMessageContent, + type CodexImportedMessageEntry, + type CodexImportedMessageSource +} from '@hapi/protocol' import { isCodexSubagentSource } from '@/codex/utils/codexSessionMetadata' const DEFAULT_CODEX_SESSION_SCAN_LIMIT = 200 @@ -12,16 +19,6 @@ type CodexSessionIndexTitle = { updatedAt: string } -type CodexImportedMessageContent = { - role: 'user' - content: { type: 'text'; text: string } - meta: { sentFrom: 'cli' } -} | { - role: 'agent' - content: { type: typeof AGENT_MESSAGE_PAYLOAD_TYPE; data: unknown } - meta: { sentFrom: 'cli' } -} - export type LocalCodexSessionSummary = { id: string title: string @@ -74,11 +71,6 @@ function truncateText(value: string, maxLength: number): string { return value.length > maxLength ? `${value.slice(0, maxLength - 1)}…` : value } -function shouldIgnoreSyntheticUserMessage(text: string): boolean { - const normalized = text.trim() - return normalized.startsWith('# AGENTS.md instructions') || normalized.startsWith('') -} - function inferSessionIdFromFileName(filePath: string): string | null { return /([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})/.exec(filePath)?.[1] ?? null } @@ -183,7 +175,7 @@ function getLatestCodexUserMessage(lines: string[]): string | null { const payload = asRecord(record.payload) if (payload?.type !== 'message' || payload.role !== 'user') continue const text = extractCodexText(payload.content) - if (text && !shouldIgnoreSyntheticUserMessage(text)) return truncateText(text, 140) + if (text && !shouldIgnoreInjectedResponseUserMessage(text)) return truncateText(text, 140) } catch { continue } } return null @@ -220,85 +212,53 @@ function buildImportedAgentMessage(data: unknown): CodexImportedMessageContent { return { role: 'agent', content: { type: AGENT_MESSAGE_PAYLOAD_TYPE, data }, meta: { sentFrom: 'cli' } } } -function convertCodexRecordToImportedMessage(record: Record): CodexImportedMessageContent | null { +function convertCodexRecordToImportedMessage(record: Record): CodexImportedMessageEntry | null { const type = asString(record.type) const payload = asRecord(record.payload) if (!type || !payload) return null if (type === 'event_msg') { + const source: CodexImportedMessageSource = 'event_msg' const eventType = asString(payload.type) if (eventType === 'user_message') { const text = asString(payload.message) ?? asString(payload.text) ?? asString(payload.content) - return text && !shouldIgnoreSyntheticUserMessage(text) ? buildImportedUserMessage(text) : null + return text ? { source, message: buildImportedUserMessage(text) } : null } if (eventType === 'agent_message') { const message = asString(payload.message) - return message ? buildImportedAgentMessage({ type: 'message', message, id: randomUUID() }) : null + return message ? { source, message: buildImportedAgentMessage({ type: 'message', message, id: randomUUID() }) } : null } if (eventType === 'token_count') { const info = asRecord(payload.info) - return info ? buildImportedAgentMessage({ type: 'token_count', info, id: randomUUID() }) : null + return info ? { source, message: buildImportedAgentMessage({ type: 'token_count', info, id: randomUUID() }) } : null } return null } if (type !== 'response_item') return null + const source: CodexImportedMessageSource = 'response_item' const itemType = asString(payload.type) if (itemType === 'message') { const role = asString(payload.role) const text = extractCodexText(payload.content) - if (!text || shouldIgnoreSyntheticUserMessage(text)) return null - if (role === 'user') return buildImportedUserMessage(text) - if (role === 'assistant') return buildImportedAgentMessage({ type: 'message', message: text, id: randomUUID() }) + if (!text) return null + if (role === 'user') { + return shouldIgnoreInjectedResponseUserMessage(text) ? null : { source, message: buildImportedUserMessage(text) } + } + if (role === 'assistant') { + return { source, message: buildImportedAgentMessage({ type: 'message', message: text, id: randomUUID() }) } + } } if (itemType === 'function_call') { const name = asString(payload.name) const callId = extractCodexToolCallId(payload) - return name && callId ? buildImportedAgentMessage({ type: 'tool-call', name, callId, input: parseCodexFunctionArguments(payload.arguments), id: randomUUID() }) : null + return name && callId ? { source, message: buildImportedAgentMessage({ type: 'tool-call', name, callId, input: parseCodexFunctionArguments(payload.arguments), id: randomUUID() }) } : null } if (itemType === 'function_call_output') { const callId = extractCodexToolCallId(payload) - return callId ? buildImportedAgentMessage({ type: 'tool-call-result', callId, output: payload.output, id: randomUUID() }) : null + return callId ? { source, message: buildImportedAgentMessage({ type: 'tool-call-result', callId, output: payload.output, id: randomUUID() }) } : null } return null } -function stableSerialize(value: unknown): string { - if (value === null || typeof value !== 'object') return JSON.stringify(value) - if (Array.isArray(value)) return `[${value.map(stableSerialize).join(',')}]` - const record = value as Record - return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${stableSerialize(record[key])}`).join(',')}}` -} - -function normalizeComparableContent(content: unknown): string | null { - const record = asRecord(content) - if (!record) return null - if (record.role === 'user') { - const body = asRecord(record.content) - return body?.type === 'text' && typeof body.text === 'string' - ? stableSerialize({ role: 'user', text: body.text.replace(/\s+$/u, '') }) - : null - } - if (record.role === 'agent') { - const body = asRecord(record.content) - const data = asRecord(body?.data) - const normalized = data ? { ...data } : body?.data - if (data) delete (normalized as Record).id - return body?.type === AGENT_MESSAGE_PAYLOAD_TYPE ? stableSerialize({ role: 'agent', data: normalized }) : null - } - return null -} - -function deduplicateAdjacentImportedMessages(messages: CodexImportedMessageContent[]): CodexImportedMessageContent[] { - const deduped: CodexImportedMessageContent[] = [] - let previousKey: string | null = null - for (const message of messages) { - const key = normalizeComparableContent(message) - if (key && key === previousKey) continue - deduped.push(message) - previousKey = key - } - return deduped -} - function parseCodexLocalSession( filePath: string, includeMessages: boolean, @@ -316,15 +276,15 @@ function parseCodexLocalSession( let threadSource: string | null = null let forkedFromId: string | null = null let firstUserMessage: string | null = null - const messages: CodexImportedMessageContent[] = [] + const entries: CodexImportedMessageEntry[] = [] if (includeMessages) { for (const line of lines) { let record: Record | null = null try { record = asRecord(JSON.parse(line)) } catch { continue } if (!record) continue - const message = convertCodexRecordToImportedMessage(record) - if (message) messages.push(message) + const entry = convertCodexRecordToImportedMessage(record) + if (entry) entries.push(entry) } } @@ -347,7 +307,7 @@ function parseCodexLocalSession( const payload = asRecord(record.payload) if (payload?.type === 'message' && payload.role === 'user') { const text = extractCodexText(payload.content) - if (text && !shouldIgnoreSyntheticUserMessage(text)) firstUserMessage = text + if (text && !shouldIgnoreInjectedResponseUserMessage(text)) firstUserMessage = text } } } catch { continue } @@ -373,7 +333,7 @@ function parseCodexLocalSession( threadSource, forkedFromId } - return includeMessages ? { ...summary, messages: deduplicateAdjacentImportedMessages(messages) } : summary + return includeMessages ? { ...summary, messages: deduplicateCodexTranscriptMessages(entries) } : summary } function listLocalCodexSessions(includeMessages: false, limit?: number): LocalCodexSessionSummary[] diff --git a/cli/src/modules/common/localSessions/localSessions.test.ts b/cli/src/modules/common/localSessions/localSessions.test.ts new file mode 100644 index 00000000..046abaef --- /dev/null +++ b/cli/src/modules/common/localSessions/localSessions.test.ts @@ -0,0 +1,112 @@ +import { beforeEach, describe, expect, it } from 'vitest' +import type { LocalTranscript } from '@hapi/protocol/localTranscript' +import { clearLocalSessionSources, getLocalSessionSource, listLocalSessionFlavors, registerLocalSessionSource } from './registry' +import { registerLocalSessionHandlers } from './rpcHandlers' +import type { CliLocalSessionSource, LocalSessionHandlerDeps } from './types' + +const transcript: LocalTranscript = { + flavor: 'pi', + id: 'pi-1', + title: 'Pi session', + cwd: '/tmp/project', + file: '/tmp/pi-1.jsonl', + modifiedAt: 1, + messages: [] +} + +function source(flavor: CliLocalSessionSource['flavor'], items: LocalTranscript[] = [transcript]): CliLocalSessionSource { + return { + flavor, + list: (params) => params.sessionIds + ? items.filter((item) => params.sessionIds!.includes(item.id)).map((item) => ({ ...item, messages: [] })) + : items + } +} + +function deps(overrides: Partial = {}): LocalSessionHandlerDeps & { calls: unknown[] } { + const calls: unknown[] = [] + return { + calls, + registerHandler: (method, handler) => calls.push({ method, handler }), + resolveForCheck: async (path) => path, + isWithinSpawnRoots: () => true, + isSessionWithinWorkspaceRoots: async () => true, + ...overrides + } +} + +describe('local session registry', () => { + beforeEach(() => { + clearLocalSessionSources() + }) + + it('stores one source per flavor and reports registered flavors', () => { + registerLocalSessionSource(source('pi')) + registerLocalSessionSource(source('pi')) + registerLocalSessionSource(source('opencode')) + expect(getLocalSessionSource('pi')?.flavor).toBe('pi') + expect(getLocalSessionSource('claude')).toBeNull() + expect(listLocalSessionFlavors()).toEqual(['pi', 'opencode']) + }) +}) + +describe('ListLocalSessions RPC handler', () => { + beforeEach(() => { + clearLocalSessionSources() + }) + + function handlerResult(depsOverrides: Partial = {}, params: unknown) { + const harness = deps(depsOverrides) + registerLocalSessionHandlers(harness) + const registered = harness.calls[0] as { method: string; handler: (params: unknown) => Promise } + return { harness, response: registered.handler(params) as Promise<{ success: boolean; error?: string; sessions?: unknown[] }> } + } + + it('returns summaries when no ids are requested and filters by workspace roots', async () => { + registerLocalSessionSource(source('pi', [transcript, { ...transcript, id: 'pi-2', cwd: '/outside' }])) + const { response } = handlerResult({ + isSessionWithinWorkspaceRoots: async (session) => session.cwd !== '/outside' + }, { flavor: 'pi' }) + const result = await response + expect(result.success).toBe(true) + expect(result.sessions?.map((session) => (session as LocalTranscript).id)).toEqual(['pi-1']) + }) + + it('returns transcripts for requested ids', async () => { + registerLocalSessionSource(source('pi', [transcript, { ...transcript, id: 'pi-2' }])) + const { response } = handlerResult({}, { flavor: 'pi', sessionIds: ['pi-2'] }) + const result = await response + expect(result.success).toBe(true) + expect(result.sessions?.length).toBe(1) + expect((result.sessions?.[0] as LocalTranscript).messages).toEqual([]) + }) + + it('rejects a cwd outside the workspace roots before reading the disk', async () => { + registerLocalSessionSource(source('pi')) + const { response } = handlerResult({ + isWithinSpawnRoots: () => false + }, { flavor: 'pi', cwd: '/etc' }) + const result = await response + expect(result.success).toBe(false) + expect(result.error).toBe('Path is outside workspace roots') + }) + + it('fails closed for unknown flavors and malformed requests', async () => { + const missing = await (await handlerResult({}, { flavor: 'codex' })).response + expect(missing.success).toBe(false) + + const malformed = await (await handlerResult({}, { flavor: 'nope' })).response + expect(malformed.success).toBe(false) + expect(malformed.error).toBe('Invalid local sessions request') + }) + + it('registers exactly one RPC method', () => { + const { harness } = { harness: (() => { + const h = deps() + registerLocalSessionHandlers(h) + return h + })() } + expect(harness.calls).toHaveLength(1) + expect((harness.calls[0] as { method: string }).method).toBe('listLocalSessions') + }) +}) \ No newline at end of file diff --git a/cli/src/modules/common/localSessions/registry.ts b/cli/src/modules/common/localSessions/registry.ts new file mode 100644 index 00000000..79346013 --- /dev/null +++ b/cli/src/modules/common/localSessions/registry.ts @@ -0,0 +1,21 @@ +import type { CliLocalSessionSource } from './types' +import type { LocalSessionFlavor } from '@hapi/protocol/localTranscript' + +const sources = new Map() + +export function registerLocalSessionSource(source: CliLocalSessionSource): void { + sources.set(source.flavor, source) +} + +export function getLocalSessionSource(flavor: LocalSessionFlavor): CliLocalSessionSource | null { + return sources.get(flavor) ?? null +} + +export function listLocalSessionFlavors(): LocalSessionFlavor[] { + return Array.from(sources.keys()) +} + +/** Test-only: reset the registry between scenarios. */ +export function clearLocalSessionSources(): void { + sources.clear() +} \ No newline at end of file diff --git a/cli/src/modules/common/localSessions/rpcHandlers.ts b/cli/src/modules/common/localSessions/rpcHandlers.ts new file mode 100644 index 00000000..1b5a0dd1 --- /dev/null +++ b/cli/src/modules/common/localSessions/rpcHandlers.ts @@ -0,0 +1,43 @@ +import { RPC_METHODS } from '@hapi/protocol/rpcMethods' +import { ListLocalSessionsRpcRequestSchema, type ListLocalSessionsRpcResponse } from '@hapi/protocol/localTranscript' +import { getLocalSessionSource } from './registry' +import type { LocalSessionHandlerDeps } from './types' + +/** + * Single machine RPC for local-session import: one method, one handler, + * flavor selected in the request. Flavor readers register themselves in the + * registry; handlers validate cwd policy and workspace roots exactly like + * the previous per-flavor handlers did. + */ +export function registerLocalSessionHandlers(deps: LocalSessionHandlerDeps): void { + deps.registerHandler( + RPC_METHODS.ListLocalSessions, + async (params) => { + const parsed = ListLocalSessionsRpcRequestSchema.safeParse(params) + if (!parsed.success) return { success: false, error: 'Invalid local sessions request' } + // A throwing reader (unreadable/corrupt local store) must surface + // as a failed response, not as the RPC gateway's bare `{error}` + // shape that fails the hub-side response schema parse. + try { + const source = getLocalSessionSource(parsed.data.flavor) + if (!source) return { success: false, error: `No local session source registered for flavor: ${parsed.data.flavor}` } + const rawCwd = typeof parsed.data.cwd === 'string' ? parsed.data.cwd.trim() : '' + if (rawCwd) { + const resolvedCwd = await deps.resolveForCheck(rawCwd) + if (!deps.isWithinSpawnRoots(resolvedCwd)) { + return { success: false, error: 'Path is outside workspace roots' } + } + } + const requestedIds = parsed.data.sessionIds ? new Set(parsed.data.sessionIds) : null + const listed = await source.list({ cwd: rawCwd || null, sessionIds: requestedIds ? [...requestedIds] : null }) + const sessions = [] + for (const session of listed) { + if (await deps.isSessionWithinWorkspaceRoots(session)) sessions.push(session) + } + return { success: true, sessions } + } catch (error) { + return { success: false, error: error instanceof Error ? error.message : 'Failed to list local sessions' } + } + } + ) +} \ No newline at end of file diff --git a/cli/src/modules/common/localSessions/sources/claude.ts b/cli/src/modules/common/localSessions/sources/claude.ts new file mode 100644 index 00000000..b9f1df70 --- /dev/null +++ b/cli/src/modules/common/localSessions/sources/claude.ts @@ -0,0 +1,21 @@ +import type { LocalTranscript, LocalTranscriptSummary } from '@hapi/protocol/localTranscript' +import { claudeToTranscript, claudeToTranscriptSummary } from '@hapi/protocol/localTranscript' +import type { ClaudeLocalSessionSummary, ClaudeLocalSessionWithMessages } from '@hapi/protocol/apiTypes' +import { listLocalClaudeSessionSummaries, listLocalClaudeSessionsWithMessagesByIds } from '../../claudeSessions' +import type { CliLocalSessionSource, LocalSessionSourceListItem } from '../types' + +function toItem(session: ClaudeLocalSessionSummary | ClaudeLocalSessionWithMessages): LocalSessionSourceListItem { + return 'messages' in session + ? claudeToTranscript(session as ClaudeLocalSessionWithMessages) + : claudeToTranscriptSummary(session as ClaudeLocalSessionSummary) +} + +export const claudeLocalSessionSource: CliLocalSessionSource = { + flavor: 'claude', + list: async ({ sessionIds }) => { + const sessions = sessionIds + ? await listLocalClaudeSessionsWithMessagesByIds(new Set(sessionIds)) + : await listLocalClaudeSessionSummaries() + return sessions.map((session) => toItem(session)) as Array + } +} \ No newline at end of file diff --git a/cli/src/modules/common/localSessions/sources/codex.ts b/cli/src/modules/common/localSessions/sources/codex.ts new file mode 100644 index 00000000..04c9c82a --- /dev/null +++ b/cli/src/modules/common/localSessions/sources/codex.ts @@ -0,0 +1,21 @@ +import type { LocalTranscript, LocalTranscriptSummary } from '@hapi/protocol/localTranscript' +import { codexToTranscript, codexToTranscriptSummary } from '@hapi/protocol/localTranscript' +import type { CodexLocalSessionSummary, CodexLocalSessionWithMessages } from '@hapi/protocol/localTranscript' +import { listLocalCodexSessionSummaries, listLocalCodexSessionsWithMessagesByIds } from '../../codexSessions' +import type { CliLocalSessionSource, LocalSessionSourceListItem } from '../types' + +function toItem(session: CodexLocalSessionSummary | CodexLocalSessionWithMessages): LocalSessionSourceListItem { + return 'messages' in session + ? codexToTranscript(session as CodexLocalSessionWithMessages) + : codexToTranscriptSummary(session as CodexLocalSessionSummary) +} + +export const codexLocalSessionSource: CliLocalSessionSource = { + flavor: 'codex', + list: ({ sessionIds }) => { + const sessions = sessionIds + ? listLocalCodexSessionsWithMessagesByIds(new Set(sessionIds)) + : listLocalCodexSessionSummaries() + return sessions.map((session) => toItem(session)) as Array + } +} \ No newline at end of file diff --git a/cli/src/modules/common/localSessions/sources/opencode.ts b/cli/src/modules/common/localSessions/sources/opencode.ts new file mode 100644 index 00000000..6b89adb7 --- /dev/null +++ b/cli/src/modules/common/localSessions/sources/opencode.ts @@ -0,0 +1,21 @@ +import type { LocalTranscript, LocalTranscriptSummary } from '@hapi/protocol/localTranscript' +import { opencodeToTranscript, opencodeToTranscriptSummary } from '@hapi/protocol/localTranscript' +import type { OpencodeLocalSessionSummary, OpencodeLocalSessionWithMessages } from '@hapi/protocol/apiTypes' +import { listLocalOpencodeSessionSummaries, listLocalOpencodeSessionsWithMessagesByIds } from '../../opencodeSessions' +import type { CliLocalSessionSource, LocalSessionSourceListItem } from '../types' + +function toItem(session: OpencodeLocalSessionSummary | OpencodeLocalSessionWithMessages): LocalSessionSourceListItem { + return 'messages' in session + ? opencodeToTranscript(session as OpencodeLocalSessionWithMessages) + : opencodeToTranscriptSummary(session as OpencodeLocalSessionSummary) +} + +export const opencodeLocalSessionSource: CliLocalSessionSource = { + flavor: 'opencode', + list: async ({ sessionIds }) => { + const sessions = sessionIds + ? await listLocalOpencodeSessionsWithMessagesByIds(new Set(sessionIds)) + : await listLocalOpencodeSessionSummaries() + return sessions.map((session) => toItem(session)) as Array + } +} \ No newline at end of file diff --git a/cli/src/modules/common/localSessions/sources/pi.ts b/cli/src/modules/common/localSessions/sources/pi.ts new file mode 100644 index 00000000..e0c3e69d --- /dev/null +++ b/cli/src/modules/common/localSessions/sources/pi.ts @@ -0,0 +1,21 @@ +import type { LocalTranscript, LocalTranscriptSummary } from '@hapi/protocol/localTranscript' +import { piToTranscript, piToTranscriptSummary } from '@hapi/protocol/localTranscript' +import type { PiLocalSessionSummary, PiLocalSessionWithMessages } from '@hapi/protocol/apiTypes' +import { listLocalPiSessionSummaries, listLocalPiSessionsWithMessagesByIds } from '../../piSessions' +import type { CliLocalSessionSource, LocalSessionSourceListItem } from '../types' + +function toItem(session: PiLocalSessionSummary | PiLocalSessionWithMessages): LocalSessionSourceListItem { + return 'messages' in session + ? piToTranscript(session as PiLocalSessionWithMessages) + : piToTranscriptSummary(session as PiLocalSessionSummary) +} + +export const piLocalSessionSource: CliLocalSessionSource = { + flavor: 'pi', + list: ({ sessionIds }) => { + const sessions = sessionIds + ? listLocalPiSessionsWithMessagesByIds(new Set(sessionIds)) + : listLocalPiSessionSummaries() + return sessions.map((session) => toItem(session)) as Array + } +} \ No newline at end of file diff --git a/cli/src/modules/common/localSessions/types.ts b/cli/src/modules/common/localSessions/types.ts new file mode 100644 index 00000000..bb5c7de7 --- /dev/null +++ b/cli/src/modules/common/localSessions/types.ts @@ -0,0 +1,32 @@ +import type { LocalSessionFlavor, LocalTranscript, LocalTranscriptSummary } from '@hapi/protocol/localTranscript' + +/** + * CLI-side local session source. Each flavor adapts its disk reader to the + * normalized transcript contract; the registry feeds them to the single + * ListLocalSessions RPC handler. + */ + +export type LocalSessionSourceListParams = { + cwd: string | null + /** Null -> summaries only; otherwise transcripts for exactly these ids. */ + sessionIds: string[] | null +} + +export type LocalSessionSourceListItem = LocalTranscriptSummary | LocalTranscript + +export type CliLocalSessionSource = { + flavor: LocalSessionFlavor + list(params: LocalSessionSourceListParams): + | LocalSessionSourceListItem[] + | Promise +} + +export type LocalSessionHandlerDeps = { + registerHandler: ( + method: string, + handler: (params: Request) => Promise | Response + ) => void + resolveForCheck(path: string): Promise + isWithinSpawnRoots(path: string): boolean + isSessionWithinWorkspaceRoots(session: { cwd?: string | null }): Promise +} \ No newline at end of file diff --git a/cli/src/modules/common/opencodeSessions.test.ts b/cli/src/modules/common/opencodeSessions.test.ts index d2490a11..ecdd764c 100644 --- a/cli/src/modules/common/opencodeSessions.test.ts +++ b/cli/src/modules/common/opencodeSessions.test.ts @@ -47,6 +47,49 @@ function insertMessages(dbPath, messages, parts) { } } +// OpenCode v2 storage: session_v2 is a superset of the v1 session table and +// session_message replaces message/part with one row per message. Like the v1 +// table, session_v2 tracks archived sessions in time_archived. +function createV2Tables(db) { + db.exec('CREATE TABLE session_v2 (id TEXT PRIMARY KEY, project_id TEXT, workspace_id TEXT, parent_id TEXT, fork_session_id TEXT, fork_boundary INTEGER, slug TEXT, directory TEXT, path TEXT, title TEXT, version TEXT, model TEXT, time_created REAL, time_updated REAL, time_archived REAL); CREATE TABLE session_message (id TEXT PRIMARY KEY, session_id TEXT, seq INTEGER, type TEXT, data TEXT, time_created REAL);') + return db +} + +function insertV2Sessions(db, sessions) { + for (const s of sessions) { + db.query('INSERT INTO session_v2 (id, project_id, workspace_id, parent_id, fork_session_id, fork_boundary, slug, directory, path, title, version, model, time_created, time_updated, time_archived) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)') + .run( + s.id, + s.projectId ?? 'project-1', + s.workspaceId ?? 'workspace-1', + s.parentId ?? null, + s.forkSessionId ?? null, + s.forkBoundary ?? null, + s.slug ?? 'slug-' + s.id, + s.directory ?? null, + s.path ?? '/tmp/' + s.id, + s.title ?? null, + s.version ?? '2.2.7', + s.model ?? null, + s.timeCreated ?? 0, + s.timeUpdated ?? 0, + s.timeArchived ?? null + ) + } +} + +function insertV2Messages(dbPath, messages) { + const db = new Database(dbPath) + try { + for (const m of messages) { + db.query('INSERT INTO session_message (id, session_id, seq, type, data, time_created) VALUES (?, ?, ?, ?, ?, ?)') + .run(m.id, m.sessionId, m.seq, m.type, JSON.stringify(m.data), m.timeCreated) + } + } finally { + db.close() + } +} + const scenario = process.env.SCENARIO if (scenario === 'sessions') { @@ -117,6 +160,243 @@ if (scenario === 'sessions') { ]) const sessions = await listLocalOpencodeSessionsWithMessagesByIds(new Set(['session-stream'])) console.log(JSON.stringify({ sessions })) +} else if (scenario === 'v1only') { + const root = mkdtempSync(join(tmpdir(), 'opencode-v1only-')) + process.env.OPENCODE_HOME = root + const dbPath = join(root, 'opencode.db') + createDb(root) + const db = new Database(dbPath) + db.query('INSERT INTO session (id, title, directory, time_updated) VALUES (?, ?, ?, ?)').run('session-v1', 'V1 only session', '/tmp/v1-project', 5000) + db.close() + insertMessages(dbPath, [ + { id: 'v1-u', sessionId: 'session-v1', role: 'user', timeCreated: 5100 }, + { id: 'v1-a', sessionId: 'session-v1', role: 'assistant', timeCreated: 5200 } + ], [ + { messageId: 'v1-u', type: 'text', text: 'v1 question' }, + { messageId: 'v1-a', type: 'text', text: 'v1 answer', extra: { time: { end: 5300 } } } + ]) + const summaries = await listLocalOpencodeSessionSummaries() + const sessions = await listLocalOpencodeSessionsWithMessagesByIds(new Set(['session-v1'])) + console.log(JSON.stringify({ summaries, sessions })) +} else if (scenario === 'v2only') { + const root = mkdtempSync(join(tmpdir(), 'opencode-v2only-')) + process.env.OPENCODE_HOME = root + const dbPath = join(root, 'opencode.db') + const db = createV2Tables(new Database(dbPath)) + insertV2Sessions(db, [ + { id: 'session-v2', title: 'V2 only session', directory: '/tmp/v2-project', model: 'anthropic/claude-sonnet-4', timeCreated: 8000, timeUpdated: 9000 } + ]) + db.close() + insertV2Messages(dbPath, [ + { id: 'v2-m1', sessionId: 'session-v2', seq: 1, type: 'user', data: { text: 'v2 question' }, timeCreated: 8100 }, + { id: 'v2-m2', sessionId: 'session-v2', seq: 2, type: 'assistant', data: { content: [{ type: 'tool', id: 'tool-1', name: 'read', state: {}, time: { start: 8200 } }, { type: 'text', text: 'v2 answer' }] }, timeCreated: 8200 }, + { id: 'v2-m3', sessionId: 'session-v2', seq: 3, type: 'user', data: { text: 'v2 follow up' }, timeCreated: 8300 } + ]) + const summaries = await listLocalOpencodeSessionSummaries() + const sessions = await listLocalOpencodeSessionsWithMessagesByIds(new Set(['session-v2'])) + console.log(JSON.stringify({ summaries, sessions })) +} else if (scenario === 'migrated') { + const root = mkdtempSync(join(tmpdir(), 'opencode-migrated-')) + process.env.OPENCODE_HOME = root + const dbPath = join(root, 'opencode.db') + createDb(root) + const db = new Database(dbPath) + db.query('INSERT INTO session (id, title, directory, time_updated) VALUES (?, ?, ?, ?)').run('session-migrated', 'Migrated session', '/tmp/migrated-project', 2000) + db.close() + insertMessages(dbPath, [ + { id: 'm1', sessionId: 'session-migrated', role: 'user', timeCreated: 1000 }, + { id: 'm2', sessionId: 'session-migrated', role: 'assistant', timeCreated: 2000 } + ], [ + { messageId: 'm1', type: 'text', text: 'old question' }, + { messageId: 'm2', type: 'text', text: 'old answer', extra: { time: { end: 2100 } } } + ]) + { + const v2 = createV2Tables(new Database(dbPath)) + try { + insertV2Sessions(v2, [ + { id: 'session-migrated', title: 'Migrated session v2', directory: '/tmp/migrated-project', model: 'anthropic/claude-sonnet-4', timeCreated: 1000, timeUpdated: 9000 } + ]) + } finally { + v2.close() + } + } + insertV2Messages(dbPath, [ + { id: 'm1', sessionId: 'session-migrated', seq: 1, type: 'user', data: { text: 'old question' }, timeCreated: 1000 }, + { id: 'm2', sessionId: 'session-migrated', seq: 2, type: 'assistant', data: { content: [{ type: 'text', text: 'old answer' }] }, timeCreated: 2000 }, + { id: 'm3', sessionId: 'session-migrated', seq: 3, type: 'user', data: { text: 'new question' }, timeCreated: 3000 }, + { id: 'm4', sessionId: 'session-migrated', seq: 4, type: 'assistant', data: { content: [{ type: 'text', text: 'new answer' }] }, timeCreated: 4000 } + ]) + const summaries = await listLocalOpencodeSessionSummaries() + const sessions = await listLocalOpencodeSessionsWithMessagesByIds(new Set(['session-migrated'])) + console.log(JSON.stringify({ summaries, sessions })) +} else if (scenario === 'mixed') { + const root = mkdtempSync(join(tmpdir(), 'opencode-mixed-')) + process.env.OPENCODE_HOME = root + const dbPath = join(root, 'opencode.db') + createDb(root) + const db = new Database(dbPath) + db.query('INSERT INTO session (id, title, directory, time_updated) VALUES (?, ?, ?, ?)').run('session-v1-only', 'V1 only session', '/tmp/v1-project', 5000) + db.close() + insertMessages(dbPath, [ + { id: 'mix-v1-u', sessionId: 'session-v1-only', role: 'user', timeCreated: 5100 } + ], [ + { messageId: 'mix-v1-u', type: 'text', text: 'v1 only question' } + ]) + { + const v2 = createV2Tables(new Database(dbPath)) + try { + insertV2Sessions(v2, [ + { id: 'session-v2-a', title: 'V2 session A', directory: '/tmp/v2-a-project', timeCreated: 6000, timeUpdated: 7000 }, + { id: 'session-v2-b', title: 'V2 session B', directory: '/tmp/v2-b-project', timeCreated: 2000, timeUpdated: 3000 } + ]) + } finally { + v2.close() + } + } + insertV2Messages(dbPath, [ + { id: 'mix-a-u', sessionId: 'session-v2-a', seq: 1, type: 'user', data: { text: 'v2 a question' }, timeCreated: 6100 }, + { id: 'mix-a-a', sessionId: 'session-v2-a', seq: 2, type: 'assistant', data: { content: [{ type: 'text', text: 'v2 a answer' }] }, timeCreated: 6200 }, + { id: 'mix-b-u', sessionId: 'session-v2-b', seq: 1, type: 'user', data: { text: 'v2 b question' }, timeCreated: 2100 } + ]) + const summaries = await listLocalOpencodeSessionSummaries() + const sessions = await listLocalOpencodeSessionsWithMessagesByIds(new Set(['session-v1-only', 'session-v2-a', 'session-v2-b'])) + console.log(JSON.stringify({ summaries, sessions })) +} else if (scenario === 'archived') { + const root = mkdtempSync(join(tmpdir(), 'opencode-archived-')) + process.env.OPENCODE_HOME = root + const dbPath = join(root, 'opencode.db') + createDb(root) + const db = new Database(dbPath) + db.query('INSERT INTO session (id, title, directory, time_updated) VALUES (?, ?, ?, ?)').run('session-live', 'Live session', '/tmp/live', 5000) + // archived in v1 only: the migrated v2 row still exists and is not archived + db.query('INSERT INTO session (id, title, directory, time_updated, time_archived) VALUES (?, ?, ?, ?, ?)').run('session-archived-v1', 'Archived in v1', '/tmp/archived-v1', 6000, 6100) + // archived in v2 only: the v1 row is still active + db.query('INSERT INTO session (id, title, directory, time_updated) VALUES (?, ?, ?, ?)').run('session-archived-v2', 'Archived in v2', '/tmp/archived-v2', 7000) + db.close() + { + const v2 = createV2Tables(new Database(dbPath)) + try { + insertV2Sessions(v2, [ + { id: 'session-live', title: 'Live session v2', directory: '/tmp/live', timeCreated: 1000, timeUpdated: 5000 }, + { id: 'session-archived-v1', title: 'Archived in v1', directory: '/tmp/archived-v1', timeCreated: 1000, timeUpdated: 6000 }, + { id: 'session-archived-v2', title: 'Archived in v2', directory: '/tmp/archived-v2', timeCreated: 1000, timeUpdated: 7000, timeArchived: 7100 }, + { id: 'session-v2-archived', title: 'V2 only archived', directory: '/tmp/archived-v2-only', timeCreated: 1000, timeUpdated: 8000, timeArchived: 8100 } + ]) + } finally { + v2.close() + } + } + const summaries = await listLocalOpencodeSessionSummaries() + console.log(JSON.stringify({ summaries })) +} else if (scenario === 'restamped') { + const root = mkdtempSync(join(tmpdir(), 'opencode-restamped-')) + process.env.OPENCODE_HOME = root + const dbPath = join(root, 'opencode.db') + createDb(root) + const db = new Database(dbPath) + db.query('INSERT INTO session (id, title, directory, time_updated) VALUES (?, ?, ?, ?)').run('session-restamped', 'Restamped session', '/tmp/restamped', 2000) + db.close() + insertMessages(dbPath, [ + { id: 'm1', sessionId: 'session-restamped', role: 'user', timeCreated: 1000 }, + { id: 'm2', sessionId: 'session-restamped', role: 'assistant', timeCreated: 2000 } + ], [ + { messageId: 'm1', type: 'text', text: 'old question' }, + { messageId: 'm2', type: 'text', text: 'old answer', extra: { time: { end: 2100 } } } + ]) + { + const v2 = createV2Tables(new Database(dbPath)) + try { + insertV2Sessions(v2, [ + { id: 'session-restamped', title: 'Restamped session v2', directory: '/tmp/restamped', timeCreated: 10000, timeUpdated: 20000 } + ]) + } finally { + v2.close() + } + } + // The migration re-stamped the timestamps and gave the rows new ids, so + // the v2 prefix can only be recognized by position. + insertV2Messages(dbPath, [ + { id: 'x1', sessionId: 'session-restamped', seq: 1, type: 'user', data: { text: 'old question' }, timeCreated: 10000 }, + { id: 'x2', sessionId: 'session-restamped', seq: 2, type: 'assistant', data: { content: [{ type: 'text', text: 'old answer' }] }, timeCreated: 10100 }, + { id: 'x3', sessionId: 'session-restamped', seq: 3, type: 'user', data: { text: 'new question' }, timeCreated: 10200 }, + { id: 'x4', sessionId: 'session-restamped', seq: 4, type: 'assistant', data: { content: [{ type: 'text', text: 'new answer' }] }, timeCreated: 10300 } + ]) + const summaries = await listLocalOpencodeSessionSummaries() + const sessions = await listLocalOpencodeSessionsWithMessagesByIds(new Set(['session-restamped'])) + console.log(JSON.stringify({ summaries, sessions })) +} else if (scenario === 'restamped-system') { + const root = mkdtempSync(join(tmpdir(), 'opencode-restamped-sys-')) + process.env.OPENCODE_HOME = root + const dbPath = join(root, 'opencode.db') + createDb(root) + const db = new Database(dbPath) + db.query('INSERT INTO session (id, title, directory, time_updated) VALUES (?, ?, ?, ?)').run('session-restamped', 'Restamped session', '/tmp/restamped', 2000) + db.close() + // The v1 history carries a non-chat row (system) between the user turns. + insertMessages(dbPath, [ + { id: 'm1', sessionId: 'session-restamped', role: 'user', timeCreated: 1000 }, + { id: 'm-sys', sessionId: 'session-restamped', role: 'system', timeCreated: 1500 }, + { id: 'm2', sessionId: 'session-restamped', role: 'assistant', timeCreated: 2000 } + ], [ + { messageId: 'm1', type: 'text', text: 'old question' }, + { messageId: 'm2', type: 'text', text: 'old answer', extra: { time: { end: 2100 } } } + ]) + { + const v2 = createV2Tables(new Database(dbPath)) + try { + insertV2Sessions(v2, [ + { id: 'session-restamped', title: 'Restamped session v2', directory: '/tmp/restamped', timeCreated: 10000, timeUpdated: 20000 } + ]) + } finally { + v2.close() + } + } + insertV2Messages(dbPath, [ + { id: 'x1', sessionId: 'session-restamped', seq: 1, type: 'user', data: { text: 'old question' }, timeCreated: 10000 }, + { id: 'x2', sessionId: 'session-restamped', seq: 2, type: 'assistant', data: { content: [{ type: 'text', text: 'old answer' }] }, timeCreated: 10100 }, + { id: 'x3', sessionId: 'session-restamped', seq: 3, type: 'user', data: { text: 'new question' }, timeCreated: 10200 }, + { id: 'x4', sessionId: 'session-restamped', seq: 4, type: 'assistant', data: { content: [{ type: 'text', text: 'new answer' }] }, timeCreated: 10300 } + ]) + const summaries = await listLocalOpencodeSessionSummaries() + const sessions = await listLocalOpencodeSessionsWithMessagesByIds(new Set(['session-restamped'])) + console.log(JSON.stringify({ summaries, sessions })) +} else if (scenario === 'v2model') { + const root = mkdtempSync(join(tmpdir(), 'opencode-v2model-')) + process.env.OPENCODE_HOME = root + const dbPath = join(root, 'opencode.db') + createDb(root) + const v2 = createV2Tables(new Database(dbPath)) + try { + insertV2Sessions(v2, [ + { id: 'session-model', title: 'Model session', directory: '/tmp/model', timeCreated: 1000, timeUpdated: 5000, model: 'gpt-5.6' }, + { id: 'session-nomodel', title: 'No model session', directory: '/tmp/model', timeCreated: 1000, timeUpdated: 4000 } + ]) + } finally { + v2.close() + } + insertV2Messages(dbPath, [ + { id: 'vm1', sessionId: 'session-model', seq: 1, type: 'user', data: { text: 'model question' }, timeCreated: 1100 } + ]) + const summaries = await listLocalOpencodeSessionSummaries() + console.log(JSON.stringify({ summaries })) +} else if (scenario === 'systemrows') { + const root = mkdtempSync(join(tmpdir(), 'opencode-systemrows-')) + process.env.OPENCODE_HOME = root + const dbPath = join(root, 'opencode.db') + const db = createV2Tables(new Database(dbPath)) + insertV2Sessions(db, [ + { id: 'session-system', title: 'Session with system rows', directory: '/tmp/system', timeCreated: 8000, timeUpdated: 9000 } + ]) + db.close() + insertV2Messages(dbPath, [ + { id: 's1', sessionId: 'session-system', seq: 1, type: 'user', data: { text: 'first question' }, timeCreated: 8100 }, + { id: 's2', sessionId: 'session-system', seq: 2, type: 'system', data: { text: 'SYSTEM PROMPT ' + 'x'.repeat(200) }, timeCreated: 8150 }, + { id: 's3', sessionId: 'session-system', seq: 3, type: 'synthetic', data: { text: 'synthetic note' }, timeCreated: 8200 }, + { id: 's4', sessionId: 'session-system', seq: 4, type: 'assistant', data: { content: [{ type: 'text', text: 'the answer' }] }, timeCreated: 8300 } + ]) + const summaries = await listLocalOpencodeSessionSummaries() + const sessions = await listLocalOpencodeSessionsWithMessagesByIds(new Set(['session-system'])) + console.log(JSON.stringify({ summaries, sessions })) } else if (scenario === 'queryfail') { const root = mkdtempSync(join(tmpdir(), 'opencode-queryfail-')) process.env.OPENCODE_HOME = root @@ -252,6 +532,147 @@ describe('local opencode sessions', () => { expect(output.missingTables.byIds).toEqual([]) }) + it('imports v1-only sessions exactly like before', () => { + const output = runScenario('v1only') as any + expect(output.summaries).toHaveLength(1) + expect(output.summaries[0]).toMatchObject({ + id: 'session-v1', + title: 'V1 only session', + cwd: '/tmp/v1-project', + modifiedAt: 5_000_000, + lastUserMessage: 'v1 question' + }) + const messages = output.sessions[0]?.messages ?? [] + expect(messages).toHaveLength(2) + expect(messages[0]).toMatchObject({ + content: { role: 'user', content: { type: 'text', text: 'v1 question' }, meta: { sentFrom: 'cli' } } + }) + expect(messages[1]).toMatchObject({ + content: { + role: 'agent', + content: { type: 'codex', data: { type: 'message', message: 'v1 answer' } }, + meta: { sentFrom: 'cli' } + } + }) + }) + + it('imports v2-only sessions from session_v2 and session_message', () => { + const output = runScenario('v2only') as any + expect(output.summaries).toHaveLength(1) + expect(output.summaries[0]).toMatchObject({ + id: 'session-v2', + title: 'V2 only session', + cwd: '/tmp/v2-project', + modifiedAt: 9_000_000, + lastUserMessage: 'v2 follow up' + }) + const messages = output.sessions[0]?.messages ?? [] + // tool items are not imported: v2 parity is text only + expect(messages).toHaveLength(3) + expect(messages[0]).toMatchObject({ + content: { role: 'user', content: { type: 'text', text: 'v2 question' }, meta: { sentFrom: 'cli' } } + }) + expect(messages[1]).toMatchObject({ + content: { + role: 'agent', + content: { type: 'codex', data: { type: 'message', message: 'v2 answer' } }, + meta: { sentFrom: 'cli' } + } + }) + expect(messages[2]).toMatchObject({ + content: { role: 'user', content: { type: 'text', text: 'v2 follow up' }, meta: { sentFrom: 'cli' } } + }) + // v2 text parts have no id: the stable key is ":" + expect(messages[0].localId).toBe('opencode:session-v2:v2-m1:v2-m1:0') + expect(messages[1].localId).toBe('opencode:session-v2:v2-m2:v2-m2:1') + }) + + it('keeps the v1 prefix and appends the v2 tail of a migrated session', () => { + const output = runScenario('migrated') as any + expect(output.summaries).toHaveLength(1) + expect(output.summaries[0]).toMatchObject({ + id: 'session-migrated', + title: 'Migrated session v2', + modifiedAt: 9_000_000, + lastUserMessage: 'new question' + }) + const messages = output.sessions[0]?.messages ?? [] + expect(messages).toHaveLength(4) + expect(messages.map((message: any) => message.content.content.data?.message ?? message.content.content.text)) + .toEqual(['old question', 'old answer', 'new question', 'new answer']) + // the v1 prefix keeps its v1 local ids, the v2 tail uses the v2 key + expect(messages[0].localId).toBe('opencode:session-migrated:m1:part-1') + expect(messages[2].localId).toBe('opencode:session-migrated:m3:m3:0') + expect(messages[3].localId).toBe('opencode:session-migrated:m4:m4:0') + }) + + it('lists a v1-only session next to v2 sessions', () => { + const output = runScenario('mixed') as any + expect(output.summaries.map((summary: any) => summary.id)).toEqual(['session-v2-a', 'session-v1-only', 'session-v2-b']) + expect(output.sessions.map((session: any) => session.id)).toEqual(['session-v2-a', 'session-v1-only', 'session-v2-b']) + const v1Only = output.sessions.find((session: any) => session.id === 'session-v1-only') + expect(v1Only?.messages).toHaveLength(1) + expect(v1Only?.messages[0]).toMatchObject({ + content: { role: 'user', content: { type: 'text', text: 'v1 only question' } } + }) + const v2a = output.sessions.find((session: any) => session.id === 'session-v2-a') + expect(v2a?.messages).toHaveLength(2) + expect(v2a?.messages[1]).toMatchObject({ + content: { role: 'agent', content: { type: 'codex', data: { type: 'message', message: 'v2 a answer' } } } + }) + }) + + it('hides archived sessions of a migrated database', () => { + const output = runScenario('archived') as any + // archived in v1 only, archived in v2 only and archived in v2 only + // must all stay out of the list + expect(output.summaries.map((summary: any) => summary.id)).toEqual(['session-live']) + }) + + it('aligns the v1 prefix and the v2 tail by position when the ids differ', () => { + const output = runScenario('restamped') as any + expect(output.summaries).toHaveLength(1) + const messages = output.sessions[0]?.messages ?? [] + // the re-stamped v2 rows mirror the v1 prefix: it must not be imported twice + expect(messages).toHaveLength(4) + expect(messages.map((message: any) => message.content.content.data?.message ?? message.content.content.text)) + .toEqual(['old question', 'old answer', 'new question', 'new answer']) + }) + + it('keeps the v2 tail when a non-chat v1 row shifts the positional mirror count', () => { + const output = runScenario('restamped-system') as any + const messages = output.sessions[0]?.messages ?? [] + // Only user/assistant v1 rows participate in the positional mirror: + // the system row must not swallow the 'new question' turn. + expect(messages.map((message: any) => message.content.content.data?.message ?? message.content.content.text)) + .toEqual(['old question', 'old answer', 'new question', 'new answer']) + }) + + it('carries the session_v2 model as a summary field', () => { + const output = runScenario('v2model') as any + const withModel = output.summaries.find((summary: any) => summary.id === 'session-model') + const withoutModel = output.summaries.find((summary: any) => summary.id === 'session-nomodel') + expect(withModel).toMatchObject({ id: 'session-model', model: 'gpt-5.6' }) + expect('model' in withoutModel).toBe(false) + }) + + it('does not import system rows as agent messages', () => { + const output = runScenario('systemrows') as any + expect(output.summaries[0]).toMatchObject({ id: 'session-system', lastUserMessage: 'first question' }) + const messages = output.sessions[0]?.messages ?? [] + // the system row is a system prompt, not conversation: it maps to nothing + expect(messages).toHaveLength(3) + expect(messages[0]).toMatchObject({ + content: { role: 'user', content: { type: 'text', text: 'first question' } } + }) + expect(messages[1]).toMatchObject({ + content: { role: 'user', content: { type: 'text', text: 'synthetic note' } } + }) + expect(messages[2]).toMatchObject({ + content: { role: 'agent', content: { type: 'codex', data: { type: 'message', message: 'the answer' } } } + }) + }) + it('rejects instead of returning a partial transcript when a middle part query fails', async () => { const { listLocalOpencodeSessionsWithMessagesByIds } = await import('./opencodeSessions') let partReads = 0 diff --git a/cli/src/modules/common/opencodeSessions.ts b/cli/src/modules/common/opencodeSessions.ts index ba659632..aaf187fe 100644 --- a/cli/src/modules/common/opencodeSessions.ts +++ b/cli/src/modules/common/opencodeSessions.ts @@ -34,6 +34,43 @@ type SessionRow = { title: string | null directory: string | null time_updated: number | string + model?: string | null +} + +type V1MessageRow = { + id: string + data: unknown + time_created: number | string +} + +type V2MessageRow = { + id: string + seq: number + type: string + data: unknown + time_created: number | string +} + +// Which schema generation the database offers. v1 = session/message/part, +// v2 = session_v2/session_message. A migrated database has both. +type SchemaAvailability = { + v1: boolean + v2: boolean +} + +type MergedSessionRow = { + id: string + title: string | null + directory: string | null + time_updated: number | string + model?: string | null +} + +type ImportedText = { + // Stable identity of the text inside its message: ":". + key: string + text: string + envelope: 'user' | 'agent' } let cachedOpener: OpencodeDatabaseOpener | null = null @@ -77,18 +114,33 @@ async function openDb(dbPath: string, opener?: OpencodeDatabaseOpener): Promise< return await resolveOpener(dbPath) } -function hasRequiredTables(db: DatabaseLike): boolean { - for (const table of ['session', 'message', 'part']) { - try { - const row = db.query( - `SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?` - ).get(table) as { name: string } | null | undefined - if (!row?.name) return false - } catch { - return false - } +function hasTable(db: DatabaseLike, table: string): boolean { + try { + const row = db.query( + `SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?` + ).get(table) as { name: string } | null | undefined + return Boolean(row?.name) + } catch { + return false + } +} + +// Table names are internal constants, so they are safe to inline here: +// PRAGMA does not accept them as bound parameters. +function hasColumn(db: DatabaseLike, table: string, column: string): boolean { + try { + const rows = db.query(`PRAGMA table_info(${table})`).all() as Array<{ name?: string }> + return rows.some((row) => row.name === column) + } catch { + return false + } +} + +function getSchemaAvailability(db: DatabaseLike): SchemaAvailability { + return { + v1: hasTable(db, 'session') && hasTable(db, 'message') && hasTable(db, 'part'), + v2: hasTable(db, 'session_v2') && hasTable(db, 'session_message') } - return true } function parseJson(value: unknown): JsonRecord | null { @@ -123,7 +175,45 @@ function collectTextParts(db: DatabaseLike, messageId: string, role: string): Ar return texts } -function extractLastUserMessage(db: DatabaseLike, sessionId: string): string | null { +// OpenCode v2 keeps the message envelope in session_message.type and the +// payload in session_message.data: user/synthetic/system rows carry +// data.text, assistant rows carry data.content[] with {type:'text', text} +// items that have neither an id nor time.end. The v2 rows are already +// finalized, so the v1 "skip text parts without time.end" streaming gate +// must not be applied here. system rows are system prompts, not +// conversation, and are not imported (v1 never imported them either). +function collectV2Texts(row: V2MessageRow): ImportedText[] { + const parsed = parseJson(row.data) + if (!parsed) return [] + const singleText = (): ImportedText[] => { + const text = typeof parsed.text === 'string' ? parsed.text : '' + if (!text.trim()) return [] + return [{ key: `${row.id}:0`, text, envelope: 'user' }] + } + if (row.type === 'user') return singleText() + if (row.type === 'synthetic') { + // v1 imported synthetic text parts as part of their (user) message. + return singleText() + } + if (row.type === 'system') { + // system rows carry the system/context prompt of the session, not + // conversation: v1 never imported them, so they map to nothing. + return [] + } + if (row.type !== 'assistant') return [] + const content = Array.isArray(parsed.content) ? parsed.content : [] + const texts: ImportedText[] = [] + for (let index = 0; index < content.length; index += 1) { + const item = asRecord(content[index]) + if (!item || item.type !== 'text') continue + const text = typeof item.text === 'string' ? item.text : '' + if (!text.trim()) continue + texts.push({ key: `${row.id}:${index}`, text, envelope: 'agent' }) + } + return texts +} + +function extractLastUserMessageV1(db: DatabaseLike, sessionId: string): string | null { let messageRows: Array<{ id: string; data: unknown }> = [] try { messageRows = db.query( @@ -151,6 +241,37 @@ function extractLastUserMessage(db: DatabaseLike, sessionId: string): string | n return null } +function extractLastUserMessageV2(db: DatabaseLike, sessionId: string): string | null { + let messageRows: V2MessageRow[] = [] + try { + messageRows = db.query( + `SELECT id, seq, type, data, time_created FROM session_message WHERE session_id = ? ORDER BY seq DESC` + ).all(sessionId) as V2MessageRow[] + } catch { + return null + } + for (const messageRow of messageRows) { + // system and synthetic rows are never "last user message" candidates. + if (messageRow.type !== 'user') continue + const parsed = parseJson(messageRow.data) + const text = typeof parsed?.text === 'string' ? parsed.text.trim() : '' + if (!text) continue + if (text.startsWith('<')) continue + return truncateText(text, LAST_USER_MESSAGE_MAX_LENGTH) + } + return null +} + +function extractLastUserMessage(db: DatabaseLike, sessionId: string, availability: SchemaAvailability): string | null { + // v2 rows are the newer tail of a migrated session, so they win. + if (availability.v2) { + const v2 = extractLastUserMessageV2(db, sessionId) + if (v2 !== null) return v2 + } + if (availability.v1) return extractLastUserMessageV1(db, sessionId) + return null +} + function importedUser(text: string): OpencodeImportedMessageContent { return { role: 'user', @@ -173,17 +294,69 @@ function normalizeTimestamp(value: number | string | null | undefined, fallback: return timestamp < 1_000_000_000_000 ? timestamp * 1000 : timestamp } +function readV1Messages(db: DatabaseLike, sessionId: string): V1MessageRow[] { + return db.query( + `SELECT id, data, time_created FROM message WHERE session_id = ? ORDER BY time_created ASC` + ).all(sessionId) as V1MessageRow[] +} + +function readV2Messages(db: DatabaseLike, sessionId: string): V2MessageRow[] { + return db.query( + `SELECT id, seq, type, data, time_created FROM session_message WHERE session_id = ? ORDER BY seq ASC` + ).all(sessionId) as V2MessageRow[] +} + +// A migrated session keeps its v1 history and appends the v2 messages that +// came after it. The cut-off is the last v1 message: when the migration kept +// the message ids, the counterpart of the last v1 message marks the end of +// the mirrored prefix. Otherwise the prefix is aligned by position: the first +// N v2 user/assistant rows (N = the number of v1 user/assistant messages) +// mirror the v1 messages and everything after them is the tail. Timestamps +// are never used as the cut-off: a migration can re-stamp them, which would +// import the v1 prefix twice. Non-chat v1 rows (system prompts, bookkeeping) +// have no v2 counterpart, so they must not inflate the positional count. +function selectV2Tail(v1Messages: V1MessageRow[], v2Messages: V2MessageRow[]): V2MessageRow[] { + if (v2Messages.length === 0) return [] + if (v1Messages.length === 0) return v2Messages + const lastV1 = v1Messages[v1Messages.length - 1] + const counterpart = v2Messages.find((message) => message.id === lastV1.id) + if (counterpart) { + const v1Ids = new Set(v1Messages.map((message) => message.id)) + return v2Messages.filter((message) => { + if (v1Ids.has(message.id)) return false + return message.seq > counterpart.seq + }) + } + // The ids differ: align the mirrored prefix by position instead. + const v1Mirrorable = v1Messages.filter((messageRow) => { + const parsed = parseJson(messageRow.data) + const role = typeof parsed?.role === 'string' ? parsed.role : null + return role === 'user' || role === 'assistant' + }) + if (v1Mirrorable.length === 0) return v2Messages + const mirror = v2Messages.filter((message) => message.type === 'user' || message.type === 'assistant') + if (mirror.length < v1Mirrorable.length) { + // Inconsistent mirror (fewer v2 rows than v1 chat messages): keep the + // v1 transcript instead of importing a tail that may not belong here. + return [] + } + const cutoffIndex = v2Messages.indexOf(mirror[v1Mirrorable.length - 1]) + if (cutoffIndex < 0) return [] + return v2Messages.slice(cutoffIndex + 1) +} + async function buildSessionMessages( db: DatabaseLike, - summary: OpencodeLocalSessionSummary + summary: OpencodeLocalSessionSummary, + availability: SchemaAvailability ): Promise { const messages: OpencodeImportedMessage[] = [] let createdAt = summary.modifiedAt try { - const messageRows = db.query( - `SELECT id, data, time_created FROM message WHERE session_id = ? ORDER BY time_created ASC` - ).all(summary.id) as Array<{ id: string; data: unknown; time_created: number | string }> - for (const messageRow of messageRows) { + const v1Messages = availability.v1 ? readV1Messages(db, summary.id) : [] + const v2Messages = availability.v2 ? readV2Messages(db, summary.id) : [] + const v2Tail = selectV2Tail(v1Messages, v2Messages) + for (const messageRow of v1Messages) { const parsed = parseJson(messageRow.data) const role = typeof parsed?.role === 'string' ? parsed.role : null if (!role) continue @@ -199,9 +372,19 @@ async function buildSessionMessages( }) } } + for (const messageRow of v2Tail) { + createdAt = normalizeTimestamp(messageRow.time_created, createdAt) + for (const text of collectV2Texts(messageRow)) { + messages.push({ + localId: `opencode:${summary.id}:${messageRow.id}:${text.key}`, + createdAt, + content: text.envelope === 'user' ? importedUser(text.text) : importedAgent(text.text, text.key) + }) + } + } } catch (error) { - if (messages.length === 0 && error instanceof Error && /no such table: message/i.test(error.message)) { - // Fresh installations without the message table yet: empty history. + if (messages.length === 0 && error instanceof Error && /no such table: (message|session_message)/i.test(error.message)) { + // Fresh installations without the message tables yet: empty history. // Anything else (including a missing part table mid-transcript) // must propagate so callers never persist a partial snapshot. return { ...summary, messages } @@ -211,6 +394,143 @@ async function buildSessionMessages( return { ...summary, messages } } +function readV1Sessions(db: DatabaseLike, limit: number): SessionRow[] { + try { + return db.query( + `SELECT id, title, directory, time_updated FROM session WHERE time_archived IS NULL ORDER BY time_updated DESC LIMIT ?` + ).all(limit) as SessionRow[] + } catch { + return [] + } +} + +function readV2Sessions(db: DatabaseLike, limit: number): SessionRow[] { + // session_v2 tracks archived sessions like the v1 table does. + const archivedFilter = hasColumn(db, 'session_v2', 'time_archived') ? ' WHERE time_archived IS NULL' : '' + // The model column carries the launch hint (D8); older databases lack it. + const modelColumn = hasColumn(db, 'session_v2', 'model') ? ', model' : '' + try { + return db.query( + `SELECT id, title, directory, time_updated${modelColumn} FROM session_v2${archivedFilter} ORDER BY time_updated DESC LIMIT ?` + ).all(limit) as SessionRow[] + } catch { + return [] + } +} + +// Ids of the sessions that are archived in either table. A migrated database +// keeps the v1 rows of an archived session around, and the v2 row of a +// session that was archived in v1 is not archived itself, so the archive +// state of both tables has to be merged before the list is built. +function readArchivedSessionIds(db: DatabaseLike, table: 'session' | 'session_v2'): Set { + try { + const rows = db.query( + `SELECT id FROM ${table} WHERE time_archived IS NOT NULL` + ).all() as Array<{ id: string }> + return new Set(rows.map((row) => row.id)) + } catch { + return new Set() + } +} + +function collectArchivedSessionIds(db: DatabaseLike, availability: SchemaAvailability): Set { + const archivedIds = new Set() + if (availability.v1) { + for (const id of readArchivedSessionIds(db, 'session')) archivedIds.add(id) + } + if (availability.v2 && hasColumn(db, 'session_v2', 'time_archived')) { + for (const id of readArchivedSessionIds(db, 'session_v2')) archivedIds.add(id) + } + return archivedIds +} + +// One entry per session id: the v2 row wins, but a null v2 title/directory +// falls back to the v1 value instead of blanking the session. Archived +// sessions are dropped from the list. +function mergeSessionRows(v1Rows: SessionRow[], v2Rows: SessionRow[], archivedIds: Set): MergedSessionRow[] { + const merged = new Map() + for (const row of v1Rows) { + if (archivedIds.has(row.id)) continue + const entry = merged.get(row.id) ?? { v1: null, v2: null } + entry.v1 = row + merged.set(row.id, entry) + } + for (const row of v2Rows) { + if (archivedIds.has(row.id)) continue + const entry = merged.get(row.id) ?? { v1: null, v2: null } + entry.v2 = row + merged.set(row.id, entry) + } + const rows: MergedSessionRow[] = [] + for (const [id, entry] of merged) { + const v1 = entry.v1 + const v2 = entry.v2 + rows.push({ + id, + title: v2?.title ?? v1?.title ?? null, + directory: v2?.directory ?? v1?.directory ?? null, + time_updated: v2?.time_updated ?? v1?.time_updated ?? 0, + model: v2?.model ?? null + }) + } + return rows +} + +function sortByModifiedAt(rows: MergedSessionRow[]): MergedSessionRow[] { + return [...rows].sort((a, b) => normalizeTimestamp(b.time_updated, 0) - normalizeTimestamp(a.time_updated, 0)) +} + +function buildSummary( + db: DatabaseLike, + row: MergedSessionRow, + dbPath: string, + availability: SchemaAvailability +): OpencodeLocalSessionSummary { + return { + id: row.id, + title: row.title ?? '', + lastUserMessage: extractLastUserMessage(db, row.id, availability), + cwd: row.directory ?? null, + file: dbPath, + modifiedAt: normalizeTimestamp(row.time_updated, Date.now()), + ...(row.model ? { model: row.model } : {}) + } +} + +function findSessionRow(db: DatabaseLike, id: string, availability: SchemaAvailability): MergedSessionRow | null { + let v1: SessionRow | null = null + let v2: SessionRow | null = null + if (availability.v1) { + try { + const rows = db.query( + `SELECT id, title, directory, time_updated FROM session WHERE id = ?` + ).all(id) as SessionRow[] + v1 = rows[0] ?? null + } catch { + v1 = null + } + } + if (availability.v2) { + try { + const modelColumn = hasColumn(db, 'session_v2', 'model') ? ', model' : '' + const rows = db.query( + `SELECT id, title, directory, time_updated${modelColumn} FROM session_v2 WHERE id = ?` + ).all(id) as SessionRow[] + v2 = rows[0] ?? null + } catch { + v2 = null + } + } + if (!v1 && !v2) return null + return { + id, + title: v2?.title ?? v1?.title ?? null, + directory: v2?.directory ?? v1?.directory ?? null, + time_updated: v2?.time_updated ?? v1?.time_updated ?? 0, + model: v2?.model ?? null + } +} + export async function listLocalOpencodeSessionSummaries( limit = DEFAULT_OPENCODE_SESSION_SCAN_LIMIT, opener?: OpencodeDatabaseOpener @@ -220,30 +540,17 @@ export async function listLocalOpencodeSessionSummaries( const db = await openDb(dbPath, opener) if (!db) return [] try { - if (!hasRequiredTables(db)) return [] + const availability = getSchemaAvailability(db) + if (!availability.v1 && !availability.v2) return [] const exec = db.exec?.bind(db) const inTransaction = typeof exec === 'function' if (inTransaction) exec('BEGIN DEFERRED') - let rows: SessionRow[] = [] try { - rows = db.query( - `SELECT id, title, directory, time_updated FROM session WHERE time_archived IS NULL ORDER BY time_updated DESC LIMIT ?` - ).all(limit) as SessionRow[] - } catch { - if (inTransaction) { - try { exec('ROLLBACK') } catch {} - } - return [] - } - try { - const summaries = rows.map((row) => ({ - id: row.id, - title: row.title ?? '', - lastUserMessage: extractLastUserMessage(db, row.id), - cwd: row.directory ?? null, - file: dbPath, - modifiedAt: normalizeTimestamp(row.time_updated, Date.now()) - })) + const v1Rows = availability.v1 ? readV1Sessions(db, limit) : [] + const v2Rows = availability.v2 ? readV2Sessions(db, limit) : [] + const archivedIds = collectArchivedSessionIds(db, availability) + const rows = sortByModifiedAt(mergeSessionRows(v1Rows, v2Rows, archivedIds)).slice(0, limit) + const summaries = rows.map((row) => buildSummary(db, row, dbPath, availability)) if (inTransaction) exec('COMMIT') return summaries } catch (error) { @@ -266,18 +573,11 @@ export async function listLocalOpencodeSessionsWithMessagesByIds( const db = await openDb(dbPath, opener) if (!db) return [] try { - if (!hasRequiredTables(db)) return [] + const availability = getSchemaAvailability(db) + if (!availability.v1 && !availability.v2) return [] const sessions: OpencodeLocalSessionWithMessages[] = [] for (const id of ids) { - let rows: SessionRow[] = [] - try { - rows = db.query( - `SELECT id, title, directory, time_updated FROM session WHERE id = ?` - ).all(id) as SessionRow[] - } catch { - continue - } - const row = rows[0] + const row = findSessionRow(db, id, availability) if (!row) continue // Read messages and their parts inside one deferred transaction: // OpenCode may write while we scan, and a snapshot hole here would @@ -286,15 +586,8 @@ export async function listLocalOpencodeSessionsWithMessagesByIds( const inTransaction = typeof exec === 'function' if (inTransaction) exec('BEGIN DEFERRED') try { - const summary: OpencodeLocalSessionSummary = { - id: row.id, - title: row.title ?? '', - lastUserMessage: extractLastUserMessage(db, row.id), - cwd: row.directory ?? null, - file: dbPath, - modifiedAt: normalizeTimestamp(row.time_updated, Date.now()) - } - sessions.push(await buildSessionMessages(db, summary)) + const summary = buildSummary(db, row, dbPath, availability) + sessions.push(await buildSessionMessages(db, summary, availability)) if (inTransaction) exec('COMMIT') } catch (error) { if (inTransaction) { diff --git a/hub/src/sync/rpcGateway.ts b/hub/src/sync/rpcGateway.ts index c91de7fc..42d5d455 100644 --- a/hub/src/sync/rpcGateway.ts +++ b/hub/src/sync/rpcGateway.ts @@ -18,6 +18,8 @@ import { ListOpencodeSessionsRpcResponseSchema, ListPiSessionsRpcResponseSchema } from '@hapi/protocol/apiTypes' +import { ListLocalSessionsRpcResponseSchema } from '@hapi/protocol/localTranscript' +import type { ListLocalSessionsRpcResponse, LocalSessionFlavor } from '@hapi/protocol/localTranscript' import type { AbortChunkedUploadResponse, AgyModelsResponse, @@ -662,6 +664,20 @@ export class RpcGateway { return ArchiveCodexSessionRpcResponseSchema.parse(result) } + async listLocalSessionsForMachine(machineId: string, params: { + flavor: LocalSessionFlavor + cwd?: string | null + sessionIds?: string[] | null + }): Promise { + const result = await this.machineRpc( + machineId, + RPC_METHODS.ListLocalSessions, + { flavor: params.flavor, cwd: params.cwd ?? null, sessionIds: params.sessionIds ?? undefined }, + MODEL_LIST_RPC_TIMEOUT_MS + ) + return ListLocalSessionsRpcResponseSchema.parse(result) + } + async listCursorModelsForSession(sessionId: string): Promise { return await this.sessionRpc(sessionId, RPC_METHODS.ListCursorModels, {}, MODEL_LIST_RPC_TIMEOUT_MS) as RpcListCursorModelsResponse } diff --git a/hub/src/sync/sessionCache.ts b/hub/src/sync/sessionCache.ts index 4875fbe6..5991b0b3 100644 --- a/hub/src/sync/sessionCache.ts +++ b/hub/src/sync/sessionCache.ts @@ -20,12 +20,32 @@ const TURN_RECOVERY_WINDOW_MS = 10 * 60_000 const METADATA_RETRY_ATTEMPTS = 5 type RuntimeConfigKey = 'permissionMode' | 'model' | 'modelReasoningEffort' | 'effort' | 'serviceTier' | 'collaborationMode' | 'copilotAgentMode' +/** + * Codex and Claude keep their native session files on one machine, and + * local-session import binds a HAPI session to the machine it read the + * transcript from. Two sessions recorded on different machines are + * therefore separate conversations even when the native ids collide + * (copied or shared agent homes): dedup must not merge one into the other. + * Rows without a machine keep the id-only match. Pi and OpenCode are + * scoped strictly by their dedupe key instead. + */ +function isRecordedOnAnotherMachine( + field: string, + a: NonNullable, + b: NonNullable +): boolean { + if (field !== 'codexSessionId' && field !== 'claudeSessionId') return false + return typeof a.machineId === 'string' + && typeof b.machineId === 'string' + && a.machineId !== b.machineId +} + export class SessionCache { private readonly sessions: Map = new Map() private readonly lastBroadcastAtBySessionId: Map = new Map() private readonly todoBackfillAttemptedSessionIds: Set = new Set() private readonly deduplicateInProgress: Set = new Set() - private readonly deduplicatePending: Set = new Set() + private readonly deduplicatePending: Map> = new Map() private readonly pendingThinkingUntilBySessionId: Map = new Map() private readonly runtimeConfigUpdatedAtBySessionId: Map>> = new Map() /** @@ -2736,31 +2756,56 @@ export class SessionCache { // coalesce this trigger and run one more pass afterwards. This matters // 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. + // then be allowed to delete the inactive duplicate record. The pass + // re-runs from each session that asked: Codex and Claude candidates + // are filtered by the triggering session's machine, so a trigger from + // another machine needs its own pass. if (this.deduplicateInProgress.has(agentId.dedupeKey)) { - this.deduplicatePending.add(agentId.dedupeKey) + const pending = this.deduplicatePending.get(agentId.dedupeKey) ?? new Set() + pending.add(sessionId) + this.deduplicatePending.set(agentId.dedupeKey, pending) return } this.deduplicateInProgress.add(agentId.dedupeKey) + let passSessionId = sessionId + const queued: string[] = [] + const takeNextPass = (): boolean => { + const pending = this.deduplicatePending.get(agentId.dedupeKey) + this.deduplicatePending.delete(agentId.dedupeKey) + for (const id of pending ?? []) { + if (!queued.includes(id)) queued.push(id) + } + while (queued.length > 0) { + const next = queued.shift()! + const nextSession = this.sessions.get(next) + if (nextSession?.metadata && this.extractAgentSessionId(nextSession.metadata)?.dedupeKey === agentId.dedupeKey) { + passSessionId = next + return true + } + } + return false + } + try { do { - this.deduplicatePending.delete(agentId.dedupeKey) - - const currentSession = this.sessions.get(sessionId) + const currentSession = this.sessions.get(passSessionId) + const passSession = currentSession ?? session + const passMetadata = currentSession?.metadata ?? session.metadata const candidates: { id: string; session: Session }[] = [] const machineScoped = agentId.field === 'piSessionId' || agentId.field === 'opencodeSessionId' if (currentSession?.metadata && currentSession.metadata[agentId.field] === agentId.value) { if (!machineScoped || currentSession.metadata.machineId === agentId.machineId) { - candidates.push({ id: sessionId, session: currentSession }) + candidates.push({ id: passSessionId, session: currentSession }) } } for (const [existingId, existing] of this.sessions) { - if (existingId === sessionId) continue - if (existing.namespace !== session.namespace) continue + if (existingId === passSessionId) continue + if (existing.namespace !== passSession.namespace) continue if (!existing.metadata) continue if (existing.metadata[agentId.field] !== agentId.value) continue if (machineScoped && existing.metadata.machineId !== agentId.machineId) continue + if (isRecordedOnAnotherMachine(agentId.field, passMetadata, existing.metadata)) continue candidates.push({ id: existingId, session: existing }) } @@ -2782,8 +2827,8 @@ export class SessionCache { if (a.session.active !== b.session.active) return a.session.active ? -1 : 1 const updatedDelta = b.session.updatedAt - a.session.updatedAt if (updatedDelta !== 0) return updatedDelta - if (a.id === sessionId) return -1 - if (b.id === sessionId) return 1 + if (a.id === passSessionId) return -1 + if (b.id === passSessionId) return 1 return b.session.activeAt - a.session.activeAt }) const targetId = candidates[0].id @@ -2808,7 +2853,7 @@ export class SessionCache { // best-effort: duplicate remains if merge fails } } - } while (this.deduplicatePending.has(agentId.dedupeKey)) + } while (takeNextPass()) } finally { 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 42df3baa..ce066ee1 100644 --- a/hub/src/sync/sessionModel.test.ts +++ b/hub/src/sync/sessionModel.test.ts @@ -4248,6 +4248,81 @@ describe('session model', () => { store.close() }) + for (const [flavor, field] of [['codex', 'codexSessionId'], ['claude', 'claudeSessionId']] as const) { + it(`does not merge the same ${flavor} 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( + `${flavor}-tag-1`, + { path: '/tmp/project', host: 'one', machineId: 'machine-1', flavor, [field]: 'native-id' }, + null, + 'default' + ) + const s2 = cache.getOrCreateSession( + `${flavor}-tag-2`, + { path: '/tmp/project', host: 'two', machineId: 'machine-2', flavor, [field]: 'native-id' }, + null, + 'default' + ) + + await cache.deduplicateByAgentSessionId(s2.id) + + expect(cache.getSession(s1.id)).toBeDefined() + expect(cache.getSession(s2.id)).toBeDefined() + store.close() + }) + + it(`still merges the same ${flavor} session id when one side has no machine`, async () => { + const store = new Store(':memory:') + const events: SyncEvent[] = [] + const cache = new SessionCache(store, createPublisher(events)) + const s1 = cache.getOrCreateSession( + `${flavor}-tag-1`, + { path: '/tmp/project', host: 'one', flavor, [field]: 'native-id' }, + null, + 'default' + ) + const s2 = cache.getOrCreateSession( + `${flavor}-tag-2`, + { path: '/tmp/project', host: 'two', machineId: 'machine-2', flavor, [field]: 'native-id' }, + null, + 'default' + ) + + await cache.deduplicateByAgentSessionId(s2.id) + + expect([cache.getSession(s1.id), cache.getSession(s2.id)].filter(Boolean)).toHaveLength(1) + store.close() + }) + + it(`runs a ${flavor} dedup triggered on another machine while one pass is in flight`, async () => { + const store = new Store(':memory:') + const events: SyncEvent[] = [] + const cache = new SessionCache(store, createPublisher(events)) + const create = (tag: string, machineId: string) => cache.getOrCreateSession( + tag, + { path: '/tmp/project', host: machineId, machineId, flavor, [field]: 'native-id' }, + null, + 'default' + ) + const a1 = create(`${flavor}-a1`, 'machine-a') + const a2 = create(`${flavor}-a2`, 'machine-a') + const b1 = create(`${flavor}-b1`, 'machine-b') + const b2 = create(`${flavor}-b2`, 'machine-b') + + // Machine A's pass is still merging when machine B's trigger + // arrives; the follow-up pass must cover machine B's pair. + const first = cache.deduplicateByAgentSessionId(a2.id) + const second = cache.deduplicateByAgentSessionId(b2.id) + await Promise.all([first, second]) + + expect([cache.getSession(a1.id), cache.getSession(a2.id)].filter(Boolean)).toHaveLength(1) + expect([cache.getSession(b1.id), cache.getSession(b2.id)].filter(Boolean)).toHaveLength(1) + 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 6b8fd352..b69ec7e1 100644 --- a/hub/src/sync/syncEngine.ts +++ b/hub/src/sync/syncEngine.ts @@ -16,6 +16,7 @@ import type { AbortChunkedUploadResponse, CursorChatStoreStatus, CursorMigrateOu import type { UsageQueryAgent, UsageQueryAgentSettings, UsageQueryResult, UsageQuerySettingsResponse, UsageQueryTemplate } from '@hapi/protocol/usageQuery' import type { SteerQueuedMessageResponse } from '@hapi/protocol/schemas' import type { SessionStopPreparationLease } from '@hapi/protocol/rpcMethods' +import type { ListLocalSessionsRpcResponse, LocalSessionFlavor } from '@hapi/protocol/localTranscript' import type { CopilotReasoningEffortResponse, ImplementCodexPlanResult, KimiReasoningEffortResponse } from '@hapi/protocol/apiTypes' import type { AgentFlavor, BackgroundTask, CodexCollaborationMode, CopilotAgentMode, DecryptedMessage, PermissionMode, Session, SyncEvent } from '@hapi/protocol/types' import { hasConversationMessageContent, unwrapRoleWrappedRecordEnvelope } from '@hapi/protocol/messages' @@ -6064,6 +6065,14 @@ export class SyncEngine { return await this.rpcGateway.archiveCodexSessionForMachine(machineId, sessionId) } + async listLocalSessionsForMachine(machineId: string, params: { + flavor: LocalSessionFlavor + cwd?: string | null + sessionIds?: string[] | null + }): Promise { + return await this.rpcGateway.listLocalSessionsForMachine(machineId, params) + } + async listCursorModelsForSession(sessionId: string): Promise { return await this.rpcGateway.listCursorModelsForSession(sessionId) } diff --git a/hub/src/web/routes/codexDesktop.test.ts b/hub/src/web/routes/codexDesktop.test.ts index 6bcee5c9..2456581b 100644 --- a/hub/src/web/routes/codexDesktop.test.ts +++ b/hub/src/web/routes/codexDesktop.test.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, it } from 'bun:test' import { randomUUID } from 'node:crypto' -import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs' +import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { Hono } from 'hono' @@ -9,314 +9,10 @@ import { Store } from '../../store' import { SyncEngine, type Machine } from '../../sync/syncEngine' import { RpcRegistry } from '../../socket/rpcRegistry' import type { WebAppEnv } from '../middleware/auth' -import { createCodexDesktopRoutes, getDarwinCodexOpenArgs, importSelectedCodexSessions } from './codexDesktop' +import { createCodexDesktopRoutes, getDarwinCodexOpenArgs, importSelectedCodexSessions, type CodexImportedMessageContent } from './codexDesktop' const originalCodexHome = process.env.CODEX_HOME -function createTranscript(codexHome: string, sessionId: string, cwd = 'C:\\work\\project'): void { - const sessionDir = join(codexHome, 'sessions', '2026', '06', '04') - mkdirSync(sessionDir, { recursive: true }) - const transcriptPath = join(sessionDir, `rollout-${sessionId}.jsonl`) - const lines = [ - { - type: 'session_meta', - payload: { - id: sessionId, - cwd, - originator: 'codex_cli_rs', - cli_version: '0.0.0-test' - } - }, - { - type: 'response_item', - payload: { - type: 'message', - role: 'user', - content: [{ type: 'input_text', text: 'normal user message' }] - } - }, - { - type: 'response_item', - payload: { - type: 'message', - role: 'assistant', - content: [{ type: 'output_text', text: 'normal assistant message' }] - } - } - ] - writeFileSync(transcriptPath, `${lines.map((line) => JSON.stringify(line)).join('\n')}\n`, 'utf-8') -} - -function createMirroredTranscript(codexHome: string, sessionId: string): void { - const sessionDir = join(codexHome, 'sessions', '2026', '06', '04') - mkdirSync(sessionDir, { recursive: true }) - const transcriptPath = join(sessionDir, 'rollout-' + sessionId + '.jsonl') - const transcriptLines = [ - { - type: 'session_meta', - payload: { - id: sessionId, - cwd: 'C:/work/project', - originator: 'codex_cli_rs', - cli_version: '0.0.0-test' - } - }, - { - type: 'event_msg', - payload: { type: 'user_message', message: 'mirrored user message' } - }, - { - type: 'response_item', - payload: { - type: 'message', - role: 'user', - content: [{ type: 'input_text', text: 'mirrored user message\n' }] - } - } - ] - writeFileSync(transcriptPath, transcriptLines.map((line) => JSON.stringify(line)).join('\n') + '\n', 'utf-8') -} - -function createMirroredAgentMessageTranscript(codexHome: string, sessionId: string): void { - const sessionDir = join(codexHome, 'sessions', '2026', '06', '04') - mkdirSync(sessionDir, { recursive: true }) - const transcriptPath = join(sessionDir, 'rollout-' + sessionId + '.jsonl') - const transcriptLines = [ - { - type: 'session_meta', - payload: { - id: sessionId, - cwd: 'C:/work/project', - originator: 'codex_cli_rs', - cli_version: '0.0.0-test' - } - }, - { - type: 'event_msg', - payload: { type: 'agent_message', message: 'duplicated assistant message' } - }, - { - type: 'response_item', - payload: { - type: 'message', - role: 'assistant', - content: [{ type: 'output_text', text: 'duplicated assistant message' }] - } - } - ] - writeFileSync(transcriptPath, transcriptLines.map((line) => JSON.stringify(line)).join('\n') + '\n', 'utf-8') -} - -function createInjectedResponseUserTranscript(codexHome: string, sessionId: string): void { - const sessionDir = join(codexHome, 'sessions', '2026', '06', '04') - mkdirSync(sessionDir, { recursive: true }) - const transcriptPath = join(sessionDir, 'rollout-' + sessionId + '.jsonl') - const transcriptLines = [ - { - type: 'session_meta', - payload: { - id: sessionId, - cwd: 'C:/work/project', - originator: 'codex_cli_rs', - cli_version: '0.0.0-test' - } - }, - { - type: 'response_item', - payload: { - type: 'message', - role: 'user', - content: [{ type: 'input_text', text: `# AGENTS.md instructions for /repo -ignore` }] - } - }, - { - type: 'response_item', - payload: { - type: 'message', - role: 'user', - content: [{ type: 'input_text', text: ` -2026-07-07 -workspace -` }] - } - }, - { - type: 'event_msg', - payload: { type: 'user_message', message: 'real event user message' } - } - ] - writeFileSync(transcriptPath, transcriptLines.map((line) => JSON.stringify(line)).join('\n') + '\n', 'utf-8') -} - -function createEmbeddedEnvironmentPromptTranscript(codexHome: string, sessionId: string): void { - const sessionDir = join(codexHome, 'sessions', '2026', '06', '04') - mkdirSync(sessionDir, { recursive: true }) - const transcriptPath = join(sessionDir, 'rollout-' + sessionId + '.jsonl') - const transcriptLines = [ - { - type: 'session_meta', - payload: { - id: sessionId, - cwd: 'C:/work/project', - originator: 'codex_cli_rs', - cli_version: '0.0.0-test' - } - }, - { - type: 'response_item', - payload: { - type: 'message', - role: 'user', - content: [{ type: 'input_text', text: `Please inspect this transcript block: - -2026-07-07 - -This is part of my prompt.` }] - } - } - ] - writeFileSync(transcriptPath, transcriptLines.map((line) => JSON.stringify(line)).join('\n') + '\n', 'utf-8') -} - -function createSameSourceDuplicateTranscript(codexHome: string, sessionId: string): void { - const sessionDir = join(codexHome, 'sessions', '2026', '06', '04') - mkdirSync(sessionDir, { recursive: true }) - const transcriptPath = join(sessionDir, 'rollout-' + sessionId + '.jsonl') - const transcriptLines = [ - { - type: 'session_meta', - payload: { - id: sessionId, - cwd: 'C:/work/project', - originator: 'codex_cli_rs', - cli_version: '0.0.0-test' - } - }, - { - type: 'response_item', - payload: { - type: 'message', - role: 'user', - content: [{ type: 'input_text', text: 'same source user message' }] - } - }, - { - type: 'response_item', - payload: { - type: 'message', - role: 'user', - content: [{ type: 'input_text', text: 'same source user message' }] - } - }, - { - type: 'response_item', - payload: { - type: 'message', - role: 'assistant', - content: [{ type: 'output_text', text: 'same source assistant message' }] - } - }, - { - type: 'response_item', - payload: { - type: 'message', - role: 'assistant', - content: [{ type: 'output_text', text: 'same source assistant message' }] - } - } - ] - writeFileSync(transcriptPath, transcriptLines.map((line) => JSON.stringify(line)).join('\n') + '\n', 'utf-8') -} - -function createRepeatedSameTextDistinctTurnTranscript(codexHome: string, sessionId: string): void { - const sessionDir = join(codexHome, 'sessions', '2026', '06', '04') - mkdirSync(sessionDir, { recursive: true }) - const transcriptPath = join(sessionDir, 'rollout-' + sessionId + '.jsonl') - const transcriptLines = [ - { - type: 'session_meta', - payload: { - id: sessionId, - cwd: 'C:/work/project', - originator: 'codex_cli_rs', - cli_version: '0.0.0-test' - } - }, - { - type: 'event_msg', - payload: { type: 'user_message', message: 'repeat user message' } - }, - { - type: 'response_item', - payload: { - type: 'message', - role: 'user', - content: [{ type: 'input_text', text: 'repeat user message' }] - } - }, - { - type: 'response_item', - payload: { - type: 'message', - role: 'assistant', - content: [{ type: 'output_text', text: 'assistant answer' }] - } - }, - { - type: 'response_item', - payload: { - type: 'message', - role: 'user', - content: [{ type: 'input_text', text: 'repeat user message' }] - } - } - ] - writeFileSync(transcriptPath, transcriptLines.map((line) => JSON.stringify(line)).join('\n') + '\n', 'utf-8') -} - -function createMirroredAndDistinctUserTranscript(codexHome: string, sessionId: string): void { - const sessionDir = join(codexHome, 'sessions', '2026', '06', '04') - mkdirSync(sessionDir, { recursive: true }) - const transcriptPath = join(sessionDir, 'rollout-' + sessionId + '.jsonl') - const transcriptLines = [ - { - type: 'session_meta', - payload: { - id: sessionId, - cwd: 'C:/work/project', - originator: 'codex_cli_rs', - cli_version: '0.0.0-test' - } - }, - { - type: 'event_msg', - payload: { type: 'user_message', message: 'first user message' } - }, - { - type: 'response_item', - payload: { - type: 'message', - role: 'user', - content: [{ type: 'input_text', text: 'first user message' }] - } - }, - { - type: 'event_msg', - payload: { type: 'user_message', message: 'second user message' } - } - ] - writeFileSync(transcriptPath, transcriptLines.map((line) => JSON.stringify(line)).join('\n') + '\n', 'utf-8') -} - -function writeSessionIndex(codexHome: string, records: Array<{ id: string; thread_name: string; updated_at: string }>): void { - writeFileSync( - join(codexHome, 'session_index.jsonl'), - records.map((record) => JSON.stringify(record)).join('\n') + '\n', - 'utf-8' - ) -} - function createMachine(id: string, workspaceRoots: string[], namespace = 'default'): Machine { return { id, @@ -338,8 +34,8 @@ function createMachine(id: string, workspaceRoots: string[], namespace = 'defaul } } -function createImportSyncEngine(store: Store, machines: Machine[]): SyncEngine { - return { +function createImportSyncEngine(store: Store, machines: Machine[], transcripts?: () => unknown[]): SyncEngine { + const engine = { getOnlineMachinesByNamespace: (namespace: string) => machines.filter((machine) => ( machine.namespace === namespace && machine.active )), @@ -359,6 +55,59 @@ function createImportSyncEngine(store: Store, machines: Machine[]): SyncEngine { store.sessions.touchSessionUpdatedAt(sessionId, updatedAt, 'default') } } as unknown as SyncEngine + return transcripts ? withLegacyCodexSessions(engine, transcripts) : engine +} + +/** + * Serve the legacy ListCodexSessions RPC from the given provider: the + * pre-registry wire shape the hub consumes through the source descriptor's + * legacy fallback (summaries for list calls, transcripts for id fetches). + */ +function withLegacyCodexSessions(engine: SyncEngine, provider: () => unknown[]): SyncEngine { + ;(engine as unknown as Record).listCodexSessionsForMachine = async (_machineId: string, _cwd: unknown, sessionIds?: string[] | null) => { + const wanted = sessionIds?.length ? new Set(sessionIds) : null + const sessions = provider() + .filter((session): session is Record => session !== null && typeof session === 'object') + .filter((session) => !wanted || wanted.has(session.id as string)) + return { + success: true, + sessions: wanted + ? sessions + : sessions.map((session) => ({ ...session, messages: undefined })) + } + } + return engine +} + +function codexUserMessage(text: string) { + return { + role: 'user', + content: { type: 'text', text }, + meta: { sentFrom: 'cli' } + } as const +} + +function codexAgentMessage(message: string, id = 'assistant-1') { + return { + role: 'agent', + content: { type: AGENT_MESSAGE_PAYLOAD_TYPE, data: { type: 'message', message, id } }, + meta: { sentFrom: 'cli' } + } as const +} + +/** Commit-3 runner fixture: the transcript rows ListLocalSessions delivers. */ +function codexThreadFixture(id: string, messages: CodexImportedMessageContent[], overrides: { + title?: string + cwd?: string +} = {}) { + return { + id, + title: overrides.title ?? `Codex thread ${id}`, + cwd: overrides.cwd ?? 'C:\\work\\project', + file: `rollout-${id}.jsonl`, + modifiedAt: 1, + messages + } } function createRoutesApp(namespace: string): Hono { @@ -384,20 +133,16 @@ describe('Codex Desktop import routes', () => { }) it('imports normal response_item chat messages', async () => { - const codexHome = mkdtempSync(join(tmpdir(), 'hapi-codex-home-test-')) const store = new Store(':memory:') const engine = new SyncEngine(store, {} as never, new RpcRegistry(), { broadcast() {} } as never) const codexSessionId = '11111111-1111-4111-8111-111111111111' - process.env.CODEX_HOME = codexHome try { - createTranscript(codexHome, codexSessionId) - const result = await importSelectedCodexSessions({ codexSessionIds: [codexSessionId], store, namespace: 'default', - getSyncEngine: () => engine + getSyncEngine: () => withLegacyCodexSessions(engine, () => [codexThreadFixture(codexSessionId, [ codexUserMessage('normal user message'), codexAgentMessage('normal assistant message', 'assistant-1') ])]), }) expect(result.success).toBe(true) @@ -433,18 +178,14 @@ describe('Codex Desktop import routes', () => { } finally { engine.stop() store.close() - rmSync(codexHome, { recursive: true, force: true }) } }) it('refuses a transcript import for an active Codex thread when stored messages do not match its prefix', async () => { - const codexHome = mkdtempSync(join(tmpdir(), 'hapi-codex-home-active-sync-test-')) const store = new Store(':memory:') const codexSessionId = '10101010-1010-4010-8010-101010101010' - process.env.CODEX_HOME = codexHome try { - createTranscript(codexHome, codexSessionId) const liveSession = store.sessions.getOrCreateSession('live-session', { path: 'C:\\work\\project', flavor: 'codex', @@ -462,7 +203,7 @@ describe('Codex Desktop import routes', () => { codexSessionIds: [codexSessionId], store, namespace: 'default', - getSyncEngine: () => engine + getSyncEngine: () => withLegacyCodexSessions(engine, () => [codexThreadFixture(codexSessionId, [ codexUserMessage('normal user message'), codexAgentMessage('normal assistant message') ])]), }) expect(result.success).toBe(false) @@ -472,24 +213,19 @@ describe('Codex Desktop import routes', () => { expect(store.messages.getAllMessages(liveSession.id)).toHaveLength(1) } finally { store.close() - rmSync(codexHome, { recursive: true, force: true }) } }) it('updates an existing forked import when syncing the original Codex session id', async () => { - const codexHome = mkdtempSync(join(tmpdir(), 'hapi-codex-home-source-test-')) const store = new Store(':memory:') const codexSessionId = '12121212-1212-4121-8121-121212121212' - process.env.CODEX_HOME = codexHome try { - createTranscript(codexHome, codexSessionId) - const first = await importSelectedCodexSessions({ codexSessionIds: [codexSessionId], store, namespace: 'default', - getSyncEngine: () => null + getSyncEngine: () => createImportSyncEngine(store, [], () => [codexThreadFixture(codexSessionId, [ codexUserMessage('normal user message'), codexAgentMessage('normal assistant message') ])]), }) expect(first.success).toBe(true) @@ -505,7 +241,7 @@ describe('Codex Desktop import routes', () => { codexSessionIds: [codexSessionId], store, namespace: 'default', - getSyncEngine: () => null + getSyncEngine: () => createImportSyncEngine(store, [], () => [codexThreadFixture(codexSessionId, [ codexUserMessage('normal user message'), codexAgentMessage('normal assistant message') ])]), }) expect(second.success).toBe(true) @@ -517,24 +253,19 @@ describe('Codex Desktop import routes', () => { }) } finally { store.close() - rmSync(codexHome, { recursive: true, force: true }) } }) it('deduplicates mirrored event_msg and response_item user messages', async () => { - const codexHome = mkdtempSync(join(tmpdir(), 'hapi-codex-home-mirror-test-')) const store = new Store(':memory:') const codexSessionId = '66666666-6666-4666-8666-666666666666' - process.env.CODEX_HOME = codexHome try { - createMirroredTranscript(codexHome, codexSessionId) - const result = await importSelectedCodexSessions({ codexSessionIds: [codexSessionId], store, namespace: 'default', - getSyncEngine: () => null + getSyncEngine: () => createImportSyncEngine(store, [], () => [codexThreadFixture(codexSessionId, [ codexUserMessage('mirrored user message') ])]), }) expect(result.success).toBe(true) @@ -554,24 +285,19 @@ describe('Codex Desktop import routes', () => { }) } finally { store.close() - rmSync(codexHome, { recursive: true, force: true }) } }) it('deduplicates adjacent mirrored agent messages with different ids', async () => { - const codexHome = mkdtempSync(join(tmpdir(), 'hapi-codex-home-agent-mirror-test-')) const store = new Store(':memory:') const codexSessionId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' - process.env.CODEX_HOME = codexHome try { - createMirroredAgentMessageTranscript(codexHome, codexSessionId) - const result = await importSelectedCodexSessions({ codexSessionIds: [codexSessionId], store, namespace: 'default', - getSyncEngine: () => null + getSyncEngine: () => createImportSyncEngine(store, [], () => [codexThreadFixture(codexSessionId, [ codexAgentMessage('duplicated assistant message', 'event-msg-id') ])]), }) expect(result.success).toBe(true) @@ -595,24 +321,19 @@ describe('Codex Desktop import routes', () => { }) } finally { store.close() - rmSync(codexHome, { recursive: true, force: true }) } }) it('skips injected response_item user context messages', async () => { - const codexHome = mkdtempSync(join(tmpdir(), 'hapi-codex-home-injected-user-test-')) const store = new Store(':memory:') const codexSessionId = '88888888-8888-4888-8888-888888888888' - process.env.CODEX_HOME = codexHome try { - createInjectedResponseUserTranscript(codexHome, codexSessionId) - const result = await importSelectedCodexSessions({ codexSessionIds: [codexSessionId], store, namespace: 'default', - getSyncEngine: () => null + getSyncEngine: () => createImportSyncEngine(store, [], () => [codexThreadFixture(codexSessionId, [ codexUserMessage('real event user message') ])]), }) expect(result.success).toBe(true) @@ -632,24 +353,19 @@ describe('Codex Desktop import routes', () => { }) } finally { store.close() - rmSync(codexHome, { recursive: true, force: true }) } }) it('preserves a real response_item user prompt containing embedded environment_context text', async () => { - const codexHome = mkdtempSync(join(tmpdir(), 'hapi-codex-home-embedded-env-test-')) const store = new Store(':memory:') const codexSessionId = 'abababab-abab-4bab-8bab-abababababab' - process.env.CODEX_HOME = codexHome try { - createEmbeddedEnvironmentPromptTranscript(codexHome, codexSessionId) - const result = await importSelectedCodexSessions({ codexSessionIds: [codexSessionId], store, namespace: 'default', - getSyncEngine: () => null + getSyncEngine: () => createImportSyncEngine(store, [], () => [codexThreadFixture(codexSessionId, [ codexUserMessage('Please inspect this transcript block:\n\n2026-07-07\n\nThis is part of my prompt.') ])]), }) expect(result.success).toBe(true) @@ -666,24 +382,19 @@ describe('Codex Desktop import routes', () => { }) } finally { store.close() - rmSync(codexHome, { recursive: true, force: true }) } }) it('preserves adjacent duplicate messages from the same transcript source', async () => { - const codexHome = mkdtempSync(join(tmpdir(), 'hapi-codex-home-same-source-duplicate-test-')) const store = new Store(':memory:') const codexSessionId = 'babababa-baba-4aba-8aba-babababababa' - process.env.CODEX_HOME = codexHome try { - createSameSourceDuplicateTranscript(codexHome, codexSessionId) - const result = await importSelectedCodexSessions({ codexSessionIds: [codexSessionId], store, namespace: 'default', - getSyncEngine: () => null + getSyncEngine: () => createImportSyncEngine(store, [], () => [codexThreadFixture(codexSessionId, [ codexUserMessage('same source user message'), codexUserMessage('same source user message'), codexAgentMessage('same source assistant message', 'assistant-1'), codexAgentMessage('same source assistant message', 'assistant-2') ])]), }) expect(result.success).toBe(true) @@ -699,24 +410,19 @@ describe('Codex Desktop import routes', () => { ]) } finally { store.close() - rmSync(codexHome, { recursive: true, force: true }) } }) it('keeps a later response_item-only user turn with the same text', async () => { - const codexHome = mkdtempSync(join(tmpdir(), 'hapi-codex-home-repeat-user-test-')) const store = new Store(':memory:') const codexSessionId = '99999999-9999-4999-8999-999999999999' - process.env.CODEX_HOME = codexHome try { - createRepeatedSameTextDistinctTurnTranscript(codexHome, codexSessionId) - const result = await importSelectedCodexSessions({ codexSessionIds: [codexSessionId], store, namespace: 'default', - getSyncEngine: () => null + getSyncEngine: () => createImportSyncEngine(store, [], () => [codexThreadFixture(codexSessionId, [ codexUserMessage('repeat user message'), codexAgentMessage('assistant answer'), codexUserMessage('repeat user message') ])]), }) expect(result.success).toBe(true) @@ -741,24 +447,19 @@ describe('Codex Desktop import routes', () => { }) } finally { store.close() - rmSync(codexHome, { recursive: true, force: true }) } }) it('keeps distinct user turns while deduplicating mirrored user events', async () => { - const codexHome = mkdtempSync(join(tmpdir(), 'hapi-codex-home-distinct-user-test-')) const store = new Store(':memory:') const codexSessionId = '77777777-7777-4777-8777-777777777777' - process.env.CODEX_HOME = codexHome try { - createMirroredAndDistinctUserTranscript(codexHome, codexSessionId) - const result = await importSelectedCodexSessions({ codexSessionIds: [codexSessionId], store, namespace: 'default', - getSyncEngine: () => null + getSyncEngine: () => createImportSyncEngine(store, [], () => [codexThreadFixture(codexSessionId, [ codexUserMessage('first user message'), codexUserMessage('second user message') ])]), }) expect(result.success).toBe(true) @@ -790,36 +491,19 @@ describe('Codex Desktop import routes', () => { ]) } finally { store.close() - rmSync(codexHome, { recursive: true, force: true }) } }) - it('uses the latest session_index thread_name for list and imported session title', async () => { - const codexHome = mkdtempSync(join(tmpdir(), 'hapi-codex-home-index-title-test-')) + it('uses the runner-resolved thread title for the imported session name', async () => { const store = new Store(':memory:') const codexSessionId = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' - process.env.CODEX_HOME = codexHome try { - createTranscript(codexHome, codexSessionId) - writeSessionIndex(codexHome, [ - { - id: codexSessionId, - thread_name: 'old thread title', - updated_at: '2026-07-07T01:00:00.000000000Z' - }, - { - id: codexSessionId, - thread_name: 'new thread title', - updated_at: '2026-07-07T02:00:00.000000000Z' - } - ]) - const result = await importSelectedCodexSessions({ codexSessionIds: [codexSessionId], store, namespace: 'default', - getSyncEngine: () => null + getSyncEngine: () => createImportSyncEngine(store, [], () => [codexThreadFixture(codexSessionId, [ codexUserMessage('normal user message'), codexAgentMessage('normal assistant message') ], { title: 'new thread title' })]), }) expect(result.success).toBe(true) @@ -831,24 +515,19 @@ describe('Codex Desktop import routes', () => { }) } finally { store.close() - rmSync(codexHome, { recursive: true, force: true }) } }) - it('falls back to transcript title when session_index is missing', async () => { - const codexHome = mkdtempSync(join(tmpdir(), 'hapi-codex-home-no-index-title-test-')) + it('uses the transcript-derived title when the runner sends no thread name override', async () => { const store = new Store(':memory:') const codexSessionId = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc' - process.env.CODEX_HOME = codexHome try { - createTranscript(codexHome, codexSessionId) - const result = await importSelectedCodexSessions({ codexSessionIds: [codexSessionId], store, namespace: 'default', - getSyncEngine: () => null + getSyncEngine: () => createImportSyncEngine(store, [], () => [codexThreadFixture(codexSessionId, [ codexUserMessage('normal user message'), codexAgentMessage('normal assistant message') ], { title: 'normal user message' })]), }) expect(result.success).toBe(true) @@ -860,31 +539,19 @@ describe('Codex Desktop import routes', () => { }) } finally { store.close() - rmSync(codexHome, { recursive: true, force: true }) } }) - it('falls back to transcript title when session_index has no matching id', async () => { - const codexHome = mkdtempSync(join(tmpdir(), 'hapi-codex-home-index-miss-title-test-')) + it('uses the fixture title when the runner index has no entry for the thread', async () => { const store = new Store(':memory:') const codexSessionId = 'dddddddd-dddd-4ddd-8ddd-dddddddddddd' - process.env.CODEX_HOME = codexHome try { - createTranscript(codexHome, codexSessionId) - writeSessionIndex(codexHome, [ - { - id: 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee', - thread_name: 'unrelated title', - updated_at: '2026-07-07T03:00:00.000000000Z' - } - ]) - const result = await importSelectedCodexSessions({ codexSessionIds: [codexSessionId], store, namespace: 'default', - getSyncEngine: () => null + getSyncEngine: () => createImportSyncEngine(store, [], () => [codexThreadFixture(codexSessionId, [ codexUserMessage('normal user message'), codexAgentMessage('normal assistant message') ], { title: 'normal user message' })]), }) expect(result.success).toBe(true) @@ -896,33 +563,28 @@ describe('Codex Desktop import routes', () => { }) } finally { store.close() - rmSync(codexHome, { recursive: true, force: true }) } }) it('applies selected Standard and Plan config before an imported session is resumed', async () => { - const codexHome = mkdtempSync(join(tmpdir(), 'hapi-codex-home-config-test-')) const store = new Store(':memory:') const codexSessionId = '23232323-2323-4232-8232-232323232323' - process.env.CODEX_HOME = codexHome + const engine = createImportSyncEngine(store, [ + createMachine('machine-1', ['/home/user/workspace']) + ]) + const applied: Array<{ sessionId: string; config: unknown }> = [] + ;(engine as unknown as { applySessionConfig: (sessionId: string, config: unknown) => Promise }).applySessionConfig = async (sessionId, config) => { + applied.push({ sessionId, config }) + } try { - createTranscript(codexHome, codexSessionId, '/home/user/workspace/project') - const engine = createImportSyncEngine(store, [ - createMachine('machine-1', ['/home/user/workspace']) - ]) - const applied: Array<{ sessionId: string; config: unknown }> = [] - ;(engine as unknown as { applySessionConfig: (sessionId: string, config: unknown) => Promise }).applySessionConfig = async (sessionId, config) => { - applied.push({ sessionId, config }) - } - const result = await importSelectedCodexSessions({ codexSessionIds: [codexSessionId], store, namespace: 'default', - getSyncEngine: () => engine, + getSyncEngine: () => withLegacyCodexSessions(engine, () => [codexThreadFixture(codexSessionId, [ codexUserMessage('normal user message'), codexAgentMessage('normal assistant message') ], { cwd: '/home/user/workspace/project' })]), serviceTier: 'standard', - collaborationMode: 'plan' + collaborationMode: 'plan', }) expect(result.success).toBe(true) @@ -937,31 +599,42 @@ describe('Codex Desktop import routes', () => { }]) } finally { store.close() - rmSync(codexHome, { recursive: true, force: true }) } }) - it('binds imported transcripts to the unique online machine that owns the cwd', async () => { - const codexHome = mkdtempSync(join(tmpdir(), 'hapi-codex-home-machine-test-')) + it('binds the sync to the unique online machine that owns the cwd', async () => { const store = new Store(':memory:') const codexSessionId = '22222222-2222-4222-8222-222222222222' - process.env.CODEX_HOME = codexHome + const engine = createImportSyncEngine(store, [ + createMachine('machine-1', ['/home/user/workspace']), + createMachine('machine-2', ['/other/workspace']) + ]) + const listCalls: Array<{ machineId: string; cwd: string | null }> = [] + ;(engine as unknown as { listCodexSessionsForMachine: unknown }).listCodexSessionsForMachine = async (machineId: string, cwd: string | null) => { + listCalls.push({ machineId, cwd }) + return { + success: true, + sessions: [codexThreadFixture(codexSessionId, [ + codexUserMessage('normal user message'), + codexAgentMessage('normal assistant message') + ], { cwd: '/home/user/workspace/project' })] + } + } + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + app.route('/api', createCodexDesktopRoutes({ store, getSyncEngine: () => engine })) try { - createTranscript(codexHome, codexSessionId, '/home/user/workspace/project') - const engine = createImportSyncEngine(store, [ - createMachine('machine-1', ['/home/user/workspace']), - createMachine('machine-2', ['/other/workspace']) - ]) - - const result = await importSelectedCodexSessions({ - codexSessionIds: [codexSessionId], - store, - namespace: 'default', - getSyncEngine: () => engine + const response = await app.request('/api/codex/sync-session', { + method: 'POST', + body: JSON.stringify({ sessionIds: [codexSessionId], cwd: '/home/user/workspace/project' }) }) - - expect(result.success).toBe(true) + const body = await response.json() as { success: boolean } + expect(body.success).toBe(true) + expect(listCalls).toEqual([{ machineId: 'machine-1', cwd: '/home/user/workspace/project' }]) const session = store.sessions.getSessionsByNamespace('default')[0] expect(session.metadata).toMatchObject({ path: '/home/user/workspace/project', @@ -969,97 +642,108 @@ describe('Codex Desktop import routes', () => { }) } finally { store.close() - rmSync(codexHome, { recursive: true, force: true }) } }) - it('does not bind imported transcripts when multiple online machines own the cwd', async () => { - const codexHome = mkdtempSync(join(tmpdir(), 'hapi-codex-home-machine-ambiguous-test-')) + it('syncs through the first online machine when several machines own the cwd', async () => { const store = new Store(':memory:') const codexSessionId = '33333333-3333-4333-8333-333333333333' - process.env.CODEX_HOME = codexHome + const engine = createImportSyncEngine(store, [ + createMachine('machine-1', ['/home/user/workspace']), + createMachine('machine-2', ['/home/user/workspace/project']) + ]) + const listCalls: string[] = [] + ;(engine as unknown as { listCodexSessionsForMachine: unknown }).listCodexSessionsForMachine = async (machineId: string) => { + listCalls.push(machineId) + return { + success: true, + sessions: [codexThreadFixture(codexSessionId, [ + codexUserMessage('normal user message'), + codexAgentMessage('normal assistant message') + ], { cwd: '/home/user/workspace/project' })] + } + } + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + app.route('/api', createCodexDesktopRoutes({ store, getSyncEngine: () => engine })) try { - createTranscript(codexHome, codexSessionId, '/home/user/workspace/project') - const engine = createImportSyncEngine(store, [ - createMachine('machine-1', ['/home/user/workspace']), - createMachine('machine-2', ['/home/user/workspace/project']) - ]) - - const result = await importSelectedCodexSessions({ - codexSessionIds: [codexSessionId], - store, - namespace: 'default', - getSyncEngine: () => engine + const response = await app.request('/api/codex/sync-session', { + method: 'POST', + body: JSON.stringify({ sessionIds: [codexSessionId], cwd: '/home/user/workspace/project' }) }) - - expect(result.success).toBe(true) + const body = await response.json() as { success: boolean } + expect(body.success).toBe(true) + expect(listCalls).toEqual(['machine-1']) const session = store.sessions.getSessionsByNamespace('default')[0] - expect(session.metadata).toMatchObject({ - path: '/home/user/workspace/project' - }) - expect(session.metadata).not.toHaveProperty('machineId') + expect(session.metadata).toMatchObject({ machineId: 'machine-1' }) } finally { store.close() - rmSync(codexHome, { recursive: true, force: true }) } }) - it('does not bind imported transcripts when no online machine owns the cwd', async () => { - const codexHome = mkdtempSync(join(tmpdir(), 'hapi-codex-home-machine-miss-test-')) + it('syncs through the first online machine when none owns the cwd', async () => { const store = new Store(':memory:') const codexSessionId = '44444444-4444-4444-8444-444444444444' - process.env.CODEX_HOME = codexHome + const engine = createImportSyncEngine(store, [ + createMachine('machine-1', ['/home/user/other']) + ]) + const listCalls: string[] = [] + ;(engine as unknown as { listCodexSessionsForMachine: unknown }).listCodexSessionsForMachine = async (machineId: string) => { + listCalls.push(machineId) + return { + success: true, + sessions: [codexThreadFixture(codexSessionId, [ + codexUserMessage('normal user message'), + codexAgentMessage('normal assistant message') + ], { cwd: '/home/user/workspace/project' })] + } + } + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + app.route('/api', createCodexDesktopRoutes({ store, getSyncEngine: () => engine })) try { - createTranscript(codexHome, codexSessionId, '/home/user/workspace/project') - const engine = createImportSyncEngine(store, [ - createMachine('machine-1', ['/home/user/other']) - ]) - - const result = await importSelectedCodexSessions({ - codexSessionIds: [codexSessionId], - store, - namespace: 'default', - getSyncEngine: () => engine + const response = await app.request('/api/codex/sync-session', { + method: 'POST', + body: JSON.stringify({ sessionIds: [codexSessionId], cwd: '/home/user/workspace/project' }) }) - - expect(result.success).toBe(true) + const body = await response.json() as { success: boolean } + expect(body.success).toBe(true) + expect(listCalls).toEqual(['machine-1']) const session = store.sessions.getSessionsByNamespace('default')[0] - expect(session.metadata).toMatchObject({ - path: '/home/user/workspace/project' - }) - expect(session.metadata).not.toHaveProperty('machineId') + expect(session.metadata).toMatchObject({ machineId: 'machine-1' }) } finally { store.close() - rmSync(codexHome, { recursive: true, force: true }) } }) it('does not append a Runner transcript to a session bound to another machine', async () => { - const codexHome = mkdtempSync(join(tmpdir(), 'hapi-codex-home-machine-existing-test-')) const store = new Store(':memory:') const codexSessionId = '55555555-5555-4555-8555-555555555555' - process.env.CODEX_HOME = codexHome + store.sessions.getOrCreateSession(randomUUID(), { + path: '/home/user/workspace/project', + flavor: 'codex', + codexSessionId, + machineId: 'machine-existing' + }, {}, 'default') + const engine = createImportSyncEngine(store, [ + createMachine('machine-new', ['/home/user/workspace']) + ]) try { - createTranscript(codexHome, codexSessionId, '/home/user/workspace/project') - store.sessions.getOrCreateSession(randomUUID(), { - path: '/home/user/workspace/project', - flavor: 'codex', - codexSessionId, - machineId: 'machine-existing' - }, {}, 'default') - const engine = createImportSyncEngine(store, [ - createMachine('machine-new', ['/home/user/workspace']) - ]) - const result = await importSelectedCodexSessions({ codexSessionIds: [codexSessionId], store, namespace: 'default', - getSyncEngine: () => engine, - machineId: 'machine-new' + getSyncEngine: () => withLegacyCodexSessions(engine, () => [codexThreadFixture(codexSessionId, [ codexUserMessage('normal user message'), codexAgentMessage('normal assistant message') ], { cwd: '/home/user/workspace/project' })]), + machineId: 'machine-new', }) expect(result.success).toBe(true) @@ -1075,19 +759,26 @@ describe('Codex Desktop import routes', () => { ))).toBe(true) } finally { store.close() - rmSync(codexHome, { recursive: true, force: true }) } }) - it('rejects Codex transcript endpoints outside the default namespace', async () => { + it('rejects Codex desktop sidecar routes outside the default namespace', async () => { const app = createRoutesApp('team-a') - const response = await app.request('/api/codex/sessions') + const response = await app.request('/api/codex/status') expect(response.status).toBe(403) expect(await response.json()).toEqual({ success: false, error: 'Codex transcript import is not available outside the default namespace' }) + + // Transcript list and sync are available in every namespace. + const listResponse = await app.request('/api/codex/sessions') + expect(listResponse.status).toBe(503) + expect(await listResponse.json()).toMatchObject({ + success: false, + error: 'No online machine available for Codex history import' + }) }) it('allows Codex transcript endpoints in the default namespace', async () => { @@ -1136,26 +827,22 @@ describe('Codex Desktop import routes', () => { }) it('does not append imports to an archived Codex session', async () => { - const codexHome = mkdtempSync(join(tmpdir(), 'hapi-codex-home-archived-target-test-')) const store = new Store(':memory:') const codexSessionId = '15151515-1515-4515-8515-151515151515' - process.env.CODEX_HOME = codexHome + const archived = store.sessions.getOrCreateSession('archived-session', { + path: 'C:\\work\\project', + flavor: 'codex', + codexSessionId, + lifecycleState: 'archived' + }, {}, 'default') + store.messages.addMessage(archived.id, { type: 'text', text: 'archived old message' }, 'archived-1') try { - createTranscript(codexHome, codexSessionId) - const archived = store.sessions.getOrCreateSession('archived-session', { - path: 'C:\\work\\project', - flavor: 'codex', - codexSessionId, - lifecycleState: 'archived' - }, {}, 'default') - store.messages.addMessage(archived.id, { type: 'text', text: 'archived old message' }, 'archived-1') - const result = await importSelectedCodexSessions({ codexSessionIds: [codexSessionId], store, namespace: 'default', - getSyncEngine: () => null + getSyncEngine: () => createImportSyncEngine(store, [], () => [codexThreadFixture(codexSessionId, [ codexUserMessage('normal user message'), codexAgentMessage('normal assistant message') ])]), }) expect(result.success).toBe(true) @@ -1166,7 +853,6 @@ describe('Codex Desktop import routes', () => { expect(store.messages.getAllMessages(result.hapiSessionIds![0]!)).toHaveLength(2) } finally { store.close() - rmSync(codexHome, { recursive: true, force: true }) } }) diff --git a/hub/src/web/routes/codexDesktop.ts b/hub/src/web/routes/codexDesktop.ts index 2540126a..e204a1ce 100644 --- a/hub/src/web/routes/codexDesktop.ts +++ b/hub/src/web/routes/codexDesktop.ts @@ -1,60 +1,71 @@ -import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync } from 'node:fs' -import { spawn, spawnSync } from 'node:child_process' -import { randomUUID } from 'node:crypto' -import { dirname, isAbsolute, join, resolve } from 'node:path' -import { homedir, hostname, platform } from 'node:os' import { AGENT_MESSAGE_PAYLOAD_TYPE } from '@hapi/protocol' import type { CodexCollaborationMode } from '@hapi/protocol/types' -import { Hono } from 'hono' +import { Hono, type Context } from 'hono' +import type { LocalTranscript, LocalTranscriptSummary } from '@hapi/protocol/localTranscript' import type { Machine, SyncEngine } from '../../sync/syncEngine' -import type { Store, StoredMessage } from '../../store' -import { truncateOversizedMessageContent } from '../../store/contentCodec' +import type { Store } from '../../store' import type { WebAppEnv } from '../middleware/auth' +import { importLocalTranscript } from './localSessions/importLocalTranscript' +import { fetchLocalTranscriptSummaries, fetchLocalTranscriptsByIds } from './localSessions/fetchLocalTranscripts' +import { CODEX_LOCAL_SESSION_SOURCE } from './localSessions/sources' +import { + appendScriptLog, + CODEX_DESKTOP_NOT_FOUND_ERROR, + collectImportCandidates, + DIRECT_IMPORT_COMMAND, + emitImportedMessageEvents, + getCodexDesktopStatus, + getCodexImportIds, + getDarwinCodexOpenArgs, + getDirectImportRouteContext, + getRestartScriptPath, + getRestartScriptWorkspace, + isImportCandidateReusable, + launchRestartScript, + listDuplicateCodexSessionGroups, + mergeDuplicateCodexSessionGroups, + normalizeComparableContent, + stableSerialize, + type CodexDesktopStatusResponse, + type CodexDuplicateSessionGroup, + type CodexDuplicateSessionsResponse, + type CodexMergeDuplicateSessionsResponse, + type ImportCandidate, + type ScriptLaunchResponse +} from './codexExtras' -type ScriptLogKind = 'sync' | 'restart' +// Sidecar capabilities (desktop restart, duplicate merge, script logs, compare +// helpers) moved out of the import path; re-exported so this module stays the +// single Codex route import surface. +export { + appendScriptLog, + CODEX_DESKTOP_NOT_FOUND_ERROR, + CODEX_TRANSCRIPT_IMPORT_NAMESPACE_ERROR, + collectImportCandidates, + DIRECT_IMPORT_COMMAND, + emitImportedMessageEvents, + getCodexDesktopStatus, + getCodexImportIds, + getDarwinCodexOpenArgs, + getDirectImportRouteContext, + getRestartScriptPath, + getRestartScriptWorkspace, + isImportCandidateReusable, + launchRestartScript, + listDuplicateCodexSessionGroups, + mergeDuplicateCodexSessionGroups, + normalizeComparableContent, + stableSerialize, + type CodexDesktopStatusResponse, + type CodexDuplicateSessionGroup, + type CodexDuplicateSessionsResponse, + type CodexMergeDuplicateSessionsResponse, + type ImportCandidate, + type ScriptLaunchResponse +} from './codexExtras' -const DIRECT_IMPORT_COMMAND = 'direct-import' -const RESTART_SCRIPT_ENV_NAME = 'HAPI_CODEX_RESTART_SCRIPT' -const RESTART_SCRIPT_DEFAULT_FILE = 'Restart-CodexDesktop.ps1' -const RESTART_SCRIPT_ARGS = ['-Apply'] -const RESTART_SCRIPT_MESSAGE = 'Codex Desktop restart script started' - -type ScriptLaunchResponse = { - success: true - message: string - pid: number - command: string - script?: string - cwd: string - output?: string - codexDesktopRunning?: boolean - codexClientAvailable?: boolean - syncedCount?: number - sessionIds?: string[] - hapiSessionIds?: string[] -} | { - success: false - error: string - script?: string - cwd: string - output?: string - codexDesktopRunning?: boolean - codexClientAvailable?: boolean - syncedCount?: number - sessionIds?: string[] - hapiSessionIds?: string[] -} - -type CodexDesktopStatus = { - running: boolean - clientAvailable: boolean -} - -type CodexDesktopStatusResponse = { - success: true - codexDesktopRunning: boolean - codexClientAvailable: boolean -} +const NO_SYNC_SESSION_SELECTED_ERROR = '未选择需要导入的 Codex 会话' +const CODEX_TRANSCRIPT_IMPORT_NAMESPACE_ERROR = 'Codex transcript import is not available outside the default namespace' type CodexLocalSessionSummary = { id: string @@ -65,6 +76,9 @@ type CodexLocalSessionSummary = { modifiedAt: number originator?: string | null cliVersion?: string | null + source?: string | null + threadSource?: string | null + forkedFromId?: string | null } type CodexLocalSessionsResponse = { @@ -98,34 +112,7 @@ type CodexImportedMessageContent = { } } -type CodexImportedMessageSource = 'event_msg' | 'response_item' -type CodexImportedMessageEntry = { - source: CodexImportedMessageSource - message: CodexImportedMessageContent -} - -type CodexTranscriptImportData = CodexLocalSessionSummary & { - messages: CodexImportedMessageContent[] -} - -type CodexSessionIndexTitle = { - threadName: string - updatedAt: string -} -type RemoteCodexSession = CodexTranscriptImportData - -type ImportCandidate = { - sessionId: string - active: boolean - updatedAt: number - metadata: Record | null - persisted: boolean -} - -type ImportTargetSelection = { - sessionId: string | null - comparablePrefixCount: number -} +export type { CodexImportedMessageContent } type SyncSessionRequestParseResult = { sessionIds: string[] @@ -139,733 +126,12 @@ type SyncSessionRequestParseResult = { error?: string } -type CodexDuplicateSessionGroup = { - codexSessionId: string - hapiSessionIds: string[] - canonicalSessionId?: string - removedSessionIds?: string[] -} - -type CodexDuplicateSessionsResponse = { - success: true - duplicates: CodexDuplicateSessionGroup[] -} | { - success: false - error: string -} - -type CodexMergeDuplicateSessionsResponse = { - success: true - merged: CodexDuplicateSessionGroup[] - mergedCount: number -} | { - success: false - error: string -} - -type DuplicateSessionGroupCandidate = { - codexSessionId: string - sessions: ImportCandidate[] -} - -const CODEX_DESKTOP_NOT_FOUND_ERROR = '尝试重启codex客户端失败,未安装/找不到codex客户端' -const SCRIPT_TIMEOUT_ERROR = '执行超时' -const NO_SYNC_SESSION_SELECTED_ERROR = '未选择需要导入的 Codex 会话' -const CODEX_TRANSCRIPT_IMPORT_NAMESPACE_ERROR = 'Codex transcript import is not available outside the default namespace' -const DEFAULT_SCRIPT_TIMEOUT_MS = 60_000 -const DEFAULT_CODEX_SESSION_SCAN_LIMIT = 500 -const DARWIN_CODEX_APP_NAME = 'Codex' -const DARWIN_CODEX_APP_CANDIDATES = [ - '/Applications/Codex.app', - join(homedir(), 'Applications', 'Codex.app') -] - -function resolveLocalPath(pathValue: string): string { - return isAbsolute(pathValue) ? pathValue : resolve(process.cwd(), pathValue) -} - -function getScriptRoot(): string { - const configured = process.env.HAPI_CODEX_SCRIPT_ROOT?.trim() - return configured ? resolveLocalPath(configured) : process.cwd() -} - -function getDefaultScriptPath(defaultFile: string): string { - const configuredRoot = process.env.HAPI_CODEX_SCRIPT_ROOT?.trim() - if (configuredRoot) { - return join(resolveLocalPath(configuredRoot), defaultFile) - } - - const cwd = process.cwd() - const candidateRoots = [ - cwd, - resolve(cwd, '..'), - resolve(cwd, '..', '..') - ] - - for (const root of candidateRoots) { - const candidate = join(root, defaultFile) - if (existsSync(candidate)) { - return candidate - } - } - - return join(getScriptRoot(), defaultFile) -} - -function getRestartScriptPath(): string { - const configured = process.env[RESTART_SCRIPT_ENV_NAME]?.trim() - return configured ? resolveLocalPath(configured) : getDefaultScriptPath(RESTART_SCRIPT_DEFAULT_FILE) -} - -function getWorkspace(scriptPath: string): string { - const configured = process.env.HAPI_CODEX_WORKSPACE?.trim() - return configured ? resolveLocalPath(configured) : dirname(scriptPath) -} - -function getDirectImportWorkspace(): string { - const configured = process.env.HAPI_CODEX_WORKSPACE?.trim() - return configured ? resolveLocalPath(configured) : process.cwd() -} - -function expandHomePath(pathValue: string): string { - return pathValue.replace(/^~(?=$|[\\/])/, homedir()) -} - -function getCodexHome(): string { - const configured = process.env.CODEX_HOME?.trim() - return configured ? resolveLocalPath(expandHomePath(configured)) : join(homedir(), '.codex') -} - -function getCodexSessionRoots(): string[] { - const codexHome = getCodexHome() - // 中文注释:当前 direct import 只从 sessions 目录解析 transcript,避免把 archived_sessions 中暂不参与导入的会话展示给用户。 - return [join(codexHome, 'sessions')] -} - -function getCodexSessionIndexPath(): string { - return join(getCodexHome(), 'session_index.jsonl') -} - -function collectJsonlFiles(root: string, files: string[]): void { - if (!existsSync(root)) return - let entries - 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) - continue - } - if (entry.isFile() && fullPath.toLowerCase().endsWith('.jsonl')) { - files.push(fullPath) - } - } -} - function asRecord(value: unknown): Record | null { return value !== null && typeof value === 'object' && !Array.isArray(value) ? value as Record : null } -function asString(value: unknown): string | null { - return typeof value === 'string' && value.length > 0 ? value : null -} - -function extractCodexText(value: unknown): string { - if (typeof value === 'string') { - return value.trim() - } - if (Array.isArray(value)) { - return value - .map((item) => { - const record = asRecord(item) - if (record?.type === 'text' && typeof record.text === 'string') return record.text - if (record?.type === 'input_text' && typeof record.text === 'string') return record.text - if (record?.type === 'output_text' && typeof record.text === 'string') return record.text - return null - }) - .filter((part): part is string => Boolean(part)) - .join(' ') - .trim() - } - const record = asRecord(value) - if (record?.type === 'text' && typeof record.text === 'string') { - return record.text.trim() - } - if (record?.type === 'input_text' && typeof record.text === 'string') { - return record.text.trim() - } - if (record?.type === 'output_text' && typeof record.text === 'string') { - return record.text.trim() - } - return '' -} - -function truncateText(value: string, maxLength: number): string { - return value.length > maxLength ? `${value.slice(0, maxLength - 1)}…` : value -} - -function shouldIgnoreInjectedResponseUserMessage(text: string): boolean { - const normalized = text.trim() - const lower = normalized.toLowerCase() - const isAgentInstructions = lower.startsWith('# agents.md instructions') - const isEnvironmentContext = lower.startsWith('') - && lower.endsWith('') - return isAgentInstructions || isEnvironmentContext -} - -function inferSessionIdFromFileName(filePath: string): string | null { - const match = /([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})/.exec(filePath) - return match?.[1] ?? null -} - -function parseCodexFunctionArguments(value: unknown): unknown { - if (typeof value !== 'string') { - return value - } - - const trimmed = value.trim() - if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) { - return value - } - - try { - return JSON.parse(trimmed) - } catch { - return value - } -} - -function extractCodexToolCallId(payload: Record): string | null { - const candidates = ['call_id', 'callId', 'tool_call_id', 'toolCallId', 'id'] - for (const key of candidates) { - const value = payload[key] - if (typeof value === 'string' && value.length > 0) { - return value - } - } - return null -} - -function extractCodexChangedTitle(record: Record): string | null { - const type = typeof record.type === 'string' ? record.type : null - if (type === 'response_item') { - const payload = asRecord(record.payload) - if (payload?.type === 'function_call' && payload.name === 'change_title') { - const argumentsText = typeof payload.arguments === 'string' ? payload.arguments : null - if (!argumentsText) return null - try { - const parsedArguments = JSON.parse(argumentsText) as { title?: unknown } - return typeof parsedArguments.title === 'string' && parsedArguments.title.trim() - ? parsedArguments.title.trim() - : null - } catch { - return null - } - } - } - - if (type === 'event_msg') { - const payload = asRecord(record.payload) - if (payload?.type === 'mcp_tool_call_end') { - const invocation = asRecord(payload.invocation) - const argumentsRecord = asRecord(invocation?.arguments) - if (invocation?.tool === 'change_title' && typeof argumentsRecord?.title === 'string' && argumentsRecord.title.trim()) { - return argumentsRecord.title.trim() - } - } - } - - return null -} - -function getLatestCodexChangedTitle(lines: string[]): string | null { - // 中文注释:Codex 会在 transcript 中记录 change_title 调用;这里从后往前取最后一次成功设置的标题,作为弹窗主标题显示。 - for (let index = lines.length - 1; index >= 0; index -= 1) { - try { - const parsed = JSON.parse(lines[index]) - const record = asRecord(parsed) - if (!record) continue - const title = extractCodexChangedTitle(record) - if (title) { - return title - } - } catch { - continue - } - } - return null -} - -function getLatestCodexUserMessage(lines: string[]): string | null { - // 中文注释:弹窗副标题展示最近一次真实用户提问,不再显示路径,便于用户按会话内容而不是目录来识别。 - for (let index = lines.length - 1; index >= 0; index -= 1) { - try { - const parsed = JSON.parse(lines[index]) - const record = asRecord(parsed) - if (!record || record.type !== 'response_item') continue - const payload = asRecord(record.payload) - if (payload?.type !== 'message' || payload.role !== 'user') continue - const text = extractCodexText(payload.content) - if (text && !shouldIgnoreInjectedResponseUserMessage(text)) { - return truncateText(text, 140) - } - } catch { - continue - } - } - return null -} - -function getCodexSessionTitle( - cwd: string | null | undefined, - sessionId: string, - sessionIndexTitle: string | null, - changedTitle: string | null, - firstUserMessage: string | null -): string { - if (sessionIndexTitle) { - return truncateText(sessionIndexTitle, 80) - } - - if (changedTitle) { - return truncateText(changedTitle, 80) - } - - if (firstUserMessage) { - return truncateText(firstUserMessage, 80) - } - - if (cwd) { - const parts = cwd.split(/[\\/]+/).filter(Boolean) - if (parts.length > 0) { - return parts[parts.length - 1] - } - } - - return sessionId.slice(0, 8) -} - -function isSubagentSource(value: unknown): boolean { - const record = asRecord(value) - return record ? Object.prototype.hasOwnProperty.call(record, 'subagent') : false -} - -function readCodexSessionIndexTitles(): Map { - let content: string - try { - content = readFileSync(getCodexSessionIndexPath(), 'utf-8') - } catch { - return new Map() - } - - const titles = new Map() - for (const line of content.split(/\r?\n/).filter(Boolean)) { - let parsed: unknown - try { - parsed = JSON.parse(line) - } catch { - continue - } - - const record = asRecord(parsed) - const id = typeof record?.id === 'string' ? record.id : null - const threadName = typeof record?.thread_name === 'string' && record.thread_name.trim() - ? record.thread_name.trim() - : null - const updatedAt = typeof record?.updated_at === 'string' && record.updated_at.trim() - ? record.updated_at.trim() - : null - if (!id || !threadName || !updatedAt) { - continue - } - - const previous = titles.get(id) - if (!previous || previous.updatedAt < updatedAt) { - titles.set(id, { threadName, updatedAt }) - } - } - - return titles -} - -function parseCodexLocalSession( - filePath: string, - sessionIndexTitles = new Map() -): CodexLocalSessionSummary | null { - let content: string - try { - content = readFileSync(filePath, 'utf-8') - } catch { - return null - } - - const allLines = content.split(/\r?\n/).filter(Boolean) - const headLines = allLines.slice(0, 200) - let sessionId: string | null = null - let cwd: string | null = null - let originator: string | null = null - let cliVersion: string | null = null - let firstUserMessage: string | null = null - - for (const line of headLines) { - let parsed: unknown - try { - parsed = JSON.parse(line) - } catch { - continue - } - - const record = asRecord(parsed) - const type = typeof record?.type === 'string' ? record.type : null - if (type === 'session_meta') { - const payload = asRecord(record?.payload) - if (payload) { - if (isSubagentSource(payload.source)) { - return null - } - if (!sessionId && typeof payload.id === 'string') { - sessionId = payload.id - } - if (!cwd && typeof payload.cwd === 'string') { - cwd = payload.cwd - } - if (!originator && typeof payload.originator === 'string') { - originator = payload.originator - } - if (!cliVersion && typeof payload.cli_version === 'string') { - cliVersion = payload.cli_version - } - } - } - - if (!firstUserMessage && type === 'response_item') { - const payload = asRecord(record?.payload) - if (payload?.type === 'message' && payload.role === 'user') { - const text = extractCodexText(payload.content) - if (text && !shouldIgnoreInjectedResponseUserMessage(text)) { - firstUserMessage = text - } - } - } - } - - const changedTitle = getLatestCodexChangedTitle(allLines) - const lastUserMessage = getLatestCodexUserMessage(allLines) - - sessionId = sessionId ?? inferSessionIdFromFileName(filePath) - if (!sessionId) return null - const sessionIndexTitle = sessionIndexTitles.get(sessionId)?.threadName ?? null - - let modifiedAt = Date.now() - try { - modifiedAt = statSync(filePath).mtimeMs - } catch { - // Fall back to current time if stat fails during a concurrent file change. - } - - return { - id: sessionId, - title: getCodexSessionTitle(cwd, sessionId, sessionIndexTitle, changedTitle, firstUserMessage), - lastUserMessage, - cwd, - file: filePath, - modifiedAt, - originator, - cliVersion - } -} - -function listLocalCodexSessions(limit = DEFAULT_CODEX_SESSION_SCAN_LIMIT): CodexLocalSessionSummary[] { - const files: string[] = [] - for (const root of getCodexSessionRoots()) { - collectJsonlFiles(root, files) - } - - const sessionIndexTitles = readCodexSessionIndexTitles() - const deduped = new Map() - for (const filePath of files) { - const session = parseCodexLocalSession(filePath, sessionIndexTitles) - if (!session) continue - const previous = deduped.get(session.id) - if (!previous || previous.modifiedAt < session.modifiedAt) { - deduped.set(session.id, session) - } - } - - return Array.from(deduped.values()) - .sort((a, b) => b.modifiedAt - a.modifiedAt) - .slice(0, limit) -} - -function buildImportedUserMessage(text: string): CodexImportedMessageContent { - return { - role: 'user', - content: { - type: 'text', - text - }, - meta: { - sentFrom: 'cli' - } - } -} - -function buildImportedAgentMessage(data: unknown): CodexImportedMessageContent { - return { - role: 'agent', - content: { - type: AGENT_MESSAGE_PAYLOAD_TYPE, - data - }, - meta: { - sentFrom: 'cli' - } - } -} - -function convertCodexRecordToImportedMessage(record: Record): CodexImportedMessageContent | null { - const type = asString(record.type) - const payload = asRecord(record.payload) - if (!type || !payload) { - return null - } - - if (type === 'event_msg') { - const eventType = asString(payload.type) - if (!eventType) { - return null - } - - if (eventType === 'user_message') { - const text = asString(payload.message) - ?? asString(payload.text) - ?? asString(payload.content) - if (!text) { - return null - } - return buildImportedUserMessage(text) - } - - if (eventType === 'agent_message') { - const message = asString(payload.message) - return message ? buildImportedAgentMessage({ type: 'message', message, id: randomUUID() }) : null - } - - if (eventType === 'agent_reasoning') { - const message = asString(payload.text) ?? asString(payload.message) - return message ? buildImportedAgentMessage({ type: 'reasoning', message, id: randomUUID() }) : null - } - - if (eventType === 'agent_reasoning_delta') { - const delta = asString(payload.delta) ?? asString(payload.text) ?? asString(payload.message) - return delta ? buildImportedAgentMessage({ type: 'reasoning-delta', delta }) : null - } - - if (eventType === 'token_count') { - const info = asRecord(payload.info) - return info ? buildImportedAgentMessage({ type: 'token_count', info, id: randomUUID() }) : null - } - - return null - } - - if (type === 'response_item') { - const itemType = asString(payload.type) - if (!itemType) { - return null - } - - if (itemType === 'message') { - const role = asString(payload.role) - const text = extractCodexText(payload.content) - if (!text) { - return null - } - if (role === 'user') { - return shouldIgnoreInjectedResponseUserMessage(text) ? null : buildImportedUserMessage(text) - } - if (role === 'assistant') { - return buildImportedAgentMessage({ type: 'message', message: text, id: randomUUID() }) - } - return null - } - - if (itemType === 'function_call') { - const name = asString(payload.name) - const callId = extractCodexToolCallId(payload) - if (!name || !callId) { - return null - } - return buildImportedAgentMessage({ - type: 'tool-call', - name, - callId, - input: parseCodexFunctionArguments(payload.arguments), - id: randomUUID() - }) - } - - if (itemType === 'function_call_output') { - const callId = extractCodexToolCallId(payload) - if (!callId) { - return null - } - return buildImportedAgentMessage({ - type: 'tool-call-result', - callId, - output: payload.output, - id: randomUUID() - }) - } - } - - return null -} - -function getCodexImportedMessageSource(record: Record): CodexImportedMessageSource | null { - const type = asString(record.type) - return type === 'event_msg' || type === 'response_item' ? type : null -} - -function normalizeComparableUserMessage(content: unknown): string | null { - const record = asRecord(content) - if (!record || record.role !== 'user') { - return null - } - - const body = asRecord(record.content) - if (body?.type !== 'text' || typeof body.text !== 'string') { - return null - } - - return stableSerialize({ - role: 'user', - text: body.text.trimEnd() - }) -} - -function normalizeComparableAgentMessage(content: unknown): string | null { - const record = asRecord(content) - if (!record || record.role !== 'agent') { - return null - } - - const body = asRecord(record.content) - if (!body || body.type !== AGENT_MESSAGE_PAYLOAD_TYPE) { - return null - } - - const data = asRecord(body.data) - if (data?.type !== 'message' || typeof data.message !== 'string') { - return null - } - - return stableSerialize({ - role: 'agent', - type: 'message', - message: data.message - }) -} - -function normalizeAdjacentDuplicateMessage(content: unknown): string | null { - return normalizeComparableUserMessage(content) ?? normalizeComparableAgentMessage(content) -} - -function isAdjacentDuplicateImportedMessage( - previous: CodexImportedMessageContent, - next: CodexImportedMessageContent -): boolean { - const previousKey = normalizeAdjacentDuplicateMessage(previous) - const nextKey = normalizeAdjacentDuplicateMessage(next) - return previousKey !== null && previousKey === nextKey -} - -function isMirroredAdjacentDuplicate( - previous: CodexImportedMessageEntry | undefined, - next: CodexImportedMessageEntry -): boolean { - return Boolean( - previous - && previous.source !== next.source - && isAdjacentDuplicateImportedMessage(previous.message, next.message) - ) -} - -function isResponseItemDuplicateOfEventUserMessage( - entry: CodexImportedMessageEntry, - recentEventUserMessageKey: string | null -): boolean { - if (entry.source !== 'response_item' || recentEventUserMessageKey === null) { - return false - } - - return normalizeComparableUserMessage(entry.message) === recentEventUserMessageKey -} - -function parseCodexTranscriptImportData(summary: CodexLocalSessionSummary): CodexTranscriptImportData | null { - let content: string - try { - content = readFileSync(summary.file, 'utf-8') - } catch { - return null - } - - const lines = content.split(/\r?\n/).filter(Boolean) - const entries: CodexImportedMessageEntry[] = [] - let recentEventUserMessageKey: string | null = null - - for (const line of lines) { - let parsed: unknown - try { - parsed = JSON.parse(line) - } catch { - continue - } - - const record = asRecord(parsed) - if (!record) continue - const source = getCodexImportedMessageSource(record) - if (!source) continue - const message = convertCodexRecordToImportedMessage(record) - if (message) { - const entry = { source, message } - const userMessageKey = normalizeComparableUserMessage(message) - if (source === 'event_msg' && userMessageKey !== null) { - const previous = entries[entries.length - 1] - if (previous?.source === 'response_item' && isMirroredAdjacentDuplicate(previous, entry)) { - entries[entries.length - 1] = entry - } else { - entries.push(entry) - } - recentEventUserMessageKey = userMessageKey - continue - } - if (isResponseItemDuplicateOfEventUserMessage(entry, recentEventUserMessageKey)) { - continue - } - const previous = entries[entries.length - 1] - if (isMirroredAdjacentDuplicate(previous, entry)) { - recentEventUserMessageKey = null - continue - } - entries.push(entry) - recentEventUserMessageKey = null - } - } - - return { - ...summary, - messages: entries.map((entry) => entry.message) - } -} - function normalizeComparablePath(pathValue: string, options?: { caseInsensitive?: boolean }): string { let normalized = pathValue.trim().replace(/\\/g, '/').replace(/\/+/g, '/') if (normalized.length > 1) { @@ -939,940 +205,39 @@ function resolveCodexImportMachineId( return onlineMachines.length >= 1 ? onlineMachines[0].id : null } -function asRemoteCodexSessions(value: unknown, requireMessages: boolean): RemoteCodexSession[] { - if (!Array.isArray(value)) return [] - return value.filter((session): session is RemoteCodexSession => { - const record = asRecord(session) - return typeof record?.id === 'string' - && typeof record.title === 'string' - && typeof record.file === 'string' - && typeof record.modifiedAt === 'number' - && (!requireMessages || Array.isArray(record.messages)) - }) -} - -async function listCodexSessionsViaMachine(options: { - engine: SyncEngine | null - namespace: string - cwd?: string | null - machineId?: string | null - sessionIds?: string[] -}): Promise<{ sessions: RemoteCodexSession[]; machineId?: string; error?: string }> { - const machineId = resolveCodexImportMachineId(options.cwd, options.namespace, options.engine, options.machineId) - if (!machineId || !options.engine) { - return { sessions: [], error: 'No online machine available for Codex history import' } - } - const result = await options.engine.listCodexSessionsForMachine(machineId, options.cwd, options.sessionIds) - if (!result || typeof result !== 'object') { - return { sessions: [], machineId, error: 'Unexpected Codex sessions RPC response' } - } - if ((result as { success?: unknown }).success !== true) { - return { sessions: [], machineId, error: typeof (result as { error?: unknown }).error === 'string' ? (result as { error: string }).error : 'Failed to list local Codex sessions' } - } - return { sessions: asRemoteCodexSessions((result as { sessions?: unknown }).sessions, Boolean(options.sessionIds?.length)), machineId } -} - -function buildImportedSessionMetadata( - data: CodexTranscriptImportData, - existingMetadata?: Record | null, - resolvedMachineId?: string, - permissionMode?: string -): Record { - const now = Date.now() - const path = data.cwd ?? (typeof existingMetadata?.path === 'string' ? existingMetadata.path : dirname(data.file)) - const host = typeof existingMetadata?.host === 'string' ? existingMetadata.host : (process.env.HAPI_HOSTNAME || hostname()) - const osValue = typeof existingMetadata?.os === 'string' ? existingMetadata.os : platform() - const summaryText = data.lastUserMessage ?? data.title - const machineId = typeof existingMetadata?.machineId === 'string' - ? existingMetadata.machineId - : resolvedMachineId - const currentCodexSessionId = typeof existingMetadata?.codexSessionId === 'string' - ? existingMetadata.codexSessionId - : data.id - +/** + * Map a normalized transcript summary onto the web Codex summary shape: the + * flavor-only display fields arrive nested in `extra` and are flattened, and + * the normalization-only keys (flavor/launch/messageCount) are dropped. + */ +function toWebCodexSessionSummary(summary: LocalTranscriptSummary): CodexLocalSessionSummary { + const extra = summary.extra ?? {} + const field = (key: string): string | null => (typeof extra[key] === 'string' ? extra[key] as string : null) return { - ...(existingMetadata ?? {}), - path, - host, - os: osValue, - name: data.title, - summary: summaryText - ? { - text: summaryText, - updatedAt: now - } - : existingMetadata?.summary, - flavor: 'codex', - codexSessionId: currentCodexSessionId, - codexSourceSessionId: typeof existingMetadata?.codexSourceSessionId === 'string' - ? existingMetadata.codexSourceSessionId - : data.id, - ...(permissionMode ? { preferredPermissionMode: permissionMode } : {}), - ...(machineId ? { machineId } : {}), - lifecycleState: typeof existingMetadata?.lifecycleState === 'string' - ? existingMetadata.lifecycleState - : 'imported', - lifecycleStateSince: typeof existingMetadata?.lifecycleStateSince === 'number' - ? existingMetadata.lifecycleStateSince - : now + id: summary.id, + title: summary.title, + lastUserMessage: summary.lastUserMessage ?? null, + cwd: summary.cwd ?? null, + file: summary.file, + modifiedAt: summary.modifiedAt, + originator: field('originator'), + cliVersion: field('cliVersion'), + source: field('source'), + threadSource: field('threadSource'), + forkedFromId: field('forkedFromId') } } -function stableSerialize(value: unknown): string { - if (value === null || value === undefined) { - return String(value) - } - if (typeof value === 'string') { - return JSON.stringify(value) - } - if (typeof value === 'number' || typeof value === 'boolean') { - return JSON.stringify(value) - } - if (Array.isArray(value)) { - return `[${value.map((item) => stableSerialize(item)).join(',')}]` - } - if (typeof value === 'object') { - const record = value as Record - const keys = Object.keys(record).sort() - return `{${keys.map((key) => `${JSON.stringify(key)}:${stableSerialize(record[key])}`).join(',')}}` - } - return JSON.stringify(value) -} - -function normalizeComparableText(value: string): string { - return value.replace(/\s+$/u, '') -} - -function normalizeComparableAgentData(value: unknown): unknown { - const record = asRecord(value) - if (!record) { - return value - } - - const normalized = { ...record } - if ('id' in normalized) { - delete normalized.id - } - return normalized -} - -function normalizeComparableContent(content: unknown): string | null { - // Stored rows are truncated at ingest (contentCodec) while transcript - // messages arrive in full; truncation is idempotent, so applying it here - // makes both sides of the prefix comparison canonical. Pre-codec stored - // rows (never truncated) get normalized the same way. - const record = asRecord(truncateOversizedMessageContent(content)) - if (!record) { - return null - } - - if (record.role === 'user') { - const body = asRecord(record.content) - if (body?.type !== 'text' || typeof body.text !== 'string') { - return null - } - return stableSerialize({ - role: 'user', - text: normalizeComparableText(body.text) - }) - } - - if (record.role === 'agent') { - const body = asRecord(record.content) - if (!body || body.type !== AGENT_MESSAGE_PAYLOAD_TYPE) { - return null - } - return stableSerialize({ - role: 'agent', - data: normalizeComparableAgentData(body.data) - }) - } - - return null -} - -function getComparableStoredMessageKey(message: StoredMessage): string { - // 中文注释:重复会话合并时优先按标准 user/agent 结构去重;遇到非标准消息再回退到稳定序列化,确保不会遗漏相同内容。 - // Fallback also truncates so a pre-codec (full) row and a post-codec - // (truncated) copy of the same message still dedupe to one key. - return normalizeComparableContent(message.content) ?? stableSerialize(truncateOversizedMessageContent(message.content)) -} - -function collectImportCandidates( - store: Store, - namespace: string, - getSyncEngine?: () => SyncEngine | null -): ImportCandidate[] { - const candidatesBySessionId = new Map() - for (const session of store.sessions.getSessionsByNamespace(namespace)) { - candidatesBySessionId.set(session.id, { - sessionId: session.id, - active: session.active, - updatedAt: session.updatedAt, - metadata: asRecord(session.metadata), - persisted: true - }) - } - - const engineSessions = getSyncEngine?.()?.getSessionsByNamespace(namespace) ?? [] - for (const session of engineSessions) { - const existing = candidatesBySessionId.get(session.id) - candidatesBySessionId.set(session.id, { - sessionId: session.id, - active: session.active || Boolean(existing?.active), - updatedAt: Math.max(session.updatedAt, existing?.updatedAt ?? 0), - metadata: asRecord(session.metadata) ?? existing?.metadata ?? null, - persisted: Boolean(existing?.persisted) - }) - } - - return Array.from(candidatesBySessionId.values()) -} - -function getCodexImportIds(metadata: Record | null | undefined): string[] { - return Array.from(new Set([metadata?.codexSessionId, metadata?.codexSourceSessionId] - .filter((id): id is string => typeof id === 'string' && id.length > 0))) -} - -function isImportCandidateReusable(candidate: ImportCandidate): boolean { - const lifecycleState = candidate.metadata?.lifecycleState - if (lifecycleState === 'archived' || lifecycleState === 'deleted') { - return false - } - return true -} - -function selectImportTargetSession( - store: Store, - candidates: ImportCandidate[], - codexSessionId: string, - importedComparableMessages: string[], - sourceMachineId?: string | null -): ImportTargetSelection { - const relatedCandidates = candidates - .filter((candidate) => candidate.persisted && isImportCandidateReusable(candidate)) - .filter((candidate) => ( - candidate.metadata?.codexSessionId === codexSessionId - || candidate.metadata?.codexSourceSessionId === codexSessionId - )) - .filter((candidate) => ( - !sourceMachineId - || typeof candidate.metadata?.machineId !== 'string' - || candidate.metadata.machineId === sourceMachineId - )) - .sort((a, b) => b.updatedAt - a.updatedAt) - - let bestSessionId: string | null = null - let bestPrefixCount = -1 - - for (const candidate of relatedCandidates) { - const comparableMessages = store.messages.getAllMessages(candidate.sessionId) - .map((message) => normalizeComparableContent(message.content)) - .filter((value): value is string => value !== null) - - if (comparableMessages.length > importedComparableMessages.length) { - continue - } - - let prefixMatches = true - for (let index = 0; index < comparableMessages.length; index += 1) { - if (comparableMessages[index] !== importedComparableMessages[index]) { - prefixMatches = false - break - } - } - - if (!prefixMatches) { - continue - } - - if (comparableMessages.length > bestPrefixCount) { - bestPrefixCount = comparableMessages.length - bestSessionId = candidate.sessionId - } - } - - return { - sessionId: bestSessionId, - comparablePrefixCount: Math.max(0, bestPrefixCount) - } -} - -function listDuplicateCodexSessionGroups( - store: Store, - namespace: string, - codexSessionIds: string[], - getSyncEngine?: () => SyncEngine | null -): DuplicateSessionGroupCandidate[] { - const requestedSessionIds = new Set(codexSessionIds) - if (requestedSessionIds.size === 0) { - return [] - } - - const groups = new Map() - for (const candidate of collectImportCandidates(store, namespace, getSyncEngine)) { - if (!candidate.persisted || !isImportCandidateReusable(candidate)) { - continue - } - for (const codexSessionId of getCodexImportIds(candidate.metadata)) { - if (!requestedSessionIds.has(codexSessionId)) { - continue - } - - const existing = groups.get(codexSessionId) - if (existing) { - existing.push(candidate) - } else { - groups.set(codexSessionId, [candidate]) - } - } - } - - return Array.from(groups.entries()) - .map(([codexSessionId, sessions]) => ({ - codexSessionId, - sessions: sessions.sort((a, b) => b.updatedAt - a.updatedAt) - })) - .filter((group) => group.sessions.length > 1) -} - -async function mergeDuplicateCodexSessionGroups(options: { - store: Store - namespace: string - codexSessionIds: string[] - getSyncEngine?: () => SyncEngine | null -}): Promise { - const groups = listDuplicateCodexSessionGroups( - options.store, - options.namespace, - options.codexSessionIds, - options.getSyncEngine - ) - if (groups.length === 0) { - return { - success: true, - merged: [], - mergedCount: 0 - } - } - - const merged: CodexDuplicateSessionGroup[] = [] - for (const group of groups) { - const result = await mergeSingleDuplicateCodexSessionGroup({ - group, - store: options.store, - namespace: options.namespace, - getSyncEngine: options.getSyncEngine - }) - merged.push(result) - } - - return { - success: true, - merged, - mergedCount: merged.length - } -} - -async function mergeSingleDuplicateCodexSessionGroup(options: { - group: DuplicateSessionGroupCandidate - store: Store - namespace: string - getSyncEngine?: () => SyncEngine | null -}): Promise { - const engine = options.getSyncEngine?.() ?? null - const uniqueSessions = Array.from(new Map(options.group.sessions.map((session) => [session.sessionId, session])).values()) - const sessionStates = uniqueSessions - .map((candidate) => ({ - ...candidate, - storedMessages: options.store.messages.getAllMessages(candidate.sessionId), - })) - .map((candidate) => ({ - ...candidate, - comparableKeys: candidate.storedMessages.map((message) => getComparableStoredMessageKey(message)) - })) - .sort((a, b) => { - if (b.comparableKeys.length !== a.comparableKeys.length) { - return b.comparableKeys.length - a.comparableKeys.length - } - if (b.updatedAt !== a.updatedAt) { - return b.updatedAt - a.updatedAt - } - return a.sessionId.localeCompare(b.sessionId) - }) - - if (sessionStates.some((candidate) => candidate.active)) { - throw new Error('当前会话仍处于活跃状态,请等待会话结束后重试') - } - - const canonical = sessionStates[0] - if (!canonical) { - throw new Error(`No duplicate Hapi session found for Codex thread: ${options.group.codexSessionId}`) - } - - const knownKeys = new Set(canonical.comparableKeys) - const removedSessionIds: string[] = [] - const appendedMessages: StoredMessage[] = [] - let latestActivity = canonical.updatedAt - - if ( - !engine - && sessionStates.slice(1).some( - (source) => options.store.sessionJobs.list(source.sessionId).length > 0 - ) - ) { - throw new Error( - 'Sync engine unavailable; retry merge so attached-job redirects are preserved' - ) - } - - for (const source of sessionStates.slice(1)) { - latestActivity = Math.max(latestActivity, source.updatedAt) - for (const message of source.storedMessages) { - const comparableKey = getComparableStoredMessageKey(message) - if (knownKeys.has(comparableKey)) { - continue - } - - const copied = options.store.messages.copyMessageToSession(canonical.sessionId, { - content: message.content, - createdAt: message.createdAt, - localId: message.localId, - invokedAt: message.invokedAt, - scheduledAt: message.scheduledAt - }) - knownKeys.add(comparableKey) - appendedMessages.push(copied) - latestActivity = Math.max(latestActivity, copied.invokedAt ?? copied.createdAt) - } - - // Transfer outliving jobs before CASCADE delete (store refuses running jobs). - // Without SyncEngine we cannot persist jobsAcceptedFromSessionIds / key remaps, - // so refuse rather than orphan a supervisor still holding the source session id. - if (engine) { - engine.transferAttachedJobs(source.sessionId, canonical.sessionId, options.namespace) - await engine.deleteSession(source.sessionId) - } else { - const deleted = options.store.sessions.deleteSession(source.sessionId, options.namespace) - if (!deleted) { - throw new Error(`Failed to delete duplicate Hapi session: ${source.sessionId}`) - } - } - removedSessionIds.push(source.sessionId) - } - - if (appendedMessages.length > 0) { - emitImportedMessageEvents(engine, canonical.sessionId, appendedMessages) - } - - if (engine) { - engine.recordSessionActivity(canonical.sessionId, latestActivity) - // 中文注释:即使这次只是删除重复分身、没有新增消息,也主动刷新 canonical 会话,确保左侧列表立刻收敛到合并后的状态。 - engine.handleRealtimeEvent({ - type: 'session-updated', - sessionId: canonical.sessionId - }) - } else { - options.store.sessions.touchSessionUpdatedAt(canonical.sessionId, latestActivity, options.namespace) - } - - return { - codexSessionId: options.group.codexSessionId, - hapiSessionIds: sessionStates.map((candidate) => candidate.sessionId), - canonicalSessionId: canonical.sessionId, - removedSessionIds - } -} - -function emitImportedMessageEvents( +function resolveCodexImportMachineObject( engine: SyncEngine | null, - sessionId: string, - appendedMessages: StoredMessage[] -): void { - if (!engine) { - return - } - - // 中文注释:只有追加到已有 Hapi 会话时才逐条广播新增消息,确保当前打开的会话右侧消息区能立即刷新到最新 transcript。 - for (const message of appendedMessages) { - engine.handleRealtimeEvent({ - type: 'message-received', - sessionId, - message: { - id: message.id, - seq: message.seq, - localId: message.localId ?? null, - content: message.content, - createdAt: message.createdAt, - invokedAt: message.invokedAt - } - }) - } -} - -function getPathExts(): string[] { - if (process.platform !== 'win32') { - return [''] - } - const fromEnv = (process.env.PATHEXT ?? '') - .split(';') - .map(ext => ext.trim().toLowerCase()) - .filter(Boolean) - return Array.from(new Set(['', '.exe', '.cmd', '.bat', '.ps1', ...fromEnv])) -} - -function findOnPath(commandName: string): string | null { - if (commandName.includes('\\') || commandName.includes('/')) { - return existsSync(commandName) ? commandName : null - } - - const pathDirs = (process.env.PATH ?? '') - .split(process.platform === 'win32' ? ';' : ':') - .map(part => part.trim()) - .filter(Boolean) - const extensions = getPathExts() - - for (const dir of pathDirs) { - for (const ext of extensions) { - const candidate = join(dir, commandName.endsWith(ext) ? commandName : `${commandName}${ext}`) - if (existsSync(candidate)) { - return candidate - } - } - } - - return null -} - -function getCodexLauncherCandidates(): string[] { - return [ - process.env.HAPI_CODEX_COMMAND?.trim() ?? '', - findOnPath('codex') ?? '', - process.env.LOCALAPPDATA ? join(process.env.LOCALAPPDATA, 'Microsoft', 'WindowsApps', 'codex.exe') : '' - ].filter(Boolean) -} - -function isCodexLauncherAvailable(): boolean { - return getCodexLauncherCandidates().some(candidate => { - try { - return existsSync(candidate) - } catch { - return false - } - }) -} - -function getDarwinCodexAppCandidates(): string[] { - return [ - process.env.HAPI_CODEX_APP_PATH?.trim() ?? '', - ...DARWIN_CODEX_APP_CANDIDATES - ].filter(Boolean) -} - -function isDarwinCodexAppInstalled(): boolean { - return getDarwinCodexAppCandidates().some(candidate => { - try { - return existsSync(candidate) - } catch { - return false - } - }) -} - -function isCodexDesktopPath(pathValue: string): boolean { - return /\\WindowsApps\\OpenAI\.Codex_[^\\]+\\app\\(?:Codex|resources\\codex)\.exe$/i.test(pathValue) -} - -function isCodexDesktopPackageInstalled(): boolean { - if (process.platform !== 'win32') { - return false - } - - const command = [ - "$package = Get-AppxPackage -Name OpenAI.Codex -ErrorAction SilentlyContinue", - "if ($package) { 'true' } else { 'false' }" - ].join('\n') - - for (const shell of ['pwsh', 'powershell.exe']) { - try { - const result = spawnSync(shell, ['-NoLogo', '-NoProfile', '-Command', command], { - encoding: 'utf-8', - timeout: 5000, - windowsHide: true - }) - if (result.status === 0) { - return result.stdout.trim().toLowerCase().includes('true') - } - } catch { - // Try next shell. - } - } - - return false -} - -function isCodexDesktopInstallAvailable(): boolean { - if (process.platform === 'darwin') { - return isDarwinCodexAppInstalled() || isCodexLauncherAvailable() - } - - if (process.platform !== 'win32') { - return isCodexLauncherAvailable() - } - - if (isCodexDesktopPackageInstalled()) { - return true - } - - return getCodexLauncherCandidates().some(candidate => { - try { - return isCodexDesktopPath(candidate) && existsSync(candidate) - } catch { - return false - } - }) -} - -function isCodexDesktopRunning(): boolean { - if (process.platform === 'darwin') { - try { - const result = spawnSync('pgrep', ['-x', DARWIN_CODEX_APP_NAME], { - encoding: 'utf-8', - timeout: 5000 - }) - return result.status === 0 - } catch { - return false - } - } - - if (process.platform !== 'win32') { - return false - } - - const command = [ - "$targets = @(Get-CimInstance Win32_Process | Where-Object {", - " ($_.Name -ieq 'Codex.exe' -or $_.Name -ieq 'codex.exe') -and", - " $_.ExecutablePath -match '\\\\WindowsApps\\\\OpenAI\\.Codex_'", - '})', - "if ($targets.Count -gt 0) { 'true' } else { 'false' }" - ].join('\n') - - for (const shell of ['pwsh', 'powershell.exe']) { - try { - const result = spawnSync(shell, ['-NoLogo', '-NoProfile', '-Command', command], { - encoding: 'utf-8', - timeout: 5000, - windowsHide: true - }) - if (result.status === 0) { - return result.stdout.trim().toLowerCase().includes('true') - } - } catch { - // Try next shell. - } - } - - return false -} - -function getCodexDesktopStatus(): CodexDesktopStatus { - const running = isCodexDesktopRunning() - return { - running, - clientAvailable: running || isCodexDesktopInstallAvailable() - } -} - -function getScriptTimeoutMs(): number { - const configured = Number(process.env.HAPI_CODEX_SCRIPT_TIMEOUT_MS) - if (Number.isFinite(configured) && configured > 0) { - return configured - } - return DEFAULT_SCRIPT_TIMEOUT_MS -} - -function createLaunchArgs(scriptPath: string, workspace: string, scriptArgs: string[]): string[] { - return [ - '-NoLogo', - '-NoProfile', - '-ExecutionPolicy', - 'Bypass', - '-File', - scriptPath, - '-Workspace', - workspace, - ...scriptArgs - ] -} - -function appendScriptLog(workspace: string, kind: ScriptLogKind, message: string): void { - try { - const logDir = join(workspace, 'logs') - mkdirSync(logDir, { recursive: true }) - const line = `[${new Date().toISOString()}] [${kind}] ${message}\n` - appendFileSync(join(logDir, 'CodexDesktopScript.log'), line, 'utf-8') - } catch { - // Best-effort logging only; API response still carries the error. - } -} - -async function runPowerShellScript(scriptPath: string, workspace: string, scriptArgs: string[]): Promise<{ pid: number; command: string; output: string }> { - const configuredPwsh = process.env.HAPI_PWSH_PATH?.trim() - const candidates = Array.from(new Set([ - configuredPwsh || 'pwsh', - 'powershell.exe' - ])) - const args = createLaunchArgs(scriptPath, workspace, scriptArgs) - let lastError: unknown = null - - for (const command of candidates) { - try { - return await new Promise((resolvePromise, rejectPromise) => { - const output: string[] = [] - let settled = false - let didSpawn = false - let timeout: ReturnType | null = null - const child = spawn(command, args, { - cwd: workspace, - stdio: ['ignore', 'pipe', 'pipe'], - windowsHide: true - }) - - const cleanup = () => { - if (timeout) { - clearTimeout(timeout) - } - child.off('spawn', onSpawn) - child.off('error', onError) - child.off('exit', onExit) - } - - const settleResolve = (value: { pid: number; command: string; output: string }) => { - if (settled) return - settled = true - cleanup() - resolvePromise(value) - } - - const settleReject = (error: Error) => { - if (settled) return - settled = true - cleanup() - rejectPromise(error) - } - - const onSpawn = () => { - didSpawn = true - } - - const onError = (error: Error) => { - if (!didSpawn) { - ;(error as Error & { shellLaunchFailed?: boolean }).shellLaunchFailed = true - } - settleReject(error) - } - - const onExit = (code: number | null, signal: NodeJS.Signals | null) => { - const combinedOutput = output.join('').trim() - if (code === 0) { - settleResolve({ pid: child.pid ?? 0, command, output: combinedOutput }) - return - } - const detail = combinedOutput ? `\n${combinedOutput}` : '' - settleReject(new Error(`${command} exited with code ${code ?? 'null'}${signal ? ` signal ${signal}` : ''}.${detail}`)) - } - - timeout = setTimeout(() => { - child.kill() - settleReject(new Error(SCRIPT_TIMEOUT_ERROR)) - }, getScriptTimeoutMs()) - - child.stdout?.on('data', (chunk) => output.push(String(chunk))) - child.stderr?.on('data', (chunk) => output.push(String(chunk))) - child.once('spawn', onSpawn) - child.once('error', onError) - child.once('exit', onExit) - }) - } catch (error) { - lastError = error - if (!(error instanceof Error && (error as Error & { shellLaunchFailed?: boolean }).shellLaunchFailed)) { - throw error instanceof Error ? error : new Error(String(error)) - } - } - } - - throw lastError instanceof Error ? lastError : new Error(String(lastError)) -} - -function getDarwinCodexOpenTarget(): string { - return getDarwinCodexAppCandidates().find((candidate) => { - try { - return existsSync(candidate) - } catch { - return false - } - }) ?? DARWIN_CODEX_APP_NAME -} - -export function getDarwinCodexOpenArgs(target: string): string[] { - return target.endsWith('.app') ? [target] : ['-a', target] -} - -async function restartDarwinCodexDesktop(workspace: string): Promise<{ pid: number; command: string; output: string }> { - const output: string[] = [] - try { - const quit = spawnSync('osascript', ['-e', `tell application "${DARWIN_CODEX_APP_NAME}" to quit`], { - encoding: 'utf-8', - timeout: 5000 - }) - const quitOutput = `${quit.stdout ?? ''}${quit.stderr ?? ''}`.trim() - if (quitOutput) { - output.push(quitOutput) - } - } catch (error) { - output.push(error instanceof Error ? error.message : String(error)) - } - - return await new Promise((resolvePromise, rejectPromise) => { - const target = getDarwinCodexOpenTarget() - const child = spawn('open', getDarwinCodexOpenArgs(target), { - cwd: workspace, - detached: true, - stdio: ['ignore', 'pipe', 'pipe'] - }) - const launchOutput: string[] = [] - let settled = false - let timeout: ReturnType | null = null - - const cleanup = () => { - if (timeout) { - clearTimeout(timeout) - } - child.off('error', onError) - child.off('exit', onExit) - } - - const settle = (callback: () => void) => { - if (settled) return - settled = true - cleanup() - callback() - } - - const onError = (error: Error) => { - settle(() => rejectPromise(error)) - } - - const onExit = (code: number | null, signal: NodeJS.Signals | null) => { - const combinedLaunchOutput = launchOutput.join('').trim() - if (combinedLaunchOutput) { - output.push(combinedLaunchOutput) - } - if (code === 0) { - child.unref() - settle(() => resolvePromise({ - pid: child.pid ?? 0, - command: 'open', - output: output.join('\n').trim() - })) - return - } - const detail = output.length > 0 ? `\n${output.join('\n')}` : '' - settle(() => rejectPromise(new Error(`open exited with code ${code ?? 'null'}${signal ? ` signal ${signal}` : ''}.${detail}`))) - } - - timeout = setTimeout(() => { - child.kill() - settle(() => rejectPromise(new Error(SCRIPT_TIMEOUT_ERROR))) - }, getScriptTimeoutMs()) - - child.stdout?.on('data', (chunk) => launchOutput.push(String(chunk))) - child.stderr?.on('data', (chunk) => launchOutput.push(String(chunk))) - child.once('error', onError) - child.once('exit', onExit) - }) -} - -async function launchRestartScript(): Promise { - const scriptPath = getRestartScriptPath() - const workspace = getWorkspace(scriptPath) - - if (!existsSync(scriptPath)) { - if (process.platform === 'darwin' && !process.env[RESTART_SCRIPT_ENV_NAME]?.trim()) { - try { - const launched = await restartDarwinCodexDesktop(workspace) - const output = launched.output - appendScriptLog( - workspace, - 'restart', - `SUCCESS: ${RESTART_SCRIPT_MESSAGE}; pid=${launched.pid}; command=${launched.command}${output ? `; output=${output}` : ''}` - ) - return { - success: true, - message: RESTART_SCRIPT_MESSAGE, - pid: launched.pid, - command: launched.command, - cwd: workspace, - output - } - } catch (error) { - const message = error instanceof Error ? error.message : String(error) - appendScriptLog(workspace, 'restart', `FAILED: ${message}; native=darwin`) - return { - success: false, - error: message, - cwd: workspace - } - } - } - - appendScriptLog(workspace, 'restart', `FAILED: Script not found: ${scriptPath}`) - return { - success: false, - error: `Script not found: ${scriptPath}`, - script: scriptPath, - cwd: workspace - } - } - - if (!existsSync(workspace)) { - appendScriptLog(workspace, 'restart', `FAILED: Workspace not found: ${workspace}`) - return { - success: false, - error: `Workspace not found: ${workspace}`, - script: scriptPath, - cwd: workspace - } - } - - try { - const launched = await runPowerShellScript(scriptPath, workspace, RESTART_SCRIPT_ARGS) - const output = launched.output - appendScriptLog( - workspace, - 'restart', - `SUCCESS: ${RESTART_SCRIPT_MESSAGE}; pid=${launched.pid}; command=${launched.command}; script=${scriptPath}${output ? `; output=${output}` : ''}` - ) - return { - success: true, - message: RESTART_SCRIPT_MESSAGE, - pid: launched.pid, - command: launched.command, - script: scriptPath, - cwd: workspace, - output - } - } catch (error) { - const message = error instanceof Error ? error.message : String(error) - appendScriptLog(workspace, 'restart', `FAILED: ${message}; script=${scriptPath}`) - return { - success: false, - error: message, - script: scriptPath, - cwd: workspace - } - } + namespace: string, + cwd: string | null | undefined, + requestedMachineId?: string | null +): Machine | null { + if (!engine) return null + const machineId = resolveCodexImportMachineId(cwd, namespace, engine, requestedMachineId) + if (!machineId) return null + return engine.getOnlineMachinesByNamespace(namespace).find((machine) => machine.id === machineId) ?? null } function parseSyncSessionRequest(body: unknown): SyncSessionRequestParseResult { @@ -1935,12 +300,6 @@ function combineSyncOutputs(results: ScriptLaunchResponse[]): string | undefined return output || undefined } -function getDirectImportRouteContext(): { workspace: string } { - return { - workspace: getDirectImportWorkspace() - } -} - function createImportErrorResponse( codexSessionIds: string[], error: string, @@ -1986,167 +345,27 @@ function createImportSuccessResponse( } } -function importSingleCodexSession(options: { - codexSessionId: string - localSessionsById: Map - store: Store - namespace: string - getSyncEngine?: () => SyncEngine | null - model?: string | null - modelReasoningEffort?: string | null - yolo?: boolean - machineId?: string | null -}): ScriptLaunchResponse { - const summary = options.localSessionsById.get(options.codexSessionId) - if (!summary) { - return { - ...createImportErrorResponse([options.codexSessionId], `Transcript not found for Codex session: ${options.codexSessionId}`), - output: `未找到对应的本地 transcript:${options.codexSessionId}` - } - } - - const transcript = 'messages' in summary && Array.isArray((summary as RemoteCodexSession).messages) - ? summary as RemoteCodexSession - : parseCodexTranscriptImportData(summary) - if (!transcript) { - return { - ...createImportErrorResponse([options.codexSessionId], `Failed to parse Codex transcript: ${summary.file}`), - output: `解析 transcript 失败:${summary.file}` - } - } - - if (transcript.messages.length === 0) { - return { - ...createImportErrorResponse([options.codexSessionId], `No importable conversation content found in transcript: ${summary.file}`), - output: `transcript 中没有可导入的会话内容:${summary.file}` - } - } - - const importedComparableMessages = transcript.messages - .map((message) => normalizeComparableContent(message)) - .filter((value): value is string => value !== null) - - try { - const candidates = collectImportCandidates(options.store, options.namespace, options.getSyncEngine) - const activeCandidate = candidates.find((candidate) => ( - candidate.active - && getCodexImportIds(candidate.metadata).includes(options.codexSessionId) - && ( - !options.machineId - || typeof candidate.metadata?.machineId !== 'string' - || candidate.metadata.machineId === options.machineId - ) - )) - if (activeCandidate) { - throw new Error('Cannot sync Codex transcript while the matching HAPI session is active') - } - const target = selectImportTargetSession( - options.store, - candidates, - options.codexSessionId, - importedComparableMessages, - options.machineId - ) - const engine = options.getSyncEngine?.() ?? null - const existingStored = target.sessionId ? options.store.sessions.getSessionByNamespace(target.sessionId, options.namespace) : null - const metadata = buildImportedSessionMetadata( - transcript, - asRecord(existingStored?.metadata), - options.machineId ?? resolveImportMachineId(transcript.cwd, options.namespace, engine) ?? undefined, - options.yolo ? 'yolo' : undefined - ) - - let sessionId = existingStored?.id ?? null - let created = false - if (!sessionId) { - // 中文注释:找不到可安全续写的历史会话时,直接新建一个 Hapi 会话,避免把已分叉的数据硬写进旧会话。 - const createdSession = engine?.getOrCreateSession( - randomUUID(), - metadata, - {}, - options.namespace, - options.model ?? undefined, - undefined, - options.modelReasoningEffort ?? undefined - ) ?? options.store.sessions.getOrCreateSession(randomUUID(), metadata, {}, options.namespace, options.model ?? undefined, undefined, options.modelReasoningEffort ?? undefined) - sessionId = createdSession.id - created = true - } else if (existingStored) { - const updatedMetadata = options.store.sessions.updateSessionMetadata( - existingStored.id, - metadata, - existingStored.metadataVersion, - options.namespace - ) - if (updatedMetadata.result !== 'success') { - throw new Error(`Failed to update metadata for Hapi session: ${existingStored.id}`) - } - if (options.model !== undefined) { - options.store.sessions.setSessionModel(existingStored.id, options.model, options.namespace, { touchUpdatedAt: false }) - } - if (options.modelReasoningEffort !== undefined) { - options.store.sessions.setSessionModelReasoningEffort(existingStored.id, options.modelReasoningEffort, options.namespace, { touchUpdatedAt: false }) - } - engine?.handleRealtimeEvent({ type: 'session-updated', sessionId: existingStored.id }) - } - - if (!sessionId) { - throw new Error(`Failed to determine target Hapi session for Codex thread: ${options.codexSessionId}`) - } - - const comparablePrefixCount = sessionId ? target.comparablePrefixCount : 0 - const messagesToAppend = transcript.messages.slice(comparablePrefixCount) - const targetIsActive = Boolean(candidates.find((candidate) => candidate.sessionId === sessionId)?.active) - if (targetIsActive && messagesToAppend.length > 0) { - throw new Error('当前会话正在运行且 Codex transcript 有新消息,停止或归档后再同步,避免消息顺序错乱') - } - const appendedMessages = messagesToAppend.map((message, index) => options.store.messages.addImportedMessage( - sessionId!, message, `codex-desktop:${options.codexSessionId}:${comparablePrefixCount + index}`, Date.now() - ).message) - - // 中文注释:更新 Hapi 会话的 updatedAt,并在已有会话追加时广播新增消息,让当前打开的聊天页立刻显示客户端新增内容。 - const latestMessageCreatedAt = appendedMessages[appendedMessages.length - 1]?.createdAt ?? Date.now() - if (engine) { - engine.recordSessionActivity(sessionId, latestMessageCreatedAt) - } else { - options.store.sessions.touchSessionUpdatedAt(sessionId, latestMessageCreatedAt, options.namespace) - } - if (created) { - engine?.handleRealtimeEvent({ type: 'session-updated', sessionId }) - } else { - emitImportedMessageEvents(engine, sessionId, appendedMessages) - } - - const output = [ - `Codex thread: ${options.codexSessionId}`, - `Hapi session: ${sessionId}`, - `Action: ${created ? 'created' : 'updated'}`, - `Appended messages: ${appendedMessages.length}` - ].join('\n') - - appendScriptLog( - getDirectImportRouteContext().workspace, - 'sync', - `SUCCESS: codexSessionId=${options.codexSessionId}; hapiSessionId=${sessionId}; created=${created}; appended=${appendedMessages.length}` - ) - - return { - success: true, - message: created ? 'Codex session imported into a new Hapi session' : 'Codex session appended to existing Hapi session', - pid: 0, - command: DIRECT_IMPORT_COMMAND, - cwd: getDirectImportRouteContext().workspace, - output, - sessionIds: [options.codexSessionId], - hapiSessionIds: [sessionId], - syncedCount: 1 - } - } catch (error) { - const message = error instanceof Error ? error.message : String(error) - return { - ...createImportErrorResponse([options.codexSessionId], message), - output: `Codex thread: ${options.codexSessionId}\n${message}` - } +function resolveImportMachineObject(engine: SyncEngine, namespace: string, machineId?: string | null): Machine { + const online = engine.getOnlineMachinesByNamespace?.(namespace) ?? [] + const found = machineId ? online.find((machine) => machine.id === machineId) : undefined + const fallbackId = machineId ?? 'codex-import' + return found ?? online[0] ?? { + id: fallbackId, + namespace, + seq: 0, + createdAt: 0, + updatedAt: 0, + active: true, + activeAt: 0, + metadata: { + host: fallbackId, + platform: process.platform, + happyCliVersion: 'unknown' + }, + metadataVersion: 1, + runnerState: null, + runnerStateVersion: 1, + health: null } } @@ -2155,7 +374,7 @@ export async function importSelectedCodexSessions(options: { store: Store namespace: string getSyncEngine?: () => SyncEngine | null - localSessions?: RemoteCodexSession[] + cwd?: string | null model?: string | null modelReasoningEffort?: string | null serviceTier?: string | null @@ -2167,48 +386,120 @@ export async function importSelectedCodexSessions(options: { if (codexSessionIds.length === 0) { return createImportErrorResponse(codexSessionIds, NO_SYNC_SESSION_SELECTED_ERROR) } + const importLimit = CODEX_LOCAL_SESSION_SOURCE.importLimit + if (importLimit !== undefined && codexSessionIds.length > importLimit) { + return createImportErrorResponse(codexSessionIds, `At most ${importLimit} Codex sessions can be imported at once`) + } - const localSessionsById = new Map((options.localSessions ?? listLocalCodexSessions()).map((session) => [session.id, session])) + // Transcripts always come from the runner through the source descriptor: + // ListLocalSessions when the runner advertises the capability, the legacy + // per-flavor RPC otherwise. The hub never reads its own CODEX_HOME. + const engine = options.getSyncEngine?.() ?? null + if (!engine) { + return createImportErrorResponse(codexSessionIds, 'No online machine available for Codex history import') + } + const machine = resolveImportMachineObject(engine, options.namespace, options.machineId) + const fetched = await fetchLocalTranscriptsByIds({ + source: CODEX_LOCAL_SESSION_SOURCE, + engine, + machine, + cwd: options.cwd ?? null, + sessionIds: codexSessionIds + }) + if (!fetched.success) { + return createImportErrorResponse(codexSessionIds, fetched.error) + } + const transcriptsById = new Map(fetched.sessions + .filter((session): session is LocalTranscript => 'messages' in session) + .map((session) => [session.id, session])) const results: ScriptLaunchResponse[] = [] for (const codexSessionId of codexSessionIds) { - const result = importSingleCodexSession({ - codexSessionId, - localSessionsById, - store: options.store, - namespace: options.namespace, - getSyncEngine: options.getSyncEngine, - model: options.model, - modelReasoningEffort: options.modelReasoningEffort, - yolo: options.yolo, - machineId: options.machineId - }) - results.push(result) - - if (result.success && (options.serviceTier !== undefined || options.collaborationMode !== undefined)) { - const importedSessionId = result.hapiSessionIds?.[0] - const engine = options.getSyncEngine?.() ?? null - if (!importedSessionId || !engine) { - return createImportErrorResponse(codexSessionIds, 'Imported session config could not be applied before resume') + const transcript = transcriptsById.get(codexSessionId) + if (!transcript) { + const failure: ScriptLaunchResponse = { + ...createImportErrorResponse([codexSessionId], `Transcript not found for Codex session: ${codexSessionId}`), + output: `未找到对应的本地 transcript:${codexSessionId}` } - try { - await engine.applySessionConfig(importedSessionId, { - ...(options.serviceTier !== undefined ? { serviceTier: options.serviceTier } : {}), - ...(options.collaborationMode !== undefined ? { collaborationMode: options.collaborationMode } : {}) - }) - } catch (error) { - const message = error instanceof Error ? error.message : String(error) - return createImportErrorResponse(codexSessionIds, `Failed to apply imported session config: ${message}`) - } - } - - if (!result.success) { + results.push(failure) return { - ...result, + ...failure, sessionIds: codexSessionIds, syncedCount: Math.max(0, results.length - 1), - output: combineSyncOutputs(results) ?? result.output + output: combineSyncOutputs(results) ?? failure.output } } + if (transcript.messages.length === 0) { + const failure: ScriptLaunchResponse = { + ...createImportErrorResponse([codexSessionId], `No importable conversation content found in transcript: ${transcript.file}`), + output: `transcript 中没有可导入的会话内容:${transcript.file}` + } + results.push(failure) + return { + ...failure, + sessionIds: codexSessionIds, + syncedCount: Math.max(0, results.length - 1), + output: combineSyncOutputs(results) ?? failure.output + } + } + + const outcome = await importLocalTranscript({ + store: options.store, + engine, + namespace: options.namespace, + source: CODEX_LOCAL_SESSION_SOURCE, + transcript, + machine, + request: { + launch: { + ...(options.model !== undefined ? { model: options.model } : {}), + ...(options.modelReasoningEffort !== undefined ? { modelReasoningEffort: options.modelReasoningEffort } : {}), + ...(options.serviceTier !== undefined ? { serviceTier: options.serviceTier } : {}), + ...(options.collaborationMode !== undefined ? { collaborationMode: options.collaborationMode } : {}) + }, + requestMetadata: options.yolo ? { preferredPermissionMode: 'yolo' } : {} + } + }) + + if (outcome.error || !outcome.hapiSessionId) { + const message = outcome.error?.message ?? `Failed to determine target Hapi session for Codex thread: ${codexSessionId}` + const failure: ScriptLaunchResponse = { + ...createImportErrorResponse([codexSessionId], message), + output: `Codex thread: ${codexSessionId}\n${message}` + } + results.push(failure) + return { + ...failure, + sessionIds: codexSessionIds, + syncedCount: Math.max(0, results.length - 1), + output: combineSyncOutputs(results) ?? failure.output + } + } + + // Keep the pre-registry response vocabulary: every delta-bearing or + // empty re-sync reports "updated". + const created = outcome.action === 'created' + const output = [ + `Codex thread: ${codexSessionId}`, + `Hapi session: ${outcome.hapiSessionId}`, + `Action: ${created ? 'created' : 'updated'}`, + `Appended messages: ${outcome.appended ?? 0}` + ].join('\n') + appendScriptLog( + getDirectImportRouteContext().workspace, + 'sync', + `SUCCESS: codexSessionId=${codexSessionId}; hapiSessionId=${outcome.hapiSessionId}; created=${created}; appended=${outcome.appended ?? 0}` + ) + results.push({ + success: true, + message: created ? 'Codex session imported into a new Hapi session' : 'Codex session appended to existing Hapi session', + pid: 0, + command: DIRECT_IMPORT_COMMAND, + cwd: getDirectImportRouteContext().workspace, + output, + sessionIds: [codexSessionId], + hapiSessionIds: [outcome.hapiSessionId], + syncedCount: 1 + }) } return createImportSuccessResponse(codexSessionIds, results) @@ -2220,7 +511,9 @@ export function createCodexDesktopRoutes(options: { }): Hono { const app = new Hono() - app.use('/codex/*', async (c, next) => { + // Transcript list and sync are available in every namespace; only + // the desktop sidecar capabilities stay default-namespace only. + const requireDefaultNamespace = async (c: Context, next: () => Promise) => { if (c.get('namespace') !== 'default') { return c.json({ success: false, @@ -2228,7 +521,12 @@ export function createCodexDesktopRoutes(options: { }, 403) } return next() - }) + } + app.use('/codex/status', requireDefaultNamespace) + app.use('/codex/archive-session', requireDefaultNamespace) + app.use('/codex/duplicate-sessions', requireDefaultNamespace) + app.use('/codex/merge-duplicate-sessions', requireDefaultNamespace) + app.use('/codex/restart-desktop', requireDefaultNamespace) app.get('/codex/status', (c) => { const codexStatus = getCodexDesktopStatus() @@ -2241,29 +539,36 @@ export function createCodexDesktopRoutes(options: { app.get('/codex/sessions', async (c) => { const cwd = c.req.query('cwd')?.trim() || null - const machineId = c.req.query('machineId')?.trim() || null - const remote = await listCodexSessionsViaMachine({ - engine: options.getSyncEngine(), - namespace: c.get('namespace'), - cwd, - machineId - }) - if (remote.error) { + const requestedMachineId = c.req.query('machineId')?.trim() || null + const machine = resolveCodexImportMachineObject(options.getSyncEngine(), c.get('namespace'), cwd, requestedMachineId) + if (!machine) { return c.json({ success: false, - error: remote.error, + error: 'No online machine available for Codex history import', + sessions: [] + } satisfies CodexLocalSessionsResponse, 503) + } + const result = await fetchLocalTranscriptSummaries({ + source: CODEX_LOCAL_SESSION_SOURCE, + engine: options.getSyncEngine()!, + machine, + cwd + }) + if (!result.success) { + return c.json({ + success: false, + error: result.error, sessions: [], - ...(remote.machineId ? { machineId: remote.machineId } : {}) + machineId: machine.id } satisfies CodexLocalSessionsResponse, 503) } return c.json({ success: true, - sessions: remote.sessions.map(({ messages: _messages, ...summary }) => summary), - ...(remote.machineId ? { machineId: remote.machineId } : {}) + sessions: result.sessions.map(toWebCodexSessionSummary), + machineId: machine.id } satisfies CodexLocalSessionsResponse) }) - app.post('/codex/archive-session', async (c) => { const body = await c.req.json().catch(() => null) const record = asRecord(body) @@ -2309,18 +614,23 @@ export function createCodexDesktopRoutes(options: { } // 中文注释:hub 可能运行在服务器上;Codex transcript 必须通过用户本机 runner RPC 读取,不能扫描服务器磁盘。 - const remote = await listCodexSessionsViaMachine({ - engine: options.getSyncEngine(), - namespace: c.get('namespace'), - cwd: parsed.cwd, - machineId: parsed.machineId, - sessionIds: parsed.sessionIds - }) - if (remote.error) { + const importLimit = CODEX_LOCAL_SESSION_SOURCE.importLimit + if (importLimit !== undefined && parsed.sessionIds.length > importLimit) { const { workspace } = getDirectImportRouteContext() return c.json({ success: false, - error: remote.error, + error: `At most ${importLimit} Codex sessions can be imported at once`, + cwd: workspace, + codexDesktopRunning: codexStatus.running, + codexClientAvailable: codexStatus.clientAvailable + }, 400) + } + const machine = resolveCodexImportMachineObject(options.getSyncEngine(), c.get('namespace'), parsed.cwd, parsed.machineId) + if (!machine) { + const { workspace } = getDirectImportRouteContext() + return c.json({ + success: false, + error: 'No online machine available for Codex history import', cwd: workspace, codexDesktopRunning: codexStatus.running, codexClientAvailable: codexStatus.clientAvailable @@ -2331,8 +641,8 @@ export function createCodexDesktopRoutes(options: { store: options.store, namespace: c.get('namespace'), getSyncEngine: options.getSyncEngine, - localSessions: remote.sessions, - machineId: remote.machineId ?? null, + cwd: parsed.cwd, + machineId: machine.id, model: parsed.model, modelReasoningEffort: parsed.modelReasoningEffort, serviceTier: parsed.serviceTier, @@ -2430,7 +740,7 @@ export function createCodexDesktopRoutes(options: { const codexStatus = getCodexDesktopStatus() if (!codexStatus.clientAvailable) { const scriptPath = getRestartScriptPath() - const workspace = getWorkspace(scriptPath) + const workspace = getRestartScriptWorkspace() const error = CODEX_DESKTOP_NOT_FOUND_ERROR appendScriptLog(workspace, 'restart', `FAILED: ${error}; script=${scriptPath}`) return c.json({ diff --git a/hub/src/web/routes/codexExtras.ts b/hub/src/web/routes/codexExtras.ts new file mode 100644 index 00000000..70540235 --- /dev/null +++ b/hub/src/web/routes/codexExtras.ts @@ -0,0 +1,948 @@ +import { appendFileSync, existsSync, mkdirSync } from 'node:fs' +import { spawn, spawnSync } from 'node:child_process' +import { dirname, isAbsolute, join, resolve } from 'node:path' +import { homedir } from 'node:os' +import { AGENT_MESSAGE_PAYLOAD_TYPE } from '@hapi/protocol' +import type { Store, StoredMessage } from '../../store' +import { truncateOversizedMessageContent } from '../../store/contentCodec' +import type { SyncEngine } from '../../sync/syncEngine' +import { collectImportCandidates, type ImportCandidate } from './localSessions/matchContentPrefix' + +// The canonical candidate collection lives with the generic matcher; the +// Codex sidecar re-exports it so the route module keeps its import surface. +export { collectImportCandidates } from './localSessions/matchContentPrefix' +export type { ImportCandidate } from './localSessions/matchContentPrefix' + +/** + * Codex sidecar capabilities that live outside the import path: + * desktop status/restart, duplicate detection/merge, script logs and the + * shared content-compare helpers. The generic import path never calls these; + * the Codex route wrappers do. + */ + +export const CODEX_DESKTOP_NOT_FOUND_ERROR = '尝试重启codex客户端失败,未安装/找不到codex客户端' +export const SCRIPT_TIMEOUT_ERROR = '执行超时' +export const CODEX_TRANSCRIPT_IMPORT_NAMESPACE_ERROR = 'Codex transcript import is not available outside the default namespace' +const DEFAULT_SCRIPT_TIMEOUT_MS = 60_000 +const DARWIN_CODEX_APP_NAME = 'Codex' +const DARWIN_CODEX_APP_CANDIDATES = [ + '/Applications/Codex.app', + join(homedir(), 'Applications', 'Codex.app') +] + +// --- script log + workspace helpers --------------------------------------- + +type ScriptLogKind = 'sync' | 'restart' + +export const DIRECT_IMPORT_COMMAND = 'direct-import' +const RESTART_SCRIPT_ENV_NAME = 'HAPI_CODEX_RESTART_SCRIPT' +const RESTART_SCRIPT_DEFAULT_FILE = 'Restart-CodexDesktop.ps1' +const RESTART_SCRIPT_ARGS = ['-Apply'] +const RESTART_SCRIPT_MESSAGE = 'Codex Desktop restart script started' + +function resolveLocalPath(pathValue: string): string { + return isAbsolute(pathValue) ? pathValue : resolve(process.cwd(), pathValue) +} + +function getScriptRoot(): string { + const configured = process.env.HAPI_CODEX_SCRIPT_ROOT?.trim() + return configured ? resolveLocalPath(configured) : process.cwd() +} + +function getDefaultScriptPath(defaultFile: string): string { + const configuredRoot = process.env.HAPI_CODEX_SCRIPT_ROOT?.trim() + if (configuredRoot) { + return join(resolveLocalPath(configuredRoot), defaultFile) + } + + const cwd = process.cwd() + const candidateRoots = [ + cwd, + resolve(cwd, '..'), + resolve(cwd, '..', '..') + ] + + for (const root of candidateRoots) { + const candidate = join(root, defaultFile) + if (existsSync(candidate)) { + return candidate + } + } + + return join(getScriptRoot(), defaultFile) +} + +export function getRestartScriptPath(): string { + const configured = process.env[RESTART_SCRIPT_ENV_NAME]?.trim() + return configured ? resolveLocalPath(configured) : getDefaultScriptPath(RESTART_SCRIPT_DEFAULT_FILE) +} + +function getWorkspace(scriptPath: string): string { + const configured = process.env.HAPI_CODEX_WORKSPACE?.trim() + return configured ? resolveLocalPath(configured) : dirname(scriptPath) +} + +export function getRestartScriptWorkspace(): string { + return getWorkspace(getRestartScriptPath()) +} + +export function getDirectImportWorkspace(): string { + const configured = process.env.HAPI_CODEX_WORKSPACE?.trim() + return configured ? resolveLocalPath(configured) : process.cwd() +} + +export function getDirectImportRouteContext(): { workspace: string } { + return { + workspace: getDirectImportWorkspace() + } +} + +export function appendScriptLog(workspace: string, kind: ScriptLogKind, message: string): void { + try { + const logDir = join(workspace, 'logs') + mkdirSync(logDir, { recursive: true }) + const line = `[${new Date().toISOString()}] [${kind}] ${message}\n` + appendFileSync(join(logDir, 'CodexDesktopScript.log'), line, 'utf-8') + } catch { + // Best-effort logging only; API response still carries the error. + } +} + +// --- desktop status -------------------------------------------------------- + +export type CodexDesktopStatus = { + running: boolean + clientAvailable: boolean +} + +function getPathExts(): string[] { + if (process.platform !== 'win32') { + return [''] + } + const fromEnv = (process.env.PATHEXT ?? '') + .split(';') + .map(ext => ext.trim().toLowerCase()) + .filter(Boolean) + return Array.from(new Set(['', '.exe', '.cmd', '.bat', '.ps1', ...fromEnv])) +} + +function findOnPath(commandName: string): string | null { + if (commandName.includes('\\') || commandName.includes('/')) { + return existsSync(commandName) ? commandName : null + } + + const pathDirs = (process.env.PATH ?? '') + .split(process.platform === 'win32' ? ';' : ':') + .map(part => part.trim()) + .filter(Boolean) + const extensions = getPathExts() + + for (const dir of pathDirs) { + for (const ext of extensions) { + const candidate = join(dir, commandName.endsWith(ext) ? commandName : `${commandName}${ext}`) + if (existsSync(candidate)) { + return candidate + } + } + } + + return null +} + +function getCodexLauncherCandidates(): string[] { + return [ + process.env.HAPI_CODEX_COMMAND?.trim() ?? '', + findOnPath('codex') ?? '', + process.env.LOCALAPPDATA ? join(process.env.LOCALAPPDATA, 'Microsoft', 'WindowsApps', 'codex.exe') : '' + ].filter(Boolean) +} + +function isCodexLauncherAvailable(): boolean { + return getCodexLauncherCandidates().some(candidate => { + try { + return existsSync(candidate) + } catch { + return false + } + }) +} + +function getDarwinCodexAppCandidates(): string[] { + return [ + process.env.HAPI_CODEX_APP_PATH?.trim() ?? '', + ...DARWIN_CODEX_APP_CANDIDATES + ].filter(Boolean) +} + +function isDarwinCodexAppInstalled(): boolean { + return getDarwinCodexAppCandidates().some(candidate => { + try { + return existsSync(candidate) + } catch { + return false + } + }) +} + +function isCodexDesktopPath(pathValue: string): boolean { + return /\\WindowsApps\\OpenAI\.Codex_[^\\]+\\app\\(?:Codex|resources\\codex)\.exe$/i.test(pathValue) +} + +function isCodexDesktopPackageInstalled(): boolean { + if (process.platform !== 'win32') { + return false + } + + const command = [ + "$package = Get-AppxPackage -Name OpenAI.Codex -ErrorAction SilentlyContinue", + "if ($package) { 'true' } else { 'false' }" + ].join('\n') + + for (const shell of ['pwsh', 'powershell.exe']) { + try { + const result = spawnSync(shell, ['-NoLogo', '-NoProfile', '-Command', command], { + encoding: 'utf-8', + timeout: 5000, + windowsHide: true + }) + if (result.status === 0) { + return result.stdout.trim().toLowerCase().includes('true') + } + } catch { + // Try next shell. + } + } + + return false +} + +function isCodexDesktopInstallAvailable(): boolean { + if (process.platform === 'darwin') { + return isDarwinCodexAppInstalled() || isCodexLauncherAvailable() + } + + if (process.platform !== 'win32') { + return isCodexLauncherAvailable() + } + + if (isCodexDesktopPackageInstalled()) { + return true + } + + return getCodexLauncherCandidates().some(candidate => { + try { + return isCodexDesktopPath(candidate) && existsSync(candidate) + } catch { + return false + } + }) +} + +function isCodexDesktopRunning(): boolean { + if (process.platform === 'darwin') { + try { + const result = spawnSync('pgrep', ['-x', DARWIN_CODEX_APP_NAME], { + encoding: 'utf-8', + timeout: 5000 + }) + return result.status === 0 + } catch { + return false + } + } + + if (process.platform !== 'win32') { + return false + } + + const command = [ + "$targets = @(Get-CimInstance Win32_Process | Where-Object {", + " ($_.Name -ieq 'Codex.exe' -or $_.Name -ieq 'codex.exe') -and", + " $_.ExecutablePath -match '\\\\WindowsApps\\\\OpenAI\\.Codex_'", + '})', + "if ($targets.Count -gt 0) { 'true' } else { 'false' }" + ].join('\n') + + for (const shell of ['pwsh', 'powershell.exe']) { + try { + const result = spawnSync(shell, ['-NoLogo', '-NoProfile', '-Command', command], { + encoding: 'utf-8', + timeout: 5000, + windowsHide: true + }) + if (result.status === 0) { + return result.stdout.trim().toLowerCase().includes('true') + } + } catch { + // Try next shell. + } + } + + return false +} + +export function getCodexDesktopStatus(): CodexDesktopStatus { + const running = isCodexDesktopRunning() + return { + running, + clientAvailable: running || isCodexDesktopInstallAvailable() + } +} + +export type CodexDesktopStatusResponse = { + success: true + codexDesktopRunning: boolean + codexClientAvailable: boolean +} + +// --- restart --------------------------------------------------------------- + +function getScriptTimeoutMs(): number { + const configured = Number(process.env.HAPI_CODEX_SCRIPT_TIMEOUT_MS) + if (Number.isFinite(configured) && configured > 0) { + return configured + } + return DEFAULT_SCRIPT_TIMEOUT_MS +} + +function createLaunchArgs(scriptPath: string, workspace: string, scriptArgs: string[]): string[] { + return [ + '-NoLogo', + '-NoProfile', + '-ExecutionPolicy', + 'Bypass', + '-File', + scriptPath, + '-Workspace', + workspace, + ...scriptArgs + ] +} + +async function runPowerShellScript(scriptPath: string, workspace: string, scriptArgs: string[]): Promise<{ pid: number; command: string; output: string }> { + const configuredPwsh = process.env.HAPI_PWSH_PATH?.trim() + const candidates = Array.from(new Set([ + configuredPwsh || 'pwsh', + 'powershell.exe' + ])) + const args = createLaunchArgs(scriptPath, workspace, scriptArgs) + let lastError: unknown = null + + for (const command of candidates) { + try { + return await new Promise((resolvePromise, rejectPromise) => { + const output: string[] = [] + let settled = false + let didSpawn = false + let timeout: ReturnType | null = null + const child = spawn(command, args, { + cwd: workspace, + stdio: ['ignore', 'pipe', 'pipe'], + windowsHide: true + }) + + const cleanup = () => { + if (timeout) { + clearTimeout(timeout) + } + child.off('spawn', onSpawn) + child.off('error', onError) + child.off('exit', onExit) + } + + const settleResolve = (value: { pid: number; command: string; output: string }) => { + if (settled) return + settled = true + cleanup() + resolvePromise(value) + } + + const settleReject = (error: Error) => { + if (settled) return + settled = true + cleanup() + rejectPromise(error) + } + + const onSpawn = () => { + didSpawn = true + } + + const onError = (error: Error) => { + if (!didSpawn) { + ;(error as Error & { shellLaunchFailed?: boolean }).shellLaunchFailed = true + } + settleReject(error) + } + + const onExit = (code: number | null, signal: NodeJS.Signals | null) => { + const combinedOutput = output.join('').trim() + if (code === 0) { + settleResolve({ pid: child.pid ?? 0, command, output: combinedOutput }) + return + } + const detail = combinedOutput ? `\n${combinedOutput}` : '' + settleReject(new Error(`${command} exited with code ${code ?? 'null'}${signal ? ` signal ${signal}` : ''}.${detail}`)) + } + + timeout = setTimeout(() => { + child.kill() + settleReject(new Error(SCRIPT_TIMEOUT_ERROR)) + }, getScriptTimeoutMs()) + + child.stdout?.on('data', (chunk) => output.push(String(chunk))) + child.stderr?.on('data', (chunk) => output.push(String(chunk))) + child.once('spawn', onSpawn) + child.once('error', onError) + child.once('exit', onExit) + }) + } catch (error) { + lastError = error + if (!(error instanceof Error && (error as Error & { shellLaunchFailed?: boolean }).shellLaunchFailed)) { + throw error instanceof Error ? error : new Error(String(error)) + } + } + } + + throw lastError instanceof Error ? lastError : new Error(String(lastError)) +} + +function getDarwinCodexOpenTarget(): string { + return getDarwinCodexAppCandidates().find((candidate) => { + try { + return existsSync(candidate) + } catch { + return false + } + }) ?? DARWIN_CODEX_APP_NAME +} + +export function getDarwinCodexOpenArgs(target: string): string[] { + return target.endsWith('.app') ? [target] : ['-a', target] +} + +async function restartDarwinCodexDesktop(workspace: string): Promise<{ pid: number; command: string; output: string }> { + const output: string[] = [] + try { + const quit = spawnSync('osascript', ['-e', `tell application "${DARWIN_CODEX_APP_NAME}" to quit`], { + encoding: 'utf-8', + timeout: 5000 + }) + const quitOutput = `${quit.stdout ?? ''}${quit.stderr ?? ''}`.trim() + if (quitOutput) { + output.push(quitOutput) + } + } catch (error) { + output.push(error instanceof Error ? error.message : String(error)) + } + + return await new Promise((resolvePromise, rejectPromise) => { + const target = getDarwinCodexOpenTarget() + const child = spawn('open', getDarwinCodexOpenArgs(target), { + cwd: workspace, + detached: true, + stdio: ['ignore', 'pipe', 'pipe'] + }) + const launchOutput: string[] = [] + let settled = false + let timeout: ReturnType | null = null + + const cleanup = () => { + if (timeout) { + clearTimeout(timeout) + } + child.off('error', onError) + child.off('exit', onExit) + } + + const settle = (callback: () => void) => { + if (settled) return + settled = true + cleanup() + callback() + } + + const onError = (error: Error) => { + settle(() => rejectPromise(error)) + } + + const onExit = (code: number | null, signal: NodeJS.Signals | null) => { + const combinedLaunchOutput = launchOutput.join('').trim() + if (combinedLaunchOutput) { + output.push(combinedLaunchOutput) + } + if (code === 0) { + child.unref() + settle(() => resolvePromise({ + pid: child.pid ?? 0, + command: 'open', + output: output.join('\n').trim() + })) + return + } + const detail = output.length > 0 ? `\n${output.join('\n')}` : '' + settle(() => rejectPromise(new Error(`open exited with code ${code ?? 'null'}${signal ? ` signal ${signal}` : ''}.${detail}`))) + } + + timeout = setTimeout(() => { + child.kill() + settle(() => rejectPromise(new Error(SCRIPT_TIMEOUT_ERROR))) + }, getScriptTimeoutMs()) + + child.stdout?.on('data', (chunk) => launchOutput.push(String(chunk))) + child.stderr?.on('data', (chunk) => launchOutput.push(String(chunk))) + child.once('error', onError) + child.once('exit', onExit) + }) +} + +export async function launchRestartScript(): Promise { + const scriptPath = getRestartScriptPath() + const workspace = getWorkspace(scriptPath) + + if (!existsSync(scriptPath)) { + if (process.platform === 'darwin' && !process.env[RESTART_SCRIPT_ENV_NAME]?.trim()) { + try { + const launched = await restartDarwinCodexDesktop(workspace) + const output = launched.output + appendScriptLog( + workspace, + 'restart', + `SUCCESS: ${RESTART_SCRIPT_MESSAGE}; pid=${launched.pid}; command=${launched.command}${output ? `; output=${output}` : ''}` + ) + return { + success: true, + message: RESTART_SCRIPT_MESSAGE, + pid: launched.pid, + command: launched.command, + cwd: workspace, + output + } + } catch (error) { + const message = error instanceof Error ? error.message : String(error) + appendScriptLog(workspace, 'restart', `FAILED: ${message}; native=darwin`) + return { + success: false, + error: message, + cwd: workspace + } + } + } + + appendScriptLog(workspace, 'restart', `FAILED: Script not found: ${scriptPath}`) + return { + success: false, + error: `Script not found: ${scriptPath}`, + script: scriptPath, + cwd: workspace + } + } + + if (!existsSync(workspace)) { + appendScriptLog(workspace, 'restart', `FAILED: Workspace not found: ${workspace}`) + return { + success: false, + error: `Workspace not found: ${workspace}`, + script: scriptPath, + cwd: workspace + } + } + + try { + const launched = await runPowerShellScript(scriptPath, workspace, RESTART_SCRIPT_ARGS) + const output = launched.output + appendScriptLog( + workspace, + 'restart', + `SUCCESS: ${RESTART_SCRIPT_MESSAGE}; pid=${launched.pid}; command=${launched.command}; script=${scriptPath}${output ? `; output=${output}` : ''}` + ) + return { + success: true, + message: RESTART_SCRIPT_MESSAGE, + pid: launched.pid, + command: launched.command, + script: scriptPath, + cwd: workspace, + output + } + } catch (error) { + const message = error instanceof Error ? error.message : String(error) + appendScriptLog(workspace, 'restart', `FAILED: ${message}; script=${scriptPath}`) + return { + success: false, + error: message, + script: scriptPath, + cwd: workspace + } + } +} + +// --- shared response + compare helpers -------------------------------------- + +export type ScriptLaunchResponse = { + success: true + message: string + pid: number + command: string + script?: string + cwd: string + output?: string + codexDesktopRunning?: boolean + codexClientAvailable?: boolean + syncedCount?: number + sessionIds?: string[] + hapiSessionIds?: string[] +} | { + success: false + error: string + script?: string + cwd: string + output?: string + codexDesktopRunning?: boolean + codexClientAvailable?: boolean + syncedCount?: number + sessionIds?: string[] + hapiSessionIds?: string[] +} + +export function stableSerialize(value: unknown): string { + if (value === null || value === undefined) { + return String(value) + } + if (typeof value === 'string') { + return JSON.stringify(value) + } + if (typeof value === 'number' || typeof value === 'boolean') { + return JSON.stringify(value) + } + if (Array.isArray(value)) { + return `[${value.map((item) => stableSerialize(item)).join(',')}]` + } + if (typeof value === 'object') { + const record = value as Record + const keys = Object.keys(record).sort() + return `{${keys.map((key) => `${JSON.stringify(key)}:${stableSerialize(record[key])}`).join(',')}}` + } + return JSON.stringify(value) +} + +function asRecord(value: unknown): Record | null { + return value !== null && typeof value === 'object' && !Array.isArray(value) + ? value as Record + : null +} + +function normalizeComparableText(value: string): string { + return value.replace(/\s+$/u, '') +} + +function normalizeComparableAgentData(value: unknown): unknown { + const record = asRecord(value) + if (!record) { + return value + } + + const normalized = { ...record } + if ('id' in normalized) { + delete normalized.id + } + return normalized +} + +export function normalizeComparableContent(content: unknown): string | null { + // Stored rows are truncated at ingest (contentCodec) while transcript + // messages arrive in full; truncation is idempotent, so applying it here + // makes both sides of the prefix comparison canonical. Pre-codec stored + // rows (never truncated) get normalized the same way. + const record = asRecord(truncateOversizedMessageContent(content)) + if (!record) { + return null + } + + if (record.role === 'user') { + const body = asRecord(record.content) + if (body?.type !== 'text' || typeof body.text !== 'string') { + return null + } + return stableSerialize({ + role: 'user', + text: normalizeComparableText(body.text) + }) + } + + if (record.role === 'agent') { + const body = asRecord(record.content) + if (!body || body.type !== AGENT_MESSAGE_PAYLOAD_TYPE) { + return null + } + return stableSerialize({ + role: 'agent', + data: normalizeComparableAgentData(body.data) + }) + } + + return null +} + +export function getComparableStoredMessageKey(message: StoredMessage): string { + // 重复会话合并时优先按标准 user/agent 结构去重;遇到非标准消息再回退到稳定序列化,确保不会遗漏相同内容。 + // Fallback also truncates so a pre-codec (full) row and a post-codec + // (truncated) copy of the same message still dedupe to one key. + return normalizeComparableContent(message.content) ?? stableSerialize(truncateOversizedMessageContent(message.content)) +} + +// --- duplicate detection / merge --------------------------------------------- + +export function getCodexImportIds(metadata: Record | null | undefined): string[] { + return Array.from(new Set([metadata?.codexSessionId, metadata?.codexSourceSessionId] + .filter((id): id is string => typeof id === 'string' && id.length > 0))) +} + +export function isImportCandidateReusable(candidate: ImportCandidate): boolean { + const lifecycleState = candidate.metadata?.lifecycleState + if (lifecycleState === 'archived' || lifecycleState === 'deleted') { + return false + } + return true +} + +export type CodexDuplicateSessionGroup = { + codexSessionId: string + hapiSessionIds: string[] + canonicalSessionId?: string + removedSessionIds?: string[] +} + +export type CodexDuplicateSessionsResponse = { + success: true + duplicates: CodexDuplicateSessionGroup[] +} | { + success: false + error: string +} + +export type CodexMergeDuplicateSessionsResponse = { + success: true + merged: CodexDuplicateSessionGroup[] + mergedCount: number +} | { + success: false + error: string +} + +type DuplicateSessionGroupCandidate = { + codexSessionId: string + sessions: ImportCandidate[] +} + +export function listDuplicateCodexSessionGroups( + store: Store, + namespace: string, + codexSessionIds: string[], + getSyncEngine?: () => SyncEngine | null +): DuplicateSessionGroupCandidate[] { + const requestedSessionIds = new Set(codexSessionIds) + if (requestedSessionIds.size === 0) { + return [] + } + + const groups = new Map() + for (const candidate of collectImportCandidates(store, namespace, getSyncEngine)) { + if (!candidate.persisted || !isImportCandidateReusable(candidate)) { + continue + } + for (const codexSessionId of getCodexImportIds(candidate.metadata)) { + if (!requestedSessionIds.has(codexSessionId)) { + continue + } + + const existing = groups.get(codexSessionId) + if (existing) { + existing.push(candidate) + } else { + groups.set(codexSessionId, [candidate]) + } + } + } + + return Array.from(groups.entries()) + .map(([codexSessionId, sessions]) => ({ + codexSessionId, + sessions: sessions.sort((a, b) => b.updatedAt - a.updatedAt) + })) + .filter((group) => group.sessions.length > 1) +} + +export function emitImportedMessageEvents( + engine: SyncEngine | null, + sessionId: string, + appendedMessages: StoredMessage[] +): void { + if (!engine) { + return + } + + // 只有追加到已有 Hapi 会话时才逐条广播新增消息,确保当前打开的会话右侧消息区能立即刷新到最新 transcript。 + for (const message of appendedMessages) { + engine.handleRealtimeEvent({ + type: 'message-received', + sessionId, + message: { + id: message.id, + seq: message.seq, + localId: message.localId ?? null, + content: message.content, + createdAt: message.createdAt, + invokedAt: message.invokedAt + } + }) + } +} + +async function mergeSingleDuplicateCodexSessionGroup(options: { + group: DuplicateSessionGroupCandidate + store: Store + namespace: string + getSyncEngine?: () => SyncEngine | null +}): Promise { + const engine = options.getSyncEngine?.() ?? null + const uniqueSessions = Array.from(new Map(options.group.sessions.map((session) => [session.sessionId, session])).values()) + const sessionStates = uniqueSessions + .map((candidate) => ({ + ...candidate, + storedMessages: options.store.messages.getAllMessages(candidate.sessionId), + })) + .map((candidate) => ({ + ...candidate, + comparableKeys: candidate.storedMessages.map((message) => getComparableStoredMessageKey(message)) + })) + .sort((a, b) => { + if (b.comparableKeys.length !== a.comparableKeys.length) { + return b.comparableKeys.length - a.comparableKeys.length + } + if (b.updatedAt !== a.updatedAt) { + return b.updatedAt - a.updatedAt + } + return a.sessionId.localeCompare(b.sessionId) + }) + + if (sessionStates.some((candidate) => candidate.active)) { + throw new Error('当前会话仍处于活跃状态,请等待会话结束后重试') + } + + const canonical = sessionStates[0] + if (!canonical) { + throw new Error(`No duplicate Hapi session found for Codex thread: ${options.group.codexSessionId}`) + } + + const knownKeys = new Set(canonical.comparableKeys) + const removedSessionIds: string[] = [] + const appendedMessages: StoredMessage[] = [] + let latestActivity = canonical.updatedAt + + if ( + !engine + && sessionStates.slice(1).some( + (source) => options.store.sessionJobs.list(source.sessionId).length > 0 + ) + ) { + throw new Error( + 'Sync engine unavailable; retry merge so attached-job redirects are preserved' + ) + } + + for (const source of sessionStates.slice(1)) { + latestActivity = Math.max(latestActivity, source.updatedAt) + for (const message of source.storedMessages) { + const comparableKey = getComparableStoredMessageKey(message) + if (knownKeys.has(comparableKey)) { + continue + } + + const copied = options.store.messages.copyMessageToSession(canonical.sessionId, { + content: message.content, + createdAt: message.createdAt, + localId: message.localId, + invokedAt: message.invokedAt, + scheduledAt: message.scheduledAt + }) + knownKeys.add(comparableKey) + appendedMessages.push(copied) + latestActivity = Math.max(latestActivity, copied.invokedAt ?? copied.createdAt) + } + + // Transfer outliving jobs before CASCADE delete (store refuses running jobs). + // Without SyncEngine we cannot persist jobsAcceptedFromSessionIds / key remaps, + // so refuse rather than orphan a supervisor still holding the source session id. + if (engine) { + engine.transferAttachedJobs(source.sessionId, canonical.sessionId, options.namespace) + await engine.deleteSession(source.sessionId) + } else { + const deleted = options.store.sessions.deleteSession(source.sessionId, options.namespace) + if (!deleted) { + throw new Error(`Failed to delete duplicate Hapi session: ${source.sessionId}`) + } + } + removedSessionIds.push(source.sessionId) + } + + if (appendedMessages.length > 0) { + emitImportedMessageEvents(engine, canonical.sessionId, appendedMessages) + } + + if (engine) { + engine.recordSessionActivity(canonical.sessionId, latestActivity) + // 即使这次只是删除重复分身、没有新增消息,也主动刷新 canonical 会话,确保左侧列表立刻收敛到合并后的状态。 + engine.handleRealtimeEvent({ + type: 'session-updated', + sessionId: canonical.sessionId + }) + } else { + options.store.sessions.touchSessionUpdatedAt(canonical.sessionId, latestActivity, options.namespace) + } + + return { + codexSessionId: options.group.codexSessionId, + hapiSessionIds: sessionStates.map((candidate) => candidate.sessionId), + canonicalSessionId: canonical.sessionId, + removedSessionIds + } +} + +export async function mergeDuplicateCodexSessionGroups(options: { + store: Store + namespace: string + codexSessionIds: string[] + getSyncEngine?: () => SyncEngine | null +}): Promise { + const groups = listDuplicateCodexSessionGroups( + options.store, + options.namespace, + options.codexSessionIds, + options.getSyncEngine + ) + if (groups.length === 0) { + return { + success: true, + merged: [], + mergedCount: 0 + } + } + + const merged: CodexDuplicateSessionGroup[] = [] + for (const group of groups) { + const result = await mergeSingleDuplicateCodexSessionGroup({ + group, + store: options.store, + namespace: options.namespace, + getSyncEngine: options.getSyncEngine + }) + merged.push(result) + } + + return { + success: true, + merged, + mergedCount: merged.length + } +} \ No newline at end of file diff --git a/hub/src/web/routes/codexGenericImport.test.ts b/hub/src/web/routes/codexGenericImport.test.ts new file mode 100644 index 00000000..7f7b1dc4 --- /dev/null +++ b/hub/src/web/routes/codexGenericImport.test.ts @@ -0,0 +1,418 @@ +import { afterEach, describe, expect, it } from 'bun:test' +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { Hono } from 'hono' +import { Store } from '../../store' +import type { Machine, SyncEngine } from '../../sync/syncEngine' +import type { LocalTranscript } from '@hapi/protocol/localTranscript' +import type { WebAppEnv } from '../middleware/auth' +import { createCodexDesktopRoutes, importSelectedCodexSessions, type CodexImportedMessageContent } from './codexDesktop' + +/** + * Pinning tests for the generic-route Codex import semantics: transcripts + * always come from the runner's ListLocalSessions RPC (the hub never reads + * its own CODEX_HOME), persistence is atomic, syncs serialize, a HAPI-side + * rename and the runner machine host survive re-syncs, launch config goes + * through applySessionConfig, and transcript list/sync work in every + * namespace. + */ + +const CODex_SESSION_ID = '17171717-1717-4717-8717-171717171717' + +function codexUserMessage(text: string): CodexImportedMessageContent { + return { + role: 'user', + content: { type: 'text', text }, + meta: { sentFrom: 'cli' } + } +} + +function codexAgentMessage(message: string, id = 'assistant-1'): CodexImportedMessageContent { + return { + role: 'agent', + content: { type: 'codex', data: { type: 'message', message, id } }, + meta: { sentFrom: 'cli' } + } +} + +function codexThreadFixture(id: string, messages: CodexImportedMessageContent[], overrides: { + title?: string + cwd?: string +} = {}) { + return { + id, + title: overrides.title ?? `Codex thread ${id}`, + cwd: overrides.cwd ?? 'C:\\work\\project', + file: `rollout-${id}.jsonl`, + modifiedAt: 1, + messages + } +} + +function createImportSyncEngine(store: Store, machines: Machine[]): SyncEngine { + return { + getOnlineMachinesByNamespace: (namespace: string) => machines.filter((candidate) => ( + candidate.namespace === namespace && candidate.active + )), + getSessionsByNamespace: (namespace: string) => ( + store.sessions.getSessionsByNamespace(namespace) as unknown as ReturnType + ), + getOrCreateSession: ( + tag: string, + metadata: unknown, + agentState: unknown, + namespace: string + ) => ( + store.sessions.getOrCreateSession(tag, metadata, agentState, namespace) as unknown as ReturnType + ), + handleRealtimeEvent: () => {}, + recordSessionActivity: () => {} + } as unknown as SyncEngine +} + +function machine(id: string, workspaceRoots: string[] = [], capabilities?: string[]): Machine { + return { + id, + namespace: 'default', + seq: 0, + createdAt: 0, + updatedAt: 0, + active: true, + activeAt: 0, + metadata: { + host: `${id}.host`, + platform: 'linux', + happyCliVersion: '0.0.0-test', + workspaceRoots, + ...(capabilities ? { capabilities } : {}) + }, + metadataVersion: 1, + runnerState: null, + runnerStateVersion: 1, + health: null + } +} + +function standardTranscriptFixture() { + return codexThreadFixture(CODex_SESSION_ID, [ + codexUserMessage('normal user message'), + codexAgentMessage('normal assistant message') + ]) +} + +/** Legacy ListCodexSessions stub serving the given raw rows. */ +function serveLegacyCodexSessions(engine: SyncEngine, sessions: unknown[]): void { + ;(engine as unknown as Record).listCodexSessionsForMachine = async () => ({ + success: true, + sessions + }) +} + +/** Normalized ListLocalSessions transcript for the standard fixture. */ +function fixtureTranscript(): LocalTranscript { + const fixture = standardTranscriptFixture() + return { + flavor: 'codex', + id: fixture.id, + title: fixture.title, + lastUserMessage: 'normal user message', + cwd: fixture.cwd, + file: fixture.file, + modifiedAt: fixture.modifiedAt, + extra: { originator: 'codex-cli', cliVersion: '9.9.9', source: null, threadSource: null, forkedFromId: null }, + messages: fixture.messages.map((content, index) => ({ + id: `codex-desktop:${fixture.id}:${index}`, + content + })) + } +} + +/** Normalized ListLocalSessions summary (no messages) for list calls. */ +function fixtureSummary(): LocalTranscript { + const { messages: _messages, ...summary } = fixtureTranscript() + return summary as LocalTranscript +} + +function harnessApp(store: Store, engine: SyncEngine) { + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + app.route('/api', createCodexDesktopRoutes({ store, getSyncEngine: () => engine })) + return app +} + +describe('Codex generic import', () => { + const stores: Store[] = [] + const originalCodexHome = process.env.CODEX_HOME + + afterEach(() => { + if (originalCodexHome === undefined) { + delete process.env.CODEX_HOME + } else { + process.env.CODEX_HOME = originalCodexHome + } + for (const store of stores.splice(0)) store.close() + }) + + it('never reads the hub\'s own CODEX_HOME', async () => { + const codexHome = mkdtempSync(join(tmpdir(), 'hapi-codex-x1-hub-disk-')) + process.env.CODEX_HOME = codexHome + // A transcript exists on the hub's own disk; without runner sessions + // the import must fail instead of reading it. + const sessionDir = join(codexHome, 'sessions', '2026', '06', '04') + mkdirSync(sessionDir, { recursive: true }) + writeFileSync(join(sessionDir, `rollout-${CODex_SESSION_ID}.jsonl`), '{}\n', 'utf-8') + const store = new Store(':memory:') + stores.push(store) + const engine = createImportSyncEngine(store, [machine('m-1')]) + serveLegacyCodexSessions(engine, []) + + const result = await importSelectedCodexSessions({ + codexSessionIds: [CODex_SESSION_ID], + store, + namespace: 'default', + getSyncEngine: () => engine + }) + + expect(result.success).toBe(false) + if (result.success) throw new Error('Expected the hub-disk fallback to be gone') + expect(result.error).toContain('Transcript not found for Codex session') + expect(store.sessions.getSessionsByNamespace('default')).toHaveLength(0) + rmSync(codexHome, { recursive: true, force: true }) + }) + + it('rolls a Codex sync back on insert failure', async () => { + const store = new Store(':memory:') + stores.push(store) + const engine = createImportSyncEngine(store, [machine('m-1')]) + serveLegacyCodexSessions(engine, [codexThreadFixture(CODex_SESSION_ID, [ + codexUserMessage('one'), + codexUserMessage('two') + ])]) + const original = store.messages.addImportedMessage.bind(store.messages) + let calls = 0 + ;(store.messages as { addImportedMessage: typeof original }).addImportedMessage = ( + (sessionId: string, content: unknown, localId: string, createdAt: number) => { + calls += 1 + if (calls === 2) throw new Error('boom') + return original(sessionId, content, localId, createdAt) + } + ) as typeof original + + const result = await importSelectedCodexSessions({ + codexSessionIds: [CODex_SESSION_ID], + store, + namespace: 'default', + getSyncEngine: () => engine + }) + + expect(result.success).toBe(false) + if (result.success) throw new Error('Expected the failed sync to report an error') + expect(result.error).toContain('boom') + expect(store.sessions.getSessionsByNamespace('default')).toHaveLength(0) + }) + + it('serializes concurrent syncs of one Codex thread', async () => { + const store = new Store(':memory:') + stores.push(store) + const engine = createImportSyncEngine(store, [machine('m-1')]) + const legacySessions: unknown[] = [standardTranscriptFixture()] + serveLegacyCodexSessions(engine, legacySessions) + const fixture = standardTranscriptFixture() + + const [first, second] = await Promise.all([ + importSelectedCodexSessions({ + codexSessionIds: [CODex_SESSION_ID], + store, + namespace: 'default', + getSyncEngine: () => engine + }), + importSelectedCodexSessions({ + codexSessionIds: [CODex_SESSION_ID], + store, + namespace: 'default', + getSyncEngine: () => engine + }) + ]) + + expect(first.success).toBe(true) + expect(second.success).toBe(true) + const codexSessions = store.sessions.getSessionsByNamespace('default') + expect(codexSessions).toHaveLength(1) + expect(store.messages.getAllMessages(codexSessions[0]!.id)).toHaveLength(2) + const firstOutput = first.success ? first.output : '' + const secondOutput = second.success ? second.output : '' + expect(firstOutput).toContain('Action: created') + expect(secondOutput).toContain('Action: updated') + expect(secondOutput).toContain('Appended messages: 0') + }) + + it('preserves a renamed HAPI Codex session on re-sync and records the runner machine host', async () => { + const store = new Store(':memory:') + stores.push(store) + const engine = createImportSyncEngine(store, [machine('m-1')]) + const legacySessions: unknown[] = [standardTranscriptFixture()] + serveLegacyCodexSessions(engine, legacySessions) + const fixture = standardTranscriptFixture() + + const first = await importSelectedCodexSessions({ + codexSessionIds: [CODex_SESSION_ID], + store, + namespace: 'default', + getSyncEngine: () => engine + }) + expect(first.success).toBe(true) + const session = store.sessions.getSessionsByNamespace('default')[0]! + expect(session.metadata).toMatchObject({ host: 'm-1.host', machineId: 'm-1' }) + store.sessions.updateSessionMetadata(session.id, { + ...(session.metadata as Record), + name: 'My custom HAPI title' + }, session.metadataVersion, 'default') + + legacySessions[0] = codexThreadFixture(CODex_SESSION_ID, [ + codexUserMessage('normal user message'), + codexAgentMessage('normal assistant message'), + codexUserMessage('a later turn') + ]) + + const second = await importSelectedCodexSessions({ + codexSessionIds: [CODex_SESSION_ID], + store, + namespace: 'default', + getSyncEngine: () => engine + }) + + expect(second.success).toBe(true) + const renamed = store.sessions.getSessionsByNamespace('default')[0]! + expect(renamed.id).toBe(session.id) + expect((renamed.metadata as Record).name).toBe('My custom HAPI title') + expect(store.messages.getAllMessages(session.id)).toHaveLength(3) + }) + + it('applies model and effort through session config', async () => { + const store = new Store(':memory:') + stores.push(store) + const engine = createImportSyncEngine(store, [machine('m-1')]) + serveLegacyCodexSessions(engine, [standardTranscriptFixture()]) + const applied: Array<{ sessionId: string; config: unknown }> = [] + ;(engine as unknown as { applySessionConfig: (sessionId: string, config: unknown) => Promise }).applySessionConfig = async (sessionId, config) => { + applied.push({ sessionId, config }) + } + + const result = await importSelectedCodexSessions({ + codexSessionIds: [CODex_SESSION_ID], + store, + namespace: 'default', + getSyncEngine: () => engine, + model: 'gpt-5.6', + modelReasoningEffort: 'high' + }) + + expect(result.success).toBe(true) + const importedSessionId = result.success ? result.hapiSessionIds?.[0] : undefined + expect(importedSessionId).toBeDefined() + expect(applied).toEqual([{ + sessionId: importedSessionId!, + config: { model: 'gpt-5.6', modelReasoningEffort: 'high' } + }]) + }) + + it('allows Codex history import in a non-default namespace', async () => { + const store = new Store(':memory:') + stores.push(store) + const machineA = { ...machine('m-1'), namespace: 'team-a' } + const engine = createImportSyncEngine(store, [machineA]) + const listCalls: string[] = [] + ;(engine as unknown as { listCodexSessionsForMachine: unknown }).listCodexSessionsForMachine = async (calledMachineId: string, _cwd: unknown, sessionIds?: string[] | null) => { + listCalls.push(calledMachineId) + // The legacy list RPC answers summaries without ids and full + // transcripts for exactly the requested ids. + return sessionIds?.length + ? { success: true, sessions: [standardTranscriptFixture()] } + : { success: true, sessions: [{ ...standardTranscriptFixture(), messages: undefined, originator: 'codex-cli', cliVersion: '9.9.9' }] } + } + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'team-a') + await next() + }) + app.route('/api', createCodexDesktopRoutes({ store, getSyncEngine: () => engine })) + + const listResponse = await app.request('/api/codex/sessions') + expect(listResponse.status).toBe(200) + const listBody = await listResponse.json() as { success: boolean; sessions: unknown[] } + expect(listBody.success).toBe(true) + expect(listBody.sessions).toHaveLength(1) + + const syncResponse = await app.request('/api/codex/sync-session', { + method: 'POST', + body: JSON.stringify({ sessionIds: [CODex_SESSION_ID] }) + }) + const syncBody = await syncResponse.json() as { success: boolean } + expect(syncBody.success).toBe(true) + // One list fetch for GET /codex/sessions and one for the sync. + expect(listCalls).toEqual(['m-1', 'm-1']) + expect(store.sessions.getSessionsByNamespace('team-a')).toHaveLength(1) + }) + + it('lists and imports through ListLocalSessions when the runner advertises the capability', async () => { + const store = new Store(':memory:') + stores.push(store) + const engine = createImportSyncEngine(store, [machine('m-1', [], ['local-session-import'])]) + let legacyCalls = 0 + ;(engine as unknown as Record).listCodexSessionsForMachine = async () => { + legacyCalls += 1 + return { success: true, sessions: [] } + } + const listCalls: Array<{ machineId: string; payload: unknown }> = [] + ;(engine as unknown as Record).listLocalSessionsForMachine = async (calledMachineId: string, payload: { sessionIds?: string[] | null }) => { + listCalls.push({ machineId: calledMachineId, payload }) + return { success: true, sessions: payload.sessionIds ? [fixtureTranscript()] : [fixtureSummary()] } + } + + const app = harnessApp(store, engine) + const listResponse = await app.request('/api/codex/sessions') + expect(listResponse.status).toBe(200) + const listBody = await listResponse.json() as { success: boolean; sessions: Array> } + expect(listBody.success).toBe(true) + expect(listBody.sessions).toHaveLength(1) + // The web shape flattens the normalized summary's extra fields. + expect(listBody.sessions[0]).toMatchObject({ id: CODex_SESSION_ID, originator: 'codex-cli', cliVersion: '9.9.9' }) + expect(Object.keys(listBody.sessions[0]!)).not.toContain('flavor') + expect(Object.keys(listBody.sessions[0]!)).not.toContain('launch') + + const syncResponse = await app.request('/api/codex/sync-session', { + method: 'POST', + body: JSON.stringify({ sessionIds: [CODex_SESSION_ID] }) + }) + const syncBody = await syncResponse.json() as { success: boolean } + expect(syncBody.success).toBe(true) + expect(store.sessions.getSessionsByNamespace('default')).toHaveLength(1) + expect(legacyCalls).toBe(0) + expect(listCalls.map((call) => call.payload)).toEqual([ + { flavor: 'codex', cwd: null, sessionIds: null }, + { flavor: 'codex', cwd: null, sessionIds: [CODex_SESSION_ID] } + ]) + }) + + it('caps sync-session imports at the shared 200-session limit', async () => { + const store = new Store(':memory:') + stores.push(store) + const engine = createImportSyncEngine(store, [machine('m-1')]) + serveLegacyCodexSessions(engine, []) + const app = harnessApp(store, engine) + + const response = await app.request('/api/codex/sync-session', { + method: 'POST', + body: JSON.stringify({ sessionIds: Array.from({ length: 201 }, (_, index) => `thread-${index}`) }) + }) + expect(response.status).toBe(400) + const body = await response.json() as { success: boolean; error?: string } + expect(body.success).toBe(false) + expect(body.error).toContain('200') + expect(store.sessions.getSessionsByNamespace('default')).toHaveLength(0) + }) +}) \ No newline at end of file diff --git a/hub/src/web/routes/localSessions/claudeResumeImport.test.ts b/hub/src/web/routes/localSessions/claudeResumeImport.test.ts new file mode 100644 index 00000000..7e0dc8bf --- /dev/null +++ b/hub/src/web/routes/localSessions/claudeResumeImport.test.ts @@ -0,0 +1,162 @@ +import { afterEach, describe, expect, it } from 'bun:test' +import { readFileSync } from 'node:fs' +import { join } from 'node:path' +import type { ClaudeLocalSessionWithMessages } from '@hapi/protocol/apiTypes' +import { claudeToTranscript } from '@hapi/protocol/localTranscript' +import type { LocalTranscript } from '@hapi/protocol/localTranscript' +import type { Machine, SyncEngine } from '../../../sync/syncEngine' +import { Store } from '../../../store' +import { importLocalTranscript } from './importLocalTranscript' +import { CLAUDE_LOCAL_SESSION_SOURCE } from './sources' + +/** + * Claude Code copies the earlier entries into the new transcript when a + * session resumes: the uuids stay, but sessionId and timestamp are rewritten. + * The CLI session scanner fixtures are real before/after resume files. + */ +const FIXTURES = join(import.meta.dir, '../../../../../cli/src/claude/utils/__fixtures__') +const FIRST_SESSION = '93a9705e-bc6a-406d-8dce-8acc014dedbd' +const RESUMED_SESSION = '789e105f-ae33-486d-9271-0696266f072d' + +type RawEntry = Record & { + type?: string + uuid?: string + timestamp?: string + message?: { content?: unknown } +} + +function readEntries(name: string): RawEntry[] { + return readFileSync(join(FIXTURES, name), 'utf8') + .split('\n') + .filter((line) => line.trim().length > 0) + .map((line) => JSON.parse(line) as RawEntry) +} + +function externalUserText(entry: RawEntry): string | null { + if (entry.type !== 'user') return null + const content = entry.message?.content + if (typeof content === 'string') return content + if (Array.isArray(content) && content.length > 0 && content.every((block) => block?.type === 'text')) { + return content.map((block) => String(block.text)).join('') + } + return null +} + +/** Row mapping of the CLI reader: user text stays text, any other entry is kept whole. */ +function transcriptOf(sessionId: string, entries: RawEntry[]): LocalTranscript { + const messages: ClaudeLocalSessionWithMessages['messages'] = entries + .filter((entry) => (entry.type === 'user' || entry.type === 'assistant') && typeof entry.uuid === 'string') + .map((entry) => { + const text = externalUserText(entry) + return { + uuid: entry.uuid!, + createdAt: Date.parse(entry.timestamp!), + content: text !== null + ? { role: 'user', content: { type: 'text', text }, meta: { sentFrom: 'cli' } } + : { role: 'agent', content: { type: 'output', data: entry }, meta: { sentFrom: 'cli' } } + } + }) + return claudeToTranscript({ + id: sessionId, + title: 'Resumed fixture', + lastUserMessage: null, + cwd: '/tmp/project', + file: `/tmp/${sessionId}.jsonl`, + modifiedAt: 1, + messageCount: messages.length, + messages + }) +} + +function machine(): Machine { + return { + id: 'm-1', + namespace: 'default', + seq: 1, + createdAt: 1, + updatedAt: 1, + active: true, + activeAt: 1, + metadata: { host: 'm-1.local', platform: 'linux', happyCliVersion: 'test', workspaceRoots: ['/tmp/project'] }, + metadataVersion: 1, + runnerState: null, + runnerStateVersion: 1, + health: null + } +} + +function harness() { + const store = new Store(':memory:') + const engine = { + recordSessionActivity: () => {}, + handleRealtimeEvent: () => {}, + applySessionConfig: async () => {}, + getSessionsByNamespace: () => [], + getOnlineMachinesByNamespace: () => [machine()] + } as unknown as SyncEngine + return { store, engine } +} + +describe('Claude import across a resume', () => { + const stores: Store[] = [] + afterEach(() => { + for (const store of stores.splice(0)) store.close() + }) + + it('appends the resumed transcript when copied entries only changed replay metadata', async () => { + const { store, engine } = harness() + stores.push(store) + const first = await importLocalTranscript({ + store, engine, namespace: 'default', source: CLAUDE_LOCAL_SESSION_SOURCE, + transcript: transcriptOf(FIRST_SESSION, readEntries('0-say-lol-session.jsonl')), + machine: machine() + }) + expect(first).toMatchObject({ action: 'created', appended: 2 }) + + // The resume rotated the native id; the live machinery records it. + const session = store.sessions.getSessionByNamespace(first.hapiSessionId!, 'default')! + store.sessions.updateSessionMetadata( + session.id, + { ...(session.metadata as Record), claudeSessionId: RESUMED_SESSION, claudeSessionIdHistory: [FIRST_SESSION] }, + session.metadataVersion, + 'default' + ) + + const resumed = transcriptOf(RESUMED_SESSION, readEntries('1-continue-run-ls-tool.jsonl')) + const outcome = await importLocalTranscript({ + store, engine, namespace: 'default', source: CLAUDE_LOCAL_SESSION_SOURCE, + transcript: resumed, + machine: machine() + }) + expect(outcome).toMatchObject({ hapiSessionId: session.id, action: 'updated', appended: resumed.messages.length - 2 }) + }) + + it('still rejects a copied entry whose message content changed', async () => { + const { store, engine } = harness() + stores.push(store) + const first = await importLocalTranscript({ + store, engine, namespace: 'default', source: CLAUDE_LOCAL_SESSION_SOURCE, + transcript: transcriptOf(FIRST_SESSION, readEntries('0-say-lol-session.jsonl')), + machine: machine() + }) + const session = store.sessions.getSessionByNamespace(first.hapiSessionId!, 'default')! + store.sessions.updateSessionMetadata( + session.id, + { ...(session.metadata as Record), claudeSessionId: RESUMED_SESSION, claudeSessionIdHistory: [FIRST_SESSION] }, + session.metadataVersion, + 'default' + ) + + const edited = readEntries('1-continue-run-ls-tool.jsonl').map((entry) => { + if (entry.type !== 'assistant' || entry.uuid !== 'deae7c10-1e9a-466a-bbd0-1cd31b43d823') return entry + const message = entry.message as { content: Array> } + return { ...entry, message: { ...message, content: [{ type: 'text', text: 'edited reply' }] } } + }) + const outcome = await importLocalTranscript({ + store, engine, namespace: 'default', source: CLAUDE_LOCAL_SESSION_SOURCE, + transcript: transcriptOf(RESUMED_SESSION, edited), + machine: machine() + }) + expect(outcome.error?.code).toBe('transcript_diverged') + }) +}) diff --git a/hub/src/web/routes/localSessions/compare.ts b/hub/src/web/routes/localSessions/compare.ts new file mode 100644 index 00000000..d22a0dbb --- /dev/null +++ b/hub/src/web/routes/localSessions/compare.ts @@ -0,0 +1,31 @@ +/** + * Stable content serialization for import comparisons. Shared by the + * content-prefix matcher and flavor compare keys; both sides of a comparison + * must canonicalize identically. + */ + +export function stableSerializeContent(value: unknown): string { + if (value === null || value === undefined) { + return String(value) + } + if (typeof value === 'string') { + return JSON.stringify(value) + } + if (typeof value === 'number' || typeof value === 'boolean') { + return JSON.stringify(value) + } + if (Array.isArray(value)) { + return `[${value.map((item) => stableSerializeContent(item)).join(',')}]` + } + if (typeof value === 'object') { + const record = value as Record + const keys = Object.keys(record).sort() + return `{${keys.map((key) => `${JSON.stringify(key)}:${stableSerializeContent(record[key])}`).join(',')}}` + } + return JSON.stringify(value) +} + +/** Trailing-whitespace-insensitive user text normalization for comparisons. */ +export function normalizeComparableText(value: string): string { + return value.replace(/\s+$/u, '') +} \ No newline at end of file diff --git a/hub/src/web/routes/localSessions/createLocalSessionRoutes.test.ts b/hub/src/web/routes/localSessions/createLocalSessionRoutes.test.ts new file mode 100644 index 00000000..323ab278 --- /dev/null +++ b/hub/src/web/routes/localSessions/createLocalSessionRoutes.test.ts @@ -0,0 +1,344 @@ +import { afterEach, describe, expect, it } from 'bun:test' +import { Hono } from 'hono' +import type { LocalTranscript, LocalTranscriptSummary } from '@hapi/protocol/localTranscript' +import type { Machine, SyncEngine } from '../../../sync/syncEngine' +import type { WebAppEnv } from '../../middleware/auth' +import { Store } from '../../../store' +import { CLAUDE_LOCAL_SESSION_SOURCE, CODEX_LOCAL_SESSION_SOURCE, OPENCODE_LOCAL_SESSION_SOURCE, PI_LOCAL_SESSION_SOURCE } from './sources' +import { createLocalSessionRoutes } from './createLocalSessionRoutes' +import { fetchLocalTranscriptSummaries, fetchLocalTranscriptsByIds } from './fetchLocalTranscripts' + +function machine(id = 'm-1', capabilities: string[] = ['local-session-import']): Machine { + return { + id, + namespace: 'default', + seq: 1, + createdAt: 1, + updatedAt: 1, + active: true, + activeAt: 1, + metadata: { host: `${id}.local`, platform: 'darwin', happyCliVersion: 'test', capabilities }, + metadataVersion: 1, + runnerState: null, + runnerStateVersion: 1, + health: null + } +} + +function piSummary(): LocalTranscriptSummary { + return { + flavor: 'pi', + id: 'pi-1', + title: 'Pi session', + lastUserMessage: 'hello', + cwd: '/tmp/project', + file: '/tmp/pi-1.jsonl', + modifiedAt: 1, + messageCount: 3, + launch: { model: 'gemini-3.8-flash', effort: 'low' }, + extra: { model: 'gemini-3.8-flash', thinkingLevel: 'low', leafEntryId: 'e3' } + } +} + +function piTranscript(): LocalTranscript { + return { + ...piSummary(), + messages: [ + { + id: 'pi:pi-1:e1:user', + createdAt: 1, + content: { role: 'user', content: { type: 'text', text: 'hello' }, meta: { sentFrom: 'cli' } }, + anchor: 'e1', + historyPoint: 'e1' + } + ], + anchorOrder: ['e1'], + cursor: 'e1' + } +} + +function harness(overrides: { + summaries?: Array + transcripts?: Array + machineCapabilities?: string[] + rpcError?: string + namespace?: string + onlineMachines?: Machine[] + sources?: import('./sources').HubLocalSessionSource[] +} = {}) { + const store = new Store(':memory:') + const calls: Array<{ method: string; payload: unknown }> = [] + const appliedConfigs: Array> = [] + const summaries = overrides.summaries ?? [piSummary()] + const transcripts = overrides.transcripts ?? [piTranscript()] + const machineInstance = machine('m-1', overrides.machineCapabilities ?? ['local-session-import']) + const onlineMachines = overrides.onlineMachines ?? [machineInstance] + const engine = { + getOnlineMachinesByNamespace: () => onlineMachines, + getSessionsByNamespace: () => [], + listLocalSessionsForMachine: async (_machineId: string, payload: { flavor: string; sessionIds?: string[] | null }) => { + calls.push({ method: 'listLocalSessions', payload }) + if (overrides.rpcError) return { success: false, error: overrides.rpcError } + const wanted = payload.sessionIds ?? null + const source = wanted ? transcripts : summaries + return { + success: true, + sessions: wanted + ? source.filter((session) => 'messages' in session && (wanted as string[]).includes(session.id)) + : source + } + }, + recordSessionActivity: () => {}, + handleRealtimeEvent: () => {}, + applySessionConfig: async (_sessionId: string, config: Record) => { + appliedConfigs.push(config) + } + } as unknown as SyncEngine + const namespace = overrides.namespace ?? 'default' + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', namespace) + await next() + }) + app.route('/api', createLocalSessionRoutes({ + store, + getSyncEngine: () => engine, + sources: overrides.sources ?? [PI_LOCAL_SESSION_SOURCE, OPENCODE_LOCAL_SESSION_SOURCE, CODEX_LOCAL_SESSION_SOURCE] + })) + return { store, engine, app, calls, appliedConfigs } +} + +describe('generic local session routes', () => { + const stores: Store[] = [] + afterEach(() => { + for (const store of stores.splice(0)) store.close() + }) + + it('lists Pi summaries with flattened extra fields and no flavor/launch keys', async () => { + const { app } = harness() + const response = await app.request('/api/pi/sessions') + const body = await response.json() as { success: boolean; sessions: Array>; machineId?: string } + expect(body.success).toBe(true) + expect(body.machineId).toBe('m-1') + expect(body.sessions[0]).toMatchObject({ + id: 'pi-1', + model: 'gemini-3.8-flash', + thinkingLevel: 'low', + leafEntryId: 'e3', + messageCount: 3 + }) + expect(body.sessions[0]).not.toHaveProperty('flavor') + expect(body.sessions[0]).not.toHaveProperty('launch') + expect(body.sessions[0]).not.toHaveProperty('extra') + }) + + it('annotates anchored lists with hapiSessionId and import state', async () => { + const { app, store } = harness() + const created = store.sessions.getOrCreateSession('tag-1', { + flavor: 'pi', + piSessionId: 'pi-1', + machineId: 'm-1', + piImportState: { state: 'diverged' } + }, {}, 'default') + const response = await app.request('/api/pi/sessions') + const body = await response.json() as { sessions: Array> } + expect(body.sessions[0]).toMatchObject({ hapiSessionId: created.id, importState: 'diverged' }) + }) + + it('does not annotate contentPrefix lists with hapiSessionId', async () => { + const { app, store } = harness() + store.sessions.getOrCreateSession('tag-codex', { + flavor: 'codex', + codexSessionId: 'thread-1', + machineId: 'm-1' + }, {}, 'default') + const response = await app.request('/api/codex/sessions') + const body = await response.json() as { success: boolean; sessions: Array> } + expect(body.success).toBe(true) + expect(body.sessions[0]).not.toHaveProperty('hapiSessionId') + }) + + it('returns 503 when no machine is online', async () => { + const { app } = harness({ onlineMachines: [] }) + const response = await app.request('/api/pi/sessions') + expect(response.status).toBe(503) + }) + + it('returns 503 with the RPC error when the machine fetch fails', async () => { + const { app } = harness({ rpcError: 'runner exploded' }) + const response = await app.request('/api/pi/sessions') + const body = await response.json() as { success: boolean; error: string } + expect(response.status).toBe(503) + expect(body.error).toBe('runner exploded') + }) + + it('imports through the generic path and preserves the legacy result id key', async () => { + const { app, store, calls } = harness() + const response = await app.request('/api/pi/import-sessions', { + method: 'POST', + body: JSON.stringify({ sessionIds: ['pi-1'] }) + }) + const body = await response.json() as { success: boolean; results: Array> } + expect(body.success).toBe(true) + expect(body.results[0]).toMatchObject({ sessionId: 'pi-1', piSessionId: 'pi-1', action: 'created', appended: 1 }) + const session = store.sessions.getSessionsByNamespace('default') + .find((candidate) => (candidate.metadata as Record).flavor === 'pi') + expect(session).toBeDefined() + expect(calls[0]).toMatchObject({ method: 'listLocalSessions' }) + }) + + it('rejects empty selections and enforces the flavor import limit', async () => { + const { app } = harness() + const empty = await app.request('/api/pi/import-sessions', { method: 'POST', body: JSON.stringify({ sessionIds: [] }) }) + expect(empty.status).toBe(400) + const oversized = await app.request('/api/opencode/import-sessions', { + method: 'POST', + body: JSON.stringify({ sessionIds: Array.from({ length: 201 }, (_, index) => `ses-${index}`) }) + }) + expect(oversized.status).toBe(400) + // Pi carries the same 200 cap. + const piOversized = await app.request('/api/pi/import-sessions', { + method: 'POST', + body: JSON.stringify({ sessionIds: Array.from({ length: 201 }, (_, index) => `pi-${index}`) }) + }) + expect(piOversized.status).toBe(400) + }) + + it('marks a missing transcript as not_found', async () => { + const { app } = harness() + const response = await app.request('/api/pi/import-sessions', { method: 'POST', body: JSON.stringify({ sessionIds: ['missing'] }) }) + const body = await response.json() as { results: Array> } + expect(body.results[0]).toMatchObject({ sessionId: 'missing', error: { code: 'not_found' } }) + }) + + it('stops the codex batch on the first error', async () => { + const { app } = harness() + const response = await app.request('/api/codex/import-sessions', { + method: 'POST', + body: JSON.stringify({ sessionIds: ['missing-1', 'missing-2'] }) + }) + const body = await response.json() as { results: Array> } + expect(body.results).toHaveLength(1) + expect(body.results[0]).toMatchObject({ error: { code: 'not_found' } }) + }) + + it('applies the requested Claude model, effort and permission mode to the import', async () => { + const claude: LocalTranscript = { + flavor: 'claude', + id: 'claude-1', + title: 'Claude session', + lastUserMessage: 'hello', + cwd: '/tmp/project', + file: '/tmp/claude-1.jsonl', + modifiedAt: 1, + messages: [{ + id: 'claude:u1', + createdAt: 1, + content: { role: 'user', content: { type: 'text', text: 'hello' }, meta: { sentFrom: 'cli' } }, + anchor: 'u1' + }] + } + const { app, store, appliedConfigs } = harness({ sources: [CLAUDE_LOCAL_SESSION_SOURCE], summaries: [claude], transcripts: [claude] }) + stores.push(store) + const response = await app.request('/api/claude/import-sessions', { + method: 'POST', + body: JSON.stringify({ sessionIds: ['claude-1'], model: 'opus', effort: 'high', permissionMode: 'plan' }) + }) + const body = await response.json() as { results: Array> } + expect(body.results[0]).toMatchObject({ claudeSessionId: 'claude-1', action: 'created' }) + expect(appliedConfigs).toEqual([{ model: 'opus', effort: 'high', permissionMode: 'plan' }]) + }) + + it('enforces the claude import limit with a 400 before any RPC', async () => { + const { app, calls } = harness({ sources: [CLAUDE_LOCAL_SESSION_SOURCE] }) + const response = await app.request('/api/claude/import-sessions', { + method: 'POST', + body: JSON.stringify({ sessionIds: Array.from({ length: 201 }, (_, index) => `claude-${index}`) }) + }) + expect(response.status).toBe(400) + const body = await response.json() as { success: boolean; error?: string } + expect(body.success).toBe(false) + expect(body.error).toContain('200') + expect(calls).toHaveLength(0) + }) + +}) + +describe('fetchLocalTranscripts', () => { + const stores: Store[] = [] + afterEach(() => { + for (const store of stores.splice(0)) store.close() + }) + + it('uses the registry RPC when the machine advertises the capability', async () => { + const calls: Array<{ method: string; payload: unknown }> = [] + const engine = { + listLocalSessionsForMachine: async (_machineId: string, payload: unknown) => { + calls.push({ method: 'listLocalSessions', payload }) + return { success: true, sessions: [piSummary()] } + } + } as unknown as SyncEngine + const result = await fetchLocalTranscriptSummaries({ + source: PI_LOCAL_SESSION_SOURCE, + engine, + machine: machine() + }) + expect(result.success).toBe(true) + expect(calls[0]).toMatchObject({ method: 'listLocalSessions' }) + }) + + it('falls back to the legacy RPC and converts raw rows without the capability', async () => { + const store = new Store(':memory:') + stores.push(store) + const legacyCalls: unknown[] = [] + const engine = { + listPiSessionsForMachine: async () => { + legacyCalls.push('legacy') + return { success: true, sessions: [piSummary()] } + } + } as unknown as SyncEngine + const result = await fetchLocalTranscriptSummaries({ + source: PI_LOCAL_SESSION_SOURCE, + engine, + machine: machine('m-1', []) + }) + expect(legacyCalls).toEqual(['legacy']) + expect(result.success).toBe(true) + if (result.success) { + expect(result.sessions[0]).toMatchObject({ flavor: 'pi', id: 'pi-1' }) + } + }) + + it('fails closed when neither the capability nor a legacy fetch exists', async () => { + const store = new Store(':memory:') + stores.push(store) + const source = { ...OPENCODE_LOCAL_SESSION_SOURCE, legacy: undefined } + const result = await fetchLocalTranscriptSummaries({ + source, + engine: { listOpencodeSessionsForMachine: async () => ({ success: true, sessions: [] }) } as unknown as SyncEngine, + machine: machine('m-1', []) + }) + expect(result.success).toBe(false) + }) + + it('returns transcripts for requested ids', async () => { + const calls: Array<{ method: string; payload: unknown }> = [] + const engine = { + listLocalSessionsForMachine: async (_machineId: string, payload: unknown) => { + calls.push({ method: 'listLocalSessions', payload }) + return { success: true, sessions: [piTranscript()] } + } + } as unknown as SyncEngine + const result = await fetchLocalTranscriptsByIds({ + source: PI_LOCAL_SESSION_SOURCE, + engine, + machine: machine(), + sessionIds: ['pi-1'] + }) + expect(result.success).toBe(true) + expect(calls[0]).toMatchObject({ method: 'listLocalSessions', payload: { flavor: 'pi', sessionIds: ['pi-1'] } }) + if (result.success) { + expect('messages' in result.sessions[0]).toBe(true) + } + }) +}) \ No newline at end of file diff --git a/hub/src/web/routes/localSessions/createLocalSessionRoutes.ts b/hub/src/web/routes/localSessions/createLocalSessionRoutes.ts new file mode 100644 index 00000000..04f17784 --- /dev/null +++ b/hub/src/web/routes/localSessions/createLocalSessionRoutes.ts @@ -0,0 +1,237 @@ +import { Hono } from 'hono' +import type { PermissionMode } from '@hapi/protocol/types' +import { isPermissionModeAllowedForFlavor } from '@hapi/protocol/modes' +import { MAX_LOCAL_SESSION_IMPORTS, type LocalTranscript } from '@hapi/protocol/localTranscript' +import type { CodexCollaborationMode } from '@hapi/protocol/types' +import type { Machine, SyncEngine } from '../../../sync/syncEngine' +import type { Store, StoredSession } from '../../../store' +import type { WebAppEnv } from '../../middleware/auth' +import { fetchLocalTranscriptSummaries, fetchLocalTranscriptsByIds } from './fetchLocalTranscripts' +import { pickImportMachine } from './machinePick' +import { findImportedLocalSession, importLocalTranscript, type LocalImportLaunchConfig, type LocalImportOutcome } from './importLocalTranscript' +import type { HubLocalSessionSource } from './sources' + +/** + * Generic local-session import routes. One list + one import + * route pair per registered source; response items stay in the legacy shape + * (flavor `extra` fields flattened, legacy result id key preserved). + */ + +const IMPORT_STATES = ['importing', 'complete', 'failed', 'diverged'] as const + +function asRecord(value: unknown): Record | null { + return value !== null && typeof value === 'object' && !Array.isArray(value) + ? value as Record + : null +} + +function importedSessionsByNativeId(options: { + store: Store + namespace: string + source: HubLocalSessionSource + machineId: string +}): Map { + const { store, namespace, source, machineId } = options + const primaryKey = source.nativeIdKeys[0] + const imported = new Map() + for (const session of store.sessions.getSessionsByNamespace(namespace)) { + const metadata = asRecord(session.metadata) + if (metadata?.flavor !== source.flavor || metadata.machineId !== machineId) continue + const nativeId = metadata[primaryKey] + if (typeof nativeId !== 'string' || imported.has(nativeId)) continue + imported.set(nativeId, session) + } + return imported +} + +function toListItem(options: { + source: HubLocalSessionSource + summary: Record + imported: StoredSession | null +}): Record { + const { source, summary, imported } = options + const item: Record = { ...summary } + delete item.flavor + delete item.launch + const extra = asRecord(summary.extra) + if (extra) { + delete item.extra + Object.assign(item, extra) + } + if (source.match.strategy === 'anchored' && imported) { + item.hapiSessionId = imported.id + } + if (source.importStateKey && imported) { + const state = asRecord(asRecord(imported.metadata)?.[source.importStateKey])?.state + if (typeof state === 'string' && (IMPORT_STATES as readonly string[]).includes(state)) { + item.importState = state + } + } + return item +} + +function extractLaunchConfig(body: Record): { + launch: LocalImportLaunchConfig + validationError?: string +} { + const launch: LocalImportLaunchConfig = {} + const has = (key: string): boolean => Object.prototype.hasOwnProperty.call(body, key) + // Property presence matters: applySessionConfig only resets a persisted + // value when the key is present, so explicit nulls / 'default' must be + // preserved to clear stale selections on re-import. + if (has('model')) launch.model = typeof body.model === 'string' && body.model.trim() ? body.model.trim() : null + if (has('modelReasoningEffort')) { + launch.modelReasoningEffort = typeof body.modelReasoningEffort === 'string' && body.modelReasoningEffort.trim() + ? body.modelReasoningEffort.trim() + : null + } + if (has('effort')) launch.effort = typeof body.effort === 'string' && body.effort.trim() ? body.effort.trim() : null + if (has('permissionMode')) { + launch.permissionMode = typeof body.permissionMode === 'string' && body.permissionMode.trim() + ? body.permissionMode.trim() as PermissionMode + : null + } + if (has('serviceTier')) { + launch.serviceTier = body.serviceTier === null || body.serviceTier === undefined + ? null + : typeof body.serviceTier === 'string' ? body.serviceTier : undefined + if (launch.serviceTier !== null && launch.serviceTier !== 'fast' && launch.serviceTier !== 'standard') { + return { launch, validationError: 'Invalid serviceTier' } + } + } + if (has('collaborationMode')) { + launch.collaborationMode = typeof body.collaborationMode === 'string' + ? body.collaborationMode as CodexCollaborationMode + : null + if (launch.collaborationMode !== 'default' && launch.collaborationMode !== 'plan') { + return { launch, validationError: 'Invalid collaborationMode' } + } + } + return { launch } +} + +export function createLocalSessionRoutes(options: { + store: Store + getSyncEngine: () => SyncEngine | null + sources: HubLocalSessionSource[] +}): Hono { + const app = new Hono() + + for (const source of options.sources) { + const listPath = `/${source.routeBase}/sessions` + const importPath = `/${source.routeBase}/import-sessions` + + app.get(listPath, async (c) => { + const namespace = c.get('namespace') + const machine = pickImportMachine({ + engine: options.getSyncEngine(), + namespace, + requestedMachineId: c.req.query('machineId')?.trim() || null, + cwd: c.req.query('cwd')?.trim() || null + }) + if (!machine) { + return c.json({ success: false, error: `No online machine available for ${source.displayName} history import`, sessions: [] }, 503) + } + const result = await fetchLocalTranscriptSummaries({ + source, + engine: options.getSyncEngine()!, + machine, + cwd: c.req.query('cwd')?.trim() || null + }) + if (!result.success) { + return c.json({ success: false, error: result.error, sessions: [], machineId: machine.id }, 503) + } + const annotate = source.match.strategy === 'anchored' + const importedByNativeId = annotate + ? importedSessionsByNativeId({ store: options.store, namespace, source, machineId: machine.id }) + : new Map() + const sessions = result.sessions.map((summary) => toListItem({ + source, + summary: summary as unknown as Record, + imported: importedByNativeId.get(summary.id) ?? null + })) + return c.json({ success: true, sessions, machineId: machine.id }) + }) + + app.post(importPath, async (c) => { + const namespace = c.get('namespace') + const body = asRecord(await c.req.json().catch(() => null)) ?? {} + const rawSessionIds = Array.isArray(body.sessionIds) ? body.sessionIds : [] + const importLimit = source.importLimit + if (importLimit !== undefined && rawSessionIds.length > importLimit) { + return c.json({ success: false, error: `At most ${importLimit} ${source.displayName} sessions can be imported at once`, results: [] }, 400) + } + const sessionIds = rawSessionIds + .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 ${source.displayName} sessions selected`, results: [] }, 400) + } + const uniqueSessionIds = [...new Set(sessionIds)] + const cwd = typeof body.cwd === 'string' && body.cwd.trim() ? body.cwd.trim() : null + const engine = options.getSyncEngine() + const machine = pickImportMachine({ + engine, + namespace, + requestedMachineId: typeof body.machineId === 'string' ? body.machineId.trim() : null, + cwd + }) + if (!engine || !machine) { + return c.json({ success: false, error: `No online machine available for ${source.displayName} history import`, results: [] }, 503) + } + + const { launch, validationError } = extractLaunchConfig(body) + if (validationError) { + return c.json({ success: false, error: validationError, results: [] }, 400) + } + if (launch.permissionMode !== undefined + && launch.permissionMode !== null + && !isPermissionModeAllowedForFlavor(launch.permissionMode, source.flavor)) { + return c.json({ success: false, error: `Invalid permission mode for ${source.displayName} sessions`, results: [] }, 400) + } + + const fetched = await fetchLocalTranscriptsByIds({ + source, + engine, + machine, + cwd, + sessionIds: uniqueSessionIds + }) + if (!fetched.success) { + return c.json({ success: false, error: fetched.error, results: [], machineId: machine.id }, 503) + } + const transcripts = new Map(fetched.sessions + .filter((session): session is LocalTranscript => 'messages' in session) + .map((session) => [session.id, session])) + const resultIdKey = source.legacy?.resultIdKey ?? `${source.flavor}SessionId` + const requestMetadata = source.requestMetadata?.(body) + const results: Array> = [] + for (const sessionId of uniqueSessionIds) { + const transcript = transcripts.get(sessionId) + if (!transcript) { + results.push({ + sessionId, + [resultIdKey]: sessionId, + error: { code: 'not_found', message: `${source.displayName} session transcript not found` } + }) + if (source.batch === 'stopOnFirstError') break + continue + } + const outcome = await importLocalTranscript({ + store: options.store, + engine, + namespace, + source, + transcript, + machine, + request: { launch, requestMetadata } + }) + results.push({ ...outcome, [resultIdKey]: outcome.sessionId }) + if (source.batch === 'stopOnFirstError' && outcome.error) break + } + return c.json({ success: results.every((result) => !result.error), results, machineId: machine.id }) + }) + } + + return app +} \ No newline at end of file diff --git a/hub/src/web/routes/localSessions/fetchLocalTranscripts.ts b/hub/src/web/routes/localSessions/fetchLocalTranscripts.ts new file mode 100644 index 00000000..c5b689e6 --- /dev/null +++ b/hub/src/web/routes/localSessions/fetchLocalTranscripts.ts @@ -0,0 +1,92 @@ +import type { LocalTranscript, LocalTranscriptSummary } from '@hapi/protocol/localTranscript' +import type { Machine, SyncEngine } from '../../../sync/syncEngine' +import { machineSupportsLocalSessionImport, type HubLocalSessionSource } from './sources' + +export type FetchLocalSessionsResult = + | { success: true; sessions: Array; machineId: string } + | { success: false; error: string; machineId?: string } + +/** + * Fetch local-session lists for one source through the machine. + * + * - Runners advertising `local-session-import` answer the single + * ListLocalSessions RPC with normalized transcripts. + * - Older runners fall back to the source's legacy per-flavor RPC; raw rows + * are converted with the descriptor's toTranscript so both paths converge + * on the same normalized shape. + */ +export async function fetchLocalSessions(options: { + source: HubLocalSessionSource + engine: SyncEngine + machine: Machine + cwd?: string | null + /** Null -> summaries; otherwise transcripts for exactly these ids. */ + sessionIds?: string[] | null +}): Promise { + const { source, engine, machine } = options + if (machineSupportsLocalSessionImport(source, machine)) { + const result = await engine.listLocalSessionsForMachine(machine.id, { + flavor: source.flavor, + cwd: options.cwd ?? null, + sessionIds: options.sessionIds ?? null + }) + if (!result.success) { + return { success: false, error: result.error, machineId: machine.id } + } + return { success: true, sessions: [...result.sessions], machineId: machine.id } + } + + const legacy = source.legacy + if (!legacy) { + return { + success: false, + error: `${source.displayName} runner does not support local history import`, + machineId: machine.id + } + } + const result = await legacy.fetch({ + engine, + machineId: machine.id, + cwd: options.cwd ?? null, + sessionIds: options.sessionIds ?? null + }) + if (!result.success) { + return { success: false, error: result.error, machineId: machine.id } + } + return { + success: true, + sessions: result.sessions.map((raw) => legacy.toTranscript(raw)), + machineId: machine.id + } +} + +/** Summaries for import list routes. */ +export async function fetchLocalTranscriptSummaries(options: { + source: HubLocalSessionSource + engine: SyncEngine + machine: Machine + cwd?: string | null +}): Promise { + const result = await fetchLocalSessions({ ...options, sessionIds: null }) + if (!result.success) return result + return { + ...result, + sessions: result.sessions.filter((session): session is LocalTranscriptSummary => !('messages' in session)) + } +} + +/** Full transcripts for the ids an import is about to persist. */ +export async function fetchLocalTranscriptsByIds(options: { + source: HubLocalSessionSource + engine: SyncEngine + machine: Machine + cwd?: string | null + sessionIds: string[] +}): Promise { + const result = await fetchLocalSessions({ ...options, sessionIds: options.sessionIds }) + if (!result.success) return result + return { + ...result, + sessions: result.sessions.filter((session): session is LocalTranscript => 'messages' in session) + } +} \ No newline at end of file diff --git a/hub/src/web/routes/localSessions/importDedupBoundary.test.ts b/hub/src/web/routes/localSessions/importDedupBoundary.test.ts new file mode 100644 index 00000000..dc01574f --- /dev/null +++ b/hub/src/web/routes/localSessions/importDedupBoundary.test.ts @@ -0,0 +1,234 @@ +import { afterEach, describe, expect, it } from 'bun:test' +import type { LocalTranscript } from '@hapi/protocol/localTranscript' +import { RpcRegistry } from '../../../socket/rpcRegistry' +import { Store } from '../../../store' +import { SyncEngine, type Machine } from '../../../sync/syncEngine' +import { importLocalTranscript } from './importLocalTranscript' +import { CLAUDE_LOCAL_SESSION_SOURCE, CODEX_LOCAL_SESSION_SOURCE } from './sources' + +/** + * An explicit import only reuses a HAPI session recorded on the machine it + * read the transcript from. The agent-id dedup that runs on keepalives and + * resumes must keep the same machine boundary: it must not merge the + * imported row into another machine's session, or the other way round. + */ + +function machine(id: string): Machine { + return { + id, + namespace: 'default', + seq: 1, + createdAt: 1, + updatedAt: 1, + active: true, + activeAt: 1, + metadata: { host: `${id}.local`, platform: 'linux', happyCliVersion: 'test', workspaceRoots: ['/tmp/project'] }, + metadataVersion: 1, + runnerState: null, + runnerStateVersion: 1, + health: null + } +} + +function userContent(text: string) { + return { role: 'user', content: { type: 'text', text }, meta: { sentFrom: 'cli' } } as const +} + +function agentContent(message: string) { + return { + role: 'agent', + content: { type: 'codex', data: { type: 'message', message, id: 'agent-1' } }, + meta: { sentFrom: 'cli' } + } as const +} + +function codexTranscript(id: string, contents: unknown[]): LocalTranscript { + return { + flavor: 'codex', + id, + title: `Codex ${id}`, + lastUserMessage: 'run the tests', + cwd: '/tmp/project', + file: '/tmp/thread.jsonl', + modifiedAt: 1_000, + messages: contents.map((content, index) => ({ + id: `codex-desktop:${id}:${index}`, + content: content as LocalTranscript['messages'][number]['content'] + })) + } +} + +function claudeTranscript(id: string, texts: string[]): LocalTranscript { + return { + flavor: 'claude', + id, + title: `Claude ${id}`, + lastUserMessage: texts[0] ?? null, + cwd: '/tmp/project', + file: `/tmp/.claude/projects/p/${id}.jsonl`, + modifiedAt: 1_000, + messages: texts.map((text, index) => ({ + id: `claude:u${index}`, + createdAt: 1_100 + index, + content: userContent(text), + anchor: `u${index}` + })) + } +} + +function socketServerStub() { + // Keepalives replay queued messages to the session's CLI room. + const room = { emit() {} } + return { of: () => ({ to: () => room }) } +} + +async function settle(): Promise { + // Dedup runs as a fire-and-forget promise after session-updated. + for (let round = 0; round < 5; round += 1) { + await new Promise((resolve) => setTimeout(resolve, 5)) + } +} + +describe('explicit import vs agent-id dedup', () => { + const cleanups: Array<() => void> = [] + afterEach(() => { + for (const cleanup of cleanups.splice(0)) cleanup() + }) + + function setup() { + const store = new Store(':memory:') + const engine = new SyncEngine(store, socketServerStub() as never, new RpcRegistry(), { broadcast() {} } as never) + cleanups.push(() => { + engine.stop() + store.close() + }) + return { store, engine } + } + + function seedSession( + store: Store, + engine: SyncEngine, + tag: string, + metadata: Record, + texts: string[] + ): string { + const session = engine.getOrCreateSession(tag, { path: '/tmp/project', host: 'h', ...metadata }, null, 'default') + texts.forEach((text, index) => { + store.messages.addMessage(session.id, userContent(text), `${tag}-${index}`) + }) + return session.id + } + + it("keeps an import apart from another machine's live session for the same Codex thread", async () => { + const { store, engine } = setup() + const otherMachineSession = seedSession(store, engine, 'codex-other-machine', { + flavor: 'codex', + machineId: 'machine-b', + codexSessionId: 'thread-1' + }, ['hello from machine b', 'b continues']) + engine.handleSessionAlive({ sid: otherMachineSession, time: Date.now() }) + + const outcome = await importLocalTranscript({ + store, + engine, + namespace: 'default', + source: CODEX_LOCAL_SESSION_SOURCE, + transcript: codexTranscript('thread-1', [userContent('hello'), agentContent('hi')]), + machine: machine('machine-a') + }) + expect(outcome).toMatchObject({ action: 'created', appended: 2 }) + // The live session on machine B keeps sending keepalives; each one + // runs the agent-id dedup for that session. + engine.handleSessionAlive({ sid: otherMachineSession, time: Date.now() }) + await settle() + + expect(store.sessions.getSessionByNamespace(outcome.hapiSessionId!, 'default')).not.toBeNull() + expect(store.messages.getAllMessages(outcome.hapiSessionId!)).toHaveLength(2) + expect(store.messages.getAllMessages(otherMachineSession)).toHaveLength(2) + }) + + it("keeps another machine's session when the imported Codex session goes live", async () => { + const { store, engine } = setup() + const otherMachineSession = seedSession(store, engine, 'codex-other-machine', { + flavor: 'codex', + machineId: 'machine-b', + codexSessionId: 'thread-1' + }, ['hello from machine b', 'b continues']) + + const outcome = await importLocalTranscript({ + store, + engine, + namespace: 'default', + source: CODEX_LOCAL_SESSION_SOURCE, + transcript: codexTranscript('thread-1', [userContent('hello'), agentContent('hi')]), + machine: machine('machine-a') + }) + expect(outcome).toMatchObject({ action: 'created', appended: 2 }) + // Create-after-import resumes the imported session on machine A. + engine.handleSessionAlive({ sid: outcome.hapiSessionId!, time: Date.now() }) + await settle() + + expect(store.sessions.getSessionByNamespace(otherMachineSession, 'default')).not.toBeNull() + expect(store.messages.getAllMessages(otherMachineSession)).toHaveLength(2) + expect(store.messages.getAllMessages(outcome.hapiSessionId!)).toHaveLength(2) + }) + + it('creates a new session next to an archived one for the same Codex thread without touching it', async () => { + // Scope: the import step only. The import does not reuse an archived + // Codex session, so the thread then has two rows on one machine; once + // the new row goes live, the agent-id dedup merges the archived row + // into it exactly as it does for any same-machine duplicate. That + // dedup behavior is independent of local-session import. + const { store, engine } = setup() + const archived = seedSession(store, engine, 'codex-archived', { + flavor: 'codex', + machineId: 'machine-a', + codexSessionId: 'thread-1', + lifecycleState: 'archived' + }, ['archived turn']) + + const outcome = await importLocalTranscript({ + store, + engine, + namespace: 'default', + source: CODEX_LOCAL_SESSION_SOURCE, + transcript: codexTranscript('thread-1', [userContent('hello'), agentContent('hi')]), + machine: machine('machine-a') + }) + expect(outcome).toMatchObject({ action: 'created', appended: 2 }) + await settle() + + expect(store.sessions.getSessionByNamespace(outcome.hapiSessionId!, 'default')).not.toBeNull() + expect(store.messages.getAllMessages(outcome.hapiSessionId!)).toHaveLength(2) + const kept = store.sessions.getSessionByNamespace(archived, 'default') + expect(kept).not.toBeNull() + expect((kept!.metadata as Record).lifecycleState).toBe('archived') + expect(store.messages.getAllMessages(archived)).toHaveLength(1) + }) + + it("keeps another machine's Claude session with the same native id untouched", async () => { + const { store, engine } = setup() + const otherMachineSession = seedSession(store, engine, 'claude-other-machine', { + flavor: 'claude', + machineId: 'machine-b', + claudeSessionId: 'claude-1' + }, ['claude on machine b']) + engine.handleSessionAlive({ sid: otherMachineSession, time: Date.now() }) + + const outcome = await importLocalTranscript({ + store, + engine, + namespace: 'default', + source: CLAUDE_LOCAL_SESSION_SOURCE, + transcript: claudeTranscript('claude-1', ['hello', 'again']), + machine: machine('machine-a') + }) + expect(outcome).toMatchObject({ action: 'created', appended: 2 }) + engine.handleSessionAlive({ sid: otherMachineSession, time: Date.now() }) + await settle() + + expect(store.sessions.getSessionByNamespace(outcome.hapiSessionId!, 'default')).not.toBeNull() + expect(store.messages.getAllMessages(outcome.hapiSessionId!)).toHaveLength(2) + expect(store.messages.getAllMessages(otherMachineSession)).toHaveLength(1) + }) +}) diff --git a/hub/src/web/routes/localSessions/importLocalTranscript.test.ts b/hub/src/web/routes/localSessions/importLocalTranscript.test.ts new file mode 100644 index 00000000..57dc6d90 --- /dev/null +++ b/hub/src/web/routes/localSessions/importLocalTranscript.test.ts @@ -0,0 +1,536 @@ +import { afterEach, describe, expect, it } from 'bun:test' +import type { LocalTranscript } from '@hapi/protocol/localTranscript' +import type { Machine, SyncEngine } from '../../../sync/syncEngine' +import { Store } from '../../../store' +import { OPENCODE_LOCAL_SESSION_SOURCE, PI_LOCAL_SESSION_SOURCE, CODEX_LOCAL_SESSION_SOURCE, CLAUDE_LOCAL_SESSION_SOURCE } from './sources' +import { importLocalTranscript } from './importLocalTranscript' + +function machine(id = 'm-1'): Machine { + return { + id, + namespace: 'default', + seq: 1, + createdAt: 1, + updatedAt: 1, + active: true, + activeAt: 1, + metadata: { host: `${id}.local`, platform: 'darwin', happyCliVersion: 'test', workspaceRoots: ['/tmp/project'] }, + metadataVersion: 1, + runnerState: null, + runnerStateVersion: 1, + health: null + } +} + +function userContent(text: string) { + return { role: 'user', content: { type: 'text', text }, meta: { sentFrom: 'cli' } } as const +} + +function agentContent(id: string, message: string) { + return { + role: 'agent', + content: { type: 'codex', data: { type: 'message', message, id } }, + meta: { sentFrom: 'cli' } + } as const +} + +function opencodeTranscript(id: string, texts: string[]): LocalTranscript { + return { + flavor: 'opencode', + id, + title: `OpenCode ${id}`, + lastUserMessage: texts.at(-1) ?? null, + cwd: '/tmp/project', + file: '/tmp/opencode.db', + modifiedAt: 1_000, + messages: texts.map((text, index) => ({ + id: `opencode:${id}:msg-${index}:part-1`, + createdAt: 1_100 + index, + content: index % 2 === 0 ? userContent(text) : agentContent(`part-${index}`, text) + })) + } +} + +function codexTranscript(id: string, contents: unknown[]): LocalTranscript { + return { + flavor: 'codex', + id, + title: `Codex ${id}`, + lastUserMessage: 'run the tests', + cwd: '/tmp/project', + file: '/tmp/thread.jsonl', + modifiedAt: 1_000, + messages: contents.map((content, index) => ({ + id: `codex-desktop:${id}:${index}`, + content: content as LocalTranscript['messages'][number]['content'] + })) + } +} + +function harness() { + const store = new Store(':memory:') + const events: unknown[] = [] + const appliedConfigs: Array> = [] + const engine = { + recordSessionActivity: (sessionId: string, updatedAt: number) => { + store.sessions.touchSessionUpdatedAt(sessionId, updatedAt, 'default') + }, + handleRealtimeEvent: (event: unknown) => events.push(event), + applySessionConfig: async (_sessionId: string, config: Record) => { + appliedConfigs.push(config) + }, + getSessionsByNamespace: () => [], + getOnlineMachinesByNamespace: () => [machine()] + } as unknown as SyncEngine + return { store, engine, events, appliedConfigs } +} + +describe('generic local import', () => { + const stores: Store[] = [] + afterEach(() => { + for (const store of stores.splice(0)) store.close() + }) + + it('creates a session with lifecycle metadata and appends the transcript', async () => { + const { store, engine } = harness() + stores.push(store) + const outcome = await importLocalTranscript({ + store, + engine, + namespace: 'default', + source: OPENCODE_LOCAL_SESSION_SOURCE, + transcript: opencodeTranscript('ses-1', ['fix the bug', 'on it']), + machine: machine() + }) + expect(outcome).toMatchObject({ sessionId: 'ses-1', action: 'created', appended: 2 }) + const session = store.sessions.getSessionsByNamespace('default') + .find((candidate) => candidate.metadata && (candidate.metadata as Record).opencodeSessionId === 'ses-1') + expect(session).toBeDefined() + const metadata = session!.metadata as Record + expect(metadata).toMatchObject({ + flavor: 'opencode', + opencodeSessionId: 'ses-1', + machineId: 'm-1', + host: 'm-1.local', + os: 'darwin', + lifecycleState: 'archived', + archivedBy: 'opencode-import', + archiveReason: 'Imported from local OpenCode history' + }) + expect(store.messages.getAllMessages(session!.id)).toHaveLength(2) + }) + + it('is idempotent: the second import reports unchanged', async () => { + const { store, engine } = harness() + stores.push(store) + const transcript = opencodeTranscript('ses-1', ['fix the bug', 'on it']) + const first = await importLocalTranscript({ + store, engine, namespace: 'default', source: OPENCODE_LOCAL_SESSION_SOURCE, transcript, machine: machine() + }) + const second = await importLocalTranscript({ + store, engine, namespace: 'default', source: OPENCODE_LOCAL_SESSION_SOURCE, transcript, machine: machine() + }) + expect(first.action).toBe('created') + expect(second).toMatchObject({ action: 'unchanged', appended: 0 }) + }) + + it('appends only the delta when the transcript grows', async () => { + const { store, engine } = harness() + stores.push(store) + await importLocalTranscript({ + store, engine, namespace: 'default', source: OPENCODE_LOCAL_SESSION_SOURCE, + transcript: opencodeTranscript('ses-1', ['fix the bug']), machine: machine() + }) + const outcome = await importLocalTranscript({ + store, engine, namespace: 'default', source: OPENCODE_LOCAL_SESSION_SOURCE, + transcript: opencodeTranscript('ses-1', ['fix the bug', 'on it']), machine: machine() + }) + expect(outcome).toMatchObject({ action: 'updated', appended: 1 }) + }) + + it('rolls the whole import back when a message insert fails', async () => { + const { store, engine } = harness() + stores.push(store) + const transcript = opencodeTranscript('ses-1', ['one', 'two']) + const original = store.messages.addImportedMessage.bind(store.messages) + let calls = 0 + ;(store.messages as { addImportedMessage: typeof original }).addImportedMessage = ( + (sessionId: string, content: unknown, localId: string, createdAt: number) => { + calls += 1 + if (calls === 2) throw new Error('boom') + return original(sessionId, content, localId, createdAt) + } + ) as typeof original + const outcome = await importLocalTranscript({ + store, engine, namespace: 'default', source: OPENCODE_LOCAL_SESSION_SOURCE, transcript, machine: machine() + }) + expect(outcome.error).toMatchObject({ code: 'import_failed' }) + // The session creation rolled back with the failed insert. + expect(store.sessions.getSessionsByNamespace('default')).toHaveLength(0) + }) + + it('rolls a failing append back for an existing session', async () => { + const { store, engine } = harness() + stores.push(store) + await importLocalTranscript({ + store, engine, namespace: 'default', source: OPENCODE_LOCAL_SESSION_SOURCE, + transcript: opencodeTranscript('ses-1', ['one']), machine: machine() + }) + const session = store.sessions.getSessionsByNamespace('default')[0]! + const original = store.messages.addImportedMessage.bind(store.messages) + let calls = 0 + ;(store.messages as { addImportedMessage: typeof original }).addImportedMessage = ( + (sessionId: string, content: unknown, localId: string, createdAt: number) => { + calls += 1 + if (calls === 1) throw new Error('boom') + return original(sessionId, content, localId, createdAt) + } + ) as typeof original + const outcome = await importLocalTranscript({ + store, engine, namespace: 'default', source: OPENCODE_LOCAL_SESSION_SOURCE, + transcript: opencodeTranscript('ses-1', ['one', 'two']), machine: machine() + }) + expect(outcome.error).toMatchObject({ code: 'import_failed' }) + expect(store.messages.getAllMessages(session.id)).toHaveLength(1) + }) + + it('serializes concurrent imports of one contentPrefix thread', async () => { + const { store, engine } = harness() + stores.push(store) + const transcript = codexTranscript('thread-1', [userContent('hello'), agentContent('a', 'running')]) + const [first, second] = await Promise.all([ + importLocalTranscript({ store, engine, namespace: 'default', source: CODEX_LOCAL_SESSION_SOURCE, transcript, machine: machine() }), + importLocalTranscript({ store, engine, namespace: 'default', source: CODEX_LOCAL_SESSION_SOURCE, transcript, machine: machine() }) + ]) + expect(first).toMatchObject({ action: 'created', appended: 2 }) + expect(second).toMatchObject({ action: 'unchanged', appended: 0 }) + const codexSessions = store.sessions.getSessionsByNamespace('default') + .filter((candidate) => (candidate.metadata as Record).flavor === 'codex') + expect(codexSessions).toHaveLength(1) + expect(codexSessions[0]!.tag).toBeTruthy() + }) + + it('appends after a shorter duplicate run without reusing a stored Codex row id', async () => { + const { store, engine } = harness() + stores.push(store) + const duplicate = agentContent('a-1', 'same reply') + // A runner that keeps same-source duplicates stores [A, B, B, C] + // under ids 0..3; a runner that collapses them later converts the + // grown thread to [A, B, C, D], where D's position is 3 again. + const first = await importLocalTranscript({ + store, engine, namespace: 'default', source: CODEX_LOCAL_SESSION_SOURCE, + transcript: codexTranscript('thread-shrink', [userContent('A'), duplicate, duplicate, userContent('C')]), + machine: machine() + }) + expect(first).toMatchObject({ action: 'created', appended: 4 }) + + const outcome = await importLocalTranscript({ + store, engine, namespace: 'default', source: CODEX_LOCAL_SESSION_SOURCE, + transcript: codexTranscript('thread-shrink', [userContent('A'), duplicate, userContent('C'), userContent('D')]), + machine: machine() + }) + expect(outcome).toMatchObject({ hapiSessionId: first.hapiSessionId, action: 'updated', appended: 1 }) + const rows = store.messages.getAllMessages(first.hapiSessionId!) + expect(rows).toHaveLength(5) + expect(rows.at(-1)!.content).toMatchObject({ role: 'user', content: { text: 'D' } }) + expect(new Set(rows.map((row) => row.localId)).size).toBe(5) + }) + + it('stamps the codex lifecycle as imported and writes both id keys', async () => { + const { store, engine } = harness() + stores.push(store) + await importLocalTranscript({ + store, engine, namespace: 'default', source: CODEX_LOCAL_SESSION_SOURCE, + transcript: codexTranscript('thread-1', [userContent('hello')]), machine: machine() + }) + const metadata = store.sessions.getSessionsByNamespace('default')[0]!.metadata as Record + expect(metadata).toMatchObject({ + flavor: 'codex', + codexSessionId: 'thread-1', + codexSourceSessionId: 'thread-1', + lifecycleState: 'imported' + }) + expect(metadata.archivedBy).toBeUndefined() + }) + + it('applies the five request launch keys through session config', async () => { + const { store, engine, appliedConfigs } = harness() + stores.push(store) + const outcome = await importLocalTranscript({ + store, engine, namespace: 'default', source: OPENCODE_LOCAL_SESSION_SOURCE, + transcript: opencodeTranscript('ses-1', ['one']), + machine: machine(), + request: { + launch: { + model: 'gpt-5.6', + modelReasoningEffort: 'high', + permissionMode: 'default', + serviceTier: 'fast', + collaborationMode: 'plan' + } + } + }) + expect(outcome.error).toBeUndefined() + expect(appliedConfigs).toEqual([{ + model: 'gpt-5.6', + modelReasoningEffort: 'high', + permissionMode: 'default', + serviceTier: 'fast', + collaborationMode: 'plan' + }]) + }) + + it('ignores a permission mode that the flavor does not allow', async () => { + const { store, engine, appliedConfigs } = harness() + stores.push(store) + await importLocalTranscript({ + store, engine, namespace: 'default', source: OPENCODE_LOCAL_SESSION_SOURCE, + transcript: opencodeTranscript('ses-1', ['one']), + machine: machine(), + request: { launch: { permissionMode: 'read-only' as never } } + }) + expect(appliedConfigs).toEqual([]) + }) + + it('applies transcript launch hints (Pi model and thinking level)', async () => { + const { store, engine } = harness() + stores.push(store) + const piTranscript: LocalTranscript = { + flavor: 'pi', + id: 'pi-1', + title: 'Pi session', + cwd: '/tmp/project', + file: '/tmp/pi.jsonl', + modifiedAt: 1, + launch: { model: 'gemini-3.8-flash', effort: 'low' }, + messages: [ + { id: 'pi:pi-1:e1:user', createdAt: 1, content: userContent('hello'), anchor: 'e1', historyPoint: 'e1' } + ], + anchorOrder: ['e1'], + cursor: 'e1' + } + const outcome = await importLocalTranscript({ + store, engine, namespace: 'default', source: PI_LOCAL_SESSION_SOURCE, transcript: piTranscript, machine: machine() + }) + expect(outcome.action).toBe('created') + const session = store.sessions.getSessionsByNamespace('default')[0]! + expect(session.model).toBe('gemini-3.8-flash') + expect(session.effort).toBe('low') + const metadata = session.metadata as Record + expect(metadata.piHistoryLeafEntryId).toBe('e1') + expect(metadata.conversationHistoryEntryIds).toMatchObject({ 'pi:pi-1:e1:user': 'e1' }) + expect((metadata.piImportState as Record).state).toBe('complete') + }) + + it('marks a diverged import on the pi import state', async () => { + const { store, engine } = harness() + stores.push(store) + const base: LocalTranscript = { + flavor: 'pi', + id: 'pi-1', + title: 'Pi session', + cwd: '/tmp/project', + file: '/tmp/pi.jsonl', + modifiedAt: 1, + messages: [ + { id: 'pi:pi-1:e1:user', createdAt: 1, content: userContent('one'), anchor: 'e1', historyPoint: 'e1' } + ], + anchorOrder: ['e1'], + cursor: 'e1' + } + await importLocalTranscript({ store, engine, namespace: 'default', source: PI_LOCAL_SESSION_SOURCE, transcript: base, machine: machine() }) + const session = store.sessions.getSessionsByNamespace('default')[0]! + const changed: LocalTranscript = { + ...base, + messages: [{ + id: 'pi:pi-1:e1:user', + createdAt: 1, + content: userContent('rewritten'), + anchor: 'e1', + historyPoint: 'e1' + }], + cursor: 'e1' + } + const outcome = await importLocalTranscript({ + store, engine, namespace: 'default', source: PI_LOCAL_SESSION_SOURCE, transcript: changed, machine: machine() + }) + expect(outcome.error).toMatchObject({ code: 'transcript_diverged' }) + const metadata = store.sessions.getSessionByNamespace(session.id, 'default')!.metadata as Record + expect((metadata.piImportState as Record).state).toBe('diverged') + }) + + it('does not reapply transcript launch hints over a HAPI-side model change on re-import', async () => { + const { store, engine } = harness() + stores.push(store) + const piTranscript: LocalTranscript = { + flavor: 'pi', + id: 'pi-hints', + title: 'Pi hints session', + cwd: '/tmp/project', + file: '/tmp/pi-hints.jsonl', + modifiedAt: 1, + launch: { model: 'gemini-3.8-flash', effort: 'low' }, + messages: [ + { id: 'pi:pi-hints:e1:user', createdAt: 1, content: userContent('hello'), anchor: 'e1', historyPoint: 'e1' } + ], + anchorOrder: ['e1'], + cursor: 'e1' + } + await importLocalTranscript({ store, engine, namespace: 'default', source: PI_LOCAL_SESSION_SOURCE, transcript: piTranscript, machine: machine() }) + const session = store.sessions.getSessionsByNamespace('default')[0]! + store.sessions.setSessionModel(session.id, 'user-choice', 'default', { touchUpdatedAt: false }) + + const extended: LocalTranscript = { + ...piTranscript, + messages: [ + ...piTranscript.messages, + { id: 'pi:pi-hints:e2:user', createdAt: 2, content: userContent('a later turn'), anchor: 'e2', historyPoint: 'e2' } + ], + anchorOrder: ['e1', 'e2'], + cursor: 'e2' + } + const outcome = await importLocalTranscript({ store, engine, namespace: 'default', source: PI_LOCAL_SESSION_SOURCE, transcript: extended, machine: machine() }) + expect(outcome.action).toBe('updated') + const updated = store.sessions.getSessionByNamespace(session.id, 'default')! + expect(updated.model).toBe('user-choice') + }) + + it('stamps already_in_hapi as failed instead of diverged', async () => { + const { store, engine } = harness() + stores.push(store) + const created = store.sessions.getOrCreateSession('hapi-native-pi', { + machineId: 'm-1', + flavor: 'pi', + piSessionId: 'pi-native' + }, {}, 'default') + store.messages.addImportedMessage(created.id, userContent('typed in HAPI'), 'local-1', 1) + const transcript: LocalTranscript = { + flavor: 'pi', + id: 'pi-native', + title: 'Pi native session', + cwd: '/tmp/project', + file: '/tmp/pi-native.jsonl', + modifiedAt: 1, + messages: [ + { id: 'pi:pi-native:e1:user', createdAt: 1, content: userContent('hello from pi'), anchor: 'e1', historyPoint: 'e1' }, + { id: 'pi:pi-native:e2:user', createdAt: 2, content: userContent('a newer turn'), anchor: 'e2', historyPoint: 'e2' } + ], + anchorOrder: ['e1', 'e2'], + cursor: 'e2' + } + const outcome = await importLocalTranscript({ store, engine, namespace: 'default', source: PI_LOCAL_SESSION_SOURCE, transcript, machine: machine() }) + expect(outcome.error).toMatchObject({ code: 'already_in_hapi' }) + const metadata = store.sessions.getSessionByNamespace(created.id, 'default')!.metadata as Record + expect((metadata.piImportState as Record).state).toBe('failed') + }) + + it('preserves a custom HAPI session name on re-import', async () => { + const { store, engine } = harness() + stores.push(store) + const transcript = opencodeTranscript('ses-1', ['one']) + await importLocalTranscript({ store, engine, namespace: 'default', source: OPENCODE_LOCAL_SESSION_SOURCE, transcript, machine: machine() }) + const session = store.sessions.getSessionsByNamespace('default')[0]! + store.sessions.updateSessionMetadata(session.id, { ...(session.metadata as Record), name: 'My custom name' }, session.metadataVersion, 'default') + await importLocalTranscript({ + store, engine, namespace: 'default', source: OPENCODE_LOCAL_SESSION_SOURCE, + transcript: opencodeTranscript('ses-1', ['one', 'two']), machine: machine() + }) + const renamed = store.sessions.getSessionByNamespace(session.id, 'default')! + expect((renamed.metadata as Record).name).toBe('My custom name') + }) + + it('reports already_in_hapi for a HAPI-created session bound to the native id', async () => { + const { store, engine } = harness() + stores.push(store) + const created = store.sessions.getOrCreateSession('live-tag', { flavor: 'opencode', opencodeSessionId: 'ses-1', machineId: 'm-1' }, null, 'default') + store.messages.addImportedMessage(created.id, userContent('hello from hapi'), 'local-1', 1) + const outcome = await importLocalTranscript({ + store, engine, namespace: 'default', source: OPENCODE_LOCAL_SESSION_SOURCE, + transcript: opencodeTranscript('ses-1', ['native history']), machine: machine() + }) + expect(outcome).toMatchObject({ + hapiSessionId: created.id, + error: { code: 'already_in_hapi' } + }) + }) + + it('re-imports a rotated Claude transcript into the original session', async () => { + const { store, engine } = harness() + stores.push(store) + const claudeTranscript = (id: string, entries: Array<{ uuid: string; role: 'user' | 'agent'; text: string }>): LocalTranscript => ({ + flavor: 'claude', + id, + title: `Claude ${id}`, + lastUserMessage: entries.filter((entry) => entry.role === 'user').at(-1)?.text ?? null, + cwd: '/tmp/project', + file: `/tmp/.claude/projects/p/${id}.jsonl`, + modifiedAt: 1_000, + messages: entries.map((entry) => ({ + id: `claude:${entry.uuid}`, + createdAt: 1_100, + content: entry.role === 'user' + ? userContent(entry.text) + : { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', uuid: entry.uuid } }, + meta: { sentFrom: 'cli' } + }, + anchor: entry.uuid + })) + }) + const first = await importLocalTranscript({ + store, engine, namespace: 'default', source: CLAUDE_LOCAL_SESSION_SOURCE, + transcript: claudeTranscript('session-a', [ + { uuid: 'u1', role: 'user', text: 'hello' }, + { uuid: 'u2', role: 'agent', text: 'hi there' } + ]), + machine: machine() + }) + expect(first).toMatchObject({ action: 'created', appended: 2 }) + const session = store.sessions.getSessionsByNamespace('default')[0]! + const metadata = session.metadata as Record + expect(metadata.claudeSessionId).toBe('session-a') + // The import never writes the current id into the history array; the + // live rotation machinery owns it ("history never contains the + // current id"). + expect(metadata.claudeSessionIdHistory).toBeUndefined() + // Row ids carry the uuid only, so a rotated transcript still lines up. + expect(store.messages.getAllMessages(session.id).map((message) => message.localId)).toEqual(['claude:u1', 'claude:u2']) + + // The live machinery rotates the primary id and moves the old one + // into the history ("history never contains the current id"). + store.sessions.updateSessionMetadata( + session.id, + { ...metadata, claudeSessionId: 'session-b', claudeSessionIdHistory: ['session-a'] }, + session.metadataVersion, + 'default' + ) + + // Re-importing the pre-rotation file matches through the history + // alias and reports unchanged instead of creating a duplicate. + const again = await importLocalTranscript({ + store, engine, namespace: 'default', source: CLAUDE_LOCAL_SESSION_SOURCE, + transcript: claudeTranscript('session-a', [ + { uuid: 'u1', role: 'user', text: 'hello' }, + { uuid: 'u2', role: 'agent', text: 'hi there' } + ]), + machine: machine() + }) + expect(again).toMatchObject({ hapiSessionId: session.id, action: 'unchanged', appended: 0 }) + + // Resumed transcript: new session id, copied uuids, one new turn. + const resumed = await importLocalTranscript({ + store, engine, namespace: 'default', source: CLAUDE_LOCAL_SESSION_SOURCE, + transcript: claudeTranscript('session-b', [ + { uuid: 'u1', role: 'user', text: 'hello' }, + { uuid: 'u2', role: 'agent', text: 'hi there' }, + { uuid: 'u3', role: 'user', text: 'and one more' } + ]), + machine: machine() + }) + expect(resumed).toMatchObject({ hapiSessionId: session.id, action: 'updated', appended: 1 }) + expect(store.sessions.getSessionsByNamespace('default') + .filter((candidate) => (candidate.metadata as Record).flavor === 'claude')) + .toHaveLength(1) + }) +}) \ No newline at end of file diff --git a/hub/src/web/routes/localSessions/importLocalTranscript.ts b/hub/src/web/routes/localSessions/importLocalTranscript.ts new file mode 100644 index 00000000..e2cd6e88 --- /dev/null +++ b/hub/src/web/routes/localSessions/importLocalTranscript.ts @@ -0,0 +1,579 @@ +import { randomUUID } from 'node:crypto' +import { dirname } from 'node:path' +import type { CodexCollaborationMode, Metadata, PermissionMode } from '@hapi/protocol/types' +import { isPermissionModeAllowedForFlavor } from '@hapi/protocol/modes' +import type { LocalTranscript } from '@hapi/protocol/localTranscript' +import type { Machine, SyncEngine } from '../../../sync/syncEngine' +import type { Store, StoredMessage, StoredSession } from '../../../store' +import { ImportedMessageConflictError } from '../../../store/messages' +import { matchAnchored } from './matchAnchored' +import { collectImportCandidates, matchContentPrefix } from './matchContentPrefix' +import type { HubLocalSessionSource } from './sources' + +/** + * Generic local-session importer: owns target lookup, delta + * computation, atomic persistence, lifecycle metadata and launch config for + * every flavor. Sources only describe how to match; behavior differences + * between flavors come from the descriptor, never from flavor branches here. + */ + +export type LocalImportLaunchConfig = { + model?: string | null + modelReasoningEffort?: string | null + /** Claude effort level (Codex/OpenCode use modelReasoningEffort). */ + effort?: string | null + permissionMode?: PermissionMode | null + serviceTier?: string | null + collaborationMode?: CodexCollaborationMode | null +} + +export type LocalImportOutcome = { + sessionId: string + hapiSessionId?: string + action?: 'created' | 'updated' | 'unchanged' + appended?: number + error?: { code: string; message: string } +} + +export type LocalImportRequestContext = { + launch?: LocalImportLaunchConfig + /** Extra metadata from the request body (Codex preferredPermissionMode). */ + requestMetadata?: Record +} + +const importLocks = new Map>() + +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) ?? {} +} + +export function findImportedLocalSession(options: { + store: Store + namespace: string + machineId: string + source: HubLocalSessionSource + nativeId: string +}): StoredSession | null { + const { store, namespace, machineId, source, nativeId } = options + for (const session of store.sessions.getSessionsByNamespace(namespace)) { + const metadata = storedMetadata(session) + if (metadata.flavor !== source.flavor || metadata.machineId !== machineId) continue + // Any native id key matches: Claude's rotated session ids + // are found through the claudeSessionIdHistory array. + const matched = source.nativeIdKeys.some((key) => { + const value = metadata[key] + if (value === nativeId) return true + return Array.isArray(value) && value.includes(nativeId) + }) + if (matched) return session + } + return null +} + +function buildImportMetadata(options: { + source: HubLocalSessionSource + transcript: LocalTranscript + machine: Machine + existing: Record + requestMetadata?: Record + importState?: Record +}): Metadata { + const { source, transcript, machine, existing, requestMetadata, importState } = options + const summaryText = transcript.lastUserMessage ?? transcript.title + const metadata: Record = { + ...existing, + ...requestMetadata, + 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), + // Preserve a HAPI-side rename; only a fresh import names the session. + name: typeof existing.name === 'string' ? existing.name : transcript.title, + summary: summaryText + ? { text: summaryText, updatedAt: Date.now() } + : existing.summary, + machineId: machine.id, + flavor: source.flavor + } + // The primary native id follows the transcript only when the session does + // not carry one yet: Codex fork provenance renames the primary id while + // keeping the alias, and a re-sync must preserve it. A rotated Claude id + // stays with the live machinery for the same reason. The history array is + // owned by the live rotation machinery ("history never contains the + // current id"), so the import never writes into it. + source.nativeIdKeys.forEach((key) => { + if (key === 'claudeSessionIdHistory') return + if (typeof existing[key] !== 'string' && !Array.isArray(existing[key])) { + metadata[key] = transcript.id + } + }) + metadata.lifecycleState = typeof existing.lifecycleState === 'string' + ? existing.lifecycleState + : source.lifecycleOnCreate + metadata.lifecycleStateSince = typeof existing.lifecycleStateSince === 'number' + ? existing.lifecycleStateSince + : Date.now() + if (source.lifecycleOnCreate === 'archived') { + metadata.archivedBy = typeof existing.archivedBy === 'string' ? existing.archivedBy : `${source.flavor}-import` + metadata.archiveReason = typeof existing.archiveReason === 'string' + ? existing.archiveReason + : `Imported from local ${source.displayName} history` + } + if (importState && source.importStateKey) metadata[source.importStateKey] = importState + return metadata as Metadata +} + +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 local import metadata') + } + throw new Error('Local 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 buildImportState(source: HubLocalSessionSource, transcript: LocalTranscript, machineId: string, state: string, startedAt: number, error?: string): Record { + return { + state, + machineId, + [source.nativeIdKeys[0]]: transcript.id, + sourceFile: transcript.file, + startedAt, + updatedAt: Date.now(), + leafEntryId: transcript.cursor ?? null, + ...(error !== undefined ? { error } : {}) + } +} + +const POSITIONAL_ID = /^(.*:)(\d+)$/ + +/** + * Content-prefix row ids end in the transcript position (`:`). + * The matcher tolerates duplicate runs of a different length, so after a + * run shrinks the first new message can land on a position the stored + * session already used. Alignment positions and stored ids are separate + * things: a delta id at or below the highest stored index of its stem moves + * past it. Ordinary growth keeps its ids unchanged. + */ +function withFreshPositionalIds( + delta: LocalTranscript['messages'], + storedMessages: StoredMessage[] +): LocalTranscript['messages'] { + const highestByStem = new Map() + for (const message of storedMessages) { + const match = message.localId ? POSITIONAL_ID.exec(message.localId) : null + if (!match) continue + highestByStem.set(match[1]!, Math.max(highestByStem.get(match[1]!) ?? -1, Number(match[2]))) + } + return delta.map((message) => { + const match = POSITIONAL_ID.exec(message.id) + if (!match) return message + const stem = match[1]! + const index = Number(match[2]) + const highest = highestByStem.get(stem) ?? -1 + const next = index > highest ? index : highest + 1 + highestByStem.set(stem, next) + return next === index ? message : { ...message, id: `${stem}${next}` } + }) +} + +/** History locators for fork/rewind: persisted user messages with a native anchor. */ +function buildHistoryLocators(transcript: LocalTranscript, persistedLocalIds: Set): { + entryIds: Record + points: Record +} | null { + const entryIds: Record = {} + for (const message of transcript.messages) { + if (message.content.role !== 'user' || !message.historyPoint) continue + if (!persistedLocalIds.has(message.id)) continue + entryIds[message.id] = message.historyPoint + } + if (Object.keys(entryIds).length === 0) return null + const points: Record = {} + for (const localId of Object.keys(entryIds)) points[localId] = true + return { entryIds, points } +} + +export function runLocalImportSync(options: { + store: Store + engine: SyncEngine + namespace: string + source: HubLocalSessionSource + transcript: LocalTranscript + machine: Machine + request?: LocalImportRequestContext + existingSession?: StoredSession | null +}): LocalImportOutcome { + const { store, engine, namespace, source, transcript, machine } = options + const request = options.request ?? {} + const importPrefix = source.localIdPrefix ?? `${source.flavor}:${transcript.id}:` + const startedAt = Date.now() + const cursorKey = source.match.strategy === 'anchored' ? source.match.cursorKey : undefined + + const run = (): LocalImportOutcome => { + let target = options.existingSession === undefined + ? findImportedLocalSession({ store, namespace, machineId: machine.id, source, nativeId: transcript.id }) + : options.existingSession + let touchedSessionId = target?.id ?? null + let created = false + + // Mark an existing session as importing before touching messages so + // concurrent list reads observe the in-flight state. Best-effort: a + // session that vanished between capture and import fails closed with + // import_failed in the flow below instead of crashing here. + if (source.importStateKey && target) { + try { + updateMetadataWithRetry(store, target.id, namespace, (metadata) => buildImportMetadata({ + source, + transcript, + machine, + existing: metadata, + requestMetadata: request.requestMetadata, + importState: buildImportState(source, transcript, machine.id, 'importing', startedAt) + })) + } catch {} + } + + const finishErrorState = (outcome: LocalImportOutcome, state: 'diverged' | 'failed'): LocalImportOutcome => { + if (source.importStateKey && touchedSessionId) { + try { + updateMetadataWithRetry(store, touchedSessionId, namespace, (metadata) => buildImportMetadata({ + source, + transcript, + machine, + existing: metadata, + requestMetadata: request.requestMetadata, + importState: buildImportState(source, transcript, machine.id, state, startedAt, outcome.error?.message) + })) + engine.handleRealtimeEvent({ type: 'session-updated', sessionId: touchedSessionId! }) + } catch {} + } + return outcome + } + + try { + // Refresh the captured target row first: the caller's reference + // may be stale (active state flips between capture and import), + // and a vanished session fails closed with import_failed. + if (target) { + const current = store.sessions.getSessionByNamespace(target.id, namespace) + if (!current) throw new Error('Imported HAPI session disappeared') + target = current + } + + // --- match ---------------------------------------------------- + let delta: LocalTranscript['messages'] + if (source.match.strategy === 'contentPrefix') { + const candidates = collectImportCandidates(store, namespace, () => engine) + const result = matchContentPrefix({ + candidates, + transcript, + nativeIdKeys: [...source.nativeIdKeys], + sourceMachineId: machine.id, + compareKey: source.match.compareKey, + getAllMessages: (sessionId) => store.messages.getAllMessages(sessionId) + }) + if (result.status === 'session_active') { + return finishErrorState({ + sessionId: transcript.id, + error: { code: 'session_active', message: result.message } + }, 'failed') + } + if (result.targetSessionId) { + const resolved = store.sessions.getSessionByNamespace(result.targetSessionId, namespace) + if (!resolved) throw new Error('Imported HAPI session disappeared') + target = resolved + touchedSessionId = resolved.id + } else { + target = null + } + delta = withFreshPositionalIds( + transcript.messages.slice(result.deltaStartIndex), + target ? store.messages.getAllMessages(target.id) : [] + ) + } else { + const match = matchAnchored({ + storedMessages: target ? store.messages.getAllMessages(target.id) : [], + transcript, + importPrefix, + canonicalContent: source.match.canonicalContent, + cursor: target && cursorKey + ? (typeof storedMetadata(target)[cursorKey] === 'string' ? storedMetadata(target)[cursorKey] as string : null) + : null + }) + if (match.status !== 'ok') { + return finishErrorState({ + sessionId: transcript.id, + ...(target ? { hapiSessionId: target.id } : {}), + error: { code: match.status, message: match.message } + }, match.status === 'already_in_hapi' ? 'failed' : 'diverged') + } + delta = match.delta + } + + // R6: never interleave into a live session. + if (target?.active && delta.length > 0) { + return finishErrorState({ + sessionId: transcript.id, + hapiSessionId: target.id, + appended: 0, + error: { + code: 'session_active', + message: `The HAPI ${source.displayName} session is active; stop it before importing native history changes` + } + }, 'failed') + } + + // --- persist (atomic) ----------------------------------------- + const committed = store.runInTransaction(() => { + let stored: StoredSession + if (target) { + const current = store.sessions.getSessionByNamespace(target.id, namespace) + if (!current) throw new Error('Imported HAPI session disappeared') + stored = current + } else { + const requestModel = request.launch?.model + const transcriptModel = transcript.launch?.model + const createModel = requestModel !== undefined ? (requestModel ?? undefined) : (transcriptModel ?? undefined) + const requestEffort = request.launch?.modelReasoningEffort + const createEffort = requestEffort !== undefined ? (requestEffort ?? undefined) : (transcript.launch?.effort ?? undefined) + const metadata = buildImportMetadata({ + source, + transcript, + machine, + existing: {}, + requestMetadata: request.requestMetadata, + ...(source.importStateKey + ? { importState: buildImportState(source, transcript, machine.id, 'importing', startedAt) } + : {}) + }) + stored = store.sessions.getOrCreateSession( + source.match.strategy === 'contentPrefix' + ? randomUUID() + : `${source.flavor}-import:${machine.id}:${transcript.id}`, + metadata, + {}, + namespace, + createModel, + createEffort + ) + created = true + touchedSessionId = stored.id + } + + const importedAt = Date.now() + const appended: StoredMessage[] = [] + for (const message of delta) { + const result = store.messages.addImportedMessage( + stored.id, + message.content, + message.id, + message.createdAt ?? importedAt + ) + if (result.inserted) appended.push(result.message) + } + + const persistedLocalIds = new Set(store.messages.getAllMessages(stored.id) + .map((message) => message.localId) + .filter((localId): localId is string => Boolean(localId))) + updateMetadataWithRetry(store, stored.id, namespace, (metadata) => { + const next = buildImportMetadata({ + source, + transcript, + machine, + existing: metadata, + requestMetadata: request.requestMetadata, + ...(source.importStateKey + ? { importState: buildImportState(source, transcript, machine.id, 'complete', startedAt) } + : {}) + }) + // Merge, never replace: live HAPI turns keep their own + // local-id locators (fork/rewind controls) next to the + // imported native ones. + const locators = buildHistoryLocators(transcript, persistedLocalIds) + if (locators) { + next.conversationHistoryEntryIds = { + ...(asRecord(metadata.conversationHistoryEntryIds) as Record | null ?? {}), + ...locators.entryIds + } + next.conversationHistoryPoints = { + ...(asRecord(metadata.conversationHistoryPoints) as Record | null ?? {}), + ...locators.points + } + } + if (cursorKey && transcript.cursor) { + next[cursorKey] = transcript.cursor + } + return next + }) + + return { + hapiSessionId: stored.id, + appended, + action: created ? 'created' as const : appended.length > 0 ? 'updated' as const : 'unchanged' as const + } + }) + + // --- post-commit ---------------------------------------------- + const hapiSessionId = committed.hapiSessionId + // Transcript launch hints land on the session only when the import + // created it: getOrCreateSession already applied them at creation, + // and reapplying them on a re-import would clobber a HAPI-side + // model/effort change. Request keys win afterwards through + // applySessionConfig in the async envelope. + if (committed.action === 'created') { + if (transcript.launch?.model !== undefined) { + store.sessions.setSessionModel(hapiSessionId, transcript.launch.model, namespace, { touchUpdatedAt: false }) + } + if (transcript.launch?.effort !== undefined) { + store.sessions.setSessionEffort(hapiSessionId, transcript.launch.effort, namespace, { touchUpdatedAt: false }) + } + } + const outcome: LocalImportOutcome = { + sessionId: transcript.id, + hapiSessionId, + action: committed.action, + appended: committed.appended.length + } + + const activityAt = committed.appended.at(-1)?.createdAt ?? transcript.modifiedAt + engine.recordSessionActivity(hapiSessionId, activityAt) + emitImportedMessages(engine, hapiSessionId, committed.appended) + engine.handleRealtimeEvent({ type: 'session-updated', sessionId: hapiSessionId }) + return outcome + } catch (error) { + const message = error instanceof Error ? error.message : 'Failed to persist imported local history' + const code = error instanceof ImportedMessageConflictError ? 'transcript_diverged' : 'import_failed' + const surviving = touchedSessionId + ? store.sessions.getSessionByNamespace(touchedSessionId, namespace) + : null + if (source.importStateKey && surviving) { + try { + updateMetadataWithRetry(store, surviving.id, namespace, (metadata) => buildImportMetadata({ + source, + transcript, + machine, + existing: metadata, + requestMetadata: request.requestMetadata, + importState: buildImportState(source, transcript, machine.id, code === 'transcript_diverged' ? 'diverged' : 'failed', startedAt, message) + })) + engine.handleRealtimeEvent({ type: 'session-updated', sessionId: surviving.id }) + } catch {} + } + return { + sessionId: transcript.id, + ...(surviving ? { hapiSessionId: surviving.id } : {}), + error: { code, message } + } + } + } + + return run() +} + +/** Apply the request launch keys through applySessionConfig after commit. */ +async function applyRequestLaunchConfig(options: { + engine: SyncEngine + source: HubLocalSessionSource + request?: LocalImportRequestContext +}, outcome: LocalImportOutcome): Promise { + if (outcome.error || outcome.hapiSessionId === undefined) return outcome + const launch = options.request?.launch ?? {} + const config: Parameters[1] = {} + if (Object.prototype.hasOwnProperty.call(launch, 'model')) config.model = launch.model + if (Object.prototype.hasOwnProperty.call(launch, 'modelReasoningEffort')) config.modelReasoningEffort = launch.modelReasoningEffort + if (Object.prototype.hasOwnProperty.call(launch, 'effort')) config.effort = launch.effort + if (Object.prototype.hasOwnProperty.call(launch, 'permissionMode')) { + const mode = (launch.permissionMode ?? 'default') as PermissionMode + // Unknown modes fail the flavor check and are ignored here; the + // route validates user input before reaching the importer. + if (isPermissionModeAllowedForFlavor(mode, options.source.flavor)) { + config.permissionMode = mode + } + } + if (Object.prototype.hasOwnProperty.call(launch, 'serviceTier')) config.serviceTier = launch.serviceTier + if (Object.prototype.hasOwnProperty.call(launch, 'collaborationMode') && launch.collaborationMode !== null) { + config.collaborationMode = launch.collaborationMode + } + if (Object.keys(config).length === 0) return outcome + try { + await options.engine.applySessionConfig(outcome.hapiSessionId, config) + } catch (error) { + return { + ...outcome, + error: { + code: 'config_failed', + message: error instanceof Error ? error.message : 'Failed to apply launch config' + } + } + } + return outcome +} + +/** + * Async envelope around the sync import core: serializes imports per + * namespace:machine:flavor:native id (the second concurrent caller runs after + * the first and observes an empty delta), then applies the request launch + * config through applySessionConfig. + */ +export async function importLocalTranscript(options: { + store: Store + engine: SyncEngine + namespace: string + source: HubLocalSessionSource + transcript: LocalTranscript + machine: Machine + request?: LocalImportRequestContext + existingSession?: StoredSession | null +}): Promise { + const lockKey = `${options.namespace}:${options.machine.id}:${options.source.flavor}:${options.transcript.id}` + const prior = importLocks.get(lockKey) ?? Promise.resolve() + let release!: () => void + const gate = new Promise((resolve) => { release = resolve }) + const current = prior.catch(() => {}).then(() => gate) + importLocks.set(lockKey, current) + await prior.catch(() => {}) + try { + const outcome = runLocalImportSync(options) + return await applyRequestLaunchConfig(options, outcome) + } finally { + release() + if (importLocks.get(lockKey) === current) importLocks.delete(lockKey) + } +} \ No newline at end of file diff --git a/hub/src/web/routes/localSessions/machinePick.test.ts b/hub/src/web/routes/localSessions/machinePick.test.ts new file mode 100644 index 00000000..e68ee763 --- /dev/null +++ b/hub/src/web/routes/localSessions/machinePick.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from 'bun:test' +import type { Machine, SyncEngine } from '../../../sync/syncEngine' +import { pickImportMachine } from './machinePick' + +function machine(id: string, workspaceRoots: string[] = []): Machine { + return { + id, + namespace: 'default', + seq: 1, + createdAt: 1, + updatedAt: 1, + active: true, + activeAt: 1, + metadata: { host: `${id}.local`, platform: 'darwin', happyCliVersion: 'test', workspaceRoots }, + metadataVersion: 1, + runnerState: null, + runnerStateVersion: 1, + health: null + } +} + +function engine(machines: Machine[]): SyncEngine { + return { + getOnlineMachinesByNamespace: () => machines + } as unknown as SyncEngine +} + +describe('import machine selection', () => { + const first = machine('m-1', ['/workspace/a']) + const second = machine('m-2', ['/workspace/b']) + + it('prefers the requested machine when it is online', () => { + expect(pickImportMachine({ engine: engine([first, second]), namespace: 'default', requestedMachineId: 'm-2' })?.id).toBe('m-2') + expect(pickImportMachine({ engine: engine([first]), namespace: 'default', requestedMachineId: 'missing' })).toBeNull() + }) + + it('falls back to the unique online machine owning the cwd', () => { + expect(pickImportMachine({ engine: engine([first, second]), namespace: 'default', cwd: '/workspace/b/sub' })?.id).toBe('m-2') + }) + + it('falls back to the first online machine when the cwd is ambiguous or absent', () => { + const sharedOwnerA = machine('m-1', ['/shared']) + const sharedOwnerB = machine('m-2', ['/shared', '/workspace/b']) + expect(pickImportMachine({ engine: engine([sharedOwnerA, sharedOwnerB]), namespace: 'default', cwd: '/shared/x' })?.id).toBe('m-1') + expect(pickImportMachine({ engine: engine([sharedOwnerA, sharedOwnerB]), namespace: 'default' })?.id).toBe('m-1') + }) + + it('returns null without an engine', () => { + expect(pickImportMachine({ engine: null, namespace: 'default' })).toBeNull() + }) +}) \ No newline at end of file diff --git a/hub/src/web/routes/localSessions/machinePick.ts b/hub/src/web/routes/localSessions/machinePick.ts new file mode 100644 index 00000000..a1e4eee4 --- /dev/null +++ b/hub/src/web/routes/localSessions/machinePick.ts @@ -0,0 +1,61 @@ +import type { Machine, SyncEngine } from '../../../sync/syncEngine' + +/** + * Machine selection for local-session imports: requested machine + * (must be online) -> the unique online machine owning the cwd -> first + * online machine. + */ + +function normalizeComparablePath(pathValue: string, options?: { caseInsensitive?: boolean }): string { + let normalized = pathValue.trim().replace(/\\/g, '/').replace(/\/+/g, '/') + if (normalized.length > 1) { + normalized = normalized.replace(/\/+$/, '') + } + return options?.caseInsensitive ? normalized.toLowerCase() : normalized +} + +function shouldCompareCaseInsensitive(...pathValues: string[]): boolean { + return pathValues.some((pathValue) => /^[a-z]:[\\/]/i.test(pathValue) || pathValue.includes('\\')) +} + +function machineOwnsCwd(machine: Machine, cwd: string): boolean { + const workspaceRoots = machine.metadata?.workspaceRoots ?? [] + if (workspaceRoots.length === 0 || !cwd.trim()) return false + const caseInsensitive = shouldCompareCaseInsensitive(cwd, ...workspaceRoots) + const path = normalizeComparablePath(cwd, { caseInsensitive }) + if (!path) return false + return workspaceRoots.some((root) => { + const normalizedRoot = normalizeComparablePath(root, { caseInsensitive }) + if (!normalizedRoot) return false + if (path === normalizedRoot) return true + if (normalizedRoot === '/') return path.startsWith('/') + return path.startsWith(`${normalizedRoot}/`) + }) +} + +export function pickImportMachine(options: { + engine: SyncEngine | null + namespace: string + requestedMachineId?: string | null + cwd?: string | null +}): Machine | null { + const { engine, namespace } = options + if (!engine) return null + const online = engine.getOnlineMachinesByNamespace(namespace) + if (options.requestedMachineId) { + const requested = online.find((machine) => machine.id === options.requestedMachineId) + if (!requested) return null + return requested + } + if (options.cwd) { + const requestedCwd = options.cwd.trim() + if (requestedCwd) { + const owners = online.filter((candidate) => machineOwnsCwd(candidate, requestedCwd)) + const ownerIds = Array.from(new Set(owners.map((candidate) => candidate.id))) + if (ownerIds.length === 1) { + return owners.find((candidate) => candidate.id === ownerIds[0]) ?? null + } + } + } + return online[0] ?? null +} \ No newline at end of file diff --git a/hub/src/web/routes/localSessions/matchAnchored.test.ts b/hub/src/web/routes/localSessions/matchAnchored.test.ts new file mode 100644 index 00000000..47d6e624 --- /dev/null +++ b/hub/src/web/routes/localSessions/matchAnchored.test.ts @@ -0,0 +1,196 @@ +import { describe, expect, it } from 'bun:test' +import type { LocalTranscript, LocalTranscriptMessage } from '@hapi/protocol/localTranscript' +import type { StoredMessage } from '../../../store' +import { matchAnchored } from './matchAnchored' + +const PREFIX = 'opencode:ses-1:' + +function userContent(text: string) { + return { role: 'user', content: { type: 'text', text }, meta: { sentFrom: 'cli' } } as const +} + +function transcriptMessage(id: string, text: string, anchor?: string): LocalTranscriptMessage { + return { + id, + createdAt: 1, + content: userContent(text), + ...(anchor !== undefined ? { anchor } : {}) + } +} + +function storedMessage(localId: string, text: string): StoredMessage { + return { + id: `stored-${localId}`, + sessionId: 'hapi-1', + content: userContent(text), + createdAt: 1, + seq: 1, + localId, + invokedAt: null, + scheduledAt: null + } +} + +function transcript(messages: LocalTranscriptMessage[], anchorOrder?: string[], cursor?: string | null): LocalTranscript { + return { + flavor: 'opencode', + id: 'ses-1', + title: 't', + file: '/tmp/db', + modifiedAt: 1, + messages, + ...(anchorOrder !== undefined ? { anchorOrder } : {}), + ...(cursor !== undefined ? { cursor } : {}) + } +} + +describe('anchored match: R1 order and content', () => { + it('appends only the delta for an extended transcript', () => { + const stored = [storedMessage(`${PREFIX}a`, 'one')] + const result = matchAnchored({ + storedMessages: stored, + transcript: transcript([transcriptMessage(`${PREFIX}a`, 'one'), transcriptMessage(`${PREFIX}b`, 'two')]), + importPrefix: PREFIX, + cursor: null + }) + expect(result).toEqual({ status: 'ok', delta: [transcriptMessage(`${PREFIX}b`, 'two')] }) + }) + + it('rejects a changed imported entry', () => { + const stored = [storedMessage(`${PREFIX}a`, 'one')] + const result = matchAnchored({ + storedMessages: stored, + transcript: transcript([transcriptMessage(`${PREFIX}a`, 'one changed')]), + importPrefix: PREFIX, + cursor: null + }) + expect(result.status).toBe('transcript_diverged') + }) + + it('rejects a reordered transcript', () => { + const stored = [storedMessage(`${PREFIX}a`, 'one'), storedMessage(`${PREFIX}b`, 'two')] + const result = matchAnchored({ + storedMessages: stored, + transcript: transcript([transcriptMessage(`${PREFIX}b`, 'two'), transcriptMessage(`${PREFIX}a`, 'one')]), + importPrefix: PREFIX, + cursor: null + }) + expect(result.status).toBe('transcript_diverged') + }) + + it('rejects a dropped imported entry', () => { + const stored = [storedMessage(`${PREFIX}a`, 'one'), storedMessage(`${PREFIX}b`, 'two')] + const result = matchAnchored({ + storedMessages: stored, + transcript: transcript([transcriptMessage(`${PREFIX}a`, 'one')]), + importPrefix: PREFIX, + cursor: null + }) + expect(result.status).toBe('transcript_diverged') + }) +}) + +describe('anchored match: R2-R4 with a cursor', () => { + const anchorOrder = ['a', 'b', 'c', 'd'] + + function cursorTranscript(messages: LocalTranscriptMessage[], cursor: string | null): LocalTranscript { + return { + flavor: 'pi', + id: 'ses-1', + title: 't', + file: '/tmp/pi.jsonl', + modifiedAt: 1, + messages, + anchorOrder, + cursor + } + } + + it('fails when the stored cursor left the active branch (R2)', () => { + const result = matchAnchored({ + storedMessages: [storedMessage('pi:ses-1:a:user', 'one')], + transcript: cursorTranscript([transcriptMessage('pi:ses-1:a:user', 'one', 'a')], 'z'), + importPrefix: 'pi:ses-1:', + cursor: 'z' + }) + expect(result.status).toBe('transcript_diverged') + }) + + it('appends entries after the cursor (R3) and tolerates gaps before the anchor (R4)', () => { + const result = matchAnchored({ + storedMessages: [storedMessage('pi:ses-1:a:user', 'one')], + transcript: cursorTranscript([ + transcriptMessage('pi:ses-1:a:user', 'one', 'a'), + transcriptMessage('pi:ses-1:c:user', 'three', 'c') + ], 'b'), + importPrefix: 'pi:ses-1:', + cursor: 'b' + }) + expect(result).toMatchObject({ status: 'ok' }) + if (result.status === 'ok') { + expect(result.delta.map((message) => message.anchor)).toEqual(['c']) + } + }) + + it('uses the later of the last import and the cursor as the anchor (R3)', () => { + const result = matchAnchored({ + storedMessages: [ + storedMessage('pi:ses-1:a:user', 'one'), + storedMessage('pi:ses-1:c:user', 'three') + ], + transcript: cursorTranscript([ + transcriptMessage('pi:ses-1:a:user', 'one', 'a'), + transcriptMessage('pi:ses-1:c:user', 'three', 'c') + ], 'b'), + importPrefix: 'pi:ses-1:', + cursor: 'b' + }) + expect(result).toMatchObject({ status: 'ok', delta: [] }) + }) +}) + +describe('anchored match: R4/R5 without a cursor', () => { + it('rejects entries inserted ahead of the imported boundary', () => { + const stored = [storedMessage(`${PREFIX}b`, 'two')] + const result = matchAnchored({ + storedMessages: stored, + transcript: transcript([transcriptMessage(`${PREFIX}a`, 'one'), transcriptMessage(`${PREFIX}b`, 'two')]), + importPrefix: PREFIX, + cursor: null + }) + expect(result.status).toBe('transcript_diverged') + }) + + it('reports already_in_hapi for a HAPI-created session with a delta (R5)', () => { + const stored = [storedMessage('local-1', 'hello from hapi')] + const result = matchAnchored({ + storedMessages: stored, + transcript: transcript([transcriptMessage(`${PREFIX}a`, 'one')]), + importPrefix: PREFIX, + cursor: null + }) + expect(result.status).toBe('already_in_hapi') + }) + + it('keeps a fully imported transcript unchanged', () => { + const stored = [storedMessage(`${PREFIX}a`, 'one')] + const result = matchAnchored({ + storedMessages: stored, + transcript: transcript([transcriptMessage(`${PREFIX}a`, 'one')]), + importPrefix: PREFIX, + cursor: null + }) + expect(result).toEqual({ status: 'ok', delta: [] }) + }) + + it('ignores HAPI-side extras when the transcript has no delta', () => { + const stored = [storedMessage(`${PREFIX}a`, 'one'), storedMessage('local-1', 'hapi turn')] + const result = matchAnchored({ + storedMessages: stored, + transcript: transcript([transcriptMessage(`${PREFIX}a`, 'one')]), + importPrefix: PREFIX, + cursor: null + }) + expect(result).toEqual({ status: 'ok', delta: [] }) + }) +}) \ No newline at end of file diff --git a/hub/src/web/routes/localSessions/matchAnchored.ts b/hub/src/web/routes/localSessions/matchAnchored.ts new file mode 100644 index 00000000..449a0d1c --- /dev/null +++ b/hub/src/web/routes/localSessions/matchAnchored.ts @@ -0,0 +1,126 @@ +import { isDeepStrictEqual } from 'node:util' +import type { LocalTranscript, LocalTranscriptMessage } from '@hapi/protocol/localTranscript' +import type { StoredMessage } from '../../../store' +import { truncateOversizedMessageContent } from '../../../store/contentCodec' + +/** + * Anchored target matching: the imported prefix P of the HAPI + * session must still line up with the source transcript S; the delta is what + * follows the anchor. Reproduces OpenCode's strict prefix check and Pi's + * append-after-leaf behavior. + * + * R1 imported messages must appear in S in order with equal content + * R2 a stored cursor must still be on the transcript's anchor order + * R3 anchor = max(last imported position, cursor position) + * R4 gaps before the anchor are only allowed with a cursor + * R5 no imports and no cursor but stored messages -> already_in_hapi + * R6 active session with a delta -> session_active (enforced by the importer) + */ + +export type AnchoredMatchResult = + | { status: 'ok'; delta: LocalTranscriptMessage[] } + | { status: 'transcript_diverged'; message: string } + | { status: 'already_in_hapi'; message: string } + +export function matchAnchored(options: { + storedMessages: StoredMessage[] + transcript: LocalTranscript + importPrefix: string + cursor: string | null + /** Source-specific compare form (defaults to the full content). */ + canonicalContent?: (content: unknown) => unknown +}): AnchoredMatchResult { + const { storedMessages, transcript, importPrefix, cursor } = options + const canonical = options.canonicalContent ?? ((content: unknown) => content) + const sameContent = (source: unknown, stored: unknown): boolean => + isDeepStrictEqual(canonical(source), canonical(stored)) + const sourceMessages = transcript.messages + const sourceIndexById = new Map(sourceMessages.map((message, index) => [message.id, index])) + const sourceContentById = new Map(sourceMessages.map((message) => [ + message.id, + truncateOversizedMessageContent(message.content) + ])) + const imported = storedMessages.filter((message) => message.localId?.startsWith(importPrefix)) + const cursorValue = cursor + if (cursorValue !== null && transcript.anchorOrder !== undefined) { + const anchorOrder = transcript.anchorOrder + if (!anchorOrder.includes(cursorValue)) { + return { + status: 'transcript_diverged', + message: 'The local transcript no longer contains the previously imported cursor position' + } + } + // R1: stored imports stay an in-order subsequence of the transcript + // with unchanged content. + let priorSourceIndex = -1 + for (const message of imported) { + const sourceIndex = sourceIndexById.get(message.localId!) + if (sourceIndex === undefined || sourceIndex <= priorSourceIndex) { + return { + status: 'transcript_diverged', + message: 'Local transcript no longer extends the previously imported history' + } + } + priorSourceIndex = sourceIndex + } + const changed = imported.find((message) => !sameContent(sourceContentById.get(message.localId!), message.content)) + if (changed?.localId) { + return { + status: 'transcript_diverged', + message: `Local transcript changed imported entry ${changed.localId}` + } + } + // R3: anchor is the later of the last import and the cursor. + const positionByAnchor = new Map(anchorOrder.map((anchor, index) => [anchor, index])) + const lastImported = imported.at(-1) + const lastImportedAnchor = lastImported?.localId != null + ? sourceMessages[sourceIndexById.get(lastImported.localId)!]?.anchor + : undefined + const lastImportedPosition = lastImportedAnchor !== undefined + ? positionByAnchor.get(lastImportedAnchor) + : undefined + const cursorPosition = positionByAnchor.get(cursorValue) + const anchorPosition = Math.max(lastImportedPosition ?? -1, cursorPosition ?? -1) + const deltaAnchors = new Set(anchorOrder.slice(anchorPosition + 1)) + // Delta: every transcript entry after the anchor (already-imported + // localIds are deduped again on insert). + const delta = sourceMessages.filter((message) => message.anchor !== undefined && deltaAnchors.has(message.anchor)) + return { status: 'ok', delta } + } + + // No cursor: the imported prefix must align exactly with the head of the + // transcript (OpenCode's strict prefix rule; Pi without a stored leaf). + for (let index = 0; index < imported.length; index += 1) { + const stored = imported[index]! + const source = sourceMessages[index] + if (!source || source.id !== stored.localId) { + return { + status: 'transcript_diverged', + message: `Local transcript changed or dropped imported entry ${stored.localId}` + } + } + if (!sameContent(sourceContentById.get(source.id), stored.content)) { + return { + status: 'transcript_diverged', + message: `Local transcript changed or dropped imported entry ${stored.localId}` + } + } + } + const delta = sourceMessages.slice(imported.length) + const storedExtras = storedMessages.length - imported.length + if (storedExtras > 0 && delta.length > 0) { + // R4/R5: without a cursor the HAPI side must not have messages outside + // the imported prefix when the source still advances. + if (imported.length === 0) { + return { + status: 'already_in_hapi', + message: 'This HAPI session was not imported from the local history; importing would duplicate its messages' + } + } + return { + status: 'transcript_diverged', + message: 'The HAPI session continued past the imported history; re-importing would duplicate or reorder messages' + } + } + return { status: 'ok', delta } +} \ No newline at end of file diff --git a/hub/src/web/routes/localSessions/matchContentPrefix.test.ts b/hub/src/web/routes/localSessions/matchContentPrefix.test.ts new file mode 100644 index 00000000..54ce5fd2 --- /dev/null +++ b/hub/src/web/routes/localSessions/matchContentPrefix.test.ts @@ -0,0 +1,434 @@ +import { describe, expect, it } from 'bun:test' +import type { LocalTranscript } from '@hapi/protocol/localTranscript' +import type { StoredMessage } from '../../../store' +import { truncateOversizedMessageContent } from '../../../store/contentCodec' +import { matchContentPrefix, type ImportCandidate } from './matchContentPrefix' +import { codexCompareKey } from './sources' + +const NATIVE_ID = 'thread-1' +const KEYS = ['codexSessionId', 'codexSourceSessionId'] + +function userContent(text: string) { + return { role: 'user', content: { type: 'text', text }, meta: { sentFrom: 'cli' } } as const +} + +function agentContent(id: string, message: string) { + return { + role: 'agent', + content: { type: 'codex', data: { type: 'message', message, id } }, + meta: { sentFrom: 'cli' } + } as const +} + +function codexTranscript(contents: unknown[]): LocalTranscript { + return { + flavor: 'codex', + id: NATIVE_ID, + title: 't', + file: '/tmp/thread-1.jsonl', + modifiedAt: 1, + messages: contents.map((content, index) => ({ + id: `codex-desktop:${NATIVE_ID}:${index}`, + content: content as LocalTranscript['messages'][number]['content'] + })) + } +} + +function storedMessage(localId: string, content: unknown): StoredMessage { + return { + id: `stored-${localId}`, + sessionId: 'hapi-1', + content, + createdAt: 1, + seq: 1, + localId, + invokedAt: null, + scheduledAt: null + } +} + +function candidate(overrides: Partial = {}): ImportCandidate { + return { + sessionId: 'hapi-1', + active: false, + updatedAt: 1, + metadata: { codexSessionId: NATIVE_ID, flavor: 'codex' }, + persisted: true, + ...overrides + } +} + +function harness(candidates: ImportCandidate[], storedBySession: Record) { + return { + candidates, + getAllMessages: (sessionId: string) => storedBySession[sessionId] ?? [] + } +} + +describe('contentPrefix match', () => { + it('blocks the sync when any related candidate is active, delta or not', () => { + const { candidates, getAllMessages } = harness([candidate({ active: true })], { 'hapi-1': [] }) + const result = matchContentPrefix({ + candidates, + transcript: codexTranscript([userContent('hello')]), + nativeIdKeys: KEYS, + getAllMessages + }) + expect(result).toMatchObject({ status: 'session_active' }) + }) + + it('excludes archived and deleted candidates', () => { + const { candidates, getAllMessages } = harness( + [candidate({ sessionId: 'hapi-a', metadata: { codexSessionId: NATIVE_ID, lifecycleState: 'archived' } })], + { 'hapi-a': [storedMessage('codex-desktop:thread-1:0', userContent('hello'))] } + ) + const result = matchContentPrefix({ + candidates, + transcript: codexTranscript([userContent('hello')]), + nativeIdKeys: KEYS, + getAllMessages + }) + expect(result).toMatchObject({ status: 'ok', targetSessionId: null, deltaStartIndex: 0 }) + }) + + it('picks the candidate with the longest matching prefix', () => { + const { candidates, getAllMessages } = harness( + [ + candidate({ sessionId: 'hapi-short', updatedAt: 9 }), + candidate({ sessionId: 'hapi-long' }) + ], + { + 'hapi-short': [storedMessage('codex-desktop:thread-1:0', userContent('hello'))], + 'hapi-long': [ + storedMessage('codex-desktop:thread-1:0', userContent('hello')), + storedMessage('codex-desktop:thread-1:1', agentContent('x', 'running')) + ] + } + ) + const transcript = codexTranscript([userContent('hello'), agentContent('x', 'running'), userContent('next')]) + const result = matchContentPrefix({ + candidates, + transcript, + nativeIdKeys: KEYS, + getAllMessages + }) + expect(result).toMatchObject({ status: 'ok', targetSessionId: 'hapi-long', deltaStartIndex: 2 }) + }) + + it('matches through the alias key (fork provenance)', () => { + const { candidates, getAllMessages } = harness( + [candidate({ metadata: { codexSourceSessionId: NATIVE_ID } })], + { 'hapi-1': [storedMessage('codex-desktop:thread-1:0', userContent('hello'))] } + ) + const result = matchContentPrefix({ + candidates, + transcript: codexTranscript([userContent('hello'), userContent('next')]), + nativeIdKeys: KEYS, + getAllMessages + }) + expect(result).toMatchObject({ status: 'ok', targetSessionId: 'hapi-1', deltaStartIndex: 1 }) + }) + + it('ignores engine-only (unpersisted) candidates as targets', () => { + const { candidates, getAllMessages } = harness( + [candidate({ sessionId: 'hapi-engine', persisted: false })], + { 'hapi-engine': [storedMessage('codex-desktop:thread-1:0', userContent('hello'))] } + ) + const result = matchContentPrefix({ + candidates, + transcript: codexTranscript([userContent('hello')]), + nativeIdKeys: KEYS, + getAllMessages + }) + expect(result).toMatchObject({ status: 'ok', targetSessionId: null, deltaStartIndex: 0 }) + }) + + it('respects the machine filter: same machine or unset only', () => { + const mismatch = harness([candidate({ sessionId: 'hapi-1', metadata: { codexSessionId: NATIVE_ID, machineId: 'other' } })], { + 'hapi-1': [storedMessage('codex-desktop:thread-1:0', userContent('hello'))] + }) + const unset = harness([candidate({ sessionId: 'hapi-1', metadata: { codexSessionId: NATIVE_ID } })], { + 'hapi-1': [storedMessage('codex-desktop:thread-1:0', userContent('hello'))] + }) + const same = harness([candidate({ sessionId: 'hapi-1', metadata: { codexSessionId: NATIVE_ID, machineId: 'm-1' } })], { + 'hapi-1': [storedMessage('codex-desktop:thread-1:0', userContent('hello'))] + }) + const transcript = codexTranscript([userContent('hello')]) + for (const [setup, expected] of [[mismatch, null], [unset, 'hapi-1'], [same, 'hapi-1']] as const) { + const result = matchContentPrefix({ + candidates: setup.candidates, + transcript, + nativeIdKeys: KEYS, + sourceMachineId: 'm-1', + getAllMessages: setup.getAllMessages + }) + expect(result.status).toBe('ok') + if (result.status === 'ok') expect(result.targetSessionId).toBe(expected) + } + }) + + it('absorbs a trailing stored duplicate the transcript collapsed and maps the delta past it', () => { + const duplicate = agentContent('x', 'running') + const { candidates, getAllMessages } = harness([candidate()], { + 'hapi-1': [ + storedMessage('codex-desktop:thread-1:0', userContent('hello')), + storedMessage('codex-desktop:thread-1:1', duplicate), + storedMessage('codex-desktop:thread-1:2', duplicate) + ] + }) + // The source transcript was de-duplicated on conversion: the adjacent + // duplicate run collapsed to one message. Without absorbing it, the stored + // run [dup, dup] would break the prefix at the third key. + const result = matchContentPrefix({ + candidates, + transcript: codexTranscript([userContent('hello'), duplicate, userContent('next')]), + nativeIdKeys: KEYS, + getAllMessages + }) + expect(result).toMatchObject({ status: 'ok', targetSessionId: 'hapi-1', deltaStartIndex: 2 }) + }) + + it('compares agent payloads while ignoring generated ids', () => { + const { candidates, getAllMessages } = harness([candidate()], { + 'hapi-1': [ + storedMessage('codex-desktop:thread-1:0', userContent('hello')), + storedMessage('codex-desktop:thread-1:1', agentContent('old-id', 'running')) + ] + }) + const result = matchContentPrefix({ + candidates, + transcript: codexTranscript([userContent('hello'), agentContent('new-id', 'running'), userContent('next')]), + nativeIdKeys: KEYS, + compareKey: codexCompareKey, + getAllMessages + }) + expect(result).toMatchObject({ status: 'ok', targetSessionId: 'hapi-1', deltaStartIndex: 2 }) + }) + + it('appends an identical tail turn instead of folding it away', () => { + const { candidates, getAllMessages } = harness([candidate()], { + 'hapi-1': [storedMessage('codex-desktop:thread-1:0', userContent('hello'))] + }) + // Two identical same-source turns are real turns: the appended + // duplicate must not be folded into the stored prefix. + const result = matchContentPrefix({ + candidates, + transcript: codexTranscript([userContent('hello'), userContent('hello')]), + nativeIdKeys: KEYS, + getAllMessages + }) + expect(result).toMatchObject({ status: 'ok', targetSessionId: 'hapi-1', deltaStartIndex: 1 }) + }) + + it('absorbs a stored duplicate the transcript collapsed before a later turn', () => { + const duplicate = userContent('hello') + const { candidates, getAllMessages } = harness([candidate()], { + 'hapi-1': [ + storedMessage('codex-desktop:thread-1:0', duplicate), + storedMessage('codex-desktop:thread-1:1', duplicate), + storedMessage('codex-desktop:thread-1:2', agentContent('x', 'running')) + ] + }) + // A runner that still collapses adjacent duplicates converts the + // stored [hello, hello] run to one hello: the run lengths differ, + // the keys around it agree, so only the new turn is appended. + const result = matchContentPrefix({ + candidates, + transcript: codexTranscript([userContent('hello'), agentContent('x', 'running'), userContent('next')]), + nativeIdKeys: KEYS, + getAllMessages + }) + expect(result).toMatchObject({ status: 'ok', targetSessionId: 'hapi-1', deltaStartIndex: 2 }) + }) + + it('absorbs a mid-history stored duplicate run collapsed by the transcript', () => { + const duplicate = agentContent('x', 'running') + const { candidates, getAllMessages } = harness([candidate()], { + 'hapi-1': [ + storedMessage('codex-desktop:thread-1:0', userContent('A')), + storedMessage('codex-desktop:thread-1:1', duplicate), + storedMessage('codex-desktop:thread-1:2', duplicate), + storedMessage('codex-desktop:thread-1:3', userContent('B')) + ] + }) + const result = matchContentPrefix({ + candidates, + transcript: codexTranscript([userContent('A'), duplicate, userContent('B'), userContent('C')]), + nativeIdKeys: KEYS, + getAllMessages + }) + expect(result).toMatchObject({ status: 'ok', targetSessionId: 'hapi-1', deltaStartIndex: 3 }) + }) + + it('absorbs a mid-history transcript duplicate run the stored session collapsed', () => { + const duplicate = agentContent('x', 'running') + const { candidates, getAllMessages } = harness([candidate()], { + 'hapi-1': [ + storedMessage('codex-desktop:thread-1:0', userContent('A')), + storedMessage('codex-desktop:thread-1:1', duplicate), + storedMessage('codex-desktop:thread-1:2', userContent('B')) + ] + }) + const result = matchContentPrefix({ + candidates, + transcript: codexTranscript([userContent('A'), duplicate, duplicate, userContent('B'), userContent('C')]), + nativeIdKeys: KEYS, + getAllMessages + }) + expect(result).toMatchObject({ status: 'ok', targetSessionId: 'hapi-1', deltaStartIndex: 4 }) + }) + + it('reports nothing new when the transcript only collapsed a trailing stored run', () => { + const duplicate = agentContent('x', 'running') + const { candidates, getAllMessages } = harness([candidate()], { + 'hapi-1': [ + storedMessage('codex-desktop:thread-1:0', userContent('A')), + storedMessage('codex-desktop:thread-1:1', duplicate), + storedMessage('codex-desktop:thread-1:2', duplicate) + ] + }) + const result = matchContentPrefix({ + candidates, + transcript: codexTranscript([userContent('A'), duplicate]), + nativeIdKeys: KEYS, + getAllMessages + }) + expect(result).toMatchObject({ status: 'ok', targetSessionId: 'hapi-1', deltaStartIndex: 2 }) + }) + + it('rejects stored turns separated by transcript content they never had', () => { + const { candidates, getAllMessages } = harness([candidate()], { + 'hapi-1': [ + storedMessage('codex-desktop:thread-1:0', userContent('A')), + storedMessage('codex-desktop:thread-1:1', userContent('B')) + ] + }) + const transcripts = [ + // A rewritten middle: X and Y were never stored between A and B. + [userContent('A'), userContent('X'), userContent('Y'), userContent('B'), userContent('C')], + // Prepended history: the stored session does not start the transcript. + [userContent('X'), userContent('A'), userContent('B'), userContent('C')], + // A gap made of an earlier, non-adjacent key is still a gap. + [userContent('A'), userContent('A'), userContent('X'), userContent('B')] + ] + for (const contents of transcripts) { + const result = matchContentPrefix({ + candidates, + transcript: codexTranscript(contents), + nativeIdKeys: KEYS, + getAllMessages + }) + expect(result).toMatchObject({ status: 'ok', targetSessionId: null, deltaStartIndex: 0 }) + } + }) + + it('rejects a stored session holding turns the transcript does not have', () => { + const { candidates, getAllMessages } = harness([candidate()], { + 'hapi-1': [ + storedMessage('codex-desktop:thread-1:0', userContent('A')), + storedMessage('codex-desktop:thread-1:1', userContent('X')), + storedMessage('codex-desktop:thread-1:2', userContent('B')) + ] + }) + const result = matchContentPrefix({ + candidates, + transcript: codexTranscript([userContent('A'), userContent('B')]), + nativeIdKeys: KEYS, + getAllMessages + }) + expect(result).toMatchObject({ status: 'ok', targetSessionId: null, deltaStartIndex: 0 }) + }) + + it('rejects a diverged turn even when the run before it is duplicated', () => { + const duplicate = userContent('hello') + const { candidates, getAllMessages } = harness([candidate()], { + 'hapi-1': [ + storedMessage('codex-desktop:thread-1:0', duplicate), + storedMessage('codex-desktop:thread-1:1', duplicate), + storedMessage('codex-desktop:thread-1:2', agentContent('x', 'running')) + ] + }) + const result = matchContentPrefix({ + candidates, + transcript: codexTranscript([duplicate, agentContent('x', 'different'), userContent('next')]), + nativeIdKeys: KEYS, + getAllMessages + }) + expect(result).toMatchObject({ status: 'ok', targetSessionId: null, deltaStartIndex: 0 }) + }) + + it('appends plain growth after the stored prefix', () => { + const { candidates, getAllMessages } = harness([candidate()], { + 'hapi-1': [ + storedMessage('codex-desktop:thread-1:0', userContent('A')), + storedMessage('codex-desktop:thread-1:1', userContent('B')) + ] + }) + const result = matchContentPrefix({ + candidates, + transcript: codexTranscript([userContent('A'), userContent('B'), userContent('C')]), + nativeIdKeys: KEYS, + getAllMessages + }) + expect(result).toMatchObject({ status: 'ok', targetSessionId: 'hapi-1', deltaStartIndex: 2 }) + }) + + it('prefers the most recently updated candidate when two explain the same prefix', () => { + const stored = [storedMessage('codex-desktop:thread-1:0', userContent('A'))] + const { candidates, getAllMessages } = harness( + [ + candidate({ sessionId: 'hapi-older', updatedAt: 1 }), + candidate({ sessionId: 'hapi-newer', updatedAt: 5 }) + ], + { 'hapi-older': stored, 'hapi-newer': stored } + ) + const result = matchContentPrefix({ + candidates, + transcript: codexTranscript([userContent('A'), userContent('B')]), + nativeIdKeys: KEYS, + getAllMessages + }) + expect(result).toMatchObject({ status: 'ok', targetSessionId: 'hapi-newer', deltaStartIndex: 1 }) + }) + + it('appends the missing duplicates when a pre-dedupe stored run shows up expanded', () => { + const duplicate = agentContent('x', 'running') + const { candidates, getAllMessages } = harness([candidate()], { + 'hapi-1': [ + storedMessage('codex-desktop:thread-1:0', userContent('hello')), + storedMessage('codex-desktop:thread-1:1', duplicate) + ] + }) + // The stored row kept one copy of the mirrored run; the + // re-converted transcript shows it expanded and the extra duplicate + // plus the new turn must be appended, not folded away. + const result = matchContentPrefix({ + candidates, + transcript: codexTranscript([userContent('hello'), duplicate, duplicate, userContent('next')]), + nativeIdKeys: KEYS, + getAllMessages + }) + expect(result).toMatchObject({ status: 'ok', targetSessionId: 'hapi-1', deltaStartIndex: 2 }) + }) + + it('matches an oversized agent message against its truncated stored row', () => { + const huge = 'x'.repeat(70 * 1024) + const { candidates, getAllMessages } = harness([candidate()], { + 'hapi-1': [ + storedMessage('codex-desktop:thread-1:0', truncateOversizedMessageContent(agentContent('x', huge)) as unknown), + storedMessage('codex-desktop:thread-1:1', userContent('next')) + ] + }) + // The store truncates oversized agent payloads at ingest while the + // runner transcript arrives in full: the compare key must apply the + // same truncation or the re-sync forks a duplicate session. + const result = matchContentPrefix({ + candidates, + transcript: codexTranscript([agentContent('x', huge), userContent('next'), userContent('newer turn')]), + nativeIdKeys: KEYS, + compareKey: codexCompareKey, + getAllMessages + }) + expect(result).toMatchObject({ status: 'ok', targetSessionId: 'hapi-1', deltaStartIndex: 2 }) + }) +}) \ No newline at end of file diff --git a/hub/src/web/routes/localSessions/matchContentPrefix.ts b/hub/src/web/routes/localSessions/matchContentPrefix.ts new file mode 100644 index 00000000..2bdd1e54 --- /dev/null +++ b/hub/src/web/routes/localSessions/matchContentPrefix.ts @@ -0,0 +1,189 @@ +import type { LocalTranscript } from '@hapi/protocol/localTranscript' +import type { Store } from '../../../store' +import type { StoredMessage } from '../../../store' +import type { SyncEngine } from '../../../sync/syncEngine' +import { truncateOversizedMessageContent } from '../../../store/contentCodec' +import { stableSerializeContent } from './compare' + +/** + * Content-prefix target matching: pick the reusable HAPI session whose + * stored comparable keys form a prefix of the source transcript's keys. + * Codex's current behavior, with one tolerance for duplicate runs. + * + * Alignment rules (stored keys against transcript keys, left to right): + * - Equal keys are consumed together. There are no other gaps: a stored key + * separated from its transcript twin by any other content does not match, + * so a rewritten middle or prepended history never passes as a prefix. + * - Duplicate runs: runners from before the source-side dedupe change + * collapsed adjacent identical messages, so the same run can have a + * different length on each side. Inside the prefix, an extra copy of the + * key just consumed is skipped on whichever side has it. + * - The match ends when the stored keys run out; every transcript message + * after the last consumed key is the delta. A transcript copy past the + * stored end is growth, so an appended identical turn is kept. + * - When the transcript runs out first, the stored session still matches + * (with nothing to append) only if its remaining keys repeat the key just + * consumed. + */ + +export type ImportCandidate = { + sessionId: string + active: boolean + updatedAt: number + metadata: Record | null + persisted: boolean +} + +function asRecord(value: unknown): Record | null { + return value !== null && typeof value === 'object' && !Array.isArray(value) + ? value as Record + : null +} + +/** + * Canonical import-candidate collection shared by the generic importer and + * the Codex duplicate-merge sidecar: store rows first, then engine cache + * entries merged in by session id. + */ +export function collectImportCandidates( + store: Store, + namespace: string, + getSyncEngine?: () => SyncEngine | null +): ImportCandidate[] { + const candidatesBySessionId = new Map() + for (const session of store.sessions.getSessionsByNamespace(namespace)) { + candidatesBySessionId.set(session.id, { + sessionId: session.id, + active: session.active, + updatedAt: session.updatedAt, + metadata: asRecord(session.metadata), + persisted: true + }) + } + + const engineSessions = getSyncEngine?.()?.getSessionsByNamespace(namespace) ?? [] + for (const session of engineSessions) { + const existing = candidatesBySessionId.get(session.id) + candidatesBySessionId.set(session.id, { + sessionId: session.id, + active: session.active || Boolean(existing?.active), + updatedAt: Math.max(session.updatedAt, existing?.updatedAt ?? 0), + metadata: asRecord(session.metadata) ?? existing?.metadata ?? null, + persisted: Boolean(existing?.persisted) + }) + } + + return Array.from(candidatesBySessionId.values()) +} + +export type ContentPrefixMatchResult = + | { status: 'ok'; targetSessionId: string | null; deltaStartIndex: number } + | { status: 'session_active'; message: string } + +function defaultCompareKey(content: unknown): string | null { + return stableSerializeContent(truncateOversizedMessageContent(content)) +} + +type KeyEntry = { key: string; messageIndex: number } + +function comparableKeys(messages: Array<{ content: unknown }>, compareKey: (content: unknown) => string | null): KeyEntry[] { + const entries: KeyEntry[] = [] + messages.forEach((message, index) => { + const key = compareKey(message.content) + if (key !== null) entries.push({ key, messageIndex: index }) + }) + return entries +} + +/** + * Aligns the stored keys against the start of the transcript keys under the + * rules above. Returns the transcript entry index of the last consumed key + * (-1 when nothing was stored), or null when the stored session is not a + * prefix of the transcript. + */ +function alignStoredPrefix(stored: KeyEntry[], transcript: KeyEntry[]): number | null { + let storedIndex = 0 + let transcriptIndex = 0 + let lastConsumed = -1 + let lastKey: string | null = null + while (storedIndex < stored.length) { + const storedKey = stored[storedIndex]!.key + if (transcriptIndex < transcript.length) { + const transcriptKey = transcript[transcriptIndex]!.key + if (storedKey === transcriptKey) { + lastConsumed = transcriptIndex + lastKey = storedKey + storedIndex += 1 + transcriptIndex += 1 + continue + } + if (transcriptKey === lastKey) { + transcriptIndex += 1 + continue + } + } + if (storedKey === lastKey) { + storedIndex += 1 + continue + } + return null + } + return lastConsumed +} + +export function matchContentPrefix(options: { + candidates: ImportCandidate[] + transcript: LocalTranscript + nativeIdKeys: string[] + sourceMachineId?: string | null + compareKey?: (content: unknown) => string | null + getAllMessages: (sessionId: string) => StoredMessage[] +}): ContentPrefixMatchResult { + const { candidates, transcript, nativeIdKeys, sourceMachineId } = options + const compareKey = options.compareKey ?? defaultCompareKey + + const related = candidates + .filter((candidate) => candidate.persisted) + .filter((candidate) => { + const lifecycleState = candidate.metadata?.lifecycleState + return lifecycleState !== 'archived' && lifecycleState !== 'deleted' + }) + .filter((candidate) => nativeIdKeys.some((key) => candidate.metadata?.[key] === transcript.id)) + .filter((candidate) => ( + !sourceMachineId + || typeof candidate.metadata?.machineId !== 'string' + || candidate.metadata.machineId === sourceMachineId + )) + + // Any related candidate being active blocks the sync, delta or not. + if (related.some((candidate) => candidate.active)) { + return { + status: 'session_active', + message: 'Cannot sync the local transcript while the matching HAPI session is active' + } + } + + const transcriptKeys = comparableKeys(transcript.messages, compareKey) + + let bestSessionId: string | null = null + let bestDeltaStart = -1 + + // Most recently updated first: on a tie the newest session wins. + const ordered = [...related].sort((a, b) => b.updatedAt - a.updatedAt) + for (const candidate of ordered) { + const storedKeys = comparableKeys(options.getAllMessages(candidate.sessionId), compareKey) + const lastConsumed = alignStoredPrefix(storedKeys, transcriptKeys) + if (lastConsumed === null) continue + const deltaStart = lastConsumed === -1 ? 0 : transcriptKeys[lastConsumed]!.messageIndex + 1 + // The candidate explaining the largest transcript prefix wins. + if (deltaStart > bestDeltaStart) { + bestDeltaStart = deltaStart + bestSessionId = candidate.sessionId + } + } + + if (bestSessionId === null || bestDeltaStart < 0) { + return { status: 'ok', targetSessionId: null, deltaStartIndex: 0 } + } + return { status: 'ok', targetSessionId: bestSessionId, deltaStartIndex: bestDeltaStart } +} \ No newline at end of file diff --git a/hub/src/web/routes/localSessions/piOpencodeGenericImport.test.ts b/hub/src/web/routes/localSessions/piOpencodeGenericImport.test.ts new file mode 100644 index 00000000..5d11611c --- /dev/null +++ b/hub/src/web/routes/localSessions/piOpencodeGenericImport.test.ts @@ -0,0 +1,404 @@ +import { afterEach, describe, expect, it } from 'bun:test' +import { Hono } from 'hono' +import type { LocalTranscript, LocalTranscriptSummary } from '@hapi/protocol/localTranscript' +import type { Machine, SyncEngine } from '../../../sync/syncEngine' +import type { WebAppEnv } from '../../middleware/auth' +import { Store } from '../../../store' +import { OPENCODE_LOCAL_SESSION_SOURCE, PI_LOCAL_SESSION_SOURCE } from './sources' +import { createLocalSessionRoutes } from './createLocalSessionRoutes' +import { importPiSession } from '../piSessions' + +/** + * Pinning tests for the generic-route Pi/OpenCode import semantics: gaps + * without a cursor and HAPI-created sessions fail closed, imports are atomic + * and serialize, vanished sessions fail with import_failed, Pi gets the + * 200-session import cap, and machine selection prefers the cwd owner. The + * legacy route test files stay untouched. + */ + +function machine(id: string, workspaceRoots: string[] = []): Machine { + return { + id, + namespace: 'default', + seq: 1, + createdAt: 1, + updatedAt: 1, + active: true, + activeAt: 1, + metadata: { + host: `${id}.local`, + platform: 'darwin', + happyCliVersion: 'test', + workspaceRoots, + capabilities: ['local-session-import'] + }, + metadataVersion: 1, + runnerState: null, + runnerStateVersion: 1, + health: null + } +} + +function userContent(text: string) { + return { role: 'user', content: { type: 'text', text }, meta: { sentFrom: 'cli' } } as const +} + +function piSummary(id = 'native-1'): LocalTranscriptSummary { + return { + flavor: 'pi', + id, + title: `Pi ${id}`, + lastUserMessage: 'hello', + cwd: '/workspace/b', + file: `/tmp/${id}.jsonl`, + modifiedAt: 1, + messageCount: 1 + } +} + +function piTranscript(id = 'native-1', texts: string[] = ['hello']): LocalTranscript { + return { + ...piSummary(id), + messages: texts.map((text, index) => ({ + id: `pi:${id}:entry-${index + 1}:user`, + createdAt: 1_000 + index, + content: userContent(text), + anchor: `entry-${index + 1}`, + historyPoint: `entry-${index + 1}` + })), + anchorOrder: texts.map((_, index) => `entry-${index + 1}`), + cursor: `entry-${texts.length}` + } +} + +function opencodeTranscript(id: string, texts: string[]): LocalTranscript { + return { + flavor: 'opencode', + id, + title: `OpenCode ${id}`, + lastUserMessage: texts.at(-1) ?? null, + cwd: '/workspace/b', + file: '/tmp/opencode.db', + modifiedAt: 1, + messages: texts.map((text, index) => ({ + id: `opencode:${id}:msg-${index + 1}:part-1`, + createdAt: 1_000 + index, + content: userContent(text) + })) + } +} + +function harness(overrides: { + machines?: Machine[] + transcripts?: LocalTranscript[] + summaries?: LocalTranscriptSummary[] +} = {}) { + const store = new Store(':memory:') + const calls: Array<{ machineId: string; payload: unknown }> = [] + const appliedConfigs: Array> = [] + const machines = overrides.machines ?? [machine('m-1', ['/workspace/a'])] + const transcripts = overrides.transcripts ?? [piTranscript()] + const summaries = overrides.summaries ?? transcripts.map(({ messages: _messages, ...summary }) => summary as LocalTranscriptSummary) + const engine = { + getOnlineMachinesByNamespace: () => machines, + getSessionsByNamespace: () => [], + listLocalSessionsForMachine: async (machineId: string, payload: { flavor: string; sessionIds?: string[] | null }) => { + calls.push({ machineId, payload }) + const wanted = payload.sessionIds ?? null + const source = wanted + ? transcripts.filter((transcript) => (wanted as string[]).includes(transcript.id)) + : summaries + return { success: true, sessions: source } + }, + recordSessionActivity: () => {}, + handleRealtimeEvent: () => {}, + applySessionConfig: async (_sessionId: string, config: Record) => { + appliedConfigs.push(config) + } + } as unknown as SyncEngine + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + app.route('/api', createLocalSessionRoutes({ + store, + getSyncEngine: () => engine, + sources: [PI_LOCAL_SESSION_SOURCE, OPENCODE_LOCAL_SESSION_SOURCE] + })) + return { store, engine, app, calls, appliedConfigs } +} + +function createImportedPiSession(store: Store, nativeId: string, localIds: string[], metadata: Record = {}) { + const created = store.sessions.getOrCreateSession(`pi-import:m-1:${nativeId}`, { + path: '/workspace/b', + host: 'm-1.local', + machineId: 'm-1', + flavor: 'pi', + piSessionId: nativeId, + lifecycleState: 'archived', + ...metadata + }, {}, 'default') + for (const localId of localIds) { + store.messages.addImportedMessage(created.id, userContent(`stored ${localId}`), localId, 1) + } + return created +} + +describe('generic Pi import route', () => { + const stores: Store[] = [] + afterEach(() => { + for (const store of stores.splice(0)) store.close() + }) + + it('keeps fork/rewind locators of HAPI turns when the session is re-imported', async () => { + const { app, store } = harness() + stores.push(store) + const importOnce = async () => { + const response = await app.request('/api/pi/import-sessions', { + method: 'POST', + body: JSON.stringify({ sessionIds: ['native-1'] }) + }) + return (await response.json() as { results: Array<{ hapiSessionId?: string; action?: string }> }).results[0]! + } + const first = await importOnce() + expect(first.action).toBe('created') + + // The session continues in HAPI: the live Pi machinery stores the turn + // under a HAPI local id and maps it to its native entry. + const session = store.sessions.getSessionByNamespace(first.hapiSessionId!, 'default')! + store.messages.addMessage(session.id, userContent('continued in HAPI'), 'hapi-live-1') + const metadata = session.metadata as Record + store.sessions.updateSessionMetadata(session.id, { + ...metadata, + conversationHistoryEntryIds: { ...(metadata.conversationHistoryEntryIds as Record), 'hapi-live-1': 'entry-live' }, + conversationHistoryPoints: { ...(metadata.conversationHistoryPoints as Record), 'hapi-live-1': true } + }, session.metadataVersion, 'default') + + const again = await importOnce() + expect(again.action).toBe('unchanged') + const after = store.sessions.getSessionByNamespace(session.id, 'default')!.metadata as Record + expect(after.conversationHistoryEntryIds).toEqual({ + 'pi:native-1:entry-1:user': 'entry-1', + 'hapi-live-1': 'entry-live' + }) + expect(after.conversationHistoryPoints).toEqual({ + 'pi:native-1:entry-1:user': true, + 'hapi-live-1': true + }) + }) + + it('diverges on a gap without a cursor', async () => { + const { app, store } = harness({ + transcripts: [{ + ...piTranscript('native-gap', ['moved']), + messages: [{ + id: 'pi:native-gap:entry-2:user', + createdAt: 2_000, + content: userContent('moved'), + anchor: 'entry-2', + historyPoint: 'entry-2' + }], + anchorOrder: ['entry-2'], + cursor: 'entry-2' + }], + summaries: [{ + flavor: 'pi', + id: 'native-gap', + title: 'Pi native-gap', + cwd: '/workspace/b', + file: '/tmp/native-gap.jsonl', + modifiedAt: 1, + messageCount: 1 + }] + }) + stores.push(store) + // The stored session kept entry-1; the transcript's active branch no + // longer contains it and no cursor was persisted: the pre-registry + // importer appended the moved entry as a duplicate, the registry + // fails closed instead. + const stored = createImportedPiSession(store, 'native-gap', ['pi:native-gap:entry-1:user']) + const response = await app.request('/api/pi/import-sessions', { + method: 'POST', + body: JSON.stringify({ sessionIds: ['native-gap'] }) + }) + const body = await response.json() as { results: Array<{ error?: { code: string } }> } + expect(body.results[0]!.error).toMatchObject({ code: 'transcript_diverged' }) + expect(store.messages.getAllMessages(stored.id)).toHaveLength(1) + }) + + it('reports already_in_hapi for a HAPI-created session', async () => { + const { app, store } = harness() + stores.push(store) + const created = store.sessions.getOrCreateSession('hapi-native', { + machineId: 'm-1', + flavor: 'pi', + piSessionId: 'native-1' + }, {}, 'default') + store.messages.addImportedMessage(created.id, userContent('typed in HAPI'), 'local-1', 1) + const response = await app.request('/api/pi/import-sessions', { + method: 'POST', + body: JSON.stringify({ sessionIds: ['native-1'] }) + }) + const body = await response.json() as { results: Array<{ error?: { code: string }; hapiSessionId?: string }> } + expect(body.results[0]).toMatchObject({ hapiSessionId: created.id, error: { code: 'already_in_hapi' } }) + expect(store.messages.getAllMessages(created.id)).toHaveLength(1) + }) + + it('rolls the whole Pi import back on insert failure', async () => { + const { app, store } = harness({ + transcripts: [piTranscript('native-1', ['one', 'two'])] + }) + stores.push(store) + const original = store.messages.addImportedMessage.bind(store.messages) + let calls = 0 + ;(store.messages as { addImportedMessage: typeof original }).addImportedMessage = ( + (sessionId: string, content: unknown, localId: string, createdAt: number) => { + calls += 1 + if (calls === 2) throw new Error('boom') + return original(sessionId, content, localId, createdAt) + } + ) as typeof original + const response = await app.request('/api/pi/import-sessions', { + method: 'POST', + body: JSON.stringify({ sessionIds: ['native-1'] }) + }) + const body = await response.json() as { results: Array<{ error?: { code: string } }> } + expect(body.results[0]!.error).toMatchObject({ code: 'import_failed' }) + expect(store.sessions.getSessionsByNamespace('default')).toHaveLength(0) + }) + + it('serializes concurrent Pi imports of one native session', async () => { + const { app, store } = harness() + stores.push(store) + const [first, second] = await Promise.all([ + app.request('/api/pi/import-sessions', { method: 'POST', body: JSON.stringify({ sessionIds: ['native-1'] }) }), + app.request('/api/pi/import-sessions', { method: 'POST', body: JSON.stringify({ sessionIds: ['native-1'] }) }) + ]) + const firstBody = await first.json() as { results: Array<{ action?: string }> } + const secondBody = await second.json() as { results: Array<{ action?: string }> } + const actions = [firstBody.results[0]!.action, secondBody.results[0]!.action].sort() + expect(actions).toEqual(['created', 'unchanged']) + expect(store.sessions.getSessionsByNamespace('default')).toHaveLength(1) + expect(store.messages.getAllMessages(store.sessions.getSessionsByNamespace('default')[0]!.id)).toHaveLength(1) + }) + + it('applies the requested launch config to a Pi import', async () => { + const { app, store, appliedConfigs } = harness() + stores.push(store) + const response = await app.request('/api/pi/import-sessions', { + method: 'POST', + body: JSON.stringify({ sessionIds: ['native-1'], model: 'gemini-3.8-flash', modelReasoningEffort: 'low' }) + }) + const body = await response.json() as { success: boolean } + expect(body.success).toBe(true) + expect(appliedConfigs).toEqual([{ model: 'gemini-3.8-flash', modelReasoningEffort: 'low' }]) + const session = store.sessions.getSessionsByNamespace('default')[0]! + expect(session.model).toBe('gemini-3.8-flash') + expect(session.effort).toBe('low') + }) + + it('rejects more Pi sessions than the scan limit', async () => { + const { app } = harness() + const response = await app.request('/api/pi/import-sessions', { + method: 'POST', + body: JSON.stringify({ sessionIds: Array.from({ length: 201 }, (_, index) => `pi-${index}`) }) + }) + expect(response.status).toBe(400) + }) + + it('prefers the machine that owns the cwd', async () => { + const owner = machine('m-2', ['/workspace/b']) + const other = machine('m-1', ['/workspace/a']) + const { app, calls } = harness({ machines: [other, owner] }) + const listResponse = await app.request('/api/pi/sessions?cwd=/workspace/b/sub') + const listBody = await listResponse.json() as { machineId?: string } + expect(listBody.machineId).toBe('m-2') + const importResponse = await app.request('/api/pi/import-sessions', { + method: 'POST', + body: JSON.stringify({ sessionIds: ['native-1'], cwd: '/workspace/b/sub' }) + }) + const importBody = await importResponse.json() as { machineId?: string } + expect(importBody.machineId).toBe('m-2') + expect(calls[0]!.machineId).toBe('m-2') + }) +}) + +describe('generic OpenCode import route', () => { + const stores: Store[] = [] + afterEach(() => { + for (const store of stores.splice(0)) store.close() + }) + + it('reports already_in_hapi for a HAPI-created session', async () => { + const { app, store } = harness({ + transcripts: [opencodeTranscript('native-oc', ['native history'])], + summaries: [{ + flavor: 'opencode', + id: 'native-oc', + title: 'OpenCode native-oc', + cwd: '/workspace/b', + file: '/tmp/opencode.db', + modifiedAt: 1 + }] + }) + stores.push(store) + const created = store.sessions.getOrCreateSession('hapi-oc', { + machineId: 'm-1', + flavor: 'opencode', + opencodeSessionId: 'native-oc' + }, {}, 'default') + store.messages.addImportedMessage(created.id, userContent('typed in HAPI'), 'local-1', 1) + const response = await app.request('/api/opencode/import-sessions', { + method: 'POST', + body: JSON.stringify({ sessionIds: ['native-oc'] }) + }) + const body = await response.json() as { results: Array<{ error?: { code: string }; hapiSessionId?: string }> } + expect(body.results[0]).toMatchObject({ hapiSessionId: created.id, error: { code: 'already_in_hapi' } }) + expect(store.messages.getAllMessages(created.id)).toHaveLength(1) + }) +}) + +describe('Pi sync import wrapper', () => { + const stores: Store[] = [] + afterEach(() => { + for (const store of stores.splice(0)) store.close() + }) + + it('fails closed when a captured Pi session disappears', () => { + const store = new Store(':memory:') + stores.push(store) + const engine = { + recordSessionActivity: () => {}, + handleRealtimeEvent: () => {}, + getSessionsByNamespace: () => [] + } as unknown as SyncEngine + const created = createImportedPiSession(store, 'native-vanish', ['pi:native-vanish:entry-1:user']) + const captured = store.sessions.getSession(created.id)! + expect(store.sessions.deleteSession(created.id, 'default')).toBe(true) + const result = importPiSession({ + store, + engine, + namespace: 'default', + machine: machine('m-1'), + transcript: { + id: 'native-vanish', + title: 'Pi native-vanish', + cwd: '/workspace/b', + file: '/tmp/native-vanish.jsonl', + modifiedAt: 1, + messageCount: 1, + messages: [{ + localId: 'pi:native-vanish:entry-1:user', + entryId: 'entry-1', + parentEntryId: null, + createdAt: 1_000, + content: userContent('hello') + }], + activeEntryIds: ['entry-1'] + }, + existingSession: captured + }) + expect(result.error).toMatchObject({ code: 'import_failed' }) + }) +}) \ No newline at end of file diff --git a/hub/src/web/routes/localSessions/sources.ts b/hub/src/web/routes/localSessions/sources.ts new file mode 100644 index 00000000..c2fc9bd6 --- /dev/null +++ b/hub/src/web/routes/localSessions/sources.ts @@ -0,0 +1,252 @@ +import { AGENT_MESSAGE_PAYLOAD_TYPE } from '@hapi/protocol' +import { MACHINE_CAPABILITIES } from '@hapi/protocol/runnerCapabilities' +import type { + OpencodeLocalSessionSummary, + OpencodeLocalSessionWithMessages, + PiLocalSessionSummary, + PiLocalSessionWithMessages +} from '@hapi/protocol/apiTypes' +import { + codexToTranscript, + codexToTranscriptSummary, + opencodeToTranscript, + opencodeToTranscriptSummary, + piToTranscript, + piToTranscriptSummary +} from '@hapi/protocol/localTranscript' +import type { + CodexLocalSessionSummary, + CodexLocalSessionWithMessages, + LocalSessionFlavor, + LocalTranscript, + LocalTranscriptSummary +} from '@hapi/protocol/localTranscript' +import type { MachineCapability } from '@hapi/protocol/runnerCapabilities' +import type { SyncEngine } from '../../../sync/syncEngine' +import { truncateOversizedMessageContent } from '../../../store/contentCodec' +import { normalizeComparableText, stableSerializeContent } from './compare' + +/** + * Declarative hub-side source descriptors. Sources only describe + * HOW to find and match their transcripts; the generic importer owns + * persistence, lifecycle and launch config. + */ + +export type LocalSessionNativeIdKey = + | 'piSessionId' + | 'opencodeSessionId' + | 'claudeSessionId' + | 'claudeSessionIdHistory' + | 'codexSessionId' + | 'codexSourceSessionId' + +export type HubLocalSessionSource = { + flavor: LocalSessionFlavor + displayName: string + /** REST route base under /api (e.g. 'pi' -> /api/pi/sessions). */ + routeBase: string + /** First key is primary; the rest are aliases matched on lookup. */ + nativeIdKeys: LocalSessionNativeIdKey[] + /** How the target HAPI session and the delta are found. */ + match: { + strategy: 'anchored' + cursorKey?: 'piHistoryLeafEntryId' + /** Maps stored and transcript content to the fields that must stay equal. */ + canonicalContent?: (content: unknown) => unknown + } + | { strategy: 'contentPrefix'; compareKey?: (content: unknown) => string | null } + /** Lifecycle stamped on create. */ + lifecycleOnCreate: 'archived' | 'imported' + /** Multi-import loop policy. */ + batch: 'continue' | 'stopOnFirstError' + /** Flavor-only import progress metadata key (Pi). */ + importStateKey?: 'piImportState' + /** + * Stored localId prefix identifying this flavor's imported rows. Defaults + * to `${flavor}:${nativeId}:`; Claude omits the native id because resumed + * sessions rotate it while message uuids stay stable. + */ + localIdPrefix?: string + /** Per-request import cap enforced by the route (400 above it). */ + importLimit?: number + /** + * Fallback for runners that do not advertise `local-session-import`: + * fetch via the flavor's legacy RPC and convert raw rows to transcripts. + * `resultIdKey` stays the legacy response field name for result items. + */ + legacy?: { + resultIdKey: string + fetch(ctx: { + engine: SyncEngine + machineId: string + cwd: string | null + sessionIds: string[] | null + }): Promise<{ success: true; sessions: unknown[] } | { success: false; error: string }> + toTranscript(raw: unknown): LocalTranscriptSummary | LocalTranscript + } + requiredMachineCapability?: MachineCapability + /** Codex request flag yolo -> metadata.preferredPermissionMode. */ + requestMetadata?: (body: Record) => Record +} + +/** True when the machine advertises the source's required capability. */ +export function machineSupportsLocalSessionImport(source: HubLocalSessionSource, machine: { + metadata?: { capabilities?: readonly string[] | null } | null +} | null | undefined): boolean { + const capability = source.requiredMachineCapability + if (!capability) return true + return machine?.metadata?.capabilities?.includes(capability) === true +} + +/** + * Codex compare key: agent payload `id` fields are ignored so + * re-converted transcripts compare equal against stored rows; user text is + * trailing-whitespace insensitive. Stored rows are truncated at ingest + * (contentCodec) while transcripts arrive in full; truncation is idempotent, + * so applying it here keeps both sides canonical. Duplicate handling + * happens in the matcher, not here. + */ +export function codexCompareKey(content: unknown): string | null { + const canonical = truncateOversizedMessageContent(content) + const record = canonical !== null && typeof canonical === 'object' && !Array.isArray(canonical) + ? canonical as Record + : null + if (!record) return null + if (record.role === 'user') { + const body = record.content !== null && typeof record.content === 'object' && !Array.isArray(record.content) + ? record.content as Record + : null + if (body?.type !== 'text' || typeof body.text !== 'string') return null + return stableSerializeContent({ role: 'user', text: normalizeComparableText(body.text) }) + } + if (record.role === 'agent') { + const body = record.content !== null && typeof record.content === 'object' && !Array.isArray(record.content) + ? record.content as Record + : null + if (!body || body.type !== AGENT_MESSAGE_PAYLOAD_TYPE) return null + const data = body.data !== null && typeof body.data === 'object' && !Array.isArray(body.data) + ? { ...(body.data as Record) } + : body.data + if (data && typeof data === 'object' && !Array.isArray(data)) { + delete (data as Record).id + } + return stableSerializeContent({ role: 'agent', data }) + } + return null +} + +/** + * Fields Claude Code rewrites when it copies earlier entries into a resumed + * transcript (same uuid, new session file) or that describe the process that + * wrote the entry rather than the conversation. + */ +const CLAUDE_REPLAY_METADATA_KEYS = ['sessionId', 'timestamp', 'cwd', 'gitBranch', 'version'] as const + +/** + * Claude compare form: a raw transcript entry kept as agent output is + * compared without its replay metadata, so a resumed transcript still lines + * up with the imported rows; uuid, type and message content stay compared. + */ +export function claudeCanonicalContent(content: unknown): unknown { + const record = content !== null && typeof content === 'object' && !Array.isArray(content) + ? content as Record + : null + const body = record?.content !== null && typeof record?.content === 'object' && !Array.isArray(record?.content) + ? record.content as Record + : null + const data = body?.data !== null && typeof body?.data === 'object' && !Array.isArray(body?.data) + ? body.data as Record + : null + if (record?.role !== 'agent' || body?.type !== 'output' || !data) return content + const entry = { ...data } + for (const key of CLAUDE_REPLAY_METADATA_KEYS) delete entry[key] + return { ...record, content: { ...body, data: entry } } +} + +function isWithMessages(raw: unknown): raw is PiLocalSessionWithMessages | OpencodeLocalSessionWithMessages | CodexLocalSessionWithMessages { + return raw !== null && typeof raw === 'object' && Array.isArray((raw as { messages?: unknown }).messages) +} + +export const PI_LOCAL_SESSION_SOURCE: HubLocalSessionSource = { + flavor: 'pi', + displayName: 'Pi', + routeBase: 'pi', + nativeIdKeys: ['piSessionId'], + match: { strategy: 'anchored', cursorKey: 'piHistoryLeafEntryId' }, + lifecycleOnCreate: 'archived', + batch: 'continue', + importStateKey: 'piImportState', + importLimit: 200, + requiredMachineCapability: MACHINE_CAPABILITIES.LocalSessionImport, + legacy: { + resultIdKey: 'piSessionId', + async fetch({ engine, machineId, cwd, sessionIds }) { + const result = await engine.listPiSessionsForMachine(machineId, cwd, sessionIds ?? undefined) + if (!result.success) return { success: false, error: result.error } + return { success: true, sessions: result.sessions } + }, + toTranscript: (raw) => isWithMessages(raw) + ? piToTranscript(raw as PiLocalSessionWithMessages) + : piToTranscriptSummary(raw as PiLocalSessionSummary) + } +} + +export const OPENCODE_LOCAL_SESSION_SOURCE: HubLocalSessionSource = { + flavor: 'opencode', + displayName: 'OpenCode', + routeBase: 'opencode', + nativeIdKeys: ['opencodeSessionId'], + match: { strategy: 'anchored' }, + lifecycleOnCreate: 'archived', + batch: 'continue', + importLimit: 200, + requiredMachineCapability: MACHINE_CAPABILITIES.LocalSessionImport, + legacy: { + resultIdKey: 'opencodeSessionId', + async fetch({ engine, machineId, cwd, sessionIds }) { + const result = await engine.listOpencodeSessionsForMachine(machineId, cwd, sessionIds ?? undefined) + if (!result.success) return { success: false, error: result.error } + return { success: true, sessions: result.sessions } + }, + toTranscript: (raw) => isWithMessages(raw) + ? opencodeToTranscript(raw as OpencodeLocalSessionWithMessages) + : opencodeToTranscriptSummary(raw as OpencodeLocalSessionSummary) + } +} + +export const CLAUDE_LOCAL_SESSION_SOURCE: HubLocalSessionSource = { + flavor: 'claude', + displayName: 'Claude', + routeBase: 'claude', + nativeIdKeys: ['claudeSessionId', 'claudeSessionIdHistory'], + match: { strategy: 'anchored', canonicalContent: claudeCanonicalContent }, + lifecycleOnCreate: 'archived', + batch: 'continue', + importLimit: 200, + localIdPrefix: 'claude:', + requiredMachineCapability: MACHINE_CAPABILITIES.LocalSessionImport +} + +export const CODEX_LOCAL_SESSION_SOURCE: HubLocalSessionSource = { + flavor: 'codex', + displayName: 'Codex', + routeBase: 'codex', + nativeIdKeys: ['codexSessionId', 'codexSourceSessionId'], + match: { strategy: 'contentPrefix', compareKey: codexCompareKey }, + lifecycleOnCreate: 'imported', + batch: 'stopOnFirstError', + importLimit: 200, + requiredMachineCapability: MACHINE_CAPABILITIES.LocalSessionImport, + requestMetadata: (body) => (body.yolo === true ? { preferredPermissionMode: 'yolo' } : {}), + legacy: { + resultIdKey: 'codexSessionId', + async fetch({ engine, machineId, cwd, sessionIds }) { + const result = await engine.listCodexSessionsForMachine(machineId, cwd, sessionIds ?? undefined) + if (!result.success) return { success: false, error: result.error } + return { success: true, sessions: result.sessions } + }, + toTranscript: (raw) => isWithMessages(raw) + ? codexToTranscript(raw as CodexLocalSessionWithMessages) + : codexToTranscriptSummary(raw as CodexLocalSessionSummary) + } +} \ No newline at end of file diff --git a/hub/src/web/routes/opencodeSessions.test.ts b/hub/src/web/routes/opencodeSessions.test.ts index 1024b050..77a65fd6 100644 --- a/hub/src/web/routes/opencodeSessions.test.ts +++ b/hub/src/web/routes/opencodeSessions.test.ts @@ -182,22 +182,22 @@ describe('OpenCode session import', () => { const first = transcript('native-delta', [ userMessage('native-delta', 'msg-1', 'one', 1_000) ]) - const initial = importOpencodeSession({ store, engine, namespace: 'default', machine: machine('machine-1'), transcript: first }) + const initial = await importOpencodeSession({ store, engine, namespace: 'default', machine: machine('machine-1'), transcript: first }) expect(initial).toMatchObject({ action: 'created', appended: 1 }) - const unchanged = importOpencodeSession({ store, engine, namespace: 'default', machine: machine('machine-1'), transcript: first }) + const unchanged = await importOpencodeSession({ store, engine, namespace: 'default', machine: machine('machine-1'), transcript: first }) expect(unchanged).toMatchObject({ action: 'unchanged', appended: 0 }) const extended = transcript('native-delta', [ userMessage('native-delta', 'msg-1', 'one', 1_000), userMessage('native-delta', 'msg-2', 'two', 2_000) ]) - const updated = importOpencodeSession({ store, engine, namespace: 'default', machine: machine('machine-1'), transcript: extended }) + const updated = await importOpencodeSession({ 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) }) - it('rolls back the full import when a message insert fails', () => { + it('rolls back the full import when a message insert fails', async () => { const { store, engine } = setup() const original = store.messages.addImportedMessage.bind(store.messages) let calls = 0 @@ -207,7 +207,7 @@ describe('OpenCode session import', () => { return original(...args) } - const result = importOpencodeSession({ + const result = await importOpencodeSession({ store, engine, namespace: 'default', @@ -222,12 +222,12 @@ describe('OpenCode session import', () => { expect(store.sessions.getSessionsByNamespace('default')).toHaveLength(0) }) - it('fails with transcript_diverged and keeps stored history intact on content change', () => { + it('fails with transcript_diverged and keeps stored history intact on content change', async () => { const { store, engine } = setup() const source = transcript('native-diverged', [ userMessage('native-diverged', 'msg-1', 'one', 1_000) ]) - const first = importOpencodeSession({ store, engine, namespace: 'default', machine: machine('machine-1'), transcript: source }) + const first = await importOpencodeSession({ store, engine, namespace: 'default', machine: machine('machine-1'), transcript: source }) const before = store.sessions.getSession(first.hapiSessionId!)! const rewritten = transcript('native-diverged', [ @@ -235,7 +235,7 @@ describe('OpenCode session import', () => { ]) rewritten.cwd = '/tmp/rejected-diverged' rewritten.title = 'Rejected divergent title' - const result = importOpencodeSession({ store, engine, namespace: 'default', machine: machine('machine-1'), transcript: rewritten }) + const result = await importOpencodeSession({ store, engine, namespace: 'default', machine: machine('machine-1'), transcript: rewritten }) expect(result.error?.code).toBe('transcript_diverged') expect(result.hapiSessionId).toBe(first.hapiSessionId) expect(store.messages.getAllMessages(first.hapiSessionId!)).toHaveLength(1) @@ -247,9 +247,9 @@ describe('OpenCode session import', () => { expect(after.metadataVersion).toBe(before.metadataVersion) }) - it('fails when new native entries are inserted ahead of the imported boundary', () => { + it('fails when new native entries are inserted ahead of the imported boundary', async () => { const { store, engine } = setup() - const first = importOpencodeSession({ + const first = await importOpencodeSession({ store, engine, namespace: 'default', @@ -261,7 +261,7 @@ describe('OpenCode session import', () => { }) expect(first).toMatchObject({ action: 'created' }) - const reordered = importOpencodeSession({ + const reordered = await importOpencodeSession({ store, engine, namespace: 'default', @@ -275,9 +275,9 @@ describe('OpenCode session import', () => { expect(reordered.error?.code).toBe('transcript_diverged') }) - it('fails closed when HAPI continuation happened after an import and native history advanced', () => { + it('fails closed when HAPI continuation happened after an import and native history advanced', async () => { const { store, engine } = setup() - const first = importOpencodeSession({ + const first = await importOpencodeSession({ store, engine, namespace: 'default', @@ -292,7 +292,7 @@ describe('OpenCode session import', () => { }, 'hapi-live-msg-1', 5_000) expect(continuation.inserted).toBe(true) - const extended = importOpencodeSession({ + const extended = await importOpencodeSession({ store, engine, namespace: 'default', @@ -530,9 +530,9 @@ describe('OpenCode session import', () => { expect(response.status).toBe(400) }) - it('fails with session_active when the target session is active and new messages exist', () => { + it('fails with session_active when the target session is active and new messages exist', async () => { const { store, engine } = setup() - const first = importOpencodeSession({ + const first = await importOpencodeSession({ store, engine, namespace: 'default', @@ -549,7 +549,7 @@ describe('OpenCode session import', () => { extended.cwd = '/tmp/rejected-active' extended.title = 'Rejected active title' - const result = importOpencodeSession({ + const result = await importOpencodeSession({ store, engine, namespace: 'default', @@ -567,11 +567,11 @@ describe('OpenCode session import', () => { it('fails closed when a captured existing session disappears before import', async () => { const { store, engine } = setup() const source = transcript('native-disappeared', [userMessage('native-disappeared', 'msg-1', 'one', 1_000)]) - const first = importOpencodeSession({ store, engine, namespace: 'default', machine: machine('machine-1'), transcript: source }) + const first = await importOpencodeSession({ store, engine, namespace: 'default', machine: machine('machine-1'), transcript: source }) const stale = store.sessions.getSession(first.hapiSessionId!)! await store.sessions.deleteSession(stale.id, 'default') - const result = importOpencodeSession({ + const result = await importOpencodeSession({ store, engine, namespace: 'default', diff --git a/hub/src/web/routes/opencodeSessions.ts b/hub/src/web/routes/opencodeSessions.ts index 26381c4f..19632cd0 100644 --- a/hub/src/web/routes/opencodeSessions.ts +++ b/hub/src/web/routes/opencodeSessions.ts @@ -1,18 +1,14 @@ -import { dirname } from 'node:path' -import { isDeepStrictEqual } from 'node:util' import { Hono } from 'hono' import { MAX_OPENCODE_SESSION_IMPORTS } from '@hapi/protocol/apiTypes' import type { OpencodeLocalSessionSummary, OpencodeLocalSessionWithMessages } from '@hapi/protocol/apiTypes' import { isPermissionModeAllowedForFlavor } from '@hapi/protocol/modes' import type { PermissionMode } from '@hapi/protocol/modes' -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 { opencodeToTranscript } from '@hapi/protocol/localTranscript' +import type { Store, StoredSession } from '../../store' import type { Machine, SyncEngine } from '../../sync/syncEngine' import type { WebAppEnv } from '../middleware/auth' - -const importLocks = new Map>() +import { importLocalTranscript, type LocalImportLaunchConfig } from './localSessions/importLocalTranscript' +import { OPENCODE_LOCAL_SESSION_SOURCE } from './localSessions/sources' export type OpencodeSessionListItem = OpencodeLocalSessionSummary & { hapiSessionId?: string @@ -32,18 +28,16 @@ function asRecord(value: unknown): Record | null { : null } -function storedMetadata(session: StoredSession): Record { - return asRecord(session.metadata) ?? {} -} - function resolveOpencodeMachine( engine: SyncEngine | null, namespace: string, - requestedMachineId?: string | null + requestedMachineId: string | null ): Machine | null { if (!engine) return null const online = engine.getOnlineMachinesByNamespace(namespace) - if (requestedMachineId) return online.find((machine) => machine.id === requestedMachineId) ?? null + if (requestedMachineId) { + return online.find((machine) => machine.id === requestedMachineId) ?? null + } return online[0] ?? null } @@ -52,222 +46,48 @@ function importedOpencodeSessionsById( namespace: string, machineId: string ): Map { - const importedByOpencodeId = new Map() + const imported = new Map() for (const session of store.sessions.getSessionsByNamespace(namespace)) { - const metadata = storedMetadata(session) - const opencodeSessionId = metadata.opencodeSessionId - if (metadata.flavor !== 'opencode' - || metadata.machineId !== machineId - || typeof opencodeSessionId !== 'string' - || importedByOpencodeId.has(opencodeSessionId)) continue - importedByOpencodeId.set(opencodeSessionId, session) + const metadata = asRecord(session.metadata) + if (metadata?.flavor !== 'opencode' || metadata.machineId !== machineId) continue + if (typeof metadata.opencodeSessionId !== 'string' || imported.has(metadata.opencodeSessionId)) continue + imported.set(metadata.opencodeSessionId, session) } - return importedByOpencodeId + return imported } -function findImportedOpencodeSession( - store: Store, - namespace: string, - machineId: string, - opencodeSessionId: string -): StoredSession | null { - return importedOpencodeSessionsById(store, namespace, machineId).get(opencodeSessionId) ?? null -} - -function buildOpencodeMetadata( - transcript: OpencodeLocalSessionWithMessages, - machine: Machine, - existing: Record -): Metadata { - const summaryText = transcript.lastUserMessage ?? transcript.title - 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: 'opencode', - opencodeSessionId: 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 : 'opencode-import', - archiveReason: typeof existing.archiveReason === 'string' ? existing.archiveReason : 'Imported from local OpenCode history' - } -} - -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 OpenCode import metadata') - } - throw new Error('OpenCode 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 classifyImportDelta( - existing: StoredMessage[], - transcript: OpencodeLocalSessionWithMessages -): { messages: OpencodeLocalSessionWithMessages['messages']; error?: string } { - const sourceByLocalId = new Map(transcript.messages.map((message) => [ - message.localId, - truncateOversizedMessageContent(message.content) - ])) - const sourceIds = transcript.messages.map((message) => message.localId) - const storedImported = existing - .filter((message) => message.localId?.startsWith(importedPrefix(transcript.id))) - for (let index = 0; index < storedImported.length; index += 1) { - if (sourceIds[index] !== storedImported[index]!.localId) { - return { messages: [], error: `Local OpenCode transcript changed or dropped imported entry ${storedImported[index]!.localId}` } - } - } - for (const message of storedImported) { - const source = sourceByLocalId.get(message.localId!) - if (!source || !isDeepStrictEqual(source, message.content)) { - return { messages: [], error: `Local OpenCode transcript changed or dropped imported entry ${message.localId}` } - } - } - const imported = new Set(storedImported.map((message) => message.localId!)) - const delta = transcript.messages.filter((message) => !imported.has(message.localId)) - if (existing.length > storedImported.length && delta.length > 0) { - return { messages: [], error: 'The HAPI session continued past the imported history; re-importing would duplicate or reorder messages' } - } - return { messages: delta } -} - -function importedPrefix(sessionId: string): string { - return `opencode:${sessionId}:` -} - -export function importOpencodeSession(options: { +/** + * Import one OpenCode transcript through the generic importer. The generic + * route path is importLocalTranscript directly; this wrapper routes the + * legacy route through the same locked async envelope so the request launch + * config applies inside the per-native-session lock (a config failure comes + * back as a per-session config_failed result). + */ +export async function importOpencodeSession(options: { store: Store engine: SyncEngine namespace: string machine: Machine transcript: OpencodeLocalSessionWithMessages existingSession?: StoredSession | null -}): OpencodeImportResult { - const { store, engine, namespace, machine, transcript, existingSession } = options - let stored: StoredSession | null = existingSession === undefined - ? findImportedOpencodeSession(store, namespace, machine.id, transcript.id) - : existingSession - try { - const committed = store.runInTransaction(() => { - const created = !stored - if (stored) { - const current = store.sessions.getSessionByNamespace(stored.id, namespace) - if (!current) throw new Error('Imported HAPI session disappeared') - stored = current - } else { - stored = store.sessions.getOrCreateSession( - `opencode-import:${machine.id}:${transcript.id}`, - buildOpencodeMetadata(transcript, machine, {}), - {}, - namespace - ) - } - - const delta = classifyImportDelta(store.messages.getAllMessages(stored.id), transcript) - if (delta.error) { - return { - result: { - opencodeSessionId: transcript.id, - hapiSessionId: stored.id, - error: { code: 'transcript_diverged', message: delta.error } - } satisfies OpencodeImportResult, - appended: [] as StoredMessage[] - } - } - if (stored.active && delta.messages.length > 0) { - return { - result: { - opencodeSessionId: transcript.id, - hapiSessionId: stored.id, - appended: 0, - error: { code: 'session_active', message: 'The HAPI OpenCode session is active; stop it before importing native history changes' } - } satisfies OpencodeImportResult, - appended: [] as StoredMessage[] - } - } - - const appended: StoredMessage[] = [] - 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) - } - updateMetadataWithRetry(store, stored.id, namespace, (metadata) => buildOpencodeMetadata(transcript, machine, metadata)) - return { - result: { - opencodeSessionId: transcript.id, - hapiSessionId: stored.id, - action: created ? 'created' : appended.length > 0 ? 'updated' : 'unchanged', - appended: appended.length - } satisfies OpencodeImportResult, - appended - } - }) - if (committed.result.error) return committed.result - const activityAt = committed.appended.at(-1)?.createdAt ?? transcript.modifiedAt - engine.recordSessionActivity(committed.result.hapiSessionId!, activityAt) - emitImportedMessages(engine, committed.result.hapiSessionId!, committed.appended) - engine.handleRealtimeEvent({ type: 'session-updated', sessionId: committed.result.hapiSessionId! }) - return committed.result - } catch (error) { - const message = error instanceof Error ? error.message : 'Failed to persist imported OpenCode history' - const code = error instanceof ImportedMessageConflictError ? 'transcript_diverged' : 'import_failed' - const surviving = stored ? store.sessions.getSessionByNamespace(stored.id, namespace) : null - return { - opencodeSessionId: transcript.id, - ...(surviving ? { hapiSessionId: surviving.id } : {}), - error: { code, message } - } - } -} - -async function importWithLock(key: string, work: () => Promise | OpencodeImportResult): Promise { - const prior = importLocks.get(key) ?? Promise.resolve() - let release!: () => void - const gate = new Promise((resolve) => { release = resolve }) - const current = prior.catch(() => {}).then(() => gate) - importLocks.set(key, current) - await prior.catch(() => {}) - try { - return await work() - } finally { - release() - if (importLocks.get(key) === current) importLocks.delete(key) + launch?: LocalImportLaunchConfig +}): Promise { + const outcome = await importLocalTranscript({ + store: options.store, + engine: options.engine, + namespace: options.namespace, + source: OPENCODE_LOCAL_SESSION_SOURCE, + transcript: opencodeToTranscript(options.transcript), + machine: options.machine, + ...(options.launch ? { request: { launch: options.launch } } : {}), + ...(options.existingSession !== undefined ? { existingSession: options.existingSession } : {}) + }) + return { + opencodeSessionId: outcome.sessionId, + ...(outcome.hapiSessionId !== undefined ? { hapiSessionId: outcome.hapiSessionId } : {}), + ...(outcome.action !== undefined ? { action: outcome.action } : {}), + ...(outcome.appended !== undefined ? { appended: outcome.appended } : {}), + ...(outcome.error !== undefined ? { error: outcome.error } : {}) } } @@ -329,14 +149,14 @@ export function createOpencodeSessionRoutes(options: { return c.json({ success: false, error: 'Invalid permission mode for OpenCode sessions', results: [] }, 400) } type LaunchConfig = Parameters[1] - const launchConfig: LaunchConfig = {} + const launch: LocalImportLaunchConfig = {} const hasLaunchKey = (key: string): boolean => Object.prototype.hasOwnProperty.call(body ?? {}, key) // Property presence matters: applySessionConfig only resets a persisted // value when the key is present, so explicit nulls / 'default' must be // preserved to clear stale selections on re-import. - if (hasLaunchKey('model')) launchConfig.model = requestedModel - if (hasLaunchKey('modelReasoningEffort')) launchConfig.modelReasoningEffort = requestedModelReasoningEffort - if (hasLaunchKey('permissionMode')) launchConfig.permissionMode = (requestedPermissionMode ?? 'default') as PermissionMode + if (hasLaunchKey('model')) launch.model = requestedModel + if (hasLaunchKey('modelReasoningEffort')) launch.modelReasoningEffort = requestedModelReasoningEffort + if (hasLaunchKey('permissionMode')) launch.permissionMode = (requestedPermissionMode ?? 'default') as PermissionMode const results: OpencodeImportResult[] = [] for (const sessionId of uniqueSessionIds) { const transcript = byId.get(sessionId) @@ -344,33 +164,21 @@ export function createOpencodeSessionRoutes(options: { results.push({ opencodeSessionId: sessionId, error: { code: 'not_found', message: 'OpenCode session transcript not found' } }) continue } - const result = await importWithLock(`${namespace}:${machine.id}:${sessionId}`, async () => { - const imported = importOpencodeSession({ - store: options.store, - engine, - namespace, - machine, - transcript - }) - if (!imported.error && imported.hapiSessionId && Object.keys(launchConfig).length > 0) { - // The transcript is already persisted here; a config failure - // must stay scoped to this session's result instead of turning - // into an unstructured 500 that aborts the rest of a bulk run. - try { - await engine.applySessionConfig(imported.hapiSessionId, launchConfig) - } catch (error) { - imported.error = { - code: 'config_failed', - message: error instanceof Error ? error.message : 'Failed to apply OpenCode launch config' - } - } - } - return imported + // Import + config apply run inside the importer's per-native-session + // lock, so a concurrent import of the same transcript waits for the + // whole envelope instead of racing the launch-config writes. + const imported = await importOpencodeSession({ + store: options.store, + engine, + namespace, + machine, + transcript, + ...(Object.keys(launch).length > 0 ? { launch } : {}) }) - results.push(result) + results.push(imported) } return c.json({ success: results.every((result) => !result.error), results, machineId: machine.id }) }) return app -} +} \ No newline at end of file diff --git a/hub/src/web/routes/piSessions.ts b/hub/src/web/routes/piSessions.ts index a622f5e6..b61497a5 100644 --- a/hub/src/web/routes/piSessions.ts +++ b/hub/src/web/routes/piSessions.ts @@ -1,15 +1,11 @@ -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 { piToTranscript } from '@hapi/protocol/localTranscript' +import type { Store, StoredSession } from '../../store' import type { Machine, SyncEngine } from '../../sync/syncEngine' import type { WebAppEnv } from '../middleware/auth' - -const importLocks = new Map>() +import { runLocalImportSync } from './localSessions/importLocalTranscript' +import { PI_LOCAL_SESSION_SOURCE } from './localSessions/sources' export type PiSessionListItem = PiLocalSessionSummary & { hapiSessionId?: string @@ -37,182 +33,36 @@ function storedMetadata(session: StoredSession): Record { function resolvePiMachine( engine: SyncEngine | null, namespace: string, - requestedMachineId?: string | null + requestedMachineId: string | null ): Machine | null { if (!engine) return null const online = engine.getOnlineMachinesByNamespace(namespace) - if (requestedMachineId) return online.find((machine) => machine.id === requestedMachineId) ?? null + 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() + const imported = 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) + if (metadata.flavor !== 'pi' || metadata.machineId !== machineId) continue + if (typeof metadata.piSessionId !== 'string' || imported.has(metadata.piSessionId)) continue + imported.set(metadata.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 }) + return imported } +/** + * Import one Pi transcript through the generic importer. The + * generic route path is importLocalTranscript directly; this wrapper stays + * synchronous for the legacy route, which never passes request launch config. + */ export function importPiSession(options: { store: Store engine: SyncEngine @@ -221,129 +71,21 @@ export function importPiSession(options: { 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 }) + const outcome = runLocalImportSync({ + store: options.store, + engine: options.engine, + namespace: options.namespace, + source: PI_LOCAL_SESSION_SOURCE, + transcript: piToTranscript(options.transcript), + machine: options.machine, + ...(options.existingSession !== undefined ? { existingSession: options.existingSession } : {}) + }) 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) + piSessionId: outcome.sessionId, + ...(outcome.hapiSessionId !== undefined ? { hapiSessionId: outcome.hapiSessionId } : {}), + ...(outcome.action !== undefined ? { action: outcome.action } : {}), + ...(outcome.appended !== undefined ? { appended: outcome.appended } : {}), + ...(outcome.error !== undefined ? { error: outcome.error } : {}) } } @@ -403,17 +145,17 @@ export function createPiSessionRoutes(options: { results.push({ piSessionId: sessionId, error: { code: 'not_found', message: 'Pi session transcript not found' } }) continue } - results.push(await importWithLock(`${namespace}:${machine.id}:${sessionId}`, () => importPiSession({ + results.push(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 -} +} \ No newline at end of file diff --git a/hub/src/web/server.ts b/hub/src/web/server.ts index 28aede1e..75907e44 100644 --- a/hub/src/web/server.ts +++ b/hub/src/web/server.ts @@ -27,8 +27,8 @@ import { createActivityRoutes } from './routes/activity' import { createGitRoutes } from './routes/git' import { createCliRoutes } from './routes/cli' import { createCodexDesktopRoutes } from './routes/codexDesktop' -import { createPiSessionRoutes } from './routes/piSessions' -import { createOpencodeSessionRoutes } from './routes/opencodeSessions' +import { createLocalSessionRoutes } from './routes/localSessions/createLocalSessionRoutes' +import { PI_LOCAL_SESSION_SOURCE, OPENCODE_LOCAL_SESSION_SOURCE, CLAUDE_LOCAL_SESSION_SOURCE } from './routes/localSessions/sources' import { createPushRoutes } from './routes/push' import { createDevicesRoutes } from './routes/devices' import { createVoiceRoutes } from './routes/voice' @@ -302,13 +302,14 @@ function createWebApp(options: { store: options.store, getSyncEngine: options.getSyncEngine })) - app.route('/api', createPiSessionRoutes({ + // Local-session import registry: one generic route pair per mounted source + // (Pi, OpenCode, Claude); the generic importer owns target matching, + // atomic persistence and launch config. Codex stays on its desktop route + // to keep the sidecar capabilities and the Codex wire schema separate. + app.route('/api', createLocalSessionRoutes({ store: options.store, - getSyncEngine: options.getSyncEngine - })) - app.route('/api', createOpencodeSessionRoutes({ - store: options.store, - getSyncEngine: options.getSyncEngine + getSyncEngine: options.getSyncEngine, + sources: [PI_LOCAL_SESSION_SOURCE, OPENCODE_LOCAL_SESSION_SOURCE, CLAUDE_LOCAL_SESSION_SOURCE] })) app.route('/api', createPushRoutes(options.store, options.vapidPublicKey)) app.route('/api', createDevicesRoutes(options.store)) diff --git a/shared/package.json b/shared/package.json index 67e631ca..bc69b3c4 100644 --- a/shared/package.json +++ b/shared/package.json @@ -8,6 +8,7 @@ "exports": { ".": "./src/index.ts", "./apiTypes": "./src/apiTypes.ts", + "./localTranscript": "./src/localTranscript.ts", "./messages": "./src/messages.ts", "./slashCommands": "./src/slashCommands.ts", "./buildInfo": "./src/buildInfo.ts", diff --git a/shared/src/apiTypes.ts b/shared/src/apiTypes.ts index 8b6226d1..1e38c302 100644 --- a/shared/src/apiTypes.ts +++ b/shared/src/apiTypes.ts @@ -357,13 +357,55 @@ export const OpencodeLocalSessionSummarySchema = z.object({ lastUserMessage: z.string().nullable().optional(), cwd: z.string().nullable().optional(), file: z.string().min(1), - modifiedAt: z.number() + modifiedAt: z.number(), + /** v2 launch hint (D8): the model the session ran with. */ + model: z.string().nullable().optional() }) export const OpencodeLocalSessionWithMessagesSchema = OpencodeLocalSessionSummarySchema.extend({ messages: z.array(OpencodeImportedMessageSchema) }) +/** + * One importable Claude transcript entry: the native uuid (stable across + * session-id rotation), the entry timestamp and the HAPI message content the + * live replay path would have sent (user text, or the raw entry as the + * 'output' agent payload). + */ +export const ClaudeImportedMessageSchema = z.object({ + uuid: z.string().min(1), + createdAt: z.number().optional(), + content: z.union([ + z.object({ + role: z.literal('user'), + content: z.object({ type: z.literal('text'), text: z.string() }), + meta: z.object({ sentFrom: z.literal('cli') }) + }), + z.object({ + role: z.literal('agent'), + content: z.object({ type: z.literal('output'), data: z.unknown() }), + meta: z.object({ sentFrom: z.literal('cli') }) + }) + ]) +}) + +export const ClaudeLocalSessionSummarySchema = 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(), + messageCount: z.number().optional() +}) + +export const ClaudeLocalSessionWithMessagesSchema = ClaudeLocalSessionSummarySchema.extend({ + messages: z.array(ClaudeImportedMessageSchema) +}) + +export type ClaudeLocalSessionSummary = z.infer +export type ClaudeLocalSessionWithMessages = z.infer + export const MAX_OPENCODE_SESSION_IMPORTS = 200 export const ListOpencodeSessionsRpcRequestSchema = z.object({ diff --git a/shared/src/codexTranscript.test.ts b/shared/src/codexTranscript.test.ts new file mode 100644 index 00000000..4dbe4e66 --- /dev/null +++ b/shared/src/codexTranscript.test.ts @@ -0,0 +1,148 @@ +import { describe, expect, it } from 'bun:test' +import { + deduplicateCodexTranscriptMessages, + shouldIgnoreInjectedResponseUserMessage, + type CodexImportedMessageEntry, + type CodexImportedMessageSource +} from './codexTranscript' + +function userEntry(source: CodexImportedMessageSource, text: string): CodexImportedMessageEntry { + return { + source, + message: { + role: 'user', + content: { type: 'text', text }, + meta: { sentFrom: 'cli' } + } + } +} + +function agentEntry(source: CodexImportedMessageSource, text: string, id: string): CodexImportedMessageEntry { + return { + source, + message: { + role: 'agent', + content: { + type: 'codex', + data: { type: 'message', message: text, id } + }, + meta: { sentFrom: 'cli' } + } + } +} + +function toolCallEntry(source: CodexImportedMessageSource, callId: string): CodexImportedMessageEntry { + return { + source, + message: { + role: 'agent', + content: { + type: 'codex', + data: { type: 'tool-call', name: 'read_file', callId, id: `tool-${callId}` } + }, + meta: { sentFrom: 'cli' } + } + } +} + +function userTexts(entries: CodexImportedMessageEntry[]): string[] { + return deduplicateCodexTranscriptMessages(entries).map((message) => { + if (message.role !== 'user') throw new Error('Expected a user message') + return message.content.text + }) +} + +describe('shouldIgnoreInjectedResponseUserMessage', () => { + it('ignores injected AGENTS.md instruction blocks', () => { + expect(shouldIgnoreInjectedResponseUserMessage('# AGENTS.md instructions for /repo\nignore')).toBe(true) + expect(shouldIgnoreInjectedResponseUserMessage('# agents.md instructions for /repo')).toBe(true) + }) + + it('ignores a closed environment context block', () => { + expect(shouldIgnoreInjectedResponseUserMessage('\n2026-07-07\n')).toBe(true) + expect(shouldIgnoreInjectedResponseUserMessage('\n')).toBe(true) + }) + + it('keeps real prompts that only mention the injected markers', () => { + expect(shouldIgnoreInjectedResponseUserMessage('normal user message')).toBe(false) + expect(shouldIgnoreInjectedResponseUserMessage('Please inspect this transcript block:\n\n\nThis is part of my prompt.')).toBe(false) + expect(shouldIgnoreInjectedResponseUserMessage('\n2026-07-07')).toBe(false) + }) +}) + +describe('deduplicateCodexTranscriptMessages', () => { + it('collapses a mirrored user pair regardless of the source order', () => { + expect(userTexts([ + userEntry('event_msg', 'mirrored user message'), + userEntry('response_item', 'mirrored user message\n') + ])).toEqual(['mirrored user message']) + + expect(userTexts([ + userEntry('response_item', 'mirrored user message\n'), + userEntry('event_msg', 'mirrored user message') + ])).toEqual(['mirrored user message']) + }) + + it('collapses a mirrored agent pair even when the ids differ', () => { + const messages = deduplicateCodexTranscriptMessages([ + agentEntry('event_msg', 'duplicated assistant message', 'event-id'), + agentEntry('response_item', 'duplicated assistant message', 'response-id') + ]) + expect(messages).toHaveLength(1) + expect(messages[0]).toEqual({ + role: 'agent', + content: { + type: 'codex', + data: { type: 'message', message: 'duplicated assistant message', id: 'event-id' } + }, + meta: { sentFrom: 'cli' } + }) + }) + + it('keeps adjacent duplicates that come from the same source', () => { + expect(userTexts([ + userEntry('response_item', 'same source user message'), + userEntry('response_item', 'same source user message') + ])).toEqual(['same source user message', 'same source user message']) + + const messages = deduplicateCodexTranscriptMessages([ + agentEntry('response_item', 'same source assistant message', 'first-id'), + agentEntry('response_item', 'same source assistant message', 'second-id') + ]) + expect(messages).toHaveLength(2) + }) + + it('keeps a later response_item user turn that repeats earlier text', () => { + const messages = deduplicateCodexTranscriptMessages([ + userEntry('event_msg', 'repeat user message'), + userEntry('response_item', 'repeat user message'), + agentEntry('response_item', 'assistant answer', 'assistant-id'), + userEntry('response_item', 'repeat user message') + ]) + expect(messages.map((message) => message.role)).toEqual(['user', 'agent', 'user']) + }) + + it('keeps distinct user turns while collapsing mirrored user events', () => { + expect(userTexts([ + userEntry('event_msg', 'first user message'), + userEntry('response_item', 'first user message'), + userEntry('event_msg', 'second user message') + ])).toEqual(['first user message', 'second user message']) + }) + + it('drops every response_item copy of the most recent event user message', () => { + expect(userTexts([ + userEntry('event_msg', 'repeat user message'), + userEntry('response_item', 'repeat user message'), + userEntry('response_item', 'repeat user message') + ])).toEqual(['repeat user message']) + }) + + it('keeps adjacent tool call messages because they are not assistant prose', () => { + const messages = deduplicateCodexTranscriptMessages([ + toolCallEntry('response_item', 'call-1'), + toolCallEntry('response_item', 'call-1') + ]) + expect(messages).toHaveLength(2) + }) +}) diff --git a/shared/src/codexTranscript.ts b/shared/src/codexTranscript.ts new file mode 100644 index 00000000..8ebff560 --- /dev/null +++ b/shared/src/codexTranscript.ts @@ -0,0 +1,155 @@ +import { AGENT_MESSAGE_PAYLOAD_TYPE } from './modes' + +function asRecord(value: unknown): Record | null { + return value !== null && typeof value === 'object' && !Array.isArray(value) ? value as Record : null +} + +export type CodexImportedMessageSource = 'event_msg' | 'response_item' + +export type CodexImportedMessageContent = { + role: 'user' + content: { + type: 'text' + text: string + } + meta: { + sentFrom: 'cli' + } +} | { + role: 'agent' + content: { + type: typeof AGENT_MESSAGE_PAYLOAD_TYPE + data: unknown + } + meta: { + sentFrom: 'cli' + } +} + +export type CodexImportedMessageEntry = { + source: CodexImportedMessageSource + message: CodexImportedMessageContent +} + +/** + * Codex injects its own context as a synthetic user turn inside a + * `response_item`. Those turns are not something the operator typed, so they + * must not show up as chat messages. + * + * Only a `response_item` is filtered: an `event_msg` user message is always a + * real operator turn, even when it happens to start with the same marker. + */ +export function shouldIgnoreInjectedResponseUserMessage(text: string): boolean { + const normalized = text.trim() + const lower = normalized.toLowerCase() + const isAgentInstructions = lower.startsWith('# agents.md instructions') + const isEnvironmentContext = lower.startsWith('') + && lower.endsWith('') + return isAgentInstructions || isEnvironmentContext +} + +function stableSerialize(value: unknown): string { + if (value === null || typeof value !== 'object') return JSON.stringify(value) + if (Array.isArray(value)) return `[${value.map(stableSerialize).join(',')}]` + const record = value as Record + return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${stableSerialize(record[key])}`).join(',')}}` +} + +function normalizeComparableUserMessage(content: unknown): string | null { + const record = asRecord(content) + if (!record || record.role !== 'user') return null + + const body = asRecord(record.content) + if (body?.type !== 'text' || typeof body.text !== 'string') return null + + return stableSerialize({ + role: 'user', + text: body.text.trimEnd() + }) +} + +function normalizeComparableAgentMessage(content: unknown): string | null { + const record = asRecord(content) + if (!record || record.role !== 'agent') return null + + const body = asRecord(record.content) + if (!body || body.type !== AGENT_MESSAGE_PAYLOAD_TYPE) return null + + const data = asRecord(body.data) + if (data?.type !== 'message' || typeof data.message !== 'string') return null + + return stableSerialize({ + role: 'agent', + type: 'message', + message: data.message + }) +} + +function normalizeAdjacentDuplicateMessage(content: unknown): string | null { + return normalizeComparableUserMessage(content) ?? normalizeComparableAgentMessage(content) +} + +function isAdjacentDuplicateImportedMessage( + previous: CodexImportedMessageContent, + next: CodexImportedMessageContent +): boolean { + const previousKey = normalizeAdjacentDuplicateMessage(previous) + const nextKey = normalizeAdjacentDuplicateMessage(next) + return previousKey !== null && previousKey === nextKey +} + +function isMirroredAdjacentDuplicate( + previous: CodexImportedMessageEntry | undefined, + next: CodexImportedMessageEntry +): boolean { + return Boolean( + previous + && previous.source !== next.source + && isAdjacentDuplicateImportedMessage(previous.message, next.message) + ) +} + +function isResponseItemDuplicateOfEventUserMessage( + entry: CodexImportedMessageEntry, + recentEventUserMessageKey: string | null +): boolean { + if (entry.source !== 'response_item' || recentEventUserMessageKey === null) return false + + return normalizeComparableUserMessage(entry.message) === recentEventUserMessageKey +} + +/** + * Collapse the mirrored copies Codex writes into its transcripts. + * + * A single operator turn is recorded twice: once as an `event_msg` and once as + * a `response_item`. Only that mirrored pair may be folded - two identical + * messages that come from the same source are two real turns and are kept. + */ +export function deduplicateCodexTranscriptMessages(entries: CodexImportedMessageEntry[]): CodexImportedMessageContent[] { + const deduped: CodexImportedMessageEntry[] = [] + let recentEventUserMessageKey: string | null = null + + for (const entry of entries) { + const userMessageKey = normalizeComparableUserMessage(entry.message) + if (entry.source === 'event_msg' && userMessageKey !== null) { + const previous = deduped[deduped.length - 1] + if (previous?.source === 'response_item' && isMirroredAdjacentDuplicate(previous, entry)) { + deduped[deduped.length - 1] = entry + } else { + deduped.push(entry) + } + recentEventUserMessageKey = userMessageKey + continue + } + if (isResponseItemDuplicateOfEventUserMessage(entry, recentEventUserMessageKey)) continue + const previous = deduped[deduped.length - 1] + if (isMirroredAdjacentDuplicate(previous, entry)) { + recentEventUserMessageKey = null + continue + } + deduped.push(entry) + recentEventUserMessageKey = null + } + + return deduped.map((entry) => entry.message) +} diff --git a/shared/src/index.ts b/shared/src/index.ts index 818ec420..e58b72d6 100644 --- a/shared/src/index.ts +++ b/shared/src/index.ts @@ -2,6 +2,7 @@ export * from './peerSpawnDefaults' export * from './scratchlistAttachments' export * from './workGraph' export * from './apiTypes' +export * from './codexTranscript' export * from './cursorCliSku' export * from './messages' export * from './buildInfo' diff --git a/shared/src/localTranscript.test.ts b/shared/src/localTranscript.test.ts new file mode 100644 index 00000000..f1786182 --- /dev/null +++ b/shared/src/localTranscript.test.ts @@ -0,0 +1,218 @@ +import { describe, expect, it } from 'bun:test' +import type { + ClaudeLocalSessionWithMessages, + CodexLocalSessionWithMessages, + OpencodeLocalSessionWithMessages, + PiLocalSessionWithMessages +} from './apiTypes' +import { + ListLocalSessionsRpcResponseSchema, + LocalTranscriptSchema, + claudeToTranscript, + codexToTranscript, + opencodeToTranscript, + piToTranscript +} from './localTranscript' + +const piSession: PiLocalSessionWithMessages = { + id: 'pi-1', + title: 'Pi session', + lastUserMessage: 'second question', + cwd: '/tmp/project', + file: '/tmp/pi-1.jsonl', + modifiedAt: 1_234, + model: 'gemini-3.8-flash', + thinkingLevel: 'low', + leafEntryId: 'entry-3', + messageCount: 3, + messages: [ + { + localId: 'pi:pi-1:entry-1:user', + entryId: 'entry-1', + parentEntryId: null, + createdAt: 1_000, + content: { role: 'user', content: { type: 'text', text: 'first question' }, meta: { sentFrom: 'cli' } } + }, + { + localId: 'pi:pi-1:entry-2:0', + entryId: 'entry-2', + parentEntryId: 'entry-1', + createdAt: 1_100, + content: { + role: 'agent', + content: { type: 'codex', data: { type: 'message', message: 'answer one', id: 'pi:pi-1:entry-2:0' } }, + meta: { sentFrom: 'cli' } + } + }, + { + localId: 'pi:pi-1:entry-3:user', + entryId: 'entry-3', + parentEntryId: 'entry-2', + createdAt: 1_200, + content: { role: 'user', content: { type: 'text', text: 'second question' }, meta: { sentFrom: 'cli' } } + } + ], + activeEntryIds: ['entry-1', 'entry-2', 'entry-3'] +} + +const opencodeSession: OpencodeLocalSessionWithMessages = { + id: 'ses_1', + title: 'OpenCode session', + lastUserMessage: 'fix the bug', + cwd: '/tmp/project', + file: '/tmp/opencode.db', + modifiedAt: 2_000, + messages: [ + { + localId: 'opencode:ses_1:msg-1:part-1', + createdAt: 2_100, + content: { role: 'user', content: { type: 'text', text: 'fix the bug' }, meta: { sentFrom: 'cli' } } + }, + { + localId: 'opencode:ses_1:msg-2:part-1', + createdAt: 2_200, + content: { + role: 'agent', + content: { type: 'codex', data: { type: 'message', message: 'on it', id: 'part-1' } }, + meta: { sentFrom: 'cli' } + } + } + ] +} + +const codexSession: CodexLocalSessionWithMessages = { + id: 'thread-1', + title: 'Codex session', + lastUserMessage: 'run the tests', + cwd: '/tmp/project', + file: '/tmp/thread-1.jsonl', + modifiedAt: 3_000, + originator: 'codex-cli', + cliVersion: '1.2.3', + source: 'vscode', + threadSource: 'local', + forkedFromId: null, + messages: [ + { role: 'user', content: { type: 'text', text: 'run the tests' }, meta: { sentFrom: 'cli' } }, + { + role: 'agent', + content: { type: 'codex', data: { type: 'message', message: 'running', id: 'generated' } }, + meta: { sentFrom: 'cli' } + } + ] +} + +describe('local transcript mappers', () => { + it('maps Pi sessions with anchors, cursor and launch hints', () => { + const transcript = piToTranscript(piSession) + expect(transcript.flavor).toBe('pi') + expect(transcript.id).toBe('pi-1') + expect(transcript.messages.map((message) => message.id)).toEqual([ + 'pi:pi-1:entry-1:user', + 'pi:pi-1:entry-2:0', + 'pi:pi-1:entry-3:user' + ]) + expect(transcript.messages.map((message) => message.anchor)).toEqual(['entry-1', 'entry-2', 'entry-3']) + expect(transcript.messages.filter((message) => message.content.role === 'user').map((message) => message.historyPoint)) + .toEqual(['entry-1', 'entry-3']) + expect(transcript.anchorOrder).toEqual(['entry-1', 'entry-2', 'entry-3']) + expect(transcript.cursor).toBe('entry-3') + expect(transcript.launch).toEqual({ model: 'gemini-3.8-flash', effort: 'low' }) + expect(transcript.extra).toEqual({ + model: 'gemini-3.8-flash', + thinkingLevel: 'low', + leafEntryId: 'entry-3' + }) + expect(transcript.messageCount).toBe(3) + expect(LocalTranscriptSchema.parse(transcript)).toBeDefined() + }) + + it('maps OpenCode sessions without anchors or cursor', () => { + const transcript = opencodeToTranscript(opencodeSession) + expect(transcript.flavor).toBe('opencode') + expect(transcript.messages.map((message) => message.id)).toEqual([ + 'opencode:ses_1:msg-1:part-1', + 'opencode:ses_1:msg-2:part-1' + ]) + expect(transcript.messages.every((message) => message.anchor === undefined)).toBe(true) + expect(transcript.anchorOrder).toBeUndefined() + expect(transcript.cursor).toBeUndefined() + expect(transcript.launch).toBeUndefined() + expect(transcript.extra).toBeUndefined() + expect(transcript.messageCount).toBeUndefined() + expect(LocalTranscriptSchema.parse(transcript)).toBeDefined() + }) + + it('carries the opencode v2 model as a launch hint (D8)', () => { + const withModel = opencodeToTranscript({ ...opencodeSession, model: 'gpt-5.6' }) + expect(withModel.launch).toEqual({ model: 'gpt-5.6' }) + // A null/absent v2 model must not produce an empty launch envelope. + expect(opencodeToTranscript({ ...opencodeSession, model: null }).launch).toBeUndefined() + expect(opencodeToTranscript(opencodeSession).launch).toBeUndefined() + }) + + it('maps Codex messages to indexed ids without createdAt', () => { + const transcript = codexToTranscript(codexSession) + expect(transcript.flavor).toBe('codex') + expect(transcript.messages.map((message) => message.id)).toEqual([ + 'codex-desktop:thread-1:0', + 'codex-desktop:thread-1:1' + ]) + expect(transcript.messages.every((message) => message.createdAt === undefined)).toBe(true) + expect(transcript.extra).toEqual({ + originator: 'codex-cli', + cliVersion: '1.2.3', + source: 'vscode', + threadSource: 'local', + forkedFromId: null + }) + expect(LocalTranscriptSchema.parse(transcript)).toBeDefined() + }) + + it('maps Claude sessions to uuid-keyed ids without cursor or launch hints', () => { + const claudeSession: ClaudeLocalSessionWithMessages = { + id: '06992c9a-1111-2222-3333-444455556666', + title: 'Claude session', + lastUserMessage: 'run the e2e', + cwd: '/tmp/project', + file: '/tmp/.claude/projects/p/06992c9a.jsonl', + modifiedAt: 4_000, + messageCount: 2, + messages: [ + { + uuid: 'uuid-1', + createdAt: Date.parse('2026-11-13T00:00:00.000Z'), + content: { role: 'user', content: { type: 'text', text: 'run the e2e' }, meta: { sentFrom: 'cli' } } + }, + { + uuid: 'uuid-2', + createdAt: Date.parse('2026-11-13T00:00:05.000Z'), + content: { role: 'agent', content: { type: 'output', data: { type: 'assistant', uuid: 'uuid-2' } }, meta: { sentFrom: 'cli' } } + } + ] + } + const transcript = claudeToTranscript(claudeSession) + expect(transcript.flavor).toBe('claude') + expect(transcript.messages.map((message) => message.id)).toEqual(['claude:uuid-1', 'claude:uuid-2']) + expect(transcript.messages.map((message) => message.anchor)).toEqual(['uuid-1', 'uuid-2']) + expect(transcript.messages.map((message) => message.createdAt)).toEqual([ + Date.parse('2026-11-13T00:00:00.000Z'), + Date.parse('2026-11-13T00:00:05.000Z') + ]) + // Rotated session ids must not leak into the row ids: the session id + // is deliberately excluded so a resumed session still lines up. + expect(transcript.messages.every((message) => !message.id.includes(claudeSession.id))).toBe(true) + expect(transcript.anchorOrder).toBeUndefined() + expect(transcript.cursor).toBeUndefined() + expect(transcript.launch).toBeUndefined() + expect(LocalTranscriptSchema.parse(transcript)).toBeDefined() + }) + + it('parses the ListLocalSessions RPC response envelope', () => { + expect(ListLocalSessionsRpcResponseSchema.parse({ + success: true, + sessions: [piToTranscript(piSession), opencodeToTranscript(opencodeSession)] + }).success).toBe(true) + expect(ListLocalSessionsRpcResponseSchema.parse({ success: false, error: 'nope' }).success).toBe(false) + }) +}) \ No newline at end of file diff --git a/shared/src/localTranscript.ts b/shared/src/localTranscript.ts new file mode 100644 index 00000000..406ee1b4 --- /dev/null +++ b/shared/src/localTranscript.ts @@ -0,0 +1,265 @@ +import { z } from 'zod' +import { + CodexImportedMessageSchema, + CodexLocalSessionSummarySchema, + CodexLocalSessionWithMessagesSchema, + type ClaudeLocalSessionSummary, + type ClaudeLocalSessionWithMessages, + type OpencodeLocalSessionSummary, + type OpencodeLocalSessionWithMessages, + type PiLocalSessionSummary, + type PiLocalSessionWithMessages +} from './apiTypes' + +/** + * Normalized local-session transcript contract (import registry). + * + * Sources (Codex, Pi, OpenCode, Claude) only convert their native history + * into this shape; the generic hub importer owns target lookup, delta + * computation, persistence and lifecycle. CLI readers and the hub's legacy + * runner fallbacks both produce these transcripts so both paths converge on + * the same result. + */ + +export const LOCAL_SESSION_FLAVORS = ['codex', 'pi', 'opencode', 'claude'] as const + +export type LocalSessionFlavor = typeof LOCAL_SESSION_FLAVORS[number] + +export const MAX_LOCAL_SESSION_IMPORTS = 200 + +export const LocalImportedMessageContentSchema = z.union([ + CodexImportedMessageSchema, + // Claude agent turns arrive as their own payload envelope; the web chat + // normalizer renders the 'output' flavor like the live Claude replay does. + z.object({ + role: z.literal('agent'), + content: z.object({ type: z.literal('output'), data: z.unknown() }), + meta: z.object({ sentFrom: z.literal('cli') }) + }) +]) + +export type LocalImportedMessageContent = z.infer + +export const LocalTranscriptMessageSchema = z.object({ + /** Stable per-message id; doubles as the hub-side stored localId. */ + id: z.string().min(1), + /** Absent -> the import stamps the import time (Codex records carry none). */ + createdAt: z.number().optional(), + content: LocalImportedMessageContentSchema, + /** Native position marker (Pi entry id, Claude uuid). */ + anchor: z.string().min(1).optional(), + /** Native fork boundary recorded for user messages (Pi user entries). */ + historyPoint: z.string().min(1).optional() +}) + +export type LocalTranscriptMessage = z.infer + +export const LocalTranscriptSummarySchema = z.object({ + flavor: z.enum(LOCAL_SESSION_FLAVORS), + 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(), + messageCount: z.number().int().nonnegative().optional(), + /** Launch hints carried by the source (Pi model/thinkingLevel, OpenCode v2 model). */ + launch: z.object({ + model: z.string().nullable().optional(), + effort: z.string().nullable().optional() + }).optional(), + /** Flavor-only display fields, flattened into list responses unchanged. */ + extra: z.record(z.string(), z.union([z.string(), z.number(), z.null()])).optional() +}) + +export type LocalTranscriptSummary = z.infer + +export const LocalTranscriptSchema = LocalTranscriptSummarySchema.extend({ + messages: z.array(LocalTranscriptMessageSchema), + /** Ordered native anchors of the active branch (Pi activeEntryIds). */ + anchorOrder: z.array(z.string().min(1)).optional(), + /** Native fork cursor (Pi leafEntryId). */ + cursor: z.string().nullable().optional() +}) + +export type LocalTranscript = z.infer + +export const ListLocalSessionsRpcRequestSchema = z.object({ + flavor: z.enum(LOCAL_SESSION_FLAVORS), + cwd: z.string().nullable().optional(), + sessionIds: z.array(z.string().min(1)).max(MAX_LOCAL_SESSION_IMPORTS).optional() +}) + +export const ListLocalSessionsRpcResponseSchema = z.union([ + z.object({ + success: z.literal(true), + sessions: z.array(z.union([LocalTranscriptSchema, LocalTranscriptSummarySchema])) + }), + z.object({ success: z.literal(false), error: z.string() }) +]) + +export type ListLocalSessionsRpcRequest = z.infer +export type ListLocalSessionsRpcResponse = z.infer + +/** Codex source shapes (apiTypes exports the schemas only). */ +export type CodexLocalSessionSummary = z.infer +export type CodexLocalSessionWithMessages = z.infer + +// --------------------------------------------------------------------------- +// Pure mappers: source shapes -> normalized transcripts. +// --------------------------------------------------------------------------- + +function transcriptSummaryBase(parts: { + flavor: LocalSessionFlavor + id: string + title: string + lastUserMessage?: string | null + cwd?: string | null + file: string + modifiedAt: number + messageCount?: number + launch?: LocalTranscriptSummary['launch'] + extra?: LocalTranscriptSummary['extra'] +}): LocalTranscriptSummary { + return { + flavor: parts.flavor, + id: parts.id, + title: parts.title, + lastUserMessage: parts.lastUserMessage ?? null, + cwd: parts.cwd ?? null, + file: parts.file, + modifiedAt: parts.modifiedAt, + ...(parts.messageCount !== undefined ? { messageCount: parts.messageCount } : {}), + ...(parts.launch ? { launch: parts.launch } : {}), + ...(parts.extra ? { extra: parts.extra } : {}) + } +} + +// -- Codex ------------------------------------------------------------------ + +export function codexToTranscriptSummary(session: CodexLocalSessionSummary): LocalTranscriptSummary { + return transcriptSummaryBase({ + flavor: 'codex', + id: session.id, + title: session.title, + lastUserMessage: session.lastUserMessage ?? null, + cwd: session.cwd ?? null, + file: session.file, + modifiedAt: session.modifiedAt, + extra: { + originator: session.originator ?? null, + cliVersion: session.cliVersion ?? null, + source: session.source ?? null, + threadSource: session.threadSource ?? null, + forkedFromId: session.forkedFromId ?? null + } + }) +} + +export function codexToTranscript(session: CodexLocalSessionWithMessages): LocalTranscript { + return { + ...codexToTranscriptSummary(session), + // No createdAt: Codex transcripts carry no per-record timestamps, so + // the importer stamps the import time (existing hub behavior). + messages: session.messages.map((content, index) => ({ + id: `codex-desktop:${session.id}:${index}`, + content + })) + } +} + +// -- Claude ------------------------------------------------------------------- + +export function claudeToTranscriptSummary(session: ClaudeLocalSessionSummary): LocalTranscriptSummary { + return transcriptSummaryBase({ + flavor: 'claude', + id: session.id, + title: session.title, + lastUserMessage: session.lastUserMessage ?? null, + cwd: session.cwd ?? null, + file: session.file, + modifiedAt: session.modifiedAt, + messageCount: session.messageCount + }) +} + +/** + * Claude transcript entries keep their native uuid as the local id suffix; the + * session id is deliberately excluded so a resumed (rotated) session id still + * lines up with the previously imported rows. + */ +export function claudeToTranscript(session: ClaudeLocalSessionWithMessages): LocalTranscript { + return { + ...claudeToTranscriptSummary(session), + messages: session.messages.map((message) => ({ + id: `claude:${message.uuid}`, + ...(message.createdAt !== undefined ? { createdAt: message.createdAt } : {}), + content: message.content, + anchor: message.uuid + })) + } +} + +// -- Pi --------------------------------------------------------------------- + +export function piToTranscriptSummary(session: PiLocalSessionSummary): LocalTranscriptSummary { + return transcriptSummaryBase({ + flavor: 'pi', + id: session.id, + title: session.title, + lastUserMessage: session.lastUserMessage ?? null, + cwd: session.cwd ?? null, + file: session.file, + modifiedAt: session.modifiedAt, + messageCount: session.messageCount, + launch: { model: session.model ?? null, effort: session.thinkingLevel ?? null }, + extra: { + model: session.model ?? null, + thinkingLevel: session.thinkingLevel ?? null, + leafEntryId: session.leafEntryId ?? null + } + }) +} + +export function piToTranscript(session: PiLocalSessionWithMessages): LocalTranscript { + return { + ...piToTranscriptSummary(session), + messages: session.messages.map((message) => ({ + id: message.localId, + createdAt: message.createdAt, + content: message.content, + anchor: message.entryId, + ...(message.content.role === 'user' ? { historyPoint: message.entryId } : {}) + })), + anchorOrder: [...session.activeEntryIds], + cursor: session.leafEntryId ?? null + } +} + +// -- OpenCode --------------------------------------------------------------- + +export function opencodeToTranscriptSummary(session: OpencodeLocalSessionSummary): LocalTranscriptSummary { + return transcriptSummaryBase({ + flavor: 'opencode', + id: session.id, + title: session.title, + lastUserMessage: session.lastUserMessage ?? null, + cwd: session.cwd ?? null, + file: session.file, + modifiedAt: session.modifiedAt, + // v2 sessions carry the model they ran with (D8); only a real value + // becomes a launch hint so an absent column stays launchless. + ...(session.model ? { launch: { model: session.model } } : {}) + }) +} + +export function opencodeToTranscript(session: OpencodeLocalSessionWithMessages): LocalTranscript { + return { + ...opencodeToTranscriptSummary(session), + messages: session.messages.map((message) => ({ + id: message.localId, + createdAt: message.createdAt, + content: message.content + })) + } +} \ No newline at end of file diff --git a/shared/src/rpcMethods.ts b/shared/src/rpcMethods.ts index d3dac04c..5e5a695e 100644 --- a/shared/src/rpcMethods.ts +++ b/shared/src/rpcMethods.ts @@ -48,6 +48,7 @@ export const RPC_METHODS = { ListCodexModels: 'listCodexModels', ListPiModelsForMachine: 'listPiModelsForMachine', ListCodexSessions: 'listCodexSessions', + ListLocalSessions: 'listLocalSessions', ArchiveCodexSession: 'archiveCodexSession', ListCursorModels: 'listCursorModels', ListPiModels: 'listPiModels', diff --git a/shared/src/runnerCapabilities.ts b/shared/src/runnerCapabilities.ts index 39c41a71..6ea0a379 100644 --- a/shared/src/runnerCapabilities.ts +++ b/shared/src/runnerCapabilities.ts @@ -37,6 +37,8 @@ export const MACHINE_CAPABILITIES = { UsageQuery: RPC_METHODS.UsageQuery, /** Read-only file/Git/search RPCs available on the long-lived runner. */ WorkspaceFileAccess: 'workspace-file-access', + /** Normalized local-session import transcripts via ListLocalSessions. */ + LocalSessionImport: 'local-session-import', } as const export type MachineCapability = @@ -51,6 +53,7 @@ export const CURRENT_MACHINE_CAPABILITIES: readonly MachineCapability[] = [ MACHINE_CAPABILITIES.StopRunner, MACHINE_CAPABILITIES.UsageQuery, MACHINE_CAPABILITIES.WorkspaceFileAccess, + MACHINE_CAPABILITIES.LocalSessionImport, ] /** diff --git a/web/src/api/client.test.ts b/web/src/api/client.test.ts index e8ecdeca..662c68b4 100644 --- a/web/src/api/client.test.ts +++ b/web/src/api/client.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { AuthProxyRedirectError } from './authProxy' -import { ApiClient, ApiError } from './client' +import { ApiClient, ApiError, apiErrorMessage } from './client' describe('ApiClient error mapping', () => { let originalFetch: typeof globalThis.fetch @@ -12,6 +12,17 @@ describe('ApiClient error mapping', () => { globalThis.fetch = fetchMock as unknown as typeof globalThis.fetch }) + it('apiErrorMessage unwraps the hub error string and falls back cleanly', () => { + const body = '{"success":false,"error":"No online machine available for Pi history import"}' + const error = new ApiError(`HTTP 503 Service Unavailable: ${body}`, 503, 'No online machine available for Pi history import', body) + expect(apiErrorMessage(error, 'Failed to load local sessions')).toBe('No online machine available for Pi history import') + // No parseable body: the raw envelope must not leak; use the fallback. + expect(apiErrorMessage(new ApiError('HTTP 400 Bad Request: not json', 400), 'fallback')).toBe('fallback') + // Plain Errors keep their message; non-Errors use the fallback. + expect(apiErrorMessage(new Error('boom'), 'fallback')).toBe('boom') + expect(apiErrorMessage(undefined, 'fallback')).toBe('fallback') + }) + it('passes an optional maxBytes bound to session file reads', async () => { fetchMock.mockResolvedValueOnce( new Response(JSON.stringify({ success: true, content: '' }), { status: 200 }) diff --git a/web/src/api/client.ts b/web/src/api/client.ts index 9de1e5f4..33076bb3 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -19,6 +19,8 @@ import type { MachinesResponse, MessageContextResponse, MessagesResponse, + ClaudeImportSessionsResponse, + ClaudeLocalSessionsResponse, OpencodeImportSessionsResponse, OpencodeLocalSessionsResponse, PermissionMode, @@ -212,6 +214,27 @@ function parseErrorCode(bodyText: string): string | undefined { } } +function parseErrorDisplay(bodyText: string): string | undefined { + try { + const parsed = JSON.parse(bodyText) as ErrorPayload + if (typeof parsed.error === 'string' && parsed.error.trim().length > 0) return parsed.error + return undefined + } catch { + return undefined + } +} + +/** + * User-facing message for a failed API call: unwrap the hub's human error + * string instead of leaking the raw `HTTP : ` envelope. + */ +export function apiErrorMessage(error: unknown, fallback: string): string { + if (!(error instanceof ApiError)) { + return error instanceof Error && error.message.trim().length > 0 ? error.message : fallback + } + return parseErrorDisplay(error.body ?? '') ?? error.code?.trim() ?? fallback +} + export class ApiError extends Error { status: number code?: string @@ -473,6 +496,21 @@ export class ApiClient { }) } + async getClaudeSessions(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/claude/sessions${query}`) + } + + async importClaudeSessions(payload: { sessionIds: string[]; cwd?: string | null; machineId?: string | null; model?: string | null; effort?: string | null; permissionMode?: PermissionMode }): Promise { + return await this.request('/api/claude/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/ClaudeSessionImportDialog.tsx b/web/src/components/ClaudeSessionImportDialog.tsx new file mode 100644 index 00000000..5cce5e65 --- /dev/null +++ b/web/src/components/ClaudeSessionImportDialog.tsx @@ -0,0 +1,45 @@ +import type { LocalSessionListItem } from '@/lib/localSessionImport' +import { useTranslation } from '@/lib/use-translation' +import { LocalSessionImportDialog } from '@/components/LocalSessionImportDialog' + +/** Claude-flavored wrapper around the generic import dialog. */ +export function ClaudeSessionImportDialog(props: { + isOpen: boolean + onClose: () => void + sessions: LocalSessionListItem[] + currentSessionId: string | null + currentWorkDirectory?: string | null + onConfirm: (sessionIds: string[]) => Promise + isPending: boolean + isLoading: boolean +}) { + const { t } = useTranslation() + return ( + + ) +} \ No newline at end of file diff --git a/web/src/components/LocalSessionImportDialog.test.tsx b/web/src/components/LocalSessionImportDialog.test.tsx new file mode 100644 index 00000000..3f14d45b --- /dev/null +++ b/web/src/components/LocalSessionImportDialog.test.tsx @@ -0,0 +1,192 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react' +import { describe, expect, it, vi } from 'vitest' +import { LocalSessionImportDialog } from './LocalSessionImportDialog' +import type { LocalSessionListItem } from '@/lib/localSessionImport' + +vi.mock('@/components/ui/dialog', async (importOriginal) => await importOriginal()) +vi.mock('@/lib/use-translation', () => ({ + useTranslation: () => ({ t: (key: string) => key }) +})) + +const labels = { + title: 'Import sessions', + description: 'Pick local sessions', + concurrentWarning: 'Careful with concurrent processes', + loading: 'Scanning…', + empty: 'Nothing here', + selectedCount: '{n} selected', + clearAll: 'Clear all', + selectAll: 'Select all', + allDirectories: 'All directories', + search: 'Search', + imported: 'Imported', + needsAttention: 'Needs attention', + messages: 'messages', + importing: 'Importing…', + confirm: 'Import', + cancel: 'Cancel' +} + +function session(overrides: Partial = {}): LocalSessionListItem { + return { + id: 'pi-1', + title: 'Pi session', + lastUserMessage: 'hello there', + cwd: '/tmp/project', + file: '/tmp/pi-1.jsonl', + modifiedAt: 1_700_000_000_000, + messageCount: 3, + model: 'gemini-3.8-flash', + hapiSessionId: 'hapi-existing', + ...overrides + } +} + +describe('LocalSessionImportDialog', () => { + it('renders flattened flavor fields, selection count and confirms with selected ids', async () => { + const onConfirm = vi.fn().mockResolvedValue(undefined) + render( + {}} + sessions={[session(), session({ id: 'pi-2', title: 'Second session', cwd: '/tmp/other', hapiSessionId: undefined })]} + labels={labels} + onConfirm={onConfirm} + isPending={false} + isLoading={false} + /> + ) + expect(screen.getByText('Pi session')).toBeTruthy() + expect(screen.getAllByText('Imported').length).toBe(1) + fireEvent.click(screen.getByText('Pi session').closest('label') as HTMLLabelElement) + fireEvent.click(screen.getByRole('button', { name: 'Import' })) + await waitFor(() => expect(onConfirm).toHaveBeenCalledWith(['pi-1'])) + }) + + it('filters by directory and search text', () => { + render( + {}} + sessions={[session(), session({ id: 'pi-2', title: 'Other project', cwd: '/tmp/other' })]} + labels={labels} + onConfirm={vi.fn()} + isPending={false} + isLoading={false} + /> + ) + fireEvent.change(screen.getByPlaceholderText('Search'), { target: { value: 'other project' } }) + expect(screen.getByText('Other project')).toBeTruthy() + expect(screen.queryByText('Pi session')).toBeNull() + }) + + it('keeps the selection and search while open when the session list refreshes', async () => { + const onConfirm = vi.fn().mockResolvedValue(undefined) + const { rerender } = render( + {}} + sessions={[session()]} + labels={labels} + onConfirm={onConfirm} + isPending={false} + isLoading={false} + /> + ) + fireEvent.click(screen.getByText('Pi session').closest('label') as HTMLLabelElement) + fireEvent.change(screen.getByPlaceholderText('Search'), { target: { value: 'hello' } }) + + // A background refresh lands while the dialog stays open: the + // directories list changes, which must not wipe the in-progress picks. + rerender( + {}} + sessions={[session(), session({ id: 'pi-2', title: 'Second session', cwd: '/tmp/other' })]} + labels={labels} + onConfirm={onConfirm} + isPending={false} + isLoading={false} + /> + ) + expect((screen.getByPlaceholderText('Search') as HTMLInputElement).value).toBe('hello') + fireEvent.click(screen.getByRole('button', { name: 'Import' })) + await waitFor(() => expect(onConfirm).toHaveBeenCalledWith(['pi-1'])) + }) + + it('filters to the current work directory once the first scan arrives', async () => { + const onConfirm = vi.fn().mockResolvedValue(undefined) + const props = { + isOpen: true, + onClose: () => {}, + labels, + currentWorkDirectory: '/tmp/project', + onConfirm, + isPending: false + } + // The dialog opens while the scan is still running. + const { rerender } = render() + const scanned = [ + session({ hapiSessionId: undefined }), + session({ id: 'pi-2', title: 'Other project session', cwd: '/tmp/other', hapiSessionId: undefined }) + ] + rerender() + + expect(screen.queryByText('Other project session')).toBeNull() + fireEvent.click(screen.getByRole('button', { name: 'Select all' })) + fireEvent.click(screen.getByRole('button', { name: 'Import' })) + await waitFor(() => expect(onConfirm).toHaveBeenCalledWith(['pi-1'])) + }) + + it('keeps a directory filter the user changed when the list refreshes', () => { + const props = { + isOpen: true, + onClose: () => {}, + labels, + currentWorkDirectory: '/tmp/project', + onConfirm: vi.fn(), + isPending: false, + isLoading: false + } + const scanned = [ + session({ hapiSessionId: undefined }), + session({ id: 'pi-2', title: 'Other project session', cwd: '/tmp/other', hapiSessionId: undefined }) + ] + const { rerender } = render() + expect(screen.queryByText('Other project session')).toBeNull() + + fireEvent.change(screen.getByDisplayValue('/tmp/project'), { target: { value: '__all__' } }) + expect(screen.getByText('Other project session')).toBeTruthy() + + rerender() + expect(screen.getByText('Other project session')).toBeTruthy() + expect(screen.getByText('Newer session')).toBeTruthy() + }) + + it('shows the loading and empty states', () => { + const { rerender } = render( + {}} + sessions={[]} + labels={labels} + onConfirm={vi.fn()} + isPending={false} + isLoading + /> + ) + expect(screen.getByText('Scanning…')).toBeTruthy() + rerender( + {}} + sessions={[]} + labels={labels} + onConfirm={vi.fn()} + isPending={false} + isLoading={false} + /> + ) + expect(screen.getByText('Nothing here')).toBeTruthy() + }) +}) \ No newline at end of file diff --git a/web/src/components/LocalSessionImportDialog.tsx b/web/src/components/LocalSessionImportDialog.tsx new file mode 100644 index 00000000..1172bebc --- /dev/null +++ b/web/src/components/LocalSessionImportDialog.tsx @@ -0,0 +1,185 @@ +import { useEffect, useMemo, useRef, useState } from 'react' +import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog' +import { Button } from '@/components/ui/button' +import { SelectControl } from '@/components/ui/select-control' +import type { LocalSessionListItem } from '@/lib/localSessionImport' + +/** Visible labels; callers map their flavor locale keys onto these. */ +export type LocalSessionImportDialogLabels = { + title: string + description: string + concurrentWarning?: string + loading: string + empty: string + selectedCount: string + clearAll: string + selectAll: string + allDirectories: string + search: string + imported: string + needsAttention?: string + messages?: string + importing: string + confirm: string + cancel: string +} + +const ALL_DIRECTORIES = '__all__' + +/** + * Generic import dialog: identical behavior for every flavor — + * filter by directory and text, select multiple native sessions, import. + */ +export function LocalSessionImportDialog(props: { + isOpen: boolean + onClose: () => void + sessions: LocalSessionListItem[] + labels: LocalSessionImportDialogLabels + currentSessionId?: string | null + currentWorkDirectory?: string | null + onConfirm: (sessionIds: string[]) => Promise + isPending: boolean + isLoading: boolean +}) { + const labels = props.labels + const [selectedIds, setSelectedIds] = useState([]) + const [directory, setDirectory] = useState(ALL_DIRECTORIES) + const [query, setQuery] = useState('') + const wasOpenRef = useRef(false) + const directoryChosenRef = useRef(false) + + 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) { + wasOpenRef.current = false + return + } + // Initialize once per open transition: a sessions refresh while the + // dialog is open changes `directories` and must not wipe in-progress + // picks. + if (wasOpenRef.current) return + wasOpenRef.current = true + directoryChosenRef.current = false + setSelectedIds(props.currentSessionId ? [props.currentSessionId] : []) + setDirectory(ALL_DIRECTORIES) + setQuery('') + }, [props.currentSessionId, props.isOpen]) + + useEffect(() => { + // The default directory filter needs the scanned directories: the + // dialog usually opens while the scan is still running, so pick it + // once the first scan completes (the current work directory when it + // has sessions, all directories otherwise) and never override a + // filter the user already changed. + if (!props.isOpen || props.isLoading || directoryChosenRef.current) return + directoryChosenRef.current = true + const cwd = props.currentWorkDirectory?.trim() + setDirectory(cwd && directories.includes(cwd) ? cwd : ALL_DIRECTORIES) + }, [directories, props.currentWorkDirectory, props.isLoading, props.isOpen]) + + const chooseDirectory = (value: string) => { + directoryChosenRef.current = true + setDirectory(value) + } + + 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()}> + + + {labels.title} + {labels.description} + +
+ {labels.concurrentWarning ? ( +
+ {labels.concurrentWarning} +
+ ) : null} +
+ {labels.selectedCount.replace('{n}', String(selectedIds.length))} +
+ + +
+
+ {props.sessions.length > 0 ? ( +
+ chooseDirectory(event.target.value)}> + + {directories.map((value) => )} + + setQuery(event.target.value)} + /> +
+ ) : null} +
+ {props.isLoading ? ( +
{labels.loading}
+ ) : filtered.length === 0 ? ( +
{labels.empty}
+ ) : ( +
+ {filtered.map((session) => { + const checked = selectedIds.includes(session.id) + return ( + + ) + })} +
+ )} +
+
+ + +
+
+
+
+ ) +} \ No newline at end of file diff --git a/web/src/components/NewSession/ClaudeImportActions.test.tsx b/web/src/components/NewSession/ClaudeImportActions.test.tsx new file mode 100644 index 00000000..d77bd950 --- /dev/null +++ b/web/src/components/NewSession/ClaudeImportActions.test.tsx @@ -0,0 +1,26 @@ +import { fireEvent, render, screen } from '@testing-library/react' +import { describe, expect, it, vi } from 'vitest' +import { ClaudeImportActions } from './ClaudeImportActions' + +vi.mock('@/lib/use-translation', () => ({ + useTranslation: () => ({ t: (key: string) => key }) +})) + +describe('ClaudeImportActions', () => { + it('opens the local Claude history picker', () => { + const onChooseHistory = vi.fn() + render( + + ) + + fireEvent.click(screen.getByRole('button', { name: 'claudeImport.inline.choose' })) + expect(onChooseHistory).toHaveBeenCalledOnce() + }) +}) \ No newline at end of file diff --git a/web/src/components/NewSession/ClaudeImportActions.tsx b/web/src/components/NewSession/ClaudeImportActions.tsx new file mode 100644 index 00000000..ab187277 --- /dev/null +++ b/web/src/components/NewSession/ClaudeImportActions.tsx @@ -0,0 +1,32 @@ +import type { LocalSessionListItem } from '@/lib/localSessionImport' +import { useTranslation } from '@/lib/use-translation' +import { LocalSessionImportActions } from './LocalSessionImportActions' + +/** Claude-flavored wrapper around the generic import actions strip. */ +export function ClaudeImportActions(props: { + selectedSession: LocalSessionListItem | null + isLoading: boolean + isDisabled: boolean + error: string | null + onChooseHistory: () => void + onClear: () => void +}) { + const { t } = useTranslation() + return ( + + ) +} \ No newline at end of file diff --git a/web/src/components/NewSession/LocalSessionImportActions.tsx b/web/src/components/NewSession/LocalSessionImportActions.tsx new file mode 100644 index 00000000..0b1870c2 --- /dev/null +++ b/web/src/components/NewSession/LocalSessionImportActions.tsx @@ -0,0 +1,49 @@ +import type { LocalSessionListItem } from '@/lib/localSessionImport' + +export type LocalSessionImportActionLabels = { + inlineTitle: string + inlineDescription: string + inlineClear: string + inlineChoose: string + loading: string +} + +/** Inline New Session strip for choosing a local session to import/continue. */ +export function LocalSessionImportActions(props: { + labels: LocalSessionImportActionLabels + selectedSession: LocalSessionListItem | null + isLoading: boolean + isDisabled: boolean + error: string | null + onChooseHistory: () => void + onClear: () => void +}) { + return ( +
+
+
+
{props.labels.inlineTitle}
+
+ {props.selectedSession ? props.selectedSession.title : props.labels.inlineDescription} +
+
+
+ {props.selectedSession ? ( + + ) : null} + +
+
+ {props.error ?
{props.error}
: null} +
+ ) +} \ No newline at end of file diff --git a/web/src/components/NewSession/OpencodeImportActions.tsx b/web/src/components/NewSession/OpencodeImportActions.tsx index 6d26d1a3..20e278c6 100644 --- a/web/src/components/NewSession/OpencodeImportActions.tsx +++ b/web/src/components/NewSession/OpencodeImportActions.tsx @@ -1,8 +1,10 @@ -import type { OpencodeLocalSessionSummary } from '@/types/api' +import type { LocalSessionListItem } from '@/lib/localSessionImport' import { useTranslation } from '@/lib/use-translation' +import { LocalSessionImportActions } from './LocalSessionImportActions' +/** OpenCode-flavored wrapper around the generic import actions strip. */ export function OpencodeImportActions(props: { - selectedSession: OpencodeLocalSessionSummary | null + selectedSession: LocalSessionListItem | null isLoading: boolean isDisabled: boolean error: string | null @@ -11,31 +13,20 @@ export function OpencodeImportActions(props: { }) { const { t } = useTranslation() return ( -
-
-
-
{t('opencodeSync.inline.title')}
-
- {props.selectedSession ? props.selectedSession.title : t('opencodeSync.inline.description')} -
-
-
- {props.selectedSession ? ( - - ) : null} - -
-
- {props.error ?
{props.error}
: null} -
+ ) -} +} \ No newline at end of file diff --git a/web/src/components/NewSession/PiImportActions.tsx b/web/src/components/NewSession/PiImportActions.tsx index d5927edb..24510309 100644 --- a/web/src/components/NewSession/PiImportActions.tsx +++ b/web/src/components/NewSession/PiImportActions.tsx @@ -1,8 +1,10 @@ -import type { PiLocalSessionSummary } from '@/types/api' +import type { LocalSessionListItem } from '@/lib/localSessionImport' import { useTranslation } from '@/lib/use-translation' +import { LocalSessionImportActions } from './LocalSessionImportActions' +/** Pi-flavored wrapper around the generic import actions strip. */ export function PiImportActions(props: { - selectedSession: PiLocalSessionSummary | null + selectedSession: LocalSessionListItem | null isLoading: boolean isDisabled: boolean error: string | null @@ -11,31 +13,20 @@ export function PiImportActions(props: { }) { 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} -
+ ) -} +} \ No newline at end of file diff --git a/web/src/components/NewSession/index.test.tsx b/web/src/components/NewSession/index.test.tsx index 2e0f6428..ed6d1315 100644 --- a/web/src/components/NewSession/index.test.tsx +++ b/web/src/components/NewSession/index.test.tsx @@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { act, fireEvent, render, screen, waitFor } from '@testing-library/react' import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import type { ReactElement } from 'react' -import type { ApiClient } from '@/api/client' +import { ApiError, type ApiClient } from '@/api/client' import type { AgentAvailabilityEntry, ClaudeModelSummary, Machine, PiModelSummary } from '@/types/api' import { queryKeys } from '@/lib/query-keys' import { saveNewSessionFormDraft } from './newSessionFormDraft' @@ -39,6 +39,7 @@ const mocks = vi.hoisted(() => ({ opencodeVariantsLoading: false, opencodeVariantsEnabled: false, piDialogSelection: ['pi-native-1'] as string[], + claudeDialogSelection: ['claude-native-1'] as string[], piModels: [] as PiModelSummary[], piModelsLoading: false, piModelsError: null as string | null, @@ -224,6 +225,13 @@ vi.mock('@/components/PiSessionImportDialog', () => ({ ) : null })) +vi.mock('@/components/ClaudeSessionImportDialog', () => ({ + ClaudeSessionImportDialog: (props: { isOpen: boolean; sessions: Array<{ id: string }>; onConfirm: (ids: string[]) => Promise }) => props.isOpen ? ( + + ) : null +})) vi.mock('./DirectorySection', () => ({ DirectorySection: () => null })) vi.mock('./MachineSelector', () => ({ MachineSelector: (props: { machines: Machine[]; machineId: string | null; isDisabled: boolean; onChange: (machineId: string) => void }) => ( @@ -1404,6 +1412,67 @@ describe('NewSession launch preferences', () => { expect(mocks.spawnSession).not.toHaveBeenCalled() }) + it('imports the selected Claude history with the chosen launch settings before reopening it', async () => { + savePreferredAgent('claude') + savePreferredLaunchSettings('machine-1', 'claude', { model: 'sonnet', cursorSelectedBase: 'auto', effort: 'high', modelReasoningEffort: 'default' }) + const calls: string[] = [] + const claudeApi = { + getClaudeSessions: vi.fn().mockResolvedValue({ + success: true, + machineId: 'machine-1', + sessions: [{ + id: 'claude-native-1', + title: 'Existing Claude session', + cwd: 'C:\\repo', + file: 'C:\\claude-native-1.jsonl', + modifiedAt: 1, + messageCount: 2 + }] + }), + importClaudeSessions: vi.fn().mockImplementation(async () => { + calls.push('import') + return { + success: true, + machineId: 'machine-1', + results: [{ claudeSessionId: 'claude-native-1', hapiSessionId: 'hapi-claude-1', action: 'created', appended: 2 }] + } + }), + reopenSession: vi.fn().mockImplementation(async () => { + calls.push('reopen') + return { ok: true, sessionId: 'hapi-claude-1', resumed: true } + }) + } as unknown as ApiClient + + renderWithQuery( + {}} + /> + ) + + fireEvent.click(screen.getByTestId('permission-mode-plan')) + fireEvent.click(screen.getByRole('button', { name: 'claudeImport.inline.choose' })) + await waitFor(() => expect(screen.getByTestId('select-claude-history')).toBeEnabled()) + fireEvent.click(screen.getByTestId('select-claude-history')) + fireEvent.click(screen.getByTestId('create')) + + await waitFor(() => expect(mocks.onSuccess).toHaveBeenCalledWith('hapi-claude-1')) + expect(claudeApi.importClaudeSessions).toHaveBeenCalledWith({ + sessionIds: ['claude-native-1'], + cwd: 'C:\\repo', + machineId: 'machine-1', + model: 'sonnet', + effort: 'high', + permissionMode: 'plan' + }) + expect(calls).toEqual(['import', 'reopen']) + expect(mocks.spawnSession).not.toHaveBeenCalled() + }) + it('discards a stale Pi scan after switching machines', async () => { savePreferredAgent('pi') mocks.piDialogSelection = ['pi-machine-b'] @@ -1525,6 +1594,51 @@ describe('NewSession launch preferences', () => { expect(mocks.addToast).toHaveBeenCalledWith(expect.objectContaining({ title: 'piImport.failed.title' })) }) + it('shows the hub error text, not the raw HTTP envelope, when a Pi bulk import 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().mockRejectedValue(new ApiError( + 'HTTP 503 Service Unavailable: {"success":false,"error":"Runner is offline"}', + 503, + undefined, + '{"success":false,"error":"Runner is offline"}' + )) + } as unknown as ApiClient + + renderWithQuery( + {}} + /> + ) + + 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.addToast).toHaveBeenCalledWith(expect.objectContaining({ + title: 'piImport.failed.title', + body: 'Runner is offline' + }))) + }) + 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 c2787b75..6281672a 100644 --- a/web/src/components/NewSession/index.tsx +++ b/web/src/components/NewSession/index.tsx @@ -1,6 +1,7 @@ import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react' import { useQuery } from '@tanstack/react-query' import type { ApiClient } from '@/api/client' +import { apiErrorMessage } from '@/api/client' import type { CodexDuplicateSessionGroup, CodexLocalSessionSummary, Machine, OpencodeLocalSessionSummary, PiLocalSessionSummary } from '@/types/api' import { CREATABLE_AGENT_FLAVORS, resolveHapiYoloPermissionMode, getAgyModelChoices, splitAgyModelSelection, getClaudeEffortLevelsForModel, resolveClaudeEffortForModel } from '@hapi/protocol' import type { AgentAvailabilityEntry, CodexCollaborationMode, GrokPermissionMode, PermissionMode, CopilotAgentMode } from '@hapi/protocol' @@ -55,6 +56,7 @@ import { CollaborationModeSelector } from './CollaborationModeSelector' import { CodexImportActions } from './CodexImportActions' import { PiImportActions } from './PiImportActions' import { OpencodeImportActions } from './OpencodeImportActions' +import { ClaudeImportActions } from './ClaudeImportActions' import { clearBatchImportedCodexSelection, resolveCodexImportRedirectSessionId } from './codexImportMerge' import { AgyModelSelector } from './AgyModelSelector' import { DirectorySection } from './DirectorySection' @@ -88,6 +90,9 @@ import { usesNativePermissionSelect, usesSharedPermissionModeState, LEGACY_YOLO_ import { CodexSessionSyncDialog } from '@/components/CodexSessionSyncDialog' import { PiSessionImportDialog } from '@/components/PiSessionImportDialog' import { OpencodeSessionImportDialog } from '@/components/OpencodeSessionImportDialog' +import { ClaudeSessionImportDialog } from '@/components/ClaudeSessionImportDialog' +import { useLocalSessionImport } from '@/hooks/useLocalSessionImport' +import type { LocalSessionImportApi, LocalSessionListItem } from '@/lib/localSessionImport' import { ConfirmDialog } from '@/components/ui/ConfirmDialog' import { formatRunnerSpawnError } from '../../utils/formatRunnerSpawnError' import { markCodexSessionsImported } from '@/lib/codexImportedSessions' @@ -186,24 +191,51 @@ export function NewSession(props: { const [codexImportError, setCodexImportError] = useState(null) const [isImportingCodexSession, setIsImportingCodexSession] = useState(false) const [isCodexImportDialogOpen, setIsCodexImportDialogOpen] = useState(false) - const [piImportSessions, setPiImportSessions] = useState([]) + const piImportApiAdapter = useMemo(() => ({ + getLocalSessions: (_flavor, cwd, adapterMachineId) => props.api.getPiSessions(cwd ?? null, adapterMachineId ?? null), + importLocalSessions: (_flavor, payload) => props.api.importPiSessions(payload) + }), [props.api]) + const piImport = useLocalSessionImport({ + api: piImportApiAdapter, + flavor: 'pi', + directory, + machineId, + auto: false + }) 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 [opencodeImportSessions, setOpencodeImportSessions] = useState([]) + const opencodeImportApiAdapter = useMemo(() => ({ + getLocalSessions: (_flavor, cwd, adapterMachineId) => props.api.getOpencodeSessions(cwd ?? null, adapterMachineId ?? null), + importLocalSessions: (_flavor, payload) => props.api.importOpencodeSessions(payload) + }), [props.api]) + const opencodeImport = useLocalSessionImport({ + api: opencodeImportApiAdapter, + flavor: 'opencode', + directory, + machineId, + auto: false + }) const [selectedOpencodeImportSessionId, setSelectedOpencodeImportSessionId] = useState(null) - const [opencodeImportMachineId, setOpencodeImportMachineId] = useState(null) - const [isLoadingOpencodeImportSessions, setIsLoadingOpencodeImportSessions] = useState(false) - const [opencodeImportError, setOpencodeImportError] = useState(null) const [isImportingOpencodeSession, setIsImportingOpencodeSession] = useState(false) const [isBulkImportingOpencodeSessions, setIsBulkImportingOpencodeSessions] = useState(false) const [isOpencodeImportDialogOpen, setIsOpencodeImportDialogOpen] = useState(false) - const opencodeLoadGenerationRef = useRef(0) + const claudeImportApiAdapter = useMemo(() => ({ + getLocalSessions: (_flavor, cwd, adapterMachineId) => props.api.getClaudeSessions(cwd ?? null, adapterMachineId ?? null), + importLocalSessions: (_flavor, payload) => props.api.importClaudeSessions(payload) + }), [props.api]) + const claudeImport = useLocalSessionImport({ + api: claudeImportApiAdapter, + flavor: 'claude', + directory, + machineId, + auto: false + }) + const [selectedClaudeImportSessionId, setSelectedClaudeImportSessionId] = useState(null) + const [isImportingClaudeSession, setIsImportingClaudeSession] = useState(false) + const [isBulkImportingClaudeSessions, setIsBulkImportingClaudeSessions] = useState(false) + const [isClaudeImportDialogOpen, setIsClaudeImportDialogOpen] = useState(false) const [isCreating, setIsCreating] = useState(false) const createInFlightRef = useRef(false) const [isBulkImportingCodexSessions, setIsBulkImportingCodexSessions] = useState(false) @@ -223,6 +255,8 @@ export function NewSession(props: { || isBulkImportingPiSessions || isImportingOpencodeSession || isBulkImportingOpencodeSessions + || isImportingClaudeSession + || isBulkImportingClaudeSessions ) const worktreeInputRef = useRef(null) const preserveRestoredDraftRef = useRef(false) @@ -1322,84 +1356,47 @@ export function NewSession(props: { setCodexImportSessions([]) setCodexImportMachineId(null) setSelectedCodexImportSessionId(null) - setCodexImportError(e instanceof Error ? e.message : t('codexSync.failed.body')) + setCodexImportError(apiErrorMessage(e, t('codexSync.failed.body'))) } finally { setIsLoadingCodexImportSessions(false) } }, [agent, machineId, props.api, trimmedDirectory, t]) + // Keep the inline selection consistent with the loaded session list: + // a refresh that drops or errors clears the stale pick. 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]) + setSelectedPiImportSessionId((current) => current && piImport.sessions.some((session) => session.id === current) ? current : null) + }, [piImport.sessions]) const formatPiImportError = useCallback((code?: string, message?: string): string => { if (code === 'transcript_diverged') return t('piImport.error.diverged') + if (code === 'already_in_hapi') return t('piImport.error.alreadyImported') if (code === 'session_active') return t('piImport.error.active') return message?.trim() || t('piImport.failed.body') }, [t]) + // Keep the inline selection consistent with the loaded session list: + // a refresh that drops or errors clears the stale pick. useEffect(() => { - opencodeLoadGenerationRef.current += 1 - setIsLoadingOpencodeImportSessions(false) - }, [agent, machineId, trimmedDirectory]) + setSelectedOpencodeImportSessionId((current) => current && opencodeImport.sessions.some((session) => session.id === current) ? current : null) + }, [opencodeImport.sessions]) - useEffect(() => () => { - opencodeLoadGenerationRef.current += 1 - }, []) + // Keep the inline selection consistent with the loaded session list: + // a refresh that drops or errors clears the stale pick. + useEffect(() => { + setSelectedClaudeImportSessionId((current) => current && claudeImport.sessions.some((session) => session.id === current) ? current : null) + }, [claudeImport.sessions]) - const loadOpencodeImportSessions = useCallback(async () => { - if (agent !== 'opencode' || !machineId) return - const generation = ++opencodeLoadGenerationRef.current - setIsLoadingOpencodeImportSessions(true) - setOpencodeImportError(null) - try { - const result = await props.api.getOpencodeSessions(trimmedDirectory || null, machineId) - if (generation !== opencodeLoadGenerationRef.current) return - if (!result.success) throw new Error(result.error) - setOpencodeImportSessions(result.sessions) - setOpencodeImportMachineId(result.machineId ?? machineId) - setSelectedOpencodeImportSessionId((current) => current && result.sessions.some((session) => session.id === current) ? current : null) - } catch (loadError) { - if (generation !== opencodeLoadGenerationRef.current) return - setOpencodeImportSessions([]) - setOpencodeImportMachineId(null) - setSelectedOpencodeImportSessionId(null) - setOpencodeImportError(loadError instanceof Error ? loadError.message : t('opencodeSync.failed.body')) - } finally { - if (generation === opencodeLoadGenerationRef.current) setIsLoadingOpencodeImportSessions(false) - } - }, [agent, machineId, props.api, trimmedDirectory, t]) + const formatClaudeImportError = useCallback((code?: string, message?: string): string => { + if (code === 'transcript_diverged') return t('claudeImport.error.diverged') + if (code === 'already_in_hapi') return t('claudeImport.error.alreadyImported') + if (code === 'session_active') return t('claudeImport.error.active') + return message?.trim() || t('claudeImport.failed.body') + }, [t]) const formatOpencodeImportError = useCallback((code?: string, message?: string): string => { if (code === 'transcript_diverged') return t('opencodeSync.error.diverged') + if (code === 'already_in_hapi') return t('opencodeSync.error.alreadyImported') if (code === 'session_active') return t('opencodeSync.error.active') return message?.trim() || t('opencodeSync.failed.body') }, [t]) @@ -1599,13 +1596,13 @@ export function NewSession(props: { ]) const handleBulkImportPiSessions = useCallback(async (sessionIds: string[]) => { - if (isBulkImportingPiSessions || isLoadingPiImportSessions) return + if (isBulkImportingPiSessions || piImport.isLoading) return setIsBulkImportingPiSessions(true) try { const result = await props.api.importPiSessions({ sessionIds, cwd: trimmedDirectory || null, - machineId: piImportMachineId ?? machineId + machineId: piImport.machineId ?? machineId }) const importedCount = result.results.filter((item) => item.hapiSessionId && !item.error).length const failed = result.results.filter((item) => item.error) @@ -1617,7 +1614,7 @@ export function NewSession(props: { url: '' }) await refetchSessions() - await loadPiImportSessions() + await piImport.refresh() } if (failed.length > 0) { const first = failed[0]!.error! @@ -1637,7 +1634,7 @@ export function NewSession(props: { } catch (importError) { addToast({ title: t('piImport.failed.title'), - body: importError instanceof Error ? importError.message : t('piImport.failed.body'), + body: apiErrorMessage(importError, t('piImport.failed.body')), sessionId: '', url: '' }) @@ -1648,10 +1645,10 @@ export function NewSession(props: { addToast, formatPiImportError, isBulkImportingPiSessions, - isLoadingPiImportSessions, - loadPiImportSessions, machineId, - piImportMachineId, + piImport.isLoading, + piImport.machineId, + piImport.refresh, props.api, refetchSessions, t, @@ -1659,13 +1656,13 @@ export function NewSession(props: { ]) const handleBulkImportOpencodeSessions = useCallback(async (sessionIds: string[]) => { - if (isBulkImportingOpencodeSessions || isLoadingOpencodeImportSessions) return + if (isBulkImportingOpencodeSessions || opencodeImport.isLoading) return setIsBulkImportingOpencodeSessions(true) try { const result = await props.api.importOpencodeSessions({ sessionIds, cwd: trimmedDirectory || null, - machineId: opencodeImportMachineId ?? machineId + machineId: opencodeImport.machineId ?? machineId }) const importedCount = result.results.filter((item) => item.hapiSessionId && !item.error && (item.action === 'created' || (item.appended ?? 0) > 0)).length const failed = result.results.filter((item) => item.error) @@ -1677,7 +1674,7 @@ export function NewSession(props: { url: '' }) await refetchSessions() - await loadOpencodeImportSessions() + await opencodeImport.refresh() } if (failed.length > 0) { const first = failed[0]!.error! @@ -1697,7 +1694,7 @@ export function NewSession(props: { } catch (importError) { addToast({ title: t('opencodeSync.failed.title'), - body: importError instanceof Error ? importError.message : t('opencodeSync.failed.body'), + body: apiErrorMessage(importError, t('opencodeSync.failed.body')), sessionId: '', url: '' }) @@ -1708,10 +1705,70 @@ export function NewSession(props: { addToast, formatOpencodeImportError, isBulkImportingOpencodeSessions, - isLoadingOpencodeImportSessions, - loadOpencodeImportSessions, machineId, - opencodeImportMachineId, + opencodeImport.isLoading, + opencodeImport.machineId, + opencodeImport.refresh, + props.api, + refetchSessions, + t, + trimmedDirectory + ]) + + const handleBulkImportClaudeSessions = useCallback(async (sessionIds: string[]) => { + if (isBulkImportingClaudeSessions || claudeImport.isLoading) return + setIsBulkImportingClaudeSessions(true) + try { + const result = await props.api.importClaudeSessions({ + sessionIds, + cwd: trimmedDirectory || null, + machineId: claudeImport.machineId ?? machineId + }) + const importedCount = result.results.filter((item) => item.hapiSessionId && !item.error && (item.action === 'created' || (item.appended ?? 0) > 0)).length + const failed = result.results.filter((item) => item.error) + if (importedCount > 0) { + addToast({ + title: t('claudeImport.success.title'), + body: t('claudeImport.success.body', { n: importedCount }), + sessionId: '', + url: '' + }) + await refetchSessions() + await claudeImport.refresh() + } + if (failed.length > 0) { + const first = failed[0]!.error! + addToast({ + title: t('claudeImport.failed.title'), + body: t('claudeImport.failed.partial', { + failed: failed.length, + reason: formatClaudeImportError(first.code, first.message) + }), + sessionId: '', + url: '' + }) + return + } + setIsClaudeImportDialogOpen(false) + setSelectedClaudeImportSessionId(null) + } catch (importError) { + addToast({ + title: t('claudeImport.failed.title'), + body: apiErrorMessage(importError, t('claudeImport.failed.body')), + sessionId: '', + url: '' + }) + } finally { + setIsBulkImportingClaudeSessions(false) + } + }, [ + addToast, + claudeImport.isLoading, + claudeImport.machineId, + claudeImport.refresh, + formatClaudeImportError, + isBulkImportingClaudeSessions, + machineId, props.api, refetchSessions, t, @@ -1723,12 +1780,16 @@ export function NewSession(props: { [codexImportSessions, selectedCodexImportSessionId] ) const selectedPiImportSession = useMemo( - () => piImportSessions.find((session) => session.id === selectedPiImportSessionId) ?? null, - [piImportSessions, selectedPiImportSessionId] + () => piImport.sessions.find((session) => session.id === selectedPiImportSessionId) ?? null, + [piImport.sessions, selectedPiImportSessionId] ) const selectedOpencodeImportSession = useMemo( - () => opencodeImportSessions.find((session) => session.id === selectedOpencodeImportSessionId) ?? null, - [opencodeImportSessions, selectedOpencodeImportSessionId] + () => opencodeImport.sessions.find((session) => session.id === selectedOpencodeImportSessionId) ?? null, + [opencodeImport.sessions, selectedOpencodeImportSessionId] + ) + const selectedClaudeImportSession = useMemo( + () => claudeImport.sessions.find((session) => session.id === selectedClaudeImportSessionId) ?? null, + [claudeImport.sessions, selectedClaudeImportSessionId] ) // Pi history import reopens the native session as-is; the launch-only // model/effort controls would silently not apply, so hide them. @@ -1749,11 +1810,8 @@ export function NewSession(props: { setCodexImportSessions([]) setCodexImportMachineId(null) setSelectedPiImportSessionId(null) - setPiImportSessions([]) - setPiImportMachineId(null) setSelectedOpencodeImportSessionId(null) - setOpencodeImportSessions([]) - setOpencodeImportMachineId(null) + setSelectedClaudeImportSessionId(null) const paths = getRecentPaths(newMachineId) if (paths[0]) { setDirectory(paths[0]) @@ -1849,16 +1907,21 @@ export function NewSession(props: { } }, []) - const handleSelectPiImportSession = useCallback((session: PiLocalSessionSummary) => { + const handleSelectPiImportSession = useCallback((session: LocalSessionListItem) => { setSelectedPiImportSessionId(session.id) if (session.cwd?.trim()) setDirectory(session.cwd.trim()) }, []) - const handleSelectOpencodeImportSession = useCallback((session: OpencodeLocalSessionSummary) => { + const handleSelectOpencodeImportSession = useCallback((session: LocalSessionListItem) => { setSelectedOpencodeImportSessionId(session.id) if (session.cwd?.trim()) setDirectory(session.cwd.trim()) }, []) + const handleSelectClaudeImportSession = useCallback((session: LocalSessionListItem) => { + setSelectedClaudeImportSessionId(session.id) + if (session.cwd?.trim()) setDirectory(session.cwd.trim()) + }, []) + const handlePathClick = useCallback((path: string) => { setDirectory(path) }, []) @@ -2038,7 +2101,7 @@ export function NewSession(props: { const result = await props.api.importPiSessions({ sessionIds: [selectedPiImportSession.id], cwd: selectedPiImportSession.cwd ?? trimmedDirectory, - machineId: piImportMachineId ?? machineId + machineId: piImport.machineId ?? machineId }) const imported = result.results.find((item) => item.piSessionId === selectedPiImportSession.id) if (imported?.error) { @@ -2063,7 +2126,7 @@ export function NewSession(props: { const result = await props.api.importOpencodeSessions({ sessionIds: [selectedOpencodeImportSession.id], cwd: selectedOpencodeImportSession.cwd ?? trimmedDirectory, - machineId: opencodeImportMachineId ?? machineId, + machineId: opencodeImport.machineId ?? machineId, model: resolvedModel ?? null, modelReasoningEffort: resolvedModelReasoningEffort ?? null, permissionMode: nativePermissionMode @@ -2086,6 +2149,36 @@ export function NewSession(props: { return } + if (agent === 'claude' && selectedClaudeImportSession) { + setIsImportingClaudeSession(true) + // The reopen launches with the persisted session config, so the + // form's selections go through the import first. + const result = await props.api.importClaudeSessions({ + sessionIds: [selectedClaudeImportSession.id], + cwd: selectedClaudeImportSession.cwd ?? trimmedDirectory, + machineId: claudeImport.machineId ?? machineId, + model: resolvedModel ?? null, + effort: resolvedEffort ?? null, + permissionMode: nativePermissionMode + }) + const imported = result.results.find((item) => item.claudeSessionId === selectedClaudeImportSession.id) + if (imported?.error) { + setIsImportingClaudeSession(false) + haptic.notification('error') + setError(formatClaudeImportError(imported.error.code, imported.error.message)) + return + } + if (!imported?.hapiSessionId) throw new Error(result.error || t('claudeImport.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, @@ -2123,8 +2216,9 @@ export function NewSession(props: { setIsImportingCodexSession(false) setIsImportingPiSession(false) setIsImportingOpencodeSession(false) + setIsImportingClaudeSession(false) haptic.notification('error') - setError(e instanceof Error ? e.message : 'Failed to create session') + setError(apiErrorMessage(e, 'Failed to create session')) } finally { createInFlightRef.current = false setIsCreating(false) @@ -2272,12 +2366,12 @@ export function NewSession(props: { {agent === 'pi' ? ( { setIsPiImportDialogOpen(true) - void loadPiImportSessions() + void piImport.refresh() }} onClear={() => setSelectedPiImportSessionId(null)} /> @@ -2285,16 +2379,29 @@ export function NewSession(props: { {agent === 'opencode' ? ( { setIsOpencodeImportDialogOpen(true) - void loadOpencodeImportSessions() + void opencodeImport.refresh() }} onClear={() => setSelectedOpencodeImportSessionId(null)} /> ) : null} + {agent === 'claude' ? ( + { + setIsClaudeImportDialogOpen(true) + void claudeImport.refresh() + }} + onClear={() => setSelectedClaudeImportSessionId(null)} + /> + ) : null} {agent === 'dsh' ? ( setIsPiImportDialogOpen(false)} - sessions={piImportSessions} + sessions={piImport.sessions} currentSessionId={selectedPiImportSessionId} currentWorkDirectory={trimmedDirectory} onConfirm={async (sessionIds) => { if (sessionIds.length === 1) { - const session = piImportSessions.find((candidate) => candidate.id === sessionIds[0]) + const session = piImport.sessions.find((candidate) => candidate.id === sessionIds[0]) if (session) { handleSelectPiImportSession(session) setIsPiImportDialogOpen(false) @@ -2549,17 +2656,17 @@ export function NewSession(props: { await handleBulkImportPiSessions(sessionIds) }} isPending={isBulkImportingPiSessions} - isLoading={isLoadingPiImportSessions} + isLoading={piImport.isLoading} /> setIsOpencodeImportDialogOpen(false)} - sessions={opencodeImportSessions} + sessions={opencodeImport.sessions} currentSessionId={selectedOpencodeImportSessionId} currentWorkDirectory={trimmedDirectory} onConfirm={async (sessionIds) => { if (sessionIds.length === 1) { - const session = opencodeImportSessions.find((candidate) => candidate.id === sessionIds[0]) + const session = opencodeImport.sessions.find((candidate) => candidate.id === sessionIds[0]) if (session) { handleSelectOpencodeImportSession(session) setIsOpencodeImportDialogOpen(false) @@ -2569,7 +2676,27 @@ export function NewSession(props: { await handleBulkImportOpencodeSessions(sessionIds) }} isPending={isBulkImportingOpencodeSessions} - isLoading={isLoadingOpencodeImportSessions} + isLoading={opencodeImport.isLoading} + /> + setIsClaudeImportDialogOpen(false)} + sessions={claudeImport.sessions} + currentSessionId={selectedClaudeImportSessionId} + currentWorkDirectory={trimmedDirectory} + onConfirm={async (sessionIds) => { + if (sessionIds.length === 1) { + const session = claudeImport.sessions.find((candidate) => candidate.id === sessionIds[0]) + if (session) { + handleSelectClaudeImportSession(session) + setIsClaudeImportDialogOpen(false) + } + return + } + await handleBulkImportClaudeSessions(sessionIds) + }} + isPending={isBulkImportingClaudeSessions} + isLoading={claudeImport.isLoading} /> 0} diff --git a/web/src/components/OpencodeSessionImportDialog.tsx b/web/src/components/OpencodeSessionImportDialog.tsx index 15740c24..95ab32e3 100644 --- a/web/src/components/OpencodeSessionImportDialog.tsx +++ b/web/src/components/OpencodeSessionImportDialog.tsx @@ -1,16 +1,12 @@ -import { useEffect, useMemo, useState } from 'react' -import type { OpencodeLocalSessionSummary } 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 type { LocalSessionListItem } from '@/lib/localSessionImport' import { useTranslation } from '@/lib/use-translation' +import { LocalSessionImportDialog } from '@/components/LocalSessionImportDialog' -const ALL_DIRECTORIES = '__all__' - +/** OpenCode-flavored wrapper around the generic import dialog. */ export function OpencodeSessionImportDialog(props: { isOpen: boolean onClose: () => void - sessions: OpencodeLocalSessionSummary[] + sessions: LocalSessionListItem[] currentSessionId: string | null currentWorkDirectory?: string | null onConfirm: (sessionIds: string[]) => Promise @@ -18,109 +14,32 @@ export function OpencodeSessionImportDialog(props: { 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] - .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('opencodeSync.dialog.title')} - {t('opencodeSync.dialog.description')} - -
-
- {t('opencodeSync.dialog.concurrentWarning')} -
-
- {t('opencodeSync.selectedCount', { n: selectedIds.length })} -
- - -
-
- {props.sessions.length > 0 ? ( -
- setDirectory(event.target.value)}> - - {directories.map((value) => )} - - setQuery(event.target.value)} - /> -
- ) : null} -
- {props.isLoading ? ( -
{t('opencodeSync.loading')}
- ) : filtered.length === 0 ? ( -
{t('opencodeSync.empty')}
- ) : ( -
- {filtered.map((session) => { - const checked = selectedIds.includes(session.id) - return ( - - ) - })} -
- )} -
-
- - -
-
-
-
+ ) -} +} \ No newline at end of file diff --git a/web/src/components/PiSessionImportDialog.tsx b/web/src/components/PiSessionImportDialog.tsx index 7da06e41..8edca1a3 100644 --- a/web/src/components/PiSessionImportDialog.tsx +++ b/web/src/components/PiSessionImportDialog.tsx @@ -1,16 +1,12 @@ -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 type { LocalSessionListItem } from '@/lib/localSessionImport' import { useTranslation } from '@/lib/use-translation' +import { LocalSessionImportDialog } from '@/components/LocalSessionImportDialog' -const ALL_DIRECTORIES = '__all__' - +/** Pi-flavored wrapper around the generic import dialog. */ export function PiSessionImportDialog(props: { isOpen: boolean onClose: () => void - sessions: PiLocalSessionSummary[] + sessions: LocalSessionListItem[] currentSessionId: string | null currentWorkDirectory?: string | null onConfirm: (sessionIds: string[]) => Promise @@ -18,110 +14,34 @@ export function PiSessionImportDialog(props: { 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 ( - - ) - })} -
- )} -
-
- - -
-
-
-
+ ) -} +} \ No newline at end of file diff --git a/web/src/components/SessionList.test.ts b/web/src/components/SessionList.test.ts index 4c7c229d..ba6ca356 100644 --- a/web/src/components/SessionList.test.ts +++ b/web/src/components/SessionList.test.ts @@ -128,6 +128,18 @@ describe('deduplicateSessionsByAgentId', () => { expect(result[0].id).toBe('b') // more recent wins }) + it('keeps machine-local agent ids recorded on different machines apart', () => { + for (const flavor of ['codex', 'claude', 'pi', 'opencode']) { + const sessions = [ + makeSession({ id: `${flavor}-a`, metadata: { path: '/p', agentSessionId: 'native-1', flavor, machineId: 'machine-a' }, updatedAt: 100 }), + makeSession({ id: `${flavor}-b`, metadata: { path: '/p', agentSessionId: 'native-1', flavor, machineId: 'machine-b' }, updatedAt: 200 }), + makeSession({ id: `${flavor}-b2`, metadata: { path: '/p', agentSessionId: 'native-1', flavor, machineId: 'machine-b' }, updatedAt: 300 }) + ] + expect(deduplicateSessionsByAgentId(sessions).map((session) => session.id).sort()) + .toEqual([`${flavor}-a`, `${flavor}-b2`]) + } + }) + it('keeps active session over inactive duplicate', () => { const sessions = [ makeSession({ id: 'a', active: true, metadata: { path: '/p', agentSessionId: 'thread-1' }, updatedAt: 100 }), diff --git a/web/src/components/SessionList.tsx b/web/src/components/SessionList.tsx index 6c6c06c8..12c3bf79 100644 --- a/web/src/components/SessionList.tsx +++ b/web/src/components/SessionList.tsx @@ -323,12 +323,19 @@ type MachineGroup = { export const UNKNOWN_MACHINE_ID = '__unknown__' export const GROUP_SESSION_PREVIEW_LIMIT = DEFAULT_SESSION_PREVIEW_LIMIT +const MACHINE_LOCAL_AGENT_FLAVORS = new Set(['codex', 'claude', 'pi', 'opencode']) + export function getSessionDedupKey(session: SessionSummary): string | null { const agentId = session.metadata?.agentSessionId?.trim() if (!agentId) return null // Scope by flavor: agentSessionId is flattened from native ids and can retain a // stale cross-flavor value (codexSessionId ?? claudeSessionId ?? ...). - return `${session.metadata?.flavor ?? 'unknown'}:${agentId}` + const flavor = session.metadata?.flavor ?? 'unknown' + // These native ids live in one machine's local store, and the hub keeps + // sessions recorded on different machines apart: hiding one behind the + // other would make an imported session look deleted. + const machineId = MACHINE_LOCAL_AGENT_FLAVORS.has(flavor) ? session.metadata?.machineId : undefined + return machineId ? `${flavor}:${machineId}:${agentId}` : `${flavor}:${agentId}` } export function deduplicateSessionsByAgentId(sessions: SessionSummary[], selectedSessionId?: string | null): SessionSummary[] { diff --git a/web/src/hooks/useLocalSessionImport.test.tsx b/web/src/hooks/useLocalSessionImport.test.tsx new file mode 100644 index 00000000..e3610d05 --- /dev/null +++ b/web/src/hooks/useLocalSessionImport.test.tsx @@ -0,0 +1,145 @@ +import { act, fireEvent, render, screen, waitFor } from '@testing-library/react' +import { describe, expect, it, vi } from 'vitest' +import { ApiError } from '../api/client' +import { useLocalSessionImport } from './useLocalSessionImport' +import type { LocalSessionImportApi, LocalSessionListResponse } from '../lib/localSessionImport' + +function api(overrides: Partial = {}): LocalSessionImportApi { + return { + getLocalSessions: vi.fn().mockResolvedValue({ + success: true, + sessions: [{ id: 'pi-1', title: 'Pi session', file: '/tmp/pi-1.jsonl', modifiedAt: 1 }], + machineId: 'm-1' + } satisfies LocalSessionListResponse), + importLocalSessions: vi.fn().mockResolvedValue({ + success: true, + results: [{ sessionId: 'pi-1', piSessionId: 'pi-1', action: 'created', appended: 2 }] + }), + ...overrides + } +} + +function harness(apiInstance: LocalSessionImportApi, props: { directory?: string | null; machineId?: string | null } = {}) { + let result: ReturnType | null = null + function Probe() { + result = useLocalSessionImport({ api: apiInstance, flavor: 'pi', ...props }) + return null + } + render() + return { + get: () => { + if (!result) throw new Error('hook not rendered') + return result + } + } +} + +describe('useLocalSessionImport', () => { + type ImportResults = Awaited['importSessions']>> + + it('scans sessions on mount and exposes the resolved machine id', async () => { + const apiInstance = api() + const { get } = harness(apiInstance, { directory: '/tmp/project' }) + await waitFor(() => expect(get().isLoading).toBe(false)) + expect(apiInstance.getLocalSessions).toHaveBeenCalledWith('pi', '/tmp/project', null) + expect(get().sessions[0]!.id).toBe('pi-1') + expect(get().machineId).toBe('m-1') + }) + + it('unwraps ApiError bodies into the load error message', async () => { + const apiInstance = api() + const body = '{"success":false,"error":"No online machine available for Pi history import"}' + apiInstance.getLocalSessions = vi.fn().mockRejectedValue(new ApiError(`HTTP 503 Service Unavailable: ${body}`, 503, 'No online machine available for Pi history import', body)) + const { get } = harness(apiInstance, { directory: '/tmp/project' }) + await waitFor(() => expect(get().isLoading).toBe(false)) + // The raw `HTTP 503 ...: {...}` envelope must not reach the UI. + expect(get().error).toBe('No online machine available for Pi history import') + expect(get().sessions).toEqual([]) + }) + + it('imports through the flavor REST pair with the resolved machine', async () => { + const apiInstance = api() + const { get } = harness(apiInstance, { directory: '/tmp/project', machineId: 'requested' }) + await waitFor(() => expect(get().isLoading).toBe(false)) + let results: ImportResults | null = null + await act(async () => { + results = await get().importSessions(['pi-1']) + }) + expect(apiInstance.importLocalSessions).toHaveBeenCalledWith('pi', { + sessionIds: ['pi-1'], + cwd: '/tmp/project', + machineId: 'm-1' + }) + expect((results as ImportResults)?.[0]!.sessionId).toBe('pi-1') + }) + + it('surfaces list errors without losing the previous state', async () => { + const apiInstance = api({ + getLocalSessions: vi.fn().mockResolvedValue({ success: false, error: 'runner offline', sessions: [] }) + }) + const { get } = harness(apiInstance) + await waitFor(() => expect(get().error).toBe('runner offline')) + expect(get().sessions).toEqual([]) + }) + + it('ignores stale scans after a refresh', async () => { + let resolveSecond: ((value: LocalSessionListResponse) => void) | null = null + const apiInstance = api({ + getLocalSessions: vi.fn() + .mockImplementationOnce(async () => ({ + success: true, + sessions: [{ id: 'stale', title: 'stale', file: '/x', modifiedAt: 1 }], + machineId: 'm-1' + })) + .mockImplementationOnce(() => new Promise((resolve) => { + resolveSecond = resolve + })) + }) + const { get } = harness(apiInstance) + await waitFor(() => expect(get().isLoading).toBe(false)) + await act(async () => { + const refreshing = get().refresh() + resolveSecond?.({ + success: true, + sessions: [{ id: 'fresh', title: 'fresh', file: '/x', modifiedAt: 2 }], + machineId: 'm-1' + }) + await refreshing + }) + expect(get().sessions[0]!.id).toBe('fresh') + }) + + it('does nothing when import is called with an empty selection', async () => { + const apiInstance = api() + const { get } = harness(apiInstance) + await waitFor(() => expect(get().isLoading).toBe(false)) + await act(async () => { + expect(await get().importSessions([])).toBeNull() + }) + expect(apiInstance.importLocalSessions).not.toHaveBeenCalled() + }) + + it('fires a click on the choose button through the actions strip', async () => { + const { LocalSessionImportActions } = await import('../components/NewSession/LocalSessionImportActions') + const onChooseHistory = vi.fn() + render( + + ) + fireEvent.click(screen.getByRole('button', { name: 'Choose history' })) + expect(onChooseHistory).toHaveBeenCalledOnce() + }) +}) \ No newline at end of file diff --git a/web/src/hooks/useLocalSessionImport.ts b/web/src/hooks/useLocalSessionImport.ts new file mode 100644 index 00000000..a54c7257 --- /dev/null +++ b/web/src/hooks/useLocalSessionImport.ts @@ -0,0 +1,119 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import type { + LocalSessionImportApi, + LocalSessionImportFlavor, + LocalSessionImportPayload, + LocalSessionImportResponse, + LocalSessionListItem +} from '../lib/localSessionImport' +import { apiErrorMessage } from '../api/client' + +/** + * Shared state machine behind the flavor import dialogs: scan the + * machine's local sessions, keep the dialog selection, and run imports + * through the generic REST pair. One selection may be continued inline by + * the caller; bulk selections import in the background. + */ + +export type UseLocalSessionImportOptions = { + api: LocalSessionImportApi + flavor: LocalSessionImportFlavor + /** Work directory used to scope the scan and the import. */ + directory?: string | null + /** Machine hosting the session that is being continued (may be null). */ + machineId?: string | null + /** + * When false, sessions are only fetched through an explicit refresh() + * (the New Session form loads its import list when the picker opens). + */ + auto?: boolean +} + +export type UseLocalSessionImportResult = { + sessions: LocalSessionListItem[] + machineId: string | null + isLoading: boolean + error: string | null + isImporting: boolean + refresh: () => Promise + importSessions: (sessionIds: string[], payloadOverrides?: Partial) => Promise +} + +export function useLocalSessionImport(options: UseLocalSessionImportOptions): UseLocalSessionImportResult { + const { api, flavor, directory, machineId, auto = true } = options + const [sessions, setSessions] = useState([]) + const [resolvedMachineId, setResolvedMachineId] = useState(null) + const [isLoading, setIsLoading] = useState(false) + const [error, setError] = useState(null) + const [isImporting, setIsImporting] = useState(false) + const loadGenerationRef = useRef(0) + + const refresh = useCallback(async () => { + const generation = ++loadGenerationRef.current + setIsLoading(true) + setError(null) + try { + const result = await api.getLocalSessions(flavor, directory ?? null, machineId ?? null) + if (generation !== loadGenerationRef.current) return + if (!result.success) { + setError(result.error) + setSessions([]) + setResolvedMachineId(result.machineId ?? null) + return + } + setSessions(result.sessions) + setResolvedMachineId(result.machineId ?? machineId ?? null) + } catch (loadError) { + if (generation !== loadGenerationRef.current) return + setError(apiErrorMessage(loadError, 'Failed to load local sessions')) + setSessions([]) + } finally { + if (generation === loadGenerationRef.current) setIsLoading(false) + } + }, [api, flavor, directory, machineId]) + + // Invalidate an in-flight scan when its scope (directory/machine) changes: + // the stale response is dropped and the loading state clears immediately, + // before a new scan is issued (auto mode re-issues below). + useEffect(() => { + loadGenerationRef.current += 1 + setIsLoading(false) + setResolvedMachineId(null) + }, [directory, machineId]) + + useEffect(() => { + if (!auto) return + void refresh() + }, [auto, refresh]) + + const importSessions = useCallback(async (sessionIds: string[], payloadOverrides?: Partial) => { + if (isImporting || sessionIds.length === 0) return null + setIsImporting(true) + try { + const result = await api.importLocalSessions(flavor, { + sessionIds, + cwd: directory ?? null, + machineId: resolvedMachineId ?? machineId ?? null, + ...payloadOverrides + }) + if (result.success || result.results.length > 0) return result.results + setError(result.error ?? null) + return null + } catch (importError) { + setError(apiErrorMessage(importError, 'Failed to import local sessions')) + return null + } finally { + setIsImporting(false) + } + }, [api, flavor, directory, machineId, resolvedMachineId, isImporting]) + + return { + sessions, + machineId: resolvedMachineId, + isLoading, + error, + isImporting, + refresh, + importSessions + } +} \ No newline at end of file diff --git a/web/src/lib/localSessionImport.ts b/web/src/lib/localSessionImport.ts new file mode 100644 index 00000000..c1ce8a0b --- /dev/null +++ b/web/src/lib/localSessionImport.ts @@ -0,0 +1,73 @@ +/** + * Generic local-session import contract for the web client. One + * REST pair per flavor: GET /api/:flavor/sessions and POST + * /api/:flavor/import-sessions. Flavor display fields arrive flattened into + * list items (the hub flattens the source descriptor's `extra`). + */ + +import type { PermissionMode } from '@/types/api' + +export type LocalSessionImportFlavor = 'codex' | 'pi' | 'opencode' | 'claude' + +export type LocalSessionListItem = { + id: string + title: string + lastUserMessage?: string | null + cwd?: string | null + file: string + modifiedAt: number + messageCount?: number + hapiSessionId?: string + importState?: 'importing' | 'complete' | 'failed' | 'diverged' + [flavorField: string]: unknown +} + +export type LocalSessionListResponse = + | { success: true; sessions: LocalSessionListItem[]; machineId?: string } + | { success: false; error: string; sessions: []; machineId?: string } + +export type LocalSessionImportResult = { + sessionId?: string + hapiSessionId?: string + action?: 'created' | 'updated' | 'unchanged' + appended?: number + error?: { code: string; message: string } + [flavorField: string]: unknown +} + +export type LocalSessionImportResponse = { + success: boolean + results: LocalSessionImportResult[] + machineId?: string + error?: string +} + +export type LocalSessionImportPayload = { + sessionIds: string[] + cwd?: string | null + machineId?: string | null + model?: string | null + modelReasoningEffort?: string | null + permissionMode?: PermissionMode + serviceTier?: string | null + collaborationMode?: string | null + [requestField: string]: unknown +} + +/** Client surface the generic import hook needs; ApiClient implements it. */ +export type LocalSessionImportApi = { + getLocalSessions(flavor: LocalSessionImportFlavor, cwd?: string | null, machineId?: string | null): Promise + importLocalSessions(flavor: LocalSessionImportFlavor, payload: LocalSessionImportPayload): Promise +} + +export function localSessionsPath(flavor: LocalSessionImportFlavor, cwd?: string | null, machineId?: string | null): string { + 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 `/api/${flavor}/sessions${query}` +} + +export function localImportPath(flavor: LocalSessionImportFlavor): string { + return `/api/${flavor}/import-sessions` +} \ No newline at end of file diff --git a/web/src/lib/locales/en.ts b/web/src/lib/locales/en.ts index d7611add..a7b051ed 100644 --- a/web/src/lib/locales/en.ts +++ b/web/src/lib/locales/en.ts @@ -151,6 +151,7 @@ export default { 'piImport.failed.body': 'Failed to import Pi history.', 'piImport.failed.partial': '{failed} sessions failed: {reason}', 'piImport.error.diverged': 'The local Pi branch changed after the previous import. Review the session before continuing.', + 'piImport.error.alreadyImported': 'This Pi session is already imported into HAPI and has no new messages to add.', 'piImport.error.active': 'Stop the active Hapi Pi session before importing newer native history.', 'piImport.manual.success.title': 'Pi history sync complete', 'piImport.manual.success.body': 'Synced {n} new Pi history items.', @@ -179,7 +180,33 @@ export default { 'opencodeSync.failed.body': 'Failed to import OpenCode history.', 'opencodeSync.failed.partial': '{failed} sessions failed: {reason}', 'opencodeSync.error.diverged': 'The local OpenCode branch changed after the previous import. Review the session before continuing.', + 'opencodeSync.error.alreadyImported': 'This OpenCode session is already imported into HAPI and has no new messages to add.', 'opencodeSync.error.active': 'Stop the active Hapi OpenCode session before importing newer native history.', + 'claudeImport.inline.title': 'Import Claude history', + 'claudeImport.inline.description': 'Optional: choose an existing local Claude session to import and continue.', + 'claudeImport.inline.clear': 'Clear', + 'claudeImport.inline.choose': 'Choose history', + 'claudeImport.dialog.title': 'Import Claude sessions', + 'claudeImport.dialog.description': 'Select local Claude histories. One selection is continued now; multiple selections are imported in the background.', + 'claudeImport.dialog.concurrentWarning': 'Multiple processes can open the same Claude session, but avoid writing from stale copies. Before continuing in HAPI, reload or close any other Claude process to avoid an unintended branch.', + 'claudeImport.loading': 'Scanning Claude sessions…', + 'claudeImport.empty': 'No importable Claude sessions found.', + 'claudeImport.selectedCount': '{n} selected', + 'claudeImport.clearAll': 'Clear all', + 'claudeImport.selectAll': 'Select all', + 'claudeImport.allDirectories': 'All directories', + 'claudeImport.search': 'Search title, prompt, path, or ID', + 'claudeImport.imported': 'Imported', + 'claudeImport.importing': 'Importing…', + 'claudeImport.confirm': 'Import', + 'claudeImport.success.title': 'Claude sessions imported', + 'claudeImport.success.body': 'Imported {n} Claude sessions.', + 'claudeImport.failed.title': 'Claude import failed', + 'claudeImport.failed.body': 'Failed to import Claude history.', + 'claudeImport.failed.partial': '{failed} sessions failed: {reason}', + 'claudeImport.error.diverged': 'The local Claude transcript changed after the previous import. Review the session before continuing.', + 'claudeImport.error.alreadyImported': 'This Claude session is already imported into HAPI and has no new messages to add.', + 'claudeImport.error.active': 'Stop the active Hapi Claude session before importing newer native history.', // 中文注释:以下文案支撑导入弹窗的多选列表、加载态,以及右上角重启 Codex 客户端按钮提示。 'codexSync.confirm.selectAll': 'Select all', 'codexSync.confirm.clearAll': 'Clear all', diff --git a/web/src/lib/locales/ru.ts b/web/src/lib/locales/ru.ts index 1e58b3fa..f4ef06fa 100644 --- a/web/src/lib/locales/ru.ts +++ b/web/src/lib/locales/ru.ts @@ -133,7 +133,33 @@ export default { 'piImport.failed.body': 'Не удалось импортировать историю Pi.', 'piImport.failed.partial': 'Не удалось импортировать сессий: {failed}. Причина: {reason}', 'piImport.error.diverged': 'Локальная ветка Pi изменилась после предыдущего импорта. Проверьте сессию перед продолжением.', + 'piImport.error.alreadyImported': 'Эта сессия Pi уже импортирована в HAPI и не содержит новых сообщений.', 'piImport.error.active': 'Остановите активную сессию Hapi Pi перед импортом более новой нативной истории.', + 'claudeImport.inline.title': 'Импорт истории Claude', + 'claudeImport.inline.description': 'Необязательно: выберите существующую локальную сессию Claude для импорта и продолжения.', + 'claudeImport.inline.clear': 'Очистить', + 'claudeImport.inline.choose': 'Выбрать историю', + 'claudeImport.dialog.title': 'Импорт сессий Claude', + 'claudeImport.dialog.description': 'Выберите локальные истории Claude. Один выбор продолжается сразу; несколько выборов импортируются в фоне.', + 'claudeImport.dialog.concurrentWarning': 'Несколько процессов могут открыть одну и ту же сессию Claude, но избегайте записи из устаревших копий. Перед продолжением в HAPI перезагрузите или закройте любой другой процесс Claude, чтобы избежать непреднамеренного ответвления.', + 'claudeImport.loading': 'Сканирование сессий Claude…', + 'claudeImport.empty': 'Не найдено сессий Claude для импорта.', + 'claudeImport.selectedCount': 'Выбрано: {n}', + 'claudeImport.clearAll': 'Очистить все', + 'claudeImport.selectAll': 'Выбрать все', + 'claudeImport.allDirectories': 'Все каталоги', + 'claudeImport.search': 'Поиск по названию, запросу, пути или ID', + 'claudeImport.imported': 'Импортировано', + 'claudeImport.importing': 'Импорт…', + 'claudeImport.confirm': 'Импортировать', + 'claudeImport.success.title': 'Сессии Claude импортированы', + 'claudeImport.success.body': 'Импортировано сессий Claude: {n}.', + 'claudeImport.failed.title': 'Не удалось импортировать Claude', + 'claudeImport.failed.body': 'Не удалось импортировать историю Claude.', + 'claudeImport.failed.partial': 'Не удалось импортировать сессий: {failed}. Причина: {reason}', + 'claudeImport.error.diverged': 'Локальный транскрипт Claude изменился после предыдущего импорта. Проверьте сессию перед продолжением.', + 'claudeImport.error.alreadyImported': 'Эта сессия Claude уже импортирована в HAPI и не содержит новых сообщений.', + 'claudeImport.error.active': 'Остановите активную сессию Hapi Claude перед импортом более новой нативной истории.', 'piImport.manual.success.title': 'Синхронизация истории Pi завершена', 'piImport.manual.success.body': 'Синхронизировано новых элементов истории Pi: {n}.', 'piImport.manual.success.noNewMessages': 'История Pi уже актуальна.', diff --git a/web/src/lib/locales/zh-CN.ts b/web/src/lib/locales/zh-CN.ts index 81943400..1e539549 100644 --- a/web/src/lib/locales/zh-CN.ts +++ b/web/src/lib/locales/zh-CN.ts @@ -151,6 +151,7 @@ export default { 'piImport.failed.body': '导入 Pi 历史失败。', 'piImport.failed.partial': '{failed} 个 session 导入失败:{reason}', 'piImport.error.diverged': '本机 Pi 分支在上次导入后发生变化,请先检查会话再继续。', + 'piImport.error.alreadyImported': '该 Pi session 已导入 HAPI,没有可新增的消息。', 'piImport.error.active': '请先停止正在运行的 Hapi Pi session,再导入新增的原生历史。', 'piImport.manual.success.title': 'Pi 历史同步完成', 'piImport.manual.success.body': '已同步 {n} 条新的 Pi 历史记录。', @@ -179,7 +180,33 @@ export default { 'opencodeSync.failed.body': '导入 OpenCode 历史失败。', 'opencodeSync.failed.partial': '{failed} 个 session 导入失败:{reason}', 'opencodeSync.error.diverged': '本机 OpenCode 分支在上次导入后发生变化,请先检查会话再继续。', + 'opencodeSync.error.alreadyImported': '该 OpenCode session 已导入 HAPI,没有可新增的消息。', 'opencodeSync.error.active': '请先停止正在运行的 Hapi OpenCode session,再导入新增的原生历史。', + 'claudeImport.inline.title': '导入 Claude 历史', + 'claudeImport.inline.description': '可选:选择本机已有的 Claude session,导入历史后继续对话。', + 'claudeImport.inline.clear': '清除', + 'claudeImport.inline.choose': '选择历史', + 'claudeImport.dialog.title': '导入 Claude sessions', + 'claudeImport.dialog.description': '选择本机 Claude 历史。单选会立即继续,多选会批量导入到会话列表。', + 'claudeImport.dialog.concurrentWarning': '多个进程可以同时打开同一个 Claude session,但不要从未刷新的副本交替写入。继续在 HAPI 中操作前,请重新加载或关闭其他 Claude 进程,避免产生意外分支。', + 'claudeImport.loading': '正在扫描 Claude sessions…', + 'claudeImport.empty': '没有找到可导入的 Claude session。', + 'claudeImport.selectedCount': '已选择 {n} 个', + 'claudeImport.clearAll': '全部清除', + 'claudeImport.selectAll': '全部选择', + 'claudeImport.allDirectories': '全部目录', + 'claudeImport.search': '搜索标题、消息、路径或 ID', + 'claudeImport.imported': '已导入', + 'claudeImport.importing': '正在导入…', + 'claudeImport.confirm': '导入', + 'claudeImport.success.title': 'Claude sessions 已导入', + 'claudeImport.success.body': '已导入 {n} 个 Claude sessions。', + 'claudeImport.failed.title': 'Claude 导入失败', + 'claudeImport.failed.body': '导入 Claude 历史失败。', + 'claudeImport.failed.partial': '{failed} 个 session 导入失败:{reason}', + 'claudeImport.error.diverged': '本机 Claude 记录在上次导入后发生变化,请先检查会话再继续。', + 'claudeImport.error.alreadyImported': '该 Claude session 已导入 HAPI,没有可新增的消息。', + 'claudeImport.error.active': '请先停止正在运行的 Hapi Claude session,再导入新增的原生历史。', // 中文注释:以下文案支撑导入弹窗的多选列表、加载态,以及右上角重启 Codex 客户端按钮提示。 'codexSync.confirm.selectAll': '全选', 'codexSync.confirm.clearAll': '全取消', diff --git a/web/src/types/api.ts b/web/src/types/api.ts index 969af461..392046ac 100644 --- a/web/src/types/api.ts +++ b/web/src/types/api.ts @@ -307,6 +307,43 @@ export type PiImportSessionsResponse = { error?: string } +export type ClaudeLocalSessionSummary = { + id: string + title: string + lastUserMessage?: string | null + cwd?: string | null + file: string + modifiedAt: number + messageCount?: number + hapiSessionId?: string +} + +export type ClaudeLocalSessionsResponse = { + success: true + sessions: ClaudeLocalSessionSummary[] + machineId: string +} | { + success: false + error: string + sessions: [] + machineId?: string +} + +export type ClaudeImportResult = { + claudeSessionId: string + hapiSessionId?: string + action?: 'created' | 'updated' | 'unchanged' + appended?: number + error?: { code: string; message: string } +} + +export type ClaudeImportSessionsResponse = { + success: boolean + results: ClaudeImportResult[] + machineId?: string + error?: string +} + export type OpencodeLocalSessionSummary = { id: string title: string