The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Fix closing Pi sessions before their first saved reply (#718)
Deee20c028ed2d1
diff --git a/cli/src/lib/captureResumeIdentity.spec.ts b/cli/src/lib/captureResumeIdentity.spec.tsindex f4ded10cf..000382890 100644--- a/cli/src/lib/captureResumeIdentity.spec.ts+++ b/cli/src/lib/captureResumeIdentity.spec.ts@@ -51,6 +51,13 @@ it.each([null, '/unsafe'])('retains the known id when its file is unavailable: %row.sessionId = 'known'; vi.mocked(findResumedTranscript).mockResolvedValue(path)vi.mocked(validTranscriptPath).mockReturnValue(false); expect(await captureResumeIdentity(row)).toBe(row)})+it('looks up a preallocated Pi session ID in its own project before stopping', async () => {+ Object.assign(row, { engine: 'pi', sessionId: 'preallocated', transcriptPath: null })+ expect(await captureResumeIdentity(row)).toBe(row)+ expect(findResumedTranscript).toHaveBeenCalledWith('pi', 'preallocated', { codexHome: undefined, cwd: '/work' })+ vi.mocked(findResumedTranscript).mockResolvedValue('/first-reply.jsonl')+ expect(await captureResumeIdentity(row)).toMatchObject({ sessionId: 'preallocated', transcriptPath: '/first-reply.jsonl' })+})it.each(['identity', 'cwd', 'unknown', 'gone', 'pid', 'executable', 'start'])('refuses missing or changed process evidence: %s', async mode => {if (mode === 'identity') row.processIdentity = nullif (mode === 'cwd') row.cwd = nulldiff --git a/cli/src/lib/captureResumeIdentity.ts b/cli/src/lib/captureResumeIdentity.tsindex 8d70e1cd3..babcf11e6 100644--- a/cli/src/lib/captureResumeIdentity.ts+++ b/cli/src/lib/captureResumeIdentity.ts@@ -15,7 +15,8 @@ import { isTerminalEngine } from '../engines/types.js'export async function captureResumeIdentity(session: RegisteredSession): Promise<RegisteredSession> {// A shell holds no conversation; there is nothing here to capture for it.if (isTerminalEngine(session.engine)) return session- const options = { codexHome: session.codexHome ?? undefined }+ const options = { codexHome: session.codexHome ?? undefined,+ ...(session.engine === 'pi' ? { cwd: session.cwd ?? undefined } : {}) }const keepsFile = engineKeepsTranscriptFile(session.engine)if (session.sessionId) {// A database-backed engine has the whole record already: the id IS the conversation.diff --git a/cli/src/lib/sessionCheckpoint.spec.ts b/cli/src/lib/sessionCheckpoint.spec.tsindex 68d160105..8dd80cfc2 100644--- a/cli/src/lib/sessionCheckpoint.spec.ts+++ b/cli/src/lib/sessionCheckpoint.spec.ts@@ -5,6 +5,8 @@ import { tmpdir } from 'node:os'import { SessionCheckpointStore } from './sessionCheckpoint.js'import { registry, type RegisteredSession } from './registry.js'import { sqliteReadAll } from './sqliteRead.js'+import { env } from '../config/env.js'+import { piSessionFolder } from './sessionSearch/externals/pi.js'vi.mock('node:fs/promises', async importOriginal => {const real = await importOriginal<typeof import('node:fs/promises')>()return { ...real, copyFile: vi.fn(real.copyFile), rm: vi.fn(real.rm) }@@ -29,6 +31,81 @@ beforeEach(async () => {afterEach(async () => { vi.restoreAllMocks(); for (const s of registry.list()) registry.removeAgent(s.agentId); await rm(root, { recursive: true, force: true }) })const manifest = async () => JSON.parse(await readFile(join(directory, (await readdir(directory)).find(f => /^[a-f0-9]{64}\.json$/.test(f))!), 'utf8'))+async function piSession() {+ const previousHome = env.PI_HOME+ env.PI_HOME = join(root, 'pi')+ // This fixture owns every possible source; never scan the developer's Pi store.+ Object.assign(row, { engine: 'pi', sessionId: 'preallocated-session', transcriptPath: null })+ const folder = join(env.PI_HOME, 'agent', 'sessions', piSessionFolder(row.cwd!))+ await mkdir(folder, { recursive: true })+ const path = join(folder, `2026-10-04T12-00-00-000Z_${row.sessionId}.jsonl`)+ return { path, restore: () => { env.PI_HOME = previousHome }, history: `${JSON.stringify({ type: 'session', version: 3, id: row.sessionId, cwd: row.cwd })}\n` }+}++it('checkpoints a Pi startup failure with an ID but no conversation file', async () => {+ const pi = await piSession()+ try {+ await expect(store.save(row)).rejects.toThrow('Could not save this terminal')+ const screen = 'Error: No API key found for the selected model.\nUnsent draft'+ await store.save(row, { screen })+ const saved = await manifest()+ expect(saved.source).toBeNull()+ expect(JSON.parse(await readFile(join(directory, saved.file), 'utf8'))).toMatchObject({+ engine: 'pi', sessionId: row.sessionId, screen,+ })+ await store.save(row, { screen: null }) // post-exit checkpoint+ expect(await manifest()).toEqual(saved)+ } finally { pi.restore() }+})++it.each(['before', 'during'] as const)('backs up a Pi transcript first written %s Close', async when => {+ const pi = await piSession()+ try {+ if (when === 'during') await store.save(row, { screen: 'Waiting for the first reply' })+ await writeFile(pi.path, pi.history)+ await store.save(row)+ const saved = await manifest()+ expect(saved.source).toBe(pi.path)+ expect(await readFile(join(directory, saved.file), 'utf8')).toBe(pi.history)+ expect(row.transcriptPath).toBeNull() // the captured registry row can still be stale+ await rm(pi.path)+ await expect(store.save(row, { screen: 'Still visible' })).rejects.toThrow('conversation file is unavailable')+ expect(await manifest()).toEqual(saved)+ } finally { pi.restore() }+})++it.each(['known', 'resumed', 'unreadable', 'ambiguous', 'unreadable store'] as const)('does not replace %s Pi history with only a screen', async state => {+ const pi = await piSession()+ try {+ if (state === 'known') row.transcriptPath = pi.path+ if (state === 'resumed') row.resumeOnly = true+ if (state === 'unreadable') await writeFile(pi.path, '{partial')+ if (state === 'unreadable store') {+ const folder = join(pi.path, '..')+ await rm(folder, { recursive: true })+ await writeFile(folder, 'not a directory')+ }+ if (state === 'ambiguous') {+ await writeFile(pi.path, pi.history)+ await writeFile(join(pi.path, '..', `other_${row.sessionId}.jsonl`), pi.history)+ }+ await expect(store.save(row, { screen: 'Visible terminal' })).rejects.toThrow()+ expect((await readdir(directory)).filter(file => file.endsWith('.history'))).toEqual([])+ } finally { pi.restore() }+})++it('does not back up a different Pi ID or a project with the same encoded folder', async () => {+ const pi = await piSession()+ try {+ await writeFile(pi.path, `${JSON.stringify({ type: 'session', id: row.sessionId, cwd: '/different/project' })}\n`)+ await store.save(row, { screen: 'Startup screen' })+ expect((await manifest()).source).toBeNull()+ await writeFile(pi.path, `${JSON.stringify({ type: 'session', id: `other_${row.sessionId}`, cwd: row.cwd })}\n`)+ await store.save(row, { screen: 'Startup screen' })+ expect((await manifest()).source).toBeNull()+ } finally { pi.restore() }+})+it('preserves a newly typed draft even when native history has not changed', async () => {await store.save(row, { screen: 'first draft' })const first = await manifest()diff --git a/cli/src/lib/sessionCheckpoint.ts b/cli/src/lib/sessionCheckpoint.tsindex 4015182b2..80bd0afdd 100644--- a/cli/src/lib/sessionCheckpoint.ts+++ b/cli/src/lib/sessionCheckpoint.ts@@ -8,6 +8,7 @@ import { atomicWriteJson, engineKeepsTranscriptFile, validTranscriptPath, type Rimport { readPrivateStateFile, secureStateDirectory } from './secureState.js'import { sqliteReadAll } from './sqliteRead.js'import { hermesDbPath } from '../engines/hermes/home.js'+import { findResumedTranscript } from './sessionRepair.js'export class SessionCheckpointError extends Error {readonly code = 'HISTORY_NOT_SAVED'@@ -105,7 +106,13 @@ export class SessionCheckpointStore {}const checkpoint: Checkpoint = { version: 1, agentId: s.agentId, sessionId: s.sessionId,engine: s.engine, codexHome: s.codexHome ?? null, savedAt: Date.now(), source: null, file, bytes: 0 }- if (!s.sessionId || s.engine === 'terminal') {+ const source = s.transcriptPath ?? (s.engine === 'pi' && s.sessionId+ ? await findResumedTranscript('pi', s.sessionId, { cwd: s.cwd ?? undefined }) : null)+ // Pi announces a session ID before it writes any history. In particular,+ // missing credentials can leave it here indefinitely. Preserve the screen+ // just as for an unbound chat; a known/resumed transcript must still save.+ const unwrittenPi = s.engine === 'pi' && !source && !s.resumeOnly && !previous?.source+ if (!s.sessionId || s.engine === 'terminal' || unwrittenPi) {// A shell or unused chat has no native conversation. Save its terminal// instead; the close service owns the activity check and confirmation.if (options.screen == null) {@@ -113,10 +120,9 @@ export class SessionCheckpointStore {&& (await lstat(join(this.directory, previous.file)).catch(() => null))?.isFile()) returnthrow new SessionCheckpointError('Could not save this terminal before closing it. Keep it open and try again.')}- atomicWriteJson(temporary, { version: 1, agentId: s.agentId, engine: s.engine, cwd: s.cwd,+ atomicWriteJson(temporary, { version: 1, agentId: s.agentId, sessionId: s.sessionId, engine: s.engine, cwd: s.cwd,savedAt: checkpoint.savedAt, screen: options.screen })} else if (engineKeepsTranscriptFile(s.engine)) {- const source = s.transcriptPathif (!source || !validTranscriptPath(s.engine, source, s.codexHome ?? undefined)) {throw new SessionCheckpointError('The conversation file is unavailable. The session has not been closed.')}diff --git a/cli/src/lib/sessionRepair.ts b/cli/src/lib/sessionRepair.tsindex 34d393107..938ef61e6 100644--- a/cli/src/lib/sessionRepair.ts+++ b/cli/src/lib/sessionRepair.ts@@ -25,6 +25,7 @@ import { copilotSessionCwd, copilotSessionForPid, findCopilotTranscript } from 'import { hermesDbPath, listHermesHomes } from '../engines/hermes/home.js'import { sqlitePreflightMessage } from './sqliteAvailability.js'import { sqliteReadAll, type SqliteParam } from './sqliteRead.js'+import { piSessionFolder, readPiHead } from './sessionSearch/externals/pi.js'/*** Clock granularity only. `ps` reports start time to the second, so a file created in the same second@@ -560,8 +561,28 @@ export async function claudeContinuation(transcriptPath: string): Promise<Repairexport async function findResumedTranscript(engine: AgentEngine,sessionId: string,- opts?: { codexHome?: string },+ opts?: { codexHome?: string; cwd?: string },): Promise<string | null> {+ if (engine === 'pi') {+ // Pi allocates an ID before its first reply creates the file. Look up that+ // exact ID again at Close, including after exit, without guessing by mtime.+ if (!opts?.cwd || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,126}[A-Za-z0-9]$/.test(sessionId)+ || sessionId.endsWith('.jsonl')) throw new Error('The Pi conversation location is unavailable.')+ const directory = join(env.PI_HOME, 'agent', 'sessions', piSessionFolder(opts.cwd))+ let files: string[]+ try { files = await readdir(directory) } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null+ throw error // An unreadable store is not an unwritten conversation.+ }+ const matches: string[] = []+ for (const file of files.filter(file => file.endsWith(`_${sessionId}.jsonl`))) {+ const head = await readPiHead(join(directory, file))+ if (!head || typeof head === 'symbol') throw new Error('The Pi conversation file could not be read.')+ if (head.sessionId === sessionId && await sameDir(head.cwd, opts.cwd)) matches.push(file)+ }+ if (matches.length > 1) throw new Error('More than one file matches this Pi conversation.')+ return matches.length ? join(directory, matches[0]) : null+ }if (!/^[0-9a-f-]{16,}$/i.test(sessionId)) return nullif (engine === 'codex') return resolveCodexRollout(sessionId, join(opts?.codexHome || env.CODEX_HOME, 'sessions'))if (engine !== 'claude') return null