mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-24 04:47:03 +00:00
perf(codex): optimize session history import (#2206)
This commit is contained in:
@@ -1,9 +1,14 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync, existsSync } from 'node:fs'
|
||||
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 { archiveLocalCodexSession, listLocalCodexSessionSummaries, listLocalCodexSessionsWithMessagesByIds } from './codexSessions'
|
||||
|
||||
vi.mock('node:fs', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('node:fs')>()
|
||||
return { ...actual, readFileSync: vi.fn(actual.readFileSync) }
|
||||
})
|
||||
|
||||
describe('archiveLocalCodexSession', () => {
|
||||
const originalCodexHome = process.env.CODEX_HOME
|
||||
|
||||
@@ -180,4 +185,47 @@ describe('listLocalCodexSessionSummaries', () => {
|
||||
expect(sessions[0]?.messages).toHaveLength(1)
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
it('selects the latest matching session without mistaking child transcripts for it', () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'codex-home-'))
|
||||
process.env.CODEX_HOME = root
|
||||
const dir = join(root, 'sessions')
|
||||
mkdirSync(dir, { recursive: true })
|
||||
const make = (name: string, source: unknown, text: string, seconds: number) => {
|
||||
const path = join(dir, name)
|
||||
writeFileSync(path, [
|
||||
JSON.stringify({ type: 'session_meta', payload: { id: 'wanted', cwd: '/tmp/project', source } }),
|
||||
JSON.stringify({ type: 'response_item', payload: { type: 'message', role: 'user', content: [{ type: 'input_text', text }] } })
|
||||
].join('\n'))
|
||||
utimesSync(path, seconds, seconds)
|
||||
}
|
||||
make('old.jsonl', 'cli', 'old', 100)
|
||||
make('new.jsonl', 'cli', 'new', 200)
|
||||
make('child.jsonl', { subagent: 'worker' }, 'child', 300)
|
||||
const sessions = listLocalCodexSessionsWithMessagesByIds(new Set(['wanted']))
|
||||
expect(sessions).toHaveLength(1)
|
||||
expect(sessions[0]?.file).toBe(join(dir, 'new.jsonl'))
|
||||
expect(JSON.stringify(sessions[0]?.messages)).toContain('new')
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
it('does not fully read unrelated large session files', () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'codex-home-'))
|
||||
process.env.CODEX_HOME = root
|
||||
const dir = join(root, 'sessions')
|
||||
mkdirSync(dir, { recursive: true })
|
||||
const wanted = join(dir, 'wanted.jsonl')
|
||||
const unrelated = join(dir, 'unrelated.jsonl')
|
||||
writeFileSync(wanted, JSON.stringify({ type: 'session_meta', payload: { id: 'wanted' } }) + '\n')
|
||||
writeFileSync(unrelated, JSON.stringify({ type: 'session_meta', payload: { id: 'unrelated' } }) + '\n' + 'x'.repeat(2 * 1024 * 1024))
|
||||
const spy = vi.mocked(readFileSync)
|
||||
spy.mockClear()
|
||||
try {
|
||||
expect(listLocalCodexSessionsWithMessagesByIds(new Set(['wanted'])).map(session => session.id)).toEqual(['wanted'])
|
||||
expect(spy.mock.calls.some(call => call[0] === unrelated)).toBe(false)
|
||||
} finally {
|
||||
spy.mockClear()
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync } from 'node:fs'
|
||||
import { closeSync, existsSync, mkdirSync, openSync, readSync, readdirSync, readFileSync, renameSync, statSync } from 'node:fs'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { basename, dirname, join, relative } from 'node:path'
|
||||
import { homedir } from 'node:os'
|
||||
@@ -403,10 +403,51 @@ export function listLocalCodexSessionsWithMessages(limit = DEFAULT_CODEX_SESSION
|
||||
export function listLocalCodexSessionsWithMessagesByIds(ids: Set<string>): LocalCodexSessionWithMessages[] {
|
||||
if (ids.size === 0) return []
|
||||
const sessionIndexTitles = readCodexSessionIndexTitles()
|
||||
return listLocalCodexSessionSummaries(Number.MAX_SAFE_INTEGER)
|
||||
.filter((session) => ids.has(session.id))
|
||||
.map((session) => parseCodexLocalSession(session.file, true, sessionIndexTitles))
|
||||
.filter((session): session is LocalCodexSessionWithMessages => Boolean(session))
|
||||
const files: string[] = []
|
||||
for (const root of getCodexSessionRoots()) collectJsonlFiles(root, files)
|
||||
const candidates = new Map<string, Array<{ file: string; modifiedAt: number }>>()
|
||||
for (const file of files) {
|
||||
let fd: number | undefined
|
||||
let identity: string | null = null
|
||||
let rejected = false
|
||||
try {
|
||||
// 先读取有限的元数据,再完整加载被选中的会话记录。
|
||||
fd = openSync(file, 'r')
|
||||
const buffer = Buffer.alloc(1024 * 1024)
|
||||
const size = readSync(fd, buffer, 0, buffer.length, 0)
|
||||
const prefix = buffer.subarray(0, size).toString('utf8')
|
||||
const lines = prefix.split(/\r?\n/)
|
||||
if (size === buffer.length && !prefix.endsWith('\n')) lines.pop()
|
||||
for (const line of lines.filter(Boolean).slice(0, 200)) {
|
||||
try {
|
||||
const record = asRecord(JSON.parse(line))
|
||||
if (record?.type !== 'session_meta') continue
|
||||
const payload = asRecord(record.payload)
|
||||
if (isCodexSubagentSource(payload?.source)) { rejected = true; break }
|
||||
if (!identity && typeof payload?.id === 'string') identity = payload.id
|
||||
} catch { continue }
|
||||
}
|
||||
if (!identity && !rejected) {
|
||||
// 对异常或过大的文件头保留原有解析行为。
|
||||
const fallback = parseCodexLocalSession(file, false, sessionIndexTitles)
|
||||
identity = fallback?.id ?? null
|
||||
}
|
||||
if (!identity || rejected || !ids.has(identity)) continue
|
||||
const entries = candidates.get(identity) ?? []
|
||||
entries.push({ file, modifiedAt: statSync(file).mtimeMs })
|
||||
candidates.set(identity, entries)
|
||||
} catch { continue }
|
||||
finally { if (fd !== undefined) closeSync(fd) }
|
||||
}
|
||||
const result: LocalCodexSessionWithMessages[] = []
|
||||
for (const [id, entries] of candidates) {
|
||||
entries.sort((a, b) => b.modifiedAt - a.modifiedAt)
|
||||
for (const entry of entries) {
|
||||
const session = parseCodexLocalSession(entry.file, true, sessionIndexTitles)
|
||||
if (session && session.id === id && 'messages' in session) { result.push(session); break }
|
||||
}
|
||||
}
|
||||
return result.sort((a, b) => b.modifiedAt - a.modifiedAt)
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user