fix(codex): fold a codex session into its own rollout row

Review fixes for #386.

Duplicate rows. A codex conversation showed twice, once live and once as a
past rollout row, because nothing aliased a codex session to its thread id.
That is worse than cosmetic: the stale row still resumes, so clicking it
starts a second `codex resume` on a thread already open in another pane.

  - A RESUMED session knows its thread id up front, so it folds from its own
    side: add `codexConfig.resumeSessionId` to the `claudeSessionId` chain.
    Not only in the constructor — `start()` recomputes that id at two further
    points (the mux branch, and the unconditional "third reset point" whose
    own comment already warned that omitting omp's fallback there stomps the
    mux branch's resolved alias). Both listed Claude's and omp's ids only, so
    for codex every mux reattach and boot recovery reset the alias back to
    the Codeman id and the duplicate returned.
  - A FRESH session has no thread id until codex writes the rollout, so it is
    folded from the other side. The scanner now reports
    `session_meta.originator`, which is `codeman_<sessionId>` for every pane
    Codeman spawns, and `gatherUnifiedInputs()` stamps the matching live and
    persisted rows, newest rollout winning (`/new` inside the TUI leaves
    several rollouts sharing one originator).
  - Persisted rows read `codexConfig.resumeSessionId` too. A resumed session
    demoted to a persisted-only record would otherwise lose its alias, and
    the originator fallback cannot rescue that one: a resumed rollout keeps
    its ORIGINAL session_meta, so it still names the pane that created the
    thread rather than the pane that resumed it.

Identity cache. It was written as soon as the thread id was known, but codex
writes the first user message only when the user submits, so any scan in that
window pinned `firstPrompt: undefined` for the life of the process — and the
home screen, the command palette and the search-index refresh all scan.
`shouldCacheIdentity()` now keeps an identity only once the prompt is known or
the head read filled its whole window.

Also from review: both caps count emitted rows rather than file index, so a
store of sub-agent threads no longer spends the `lastPrompt` budget before the
first row that needed it; the cache is an `LRUMap` sized like the one beside
it; the unreachable filename fallback is gone; a rollout recording no cwd is
dropped rather than emitted with `workingDir: ''`; and the unified-session
module header names all three transcript stores.

Tests. The resume wiring now has cases for a row with a thread id, a row
without one, and a `resumeId` on a non-codex row; the "no continuation is
wired" case narrows to gemini/antigravity, which is no longer true of codex.
`codex-resume-alias-survives-start.test.ts` drives a real Session through
`start()` rather than asserting on pre-stamped inputs — that gap is why the
reset points went unnoticed. Plus the maintainer's own cache repro, the
tail-budget case, a no-cwd case, and merge cases for both folds.
This commit is contained in:
Michael Grundberg
2026-09-06 21:53:38 +02:00
parent 8285fff91c
commit 327e440607
9 changed files with 442 additions and 58 deletions
+101 -5
View File
@@ -16,25 +16,29 @@
* outnumbered the threads a person can actually resume.
*/
import { describe, expect, it, beforeEach, afterEach } from 'vitest';
import { mkdtemp, mkdir, writeFile, rm, utimes } from 'node:fs/promises';
import { appendFile, mkdtemp, mkdir, writeFile, rm, utimes } from 'node:fs/promises';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { scanCodexSessionsHistory, __clearCodexIdentityCache } from '../src/codex-transcript.js';
import {
scanCodexSessionsHistory,
codexThreadBySessionId,
__clearCodexIdentityCache,
} from '../src/codex-transcript.js';
let home: string;
let prevCodexHome: string | undefined;
/** A rollout's opening line, as codex writes it. */
const sessionMeta = (opts: { id: string; cwd: string; threadSource?: string }) =>
const sessionMeta = (opts: { id: string; cwd?: string; threadSource?: string; originator?: string }) =>
JSON.stringify({
timestamp: '2026-09-02T07:05:37.421Z',
type: 'session_meta',
payload: {
id: opts.id,
session_id: opts.id,
cwd: opts.cwd,
originator: 'codex-tui',
...(opts.cwd ? { cwd: opts.cwd } : {}),
originator: opts.originator ?? 'codex-tui',
...(opts.threadSource ? { thread_source: opts.threadSource } : {}),
// The real thing embeds full base instructions here; padded so the file
// clears the size floor and exercises the head window.
@@ -194,6 +198,76 @@ describe('scanCodexSessionsHistory', () => {
expect(rows[0].firstPrompt).toBe('still found me');
});
it('reports the originator, which is how a fresh pane finds its own rollout', async () => {
await writeRollout('bbbbbbbb-bbbb-7bbb-8bbb-bbbbbbbbbbbb', [
sessionMeta({
id: 'bbbbbbbb-bbbb-7bbb-8bbb-bbbbbbbbbbbb',
cwd: '/repo/nine',
originator: 'codeman_2f1c9a44-1111-2222-3333-444455556666',
}),
itemCompletedUser('hello'),
]);
const rows = await scanCodexSessionsHistory();
expect(rows[0].originator).toBe('codeman_2f1c9a44-1111-2222-3333-444455556666');
});
it('drops a rollout that records no working directory', async () => {
// Emitting workingDir: '' would make a click post an empty directory.
await writeRollout('cccccccc-cccc-7ccc-8ccc-cccccccccccc', [
sessionMeta({ id: 'cccccccc-cccc-7ccc-8ccc-cccccccccccc' }),
itemCompletedUser('nowhere to resume into'),
]);
expect(await scanCodexSessionsHistory()).toEqual([]);
});
it('picks up a prompt written after an earlier scan saw none', async () => {
// The bug this pins: the identity cache was written as soon as the thread id
// was known, but codex writes the first UserMessage only when the user
// submits. Any scan in that window — the home screen, the command palette,
// the search-index refresh — pinned `firstPrompt: undefined` until restart.
const id = 'dddddddd-dddd-7ddd-8ddd-dddddddddddd';
const path = await writeRollout(id, [sessionMeta({ id, cwd: '/repo/ten' })]);
const before = await scanCodexSessionsHistory();
expect(before).toHaveLength(1);
expect(before[0].firstPrompt).toBeUndefined();
await appendFile(path, itemCompletedUser('the prompt, typed a moment later') + '\n', 'utf-8');
const after = await scanCodexSessionsHistory();
expect(after[0].firstPrompt).toBe('the prompt, typed a moment later');
});
it('does not spend the lastPrompt budget on rollouts it never returns', async () => {
// The budget used to count file index, so a store whose newest files are all
// sub-agent threads exhausted it before the first row that needed it.
for (let i = 0; i < 3; i++) {
await writeRollout(
`eeeeeeee-eeee-7eee-8eee-00000000000${i}`,
[
sessionMeta({ id: `eeeeeeee-eeee-7eee-8eee-00000000000${i}`, cwd: '/repo/sub', threadSource: 'subagent' }),
itemCompletedUser('subagent work'),
],
new Date('2026-09-05T00:00:00Z')
);
}
await writeRollout(
'ffffffff-ffff-7fff-8fff-ffffffffffff',
[
sessionMeta({ id: 'ffffffff-ffff-7fff-8fff-ffffffffffff', cwd: '/repo/real' }),
itemCompletedUser('opening'),
itemCompletedUser('the latest thing asked'),
],
new Date('2026-09-04T00:00:00Z')
);
const rows = await scanCodexSessionsHistory();
expect(rows).toHaveLength(1);
expect(rows[0].lastPrompt).toBe('the latest thing asked');
});
it('collapses a long prompt to a single capped line', async () => {
await writeRollout('aaaaaaaa-aaaa-7aaa-8aaa-aaaaaaaaaaaa', [
sessionMeta({ id: 'aaaaaaaa-aaaa-7aaa-8aaa-aaaaaaaaaaaa', cwd: '/repo/eight' }),
@@ -206,3 +280,25 @@ describe('scanCodexSessionsHistory', () => {
expect(rows[0].firstPrompt!.endsWith('…')).toBe(true);
});
});
describe('codexThreadBySessionId', () => {
const row = (sessionId: string, originator?: string) =>
({ sessionId, originator, workingDir: '/w', sizeBytes: 1, lastModified: '2026-09-02T00:00:00.000Z' }) as never;
it('maps a Codeman-spawned pane to the thread it is writing', () => {
const map = codexThreadBySessionId([row('thread-a', 'codeman_sess-1')]);
expect(map.get('sess-1')).toBe('thread-a');
});
it('ignores a rollout codex started on its own', () => {
expect(codexThreadBySessionId([row('thread-a', 'codex-tui')]).size).toBe(0);
expect(codexThreadBySessionId([row('thread-a', undefined)]).size).toBe(0);
});
it('keeps the newest rollout when a pane has several', () => {
// `/new` inside the codex TUI leaves the pane's originator on more than one
// rollout; the pane is on the most recent, and rows arrive newest-first.
const map = codexThreadBySessionId([row('thread-new', 'codeman_sess-1'), row('thread-old', 'codeman_sess-1')]);
expect(map.get('sess-1')).toBe('thread-new');
});
});