Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion packages/core/src/config/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1610,9 +1610,11 @@ export class Config {
return;
}
try {
// Finalize the current session's metadata before cleanup.
// Finalize the current session's metadata before cleanup, then drain
// the async write queue so no records are lost on exit.
try {
this.chatRecordingService?.finalize();
await this.chatRecordingService?.flush();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

flush() only runs on the graceful path; the EPIPE exit path now silently drops queued records.

This line correctly drains the queue on Config.shutdown(), but nonInteractiveCli.ts:181 still calls process.exit(0) directly when stdout gets EPIPE — bypassing runExitCleanup entirely, so flush() never runs and queued records are lost.

Under sync writes this was harmless: bytes were on disk before the syscall returned, regardless of how the process exited. After this PR, the same code path becomes silent data loss.

Trigger case: qwen -p "list every file in this repo" | head -1. head exits → EPIPE on stdout → process.exit(0) → ~5 queued records (the most recent assistant turn + tool results) silently lost. This is a routine CLI usage pattern — cli | head, cli | less, cli | grep -m 1 — not an edge case.

Fix: at minimum, change nonInteractiveCli.ts:181 from process.exit(0) to process.stdout.destroy(), so the natural finally → runExitCleanup chain can complete the flush. Claude Code's process.ts uses exactly this pattern — stream.destroy() on EPIPE without exiting — for the same reason.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in bf24fff at nonInteractiveCli.ts:181 — process.exit(0) → process.stdout.destroy(), with a regression test that emits EPIPE mid-stream and asserts stdout.destroy is called (mocked process.exit would throw if the bypass came back).

One subtlety from implementing it: I tried adding abortController.abort() alongside the destroy, but the abort path runs handleCancellationError which itself calls process.exit(130) — same bypass on a different code path. So the handler now only destroys stdout and lets the natural function return drive cleanup. Token waste on EPIPE is bounded by the in-flight LLM response and seems like the right trade vs. data loss.

} catch {
// Best-effort — don't block shutdown
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ async function flushMicrotasks(): Promise<void> {

function findCustomTitleRecord(): ChatRecord | undefined {
return vi
.mocked(jsonl.writeLineSync)
.mocked(jsonl.writeLine)
.mock.calls.map((c) => c[1] as ChatRecord)
.find((r) => r.type === 'system' && r.subtype === 'custom_title');
}
Expand Down Expand Up @@ -133,6 +133,10 @@ describe('ChatRecordingService - auto-title trigger', () => {
vi.spyOn(fs, 'existsSync').mockReturnValue(false);

chatRecordingService = new ChatRecordingService(mockConfig);

// writeLine is async; mockResolvedValue lets the writeChain settle when
// tests await flushMicrotasks() / chatRecordingService.flush().
vi.mocked(jsonl.writeLine).mockResolvedValue(undefined);
});

afterEach(() => {
Expand Down Expand Up @@ -174,7 +178,8 @@ describe('ChatRecordingService - auto-title trigger', () => {

it('does not overwrite a manual title', async () => {
chatRecordingService.recordCustomTitle('chose-this-myself', 'manual');
vi.mocked(jsonl.writeLineSync).mockClear();
await chatRecordingService.flush();
vi.mocked(jsonl.writeLine).mockClear();

chatRecordingService.recordAssistantTurn({
model: 'qwen-plus',
Expand Down Expand Up @@ -326,10 +331,13 @@ describe('ChatRecordingService - auto-title trigger', () => {
expect(svc.getCurrentCustomTitle()).toBe('Auto-generated title');
expect(svc.getCurrentTitleSource()).toBe('auto');

// finalize() was called by the constructor — the re-appended record
// must carry titleSource: 'auto', not 'manual'.
// finalize() was called by the constructor — drain the queued async
// write before inspecting the mock.
await svc.flush();

// The re-appended record must carry titleSource: 'auto', not 'manual'.
const finalizeRecord = vi
.mocked(jsonl.writeLineSync)
.mocked(jsonl.writeLine)
.mock.calls.map((c) => c[1] as ChatRecord)
.find((r) => r.type === 'system' && r.subtype === 'custom_title');
expect(finalizeRecord?.systemPayload).toEqual({
Expand Down Expand Up @@ -362,9 +370,10 @@ describe('ChatRecordingService - auto-title trigger', () => {

expect(svc.getCurrentCustomTitle()).toBe('User chose this');
expect(svc.getCurrentTitleSource()).toBe('manual');
await svc.flush();

const finalizeRecord = vi
.mocked(jsonl.writeLineSync)
.mocked(jsonl.writeLine)
.mock.calls.map((c) => c[1] as ChatRecord)
.find((r) => r.type === 'system' && r.subtype === 'custom_title');
expect(finalizeRecord?.systemPayload).toEqual({
Expand Down Expand Up @@ -395,9 +404,10 @@ describe('ChatRecordingService - auto-title trigger', () => {
// Must stay undefined so the JSONL isn't upgraded to a misleading
// `titleSource: 'manual'` we can't actually verify.
expect(svc.getCurrentTitleSource()).toBeUndefined();
await svc.flush();

const finalizeRecord = vi
.mocked(jsonl.writeLineSync)
.mocked(jsonl.writeLine)
.mock.calls.map((c) => c[1] as ChatRecord)
.find((r) => r.type === 'system' && r.subtype === 'custom_title');
// Payload must NOT contain a titleSource field when source is unknown.
Expand Down Expand Up @@ -494,7 +504,8 @@ describe('ChatRecordingService - auto-title trigger', () => {

// User renames while the title LLM call is still pending.
chatRecordingService.recordCustomTitle('user-chosen', 'manual');
vi.mocked(jsonl.writeLineSync).mockClear();
await chatRecordingService.flush();
vi.mocked(jsonl.writeLine).mockClear();

// Now the LLM call returns a title.
resolveLlm({ ok: true, title: 'Auto Title', modelUsed: 'qwen-turbo' });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,18 +79,22 @@ describe('ChatRecordingService - recordCustomTitle', () => {
vi.spyOn(fs, 'existsSync').mockReturnValue(false);

chatRecordingService = new ChatRecordingService(mockConfig);

// writeLine is async; mockResolvedValue lets the writeChain settle on flush.
vi.mocked(jsonl.writeLine).mockResolvedValue(undefined);
});

afterEach(() => {
vi.restoreAllMocks();
});

it('should record a custom title as a system record', () => {
it('should record a custom title as a system record', async () => {
chatRecordingService.recordCustomTitle('my-feature');
await chatRecordingService.flush();

expect(jsonl.writeLineSync).toHaveBeenCalledOnce();
expect(jsonl.writeLine).toHaveBeenCalledOnce();

const writtenRecord = vi.mocked(jsonl.writeLineSync).mock
const writtenRecord = vi.mocked(jsonl.writeLine).mock
.calls[0][1] as ChatRecord;
expect(writtenRecord.type).toBe('system');
expect(writtenRecord.subtype).toBe('custom_title');
Expand All @@ -101,24 +105,26 @@ describe('ChatRecordingService - recordCustomTitle', () => {
expect(writtenRecord.sessionId).toBe('test-session-id');
});

it('should maintain parent chain when recording title after other records', () => {
it('should maintain parent chain when recording title after other records', async () => {
chatRecordingService.recordUserMessage([{ text: 'hello' }]);
chatRecordingService.recordCustomTitle('my-feature');
await chatRecordingService.flush();

expect(jsonl.writeLineSync).toHaveBeenCalledTimes(2);
expect(jsonl.writeLine).toHaveBeenCalledTimes(2);

const userRecord = vi.mocked(jsonl.writeLineSync).mock
const userRecord = vi.mocked(jsonl.writeLine).mock
.calls[0][1] as ChatRecord;
const titleRecord = vi.mocked(jsonl.writeLineSync).mock
const titleRecord = vi.mocked(jsonl.writeLine).mock
.calls[1][1] as ChatRecord;

expect(titleRecord.parentUuid).toBe(userRecord.uuid);
});

it('should include correct metadata in the record', () => {
it('should include correct metadata in the record', async () => {
chatRecordingService.recordCustomTitle('test-title');
await chatRecordingService.flush();

const writtenRecord = vi.mocked(jsonl.writeLineSync).mock
const writtenRecord = vi.mocked(jsonl.writeLine).mock
.calls[0][1] as ChatRecord;

expect(writtenRecord.cwd).toBe('/test/project/root');
Expand All @@ -129,15 +135,16 @@ describe('ChatRecordingService - recordCustomTitle', () => {
});

describe('finalize', () => {
it('should re-append cached custom title to EOF', () => {
it('should re-append cached custom title to EOF', async () => {
chatRecordingService.recordCustomTitle('my-feature');
vi.mocked(jsonl.writeLineSync).mockClear();
await chatRecordingService.flush();
vi.mocked(jsonl.writeLine).mockClear();

chatRecordingService.finalize();
await chatRecordingService.flush();

expect(jsonl.writeLineSync).toHaveBeenCalledOnce();
const record = vi.mocked(jsonl.writeLineSync).mock
.calls[0][1] as ChatRecord;
expect(jsonl.writeLine).toHaveBeenCalledOnce();
const record = vi.mocked(jsonl.writeLine).mock.calls[0][1] as ChatRecord;
expect(record.type).toBe('system');
expect(record.subtype).toBe('custom_title');
expect(record.systemPayload).toEqual({
Expand All @@ -146,22 +153,24 @@ describe('ChatRecordingService - recordCustomTitle', () => {
});
});

it('should not write anything when no custom title was set', () => {
it('should not write anything when no custom title was set', async () => {
chatRecordingService.finalize();
await chatRecordingService.flush();

expect(jsonl.writeLineSync).not.toHaveBeenCalled();
expect(jsonl.writeLine).not.toHaveBeenCalled();
});

it('should re-append the latest title after multiple renames', () => {
it('should re-append the latest title after multiple renames', async () => {
chatRecordingService.recordCustomTitle('first-name');
chatRecordingService.recordCustomTitle('second-name');
vi.mocked(jsonl.writeLineSync).mockClear();
await chatRecordingService.flush();
vi.mocked(jsonl.writeLine).mockClear();

chatRecordingService.finalize();
await chatRecordingService.flush();

expect(jsonl.writeLineSync).toHaveBeenCalledOnce();
const record = vi.mocked(jsonl.writeLineSync).mock
.calls[0][1] as ChatRecord;
expect(jsonl.writeLine).toHaveBeenCalledOnce();
const record = vi.mocked(jsonl.writeLine).mock.calls[0][1] as ChatRecord;
expect(record.systemPayload).toEqual({
customTitle: 'second-name',
titleSource: 'manual',
Expand Down
Loading
Loading