Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
13 changes: 11 additions & 2 deletions packages/cli/src/ui/components/SessionPicker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,15 @@ function SessionListItemView({
boldSelectedPrefix = true,
}: SessionListItemViewProps): React.JSX.Element {
const timeAgo = formatRelativeTime(session.mtime);
const messageText = formatMessageCount(session.messageCount);
// `messageCount` is now optional on `SessionListItem` because counting
// requires a full readline pass over the JSONL — far too expensive to do
// in the listing path. The row simply omits the "N messages" segment
// when the count isn't available; preview-style consumers that care can
// call `SessionService.countSessionMessages(sessionId)` lazily.
Comment thread
wenshao marked this conversation as resolved.
Resolved
const messageText =
typeof session.messageCount === 'number'
Comment thread
wenshao marked this conversation as resolved.
Resolved
? formatMessageCount(session.messageCount)
: undefined;

const showUpIndicator = isFirst && showScrollUp;
const showDownIndicator = isLast && showScrollDown;
Expand Down Expand Up @@ -139,7 +147,8 @@ function SessionListItemView({
</Box>
<Box paddingLeft={2}>
<Text color={theme.text.secondary}>
{timeAgo} · {messageText}
{timeAgo}
{messageText !== undefined && ` · ${messageText}`}
{session.gitBranch && ` · ${session.gitBranch}`}
</Text>
</Box>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -177,4 +177,81 @@ describe('ChatRecordingService - recordCustomTitle', () => {
});
});
});

describe('title re-anchor invariant', () => {
it('re-anchors the title once enough non-title bytes accumulate', async () => {
// Write a title, then keep appending bulky messages until the
// running tally crosses the 32KB threshold. The first non-title
// record after the threshold should provoke a fresh
// custom_title append at EOF — keeping the title within the
// 64KB tail window the picker scans even if no lifecycle event
// (finalize) has fired.
chatRecordingService.recordCustomTitle('long-running-task');
await chatRecordingService.flush();
vi.mocked(jsonl.writeLine).mockClear();

// Each user message carries ~2KB of text — 20 of them put well
// over 32KB on the wire (counting the ~200B per-record envelope).
const bulkText = 'x'.repeat(2000);
for (let i = 0; i < 20; i++) {
chatRecordingService.recordUserMessage([{ text: bulkText }]);
}
await chatRecordingService.flush();

const writes = vi.mocked(jsonl.writeLine).mock.calls;
const titleAppendsAfterClear = writes.filter(([, record]) => {
const r = record as ChatRecord;
return r.type === 'system' && r.subtype === 'custom_title';
});

expect(titleAppendsAfterClear.length).toBeGreaterThanOrEqual(1);
// The re-anchored record must carry the same title + source as
// the original — it's a copy, not a fresh rename.
const reanchored = titleAppendsAfterClear[0][1] as ChatRecord;
expect(reanchored.systemPayload).toEqual({
customTitle: 'long-running-task',
titleSource: 'manual',
});
});

it('does not re-anchor when no title has been set', async () => {
// The counter only matters when there's a title to keep alive;
// sessions that never set one shouldn't pay for spurious writes.
const bulkText = 'x'.repeat(2000);
for (let i = 0; i < 30; i++) {
chatRecordingService.recordUserMessage([{ text: bulkText }]);
}
await chatRecordingService.flush();

const titleAppends = vi
.mocked(jsonl.writeLine)
.mock.calls.filter(([, record]) => {
const r = record as ChatRecord;
return r.type === 'system' && r.subtype === 'custom_title';
});
expect(titleAppends).toHaveLength(0);
});

it('does not re-anchor on small write bursts under threshold', async () => {
// A handful of small messages must not trigger a re-anchor —
// the cost would defeat the whole point. Threshold is 32KB;
// five 200B user messages stay safely under it.
chatRecordingService.recordCustomTitle('quick-session');
await chatRecordingService.flush();
vi.mocked(jsonl.writeLine).mockClear();

for (let i = 0; i < 5; i++) {
chatRecordingService.recordUserMessage([{ text: 'short' }]);
}
await chatRecordingService.flush();

const titleAppends = vi
.mocked(jsonl.writeLine)
.mock.calls.filter(([, record]) => {
const r = record as ChatRecord;
return r.type === 'system' && r.subtype === 'custom_title';
});
expect(titleAppends).toHaveLength(0);
});
});
});
84 changes: 84 additions & 0 deletions packages/core/src/services/chatRecordingService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,17 @@ const SESSION_FILE_DIFF_AGGREGATE_CHAR_LIMIT = 100_000;
const SESSION_FILE_DIFF_CHAR_LIMIT = 50_000;
const SESSION_FILE_CONTENT_CHAR_LIMIT = 16_000;

/**
* Re-append a fresh `custom_title` record to EOF once this many bytes
* of other JSONL content have been written since the last title
* anchor. Half of the picker's 64KB tail-read window so that even an
* oversized record landing right at the threshold keeps the title
* within scan range. Lifting this above 64KB would let the title
* fall out of the tail window between re-anchors; lowering it
* trades extra writes for a tighter safety margin.
*/
const TITLE_REANCHOR_BYTES = 32 * 1024;

Comment thread
wenshao marked this conversation as resolved.
Resolved
function isFileDiffDisplay(resultDisplay: unknown): resultDisplay is FileDiff {
if (
typeof resultDisplay !== 'object' ||
Expand Down Expand Up @@ -466,6 +477,20 @@ export class ChatRecordingService {
*/
private autoTitleController: AbortController | undefined;

/**
* Approximate bytes of JSONL content appended since the last
* `custom_title` record landed in this file. Used by the title
* re-anchor invariant: once enough non-title content accumulates
* past the last anchor, {@link appendRecord} re-appends a fresh
* `custom_title` to EOF so the picker's tail-window scan
* ({@link readSessionTitleFromFile}) keeps finding it.
*
* Without this, a long agentic turn that streams >64KB of tool
* output could push the only `custom_title` record past the 64KB
* tail window, forcing the picker into a full-file fallback.

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.

[Suggestion] This JSDoc says "forcing the picker into a full-file fallback," but the full-file fallback was removed by this PR — the picker now does a bounded head-window read (64KB from offset 0) or returns undefined. The stale wording could mislead a future reader into thinking full-file scanning still exists.

Suggested change
* tail window, forcing the picker into a full-file fallback.
forcing the picker into a head-window fallback (or returning undefined if the title is beyond both windows).

— glm-5.1 via Qwen Code /review

*/
private bytesSinceTitleAnchor = 0;

constructor(config: Config) {
this.config = config;
this.lastRecordUuid =
Expand Down Expand Up @@ -627,6 +652,65 @@ export class ChatRecordingService {
.catch((err) => {
debugLogger.error('Error appending record (async):', err);
});
this.updateTitleAnchorTracking(record);
Comment thread
wenshao marked this conversation as resolved.
Resolved
}

/**
* Maintain the "title is always in the tail window" invariant by
* counting bytes appended since the last `custom_title` record and
* re-anchoring once enough non-title content has been written.
*
* - A `custom_title` record IS the new anchor — reset the counter.
* - Without a current title (never set), the counter is irrelevant.
* - Otherwise accumulate this record's serialized size; if the
* running total breaches the threshold, re-append a fresh
* `custom_title` to EOF. The recursive `appendRecord` call will
* land this branch's first arm (subtype === 'custom_title') and
* reset the counter to 0.
*
* Size estimate uses `JSON.stringify` for parity with the actual
* write path (`jsonl.writeLine` serializes the same way). It's an
Comment thread
wenshao marked this conversation as resolved.
Resolved
* extra serialize per record, but appendRecord is already gated by
* an async I/O write whose cost dominates by orders of magnitude.
*/
private updateTitleAnchorTracking(record: ChatRecord): void {
if (record.type === 'system' && record.subtype === 'custom_title') {
this.bytesSinceTitleAnchor = 0;
return;
}
if (!this.currentCustomTitle) return;
// +1 for the trailing newline jsonl.writeLine appends.
this.bytesSinceTitleAnchor += JSON.stringify(record).length + 1;
if (this.bytesSinceTitleAnchor >= TITLE_REANCHOR_BYTES) {
this.reanchorTitle();
}
}

/**
* Append a fresh `custom_title` record to EOF using the in-memory
* cached title. Mirrors {@link finalize}'s record shape — invoked
* mid-session (every {@link TITLE_REANCHOR_BYTES} of other writes)
* so the picker's tail-window scan never has to fall back to
* scanning the middle of the file.
*/
private reanchorTitle(): void {
if (!this.currentCustomTitle) return;
try {
const record: ChatRecord = {
...this.createBaseRecord('system'),
type: 'system',
subtype: 'custom_title',
systemPayload: {
customTitle: this.currentCustomTitle,
Comment thread
wenshao marked this conversation as resolved.
Resolved
...(this.currentTitleSource
? { titleSource: this.currentTitleSource }
: {}),
},
};
this.appendRecord(record);
} catch (error) {
debugLogger.error('Error re-anchoring custom title:', error);
}
}

/**
Expand Down
22 changes: 22 additions & 0 deletions packages/core/src/services/sessionService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,28 @@ describe('SessionService', () => {
expect(result.items[0].gitBranch).toBe('main');
});

it('should NOT populate messageCount during listing', async () => {
// Listing must avoid the full-file readline that counting requires
// — message counts are now lazy and provided by
// `countSessionMessages(sessionId)` only when a UI surface (e.g.
// a session preview) is about to display them. Pinning this
// contract here so future refactors can't quietly re-introduce
// the per-file scan that used to dominate /resume open time.
readdirSyncSpy.mockReturnValue([
`${sessionIdA}.jsonl`,
] as unknown as Array<fs.Dirent<Buffer>>);
statSyncSpy.mockReturnValue({
mtimeMs: Date.now(),
isFile: () => true,
} as fs.Stats);
vi.mocked(jsonl.readLines).mockResolvedValue([recordA1]);

const result = await sessionService.listSessions();

expect(result.items).toHaveLength(1);
expect(result.items[0].messageCount).toBeUndefined();
});

it('should truncate long prompts', async () => {
const longPrompt = 'A'.repeat(300);
const recordWithLongPrompt: ChatRecord = {
Expand Down
Loading
Loading