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
172 changes: 172 additions & 0 deletions packages/core/src/core/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,78 @@ describe('Gemini Client (client.ts)', () => {
expect(newHistory.length).toBe(initialHistory.length);
expect(JSON.stringify(newHistory)).not.toContain('some old message');
});

it('clears the FileReadCache so post-reset Reads re-emit content', async () => {
const cacheClear = vi.fn();
Comment thread
wenshao marked this conversation as resolved.
Resolved
vi.mocked(mockConfig.getFileReadCache).mockReturnValue({
clear: cacheClear,
} as unknown as ReturnType<Config['getFileReadCache']>);

await client.resetChat();

expect(cacheClear).toHaveBeenCalled();
});
});

describe('history mutation invalidates FileReadCache', () => {
it('setHistory clears the cache', () => {
const cacheClear = vi.fn();
vi.mocked(mockConfig.getFileReadCache).mockReturnValue({
clear: cacheClear,
} as unknown as ReturnType<Config['getFileReadCache']>);
client['chat'] = {
setHistory: vi.fn(),
} as unknown as GeminiChat;

client.setHistory([{ role: 'user', parts: [{ text: 'replaced' }] }]);

expect(cacheClear).toHaveBeenCalled();
});

it('truncateHistory clears the cache', () => {
const cacheClear = vi.fn();
vi.mocked(mockConfig.getFileReadCache).mockReturnValue({
clear: cacheClear,
} as unknown as ReturnType<Config['getFileReadCache']>);
client['chat'] = {
truncateHistory: vi.fn(),
} as unknown as GeminiChat;

client.truncateHistory(2);

expect(cacheClear).toHaveBeenCalled();
});

it('retry strips orphaned trailing user entries and clears the cache', async () => {
const cacheClear = vi.fn();
vi.mocked(mockConfig.getFileReadCache).mockReturnValue({
clear: cacheClear,
} as unknown as ReturnType<Config['getFileReadCache']>);
const stripOrphanedUserEntriesFromHistory = vi.fn();
client['chat'] = {
addHistory: vi.fn(),
getHistory: vi.fn().mockReturnValue([]),
stripOrphanedUserEntriesFromHistory,
} as unknown as GeminiChat;
mockTurnRunFn.mockReturnValue(
(async function* () {
yield { type: GeminiEventType.Content, value: 'response' };
})(),
);

const stream = client.sendMessageStream(
[{ text: 'retry' }],
new AbortController().signal,
'prompt-retry-1',
{ type: SendMessageType.Retry },
);
for await (const _ of stream) {
/* drain */
}

expect(stripOrphanedUserEntriesFromHistory).toHaveBeenCalled();
expect(cacheClear).toHaveBeenCalled();
});
});

describe('thinking block idle cleanup and latch', () => {
Expand Down Expand Up @@ -506,6 +578,106 @@ describe('Gemini Client (client.ts)', () => {
});
});

describe('microcompaction FileReadCache invalidation', () => {
function makeReadFileResponses(count: number): Content[] {
const out: Content[] = [];
for (let i = 0; i < count; i++) {
out.push({
role: 'model',
parts: [
{
functionCall: {
name: 'read_file',
args: { file_path: `/x/${i}.ts` },
},
},
],
});
out.push({
role: 'user',
parts: [
{
functionResponse: {
name: 'read_file',
response: { output: `content of ${i}` },
},
},
],
});
}
return out;
}

beforeEach(() => {
mockTurnRunFn.mockReturnValue(
(async function* () {
yield { type: GeminiEventType.Content, value: 'response' };
})(),
);
});

it('clears the cache after microcompaction strips old read_file results', async () => {
// Default test fixture: toolResultsThresholdMinutes = 60,
// toolResultsNumToKeep = 5. Six read_file results + a 90-minute
// idle gap means the oldest one gets cleared, so the if-meta
// branch in sendMessageStream fires and must invalidate the cache.
const cacheClear = vi.fn();
vi.mocked(mockConfig.getFileReadCache).mockReturnValue({
clear: cacheClear,
} as unknown as ReturnType<Config['getFileReadCache']>);

const history = makeReadFileResponses(6);
const setHistory = vi.fn();
client['chat'] = {
addHistory: vi.fn(),
getHistory: vi.fn().mockReturnValue(history),
setHistory,
} as unknown as GeminiChat;
client['lastApiCompletionTimestamp'] = Date.now() - 90 * 60_000;

const stream = client.sendMessageStream(
[{ text: 'hi' }],
new AbortController().signal,
'prompt-mc-clear-1',
{ type: SendMessageType.UserQuery },
);
for await (const _ of stream) {
/* drain */
}

expect(setHistory).toHaveBeenCalled();
expect(cacheClear).toHaveBeenCalled();
});

it('does not clear the cache when the idle gap is below the threshold', async () => {
const cacheClear = vi.fn();
vi.mocked(mockConfig.getFileReadCache).mockReturnValue({
clear: cacheClear,
} as unknown as ReturnType<Config['getFileReadCache']>);

const history = makeReadFileResponses(6);
client['chat'] = {
addHistory: vi.fn(),
getHistory: vi.fn().mockReturnValue(history),
setHistory: vi.fn(),
} as unknown as GeminiChat;
// Recent activity — microcompaction must not fire.
client['lastApiCompletionTimestamp'] = Date.now() - 30 * 1000;

const stream = client.sendMessageStream(
[{ text: 'hi' }],
new AbortController().signal,
'prompt-mc-clear-2',
{ type: SendMessageType.UserQuery },
);
for await (const _ of stream) {
/* drain */
}

expect(cacheClear).not.toHaveBeenCalled();
});
});

describe('tryCompressChat', () => {
const mockGetHistory = vi.fn();

Expand Down
30 changes: 30 additions & 0 deletions packages/core/src/core/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,15 +206,31 @@ export class GeminiClient {

private stripOrphanedUserEntriesFromHistory() {
this.getChat().stripOrphanedUserEntriesFromHistory();
// Stripped trailing user entries can include read_file
// functionResponses from a failed-then-retried request. The
// FileReadCache would still record those reads, so the retry's
// re-issued Read could hit the file_unchanged placeholder while
// the model has nothing to fall back on. Clear to be safe.
this.config.getFileReadCache().clear();
}

setHistory(history: Content[]) {
this.getChat().setHistory(history);
// Replacing history wholesale drops any prior read_file tool
// results the FileReadCache still believes the model has seen.
// Without clearing, a follow-up Read of an unchanged file would
// return the file_unchanged placeholder for bytes that no longer
// exist in the new history.
this.config.getFileReadCache().clear();
this.forceFullIdeContext = true;
}

truncateHistory(keepCount: number) {
this.getChat().truncateHistory(keepCount);
// Truncation can drop prior read_file results past keepCount while
// the FileReadCache still records those reads — same staleness
// risk as setHistory. Clear to force re-emission.
Comment thread
wenshao marked this conversation as resolved.
Resolved
this.config.getFileReadCache().clear();
this.forceFullIdeContext = true;
}

Expand All @@ -233,6 +249,11 @@ export class GeminiClient {
async resetChat(): Promise<void> {
this.surfacedRelevantAutoMemoryPaths.clear();
this.lastApiCompletionTimestamp = null;
// startChat() rewrites the chat to its initial state. Any prior
// read_file tool results the FileReadCache still tracks are no
// longer in history, so a follow-up Read would serve a placeholder
// pointing at content the model can no longer retrieve.
Comment thread
wenshao marked this conversation as resolved.
Resolved
this.config.getFileReadCache().clear();
await this.startChat();
}

Expand Down Expand Up @@ -694,6 +715,15 @@ export class GeminiClient {
);
if (mcResult.meta) {
this.getChat().setHistory(mcResult.history);
// Microcompaction replaces old compactable tool outputs
// (including read_file) with a placeholder, but the
// FileReadCache still records the prior full Reads as "seen in
// this conversation". A follow-up Read of an unchanged file
// would then return the file_unchanged placeholder pointing at
// bytes the model can no longer retrieve from history. Drop the
// cache so post-microcompaction Reads re-emit the bytes,
// mirroring the post-compaction clear in tryCompressChat.
this.config.getFileReadCache().clear();
Comment thread
wenshao marked this conversation as resolved.
Resolved
const m = mcResult.meta;
debugLogger.debug(
`[TIME-BASED MC] gap ${m.gapMinutes}min > ${m.thresholdMinutes}min, ` +
Expand Down
Loading
Loading