Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
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
111 changes: 111 additions & 0 deletions packages/cli/src/acp-integration/session/Session.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11989,6 +11989,117 @@ describe('Session', () => {
);
});

it('does not drop a route-B send using a stale route-A token count after a model switch (#9529)', async () => {
mockConfig.getSessionTokenLimit = vi.fn().mockReturnValue(100);
// ACP model switches keep the same GeminiChat instance, so only the
// route identity changes — the chat-instance reset in the session's
// token cache never fires (#9529, follow-up to #9454/#9506).
let routeIdentity = 'route-a';
mockConfig.getModelRouteIdentity = vi.fn(() => routeIdentity);

// Prompt 1 on route A: an API-reported count lands in the session's
// private token cache.
mockGeminiClient.tryCompressChat.mockResolvedValueOnce({
originalTokenCount: 50,
newTokenCount: 50,
compressionStatus: core.CompressionStatus.NOOP,
});
mockChat.sendMessageStream = vi
.fn()
.mockResolvedValueOnce(
createStreamWithChunks([
{
type: core.StreamEventType.CHUNK,
value: {
usageMetadata: {
totalTokenCount: 101,
promptTokenCount: 101,
},
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
},
},
]),
)
.mockResolvedValueOnce(createEmptyStream());

await expect(
session.prompt({
sessionId: 'test-session-id',
prompt: [{ type: 'text', text: 'first' }],
}),
).resolves.toEqual({ stopReason: 'end_turn' });

// Switch to route B on the same chat instance.
routeIdentity = 'route-b';

// Prompt 2 on route B reaches the session-token-limit gate without
// compression info (compression throws), so the gate falls back to the
// cached count. The stale route-A count (101 > 100) must not drop a
// route-B send.
mockGeminiClient.tryCompressChat.mockRejectedValueOnce(
new Error('compression rate limited'),
);

await expect(
session.prompt({
sessionId: 'test-session-id',
prompt: [{ type: 'text', text: 'second' }],
}),
).resolves.toEqual({ stopReason: 'end_turn' });

expect(mockChat.sendMessageStream).toHaveBeenCalledTimes(2);
});

it('still intercepts a same-route send whose recorded count exceeds the session token limit (#9529)', async () => {
mockConfig.getSessionTokenLimit = vi.fn().mockReturnValue(100);
// The route never changes, so the route-scoped cache must keep the
// recorded count and let the gate trip exactly as it did before #9529.
mockConfig.getModelRouteIdentity = vi.fn(() => 'route-a');

mockGeminiClient.tryCompressChat.mockResolvedValueOnce({
originalTokenCount: 50,
newTokenCount: 50,
compressionStatus: core.CompressionStatus.NOOP,
});
mockChat.sendMessageStream = vi
.fn()
.mockResolvedValueOnce(
createStreamWithChunks([
{
type: core.StreamEventType.CHUNK,
value: {
usageMetadata: {
totalTokenCount: 101,
promptTokenCount: 101,
},
},
},
]),
)
.mockResolvedValueOnce(createEmptyStream());

await expect(
session.prompt({
sessionId: 'test-session-id',
prompt: [{ type: 'text', text: 'first' }],
}),
).resolves.toEqual({ stopReason: 'end_turn' });

// Same route, compression throws → the gate reads the recorded
// same-route count (101 > 100) and must still drop the send.
mockGeminiClient.tryCompressChat.mockRejectedValueOnce(
new Error('compression rate limited'),
);

await expect(
session.prompt({
sessionId: 'test-session-id',
prompt: [{ type: 'text', text: 'second' }],
}),
).resolves.toEqual({ stopReason: 'max_tokens' });

expect(mockChat.sendMessageStream).toHaveBeenCalledTimes(1);
});

it('returns cancelled when automatic compression is aborted', async () => {
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
mockConfig.getSessionTokenLimit = vi.fn().mockReturnValue(100);
mockGeminiClient.tryCompressChat.mockImplementation(
Expand Down
29 changes: 25 additions & 4 deletions packages/cli/src/acp-integration/session/Session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1849,6 +1849,11 @@ export class Session implements SessionContext {
private cronDisabledByTokenLimit = false;
private lastPromptTokenCount = 0;
private lastPromptTokenCountChat: GeminiChat | null = null;
// The model route that produced `lastPromptTokenCount` (Config
// .getModelRouteIdentity). ACP model switches keep the same GeminiChat, so
// the chat-instance check alone never invalidates the count on a route
// change (#9529, follow-up to #9454/#9506).
private lastPromptTokenCountRouteKey: string | undefined = undefined;
private midTurnDrainUnavailable = false;
private midTurnDrainTimeoutStrikes = 0;
// ACP can continue one logical conversation through prompt, cron, and
Expand Down Expand Up @@ -7100,15 +7105,31 @@ export class Session implements SessionContext {
return tokenCount;
}

#currentRouteKey(): string {
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
// Optional chaining keeps partial Config test mocks from throwing; a
// missing identity degrades to one stable key, i.e. no route-change
// invalidation (mirrors GeminiChat.currentRouteKey, #9454).
return this.config.getModelRouteIdentity?.() ?? '';
}

#syncPromptTokenCountWithCurrentChat(): void {
const chat = this.#getCurrentChat();
if (
this.lastPromptTokenCountChat &&
this.lastPromptTokenCountChat !== chat
) {
const routeKey = this.#currentRouteKey();
const chatChanged =
this.lastPromptTokenCountChat && this.lastPromptTokenCountChat !== chat;
// A model switch rebuilds the content generator but keeps the same
// GeminiChat, so the chat-instance check above never fires on a route
// change. A count recorded for the previous route must not anchor the
// session-token-limit gate for the new one — reset it so the gate falls
// back to the fresh send's own count (#9529, follow-up to #9454/#9506).
const routeChanged =
this.lastPromptTokenCountRouteKey !== undefined &&
this.lastPromptTokenCountRouteKey !== routeKey;
if (chatChanged || routeChanged) {
this.lastPromptTokenCount = 0;
}
this.lastPromptTokenCountChat = chat;
this.lastPromptTokenCountRouteKey = routeKey;
}

#isAbortError(error: unknown): boolean {
Expand Down
Loading