Skip to content

Commit 4d1a543

Browse files
PierrunoYTclaude
andauthored
fix(task): report emergency condense like the automatic path (#1838)
* fix(task): report emergency condense like the automatic path The emergency condense in handleContextWindowExceededError duplicated the automatic path's result handling and had diverged: - Its condense_context event carried no condenseId, so rewind cleanup could not remove the emergency summary; deleting the condense row cut after the summary and left it in place. - A condense error returned by manageContext was dropped instead of being shown as condense_context_error. - It ignored the custom CONDENSE prompt and did not pass filesReadByRoo, cwd, or rooIgnoreController. Both paths now report through one reportContextManagementResult helper, and the emergency call passes the same condense settings. The profile threshold overriding the forced 75% is left for a follow-up. Fixes #1769 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test(task): exercise an effective truncation in the emergency condense fallback Co-Authored-By: Claude Sonnet 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
1 parent e943530 commit 4d1a543

3 files changed

Lines changed: 193 additions & 77 deletions

File tree

‎src/core/message-manager/index.spec.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,50 @@ describe("MessageManager", () => {
204204
expect(hasSummary).toBe(false)
205205
})
206206

207+
it.each([
208+
["carries the condenseId", "emergency-summary", false],
209+
["has no condenseId (pre-#1769 emergency event)", undefined, true],
210+
] as const)(
211+
"deleting an emergency condense row that %s removes its summary only via the id",
212+
async (_label, eventCondenseId, summarySurvives) => {
213+
const condenseId = "emergency-summary"
214+
// The summary sits just after the last pre-condense message (ts 301), while the
215+
// condense row is emitted later (ts 400); deleting that row cuts after the summary,
216+
// so only the id-based cleanup can remove it.
217+
mockTask.clineMessages = [
218+
{ ts: 100, say: "user", text: "First" },
219+
{ ts: 300, say: "assistant", text: "Response" },
220+
{
221+
ts: 400,
222+
say: "condense_context",
223+
contextCondense: { condenseId: eventCondenseId, summary: "Summary" },
224+
},
225+
]
226+
mockTask.apiConversationHistory = [
227+
{ ts: 100, role: "user", content: [{ type: "text", text: "First" }], condenseParent: condenseId },
228+
{
229+
ts: 300,
230+
role: "assistant",
231+
content: [{ type: "text", text: "Response" }],
232+
condenseParent: condenseId,
233+
},
234+
{
235+
ts: 301,
236+
role: "user",
237+
content: [{ type: "text", text: "Summary" }],
238+
isSummary: true,
239+
condenseId,
240+
},
241+
]
242+
243+
await manager.rewindToTimestamp(400)
244+
245+
const apiCall: Array<{ isSummary?: boolean; condenseId?: string }> =
246+
mockTask.overwriteApiConversationHistory.mock.calls[0]?.[0] ?? mockTask.apiConversationHistory
247+
expect(apiCall.some((m) => m.isSummary && m.condenseId === condenseId)).toBe(summarySurvives)
248+
},
249+
)
250+
207251
it("should clear orphaned condenseParent tags via cleanup", async () => {
208252
const condenseId = "summary-123"
209253

‎src/core/task/Task.ts‎

Lines changed: 59 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ import { type AssistantMessageContent, presentAssistantMessage } from "../assist
112112
import { DispatchState, type PendingWork } from "./dispatchState"
113113
import { type RequestPolicySnapshot } from "../prompts/tools/effective-tool-policy"
114114
import { NativeToolCallParser } from "../assistant-message/NativeToolCallParser"
115-
import { manageContext, willManageContext } from "../context-management"
115+
import { type ContextManagementResult, manageContext, willManageContext } from "../context-management"
116116
import { ClineProvider } from "../webview/ClineProvider"
117117
import { MultiSearchReplaceDiffStrategy } from "../diff/strategies/multi-search-replace"
118118
import {
@@ -5430,6 +5430,56 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
54305430
return this.api.getModel().info
54315431
}
54325432

5433+
/**
5434+
* Report a manageContext result to the webview. Shared by the automatic and emergency
5435+
* condense paths so both emit the same events: a surfaced error, and a condense event
5436+
* carrying the condenseId that rewind cleanup uses to remove the matching summary.
5437+
*/
5438+
private async reportContextManagementResult(result: ContextManagementResult): Promise<void> {
5439+
if (result.error) {
5440+
await this.say("condense_context_error", result.error)
5441+
}
5442+
if (result.summary) {
5443+
const { summary, cost, prevContextTokens, newContextTokens = 0, condenseId } = result
5444+
const contextCondense: ContextCondense = {
5445+
summary,
5446+
cost,
5447+
newContextTokens,
5448+
prevContextTokens,
5449+
condenseId,
5450+
}
5451+
await this.say(
5452+
"condense_context",
5453+
undefined /* text */,
5454+
undefined /* images */,
5455+
false /* partial */,
5456+
undefined /* checkpoint */,
5457+
undefined /* progressStatus */,
5458+
{ isNonInteractive: true } /* options */,
5459+
contextCondense,
5460+
)
5461+
} else if (result.truncationId) {
5462+
// Sliding window truncation occurred (fallback when condensing fails or is disabled)
5463+
const contextTruncation: ContextTruncation = {
5464+
truncationId: result.truncationId,
5465+
messagesRemoved: result.messagesRemoved ?? 0,
5466+
prevContextTokens: result.prevContextTokens,
5467+
newContextTokens: result.newContextTokensAfterTruncation ?? 0,
5468+
}
5469+
await this.say(
5470+
"sliding_window_truncation",
5471+
undefined /* text */,
5472+
undefined /* images */,
5473+
false /* partial */,
5474+
undefined /* checkpoint */,
5475+
undefined /* progressStatus */,
5476+
{ isNonInteractive: true } /* options */,
5477+
undefined /* contextCondense */,
5478+
contextTruncation,
5479+
)
5480+
}
5481+
}
5482+
54335483
private async handleContextWindowExceededError(requestModelInfo: ModelInfo): Promise<void> {
54345484
const state = await this.providerRef.deref()?.getState()
54355485
const { profileThresholds = {} } = state ?? {}
@@ -5506,6 +5556,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
55065556
try {
55075557
// Generate environment details to include in the condensed summary
55085558
const environmentDetails = await getEnvironmentDetails(this, true)
5559+
const filesReadByRoo = await this.getFilesReadByRooSafely("handleContextWindowExceededError")
55095560

55105561
// Force aggressive truncation by keeping only 75% of the conversation history
55115562
const truncateResult = await manageContext({
@@ -5518,50 +5569,22 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
55185569
autoCondenseContextPercent: FORCED_CONTEXT_REDUCTION_PERCENT,
55195570
systemPrompt: await this.getSystemPrompt(state, modelInfo),
55205571
taskId: this.taskId,
5572+
// Recovery must summarize like the automatic path: same prompt and folded file context.
5573+
customCondensingPrompt: state?.customSupportPrompts?.CONDENSE,
55215574
profileThresholds,
55225575
currentProfileId,
55235576
metadata,
55245577
environmentDetails,
5578+
filesReadByRoo,
5579+
cwd: this.cwd,
5580+
rooIgnoreController: this.rooIgnoreController,
55255581
useAvailableInputForContextPercent,
55265582
})
55275583

55285584
if (truncateResult.messages !== this.apiConversationHistory) {
55295585
await this.overwriteApiConversationHistory(truncateResult.messages)
55305586
}
5531-
5532-
if (truncateResult.summary) {
5533-
const { summary, cost, prevContextTokens, newContextTokens = 0 } = truncateResult
5534-
const contextCondense: ContextCondense = { summary, cost, newContextTokens, prevContextTokens }
5535-
await this.say(
5536-
"condense_context",
5537-
undefined /* text */,
5538-
undefined /* images */,
5539-
false /* partial */,
5540-
undefined /* checkpoint */,
5541-
undefined /* progressStatus */,
5542-
{ isNonInteractive: true } /* options */,
5543-
contextCondense,
5544-
)
5545-
} else if (truncateResult.truncationId) {
5546-
// Sliding window truncation occurred (fallback when condensing fails or is disabled)
5547-
const contextTruncation: ContextTruncation = {
5548-
truncationId: truncateResult.truncationId,
5549-
messagesRemoved: truncateResult.messagesRemoved ?? 0,
5550-
prevContextTokens: truncateResult.prevContextTokens,
5551-
newContextTokens: truncateResult.newContextTokensAfterTruncation ?? 0,
5552-
}
5553-
await this.say(
5554-
"sliding_window_truncation",
5555-
undefined /* text */,
5556-
undefined /* images */,
5557-
false /* partial */,
5558-
undefined /* checkpoint */,
5559-
undefined /* progressStatus */,
5560-
{ isNonInteractive: true } /* options */,
5561-
undefined /* contextCondense */,
5562-
contextTruncation,
5563-
)
5564-
}
5587+
await this.reportContextManagementResult(truncateResult)
55655588
} finally {
55665589
// Notify webview that context management is complete (removes in-progress spinner)
55675590
// IMPORTANT: Must always be sent to dismiss the spinner, even on error
@@ -5818,48 +5841,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
58185841
if (truncateResult.messages !== this.apiConversationHistory) {
58195842
await this.overwriteApiConversationHistory(truncateResult.messages)
58205843
}
5821-
if (truncateResult.error) {
5822-
await this.say("condense_context_error", truncateResult.error)
5823-
}
5824-
if (truncateResult.summary) {
5825-
const { summary, cost, prevContextTokens, newContextTokens = 0, condenseId } = truncateResult
5826-
const contextCondense: ContextCondense = {
5827-
summary,
5828-
cost,
5829-
newContextTokens,
5830-
prevContextTokens,
5831-
condenseId,
5832-
}
5833-
await this.say(
5834-
"condense_context",
5835-
undefined /* text */,
5836-
undefined /* images */,
5837-
false /* partial */,
5838-
undefined /* checkpoint */,
5839-
undefined /* progressStatus */,
5840-
{ isNonInteractive: true } /* options */,
5841-
contextCondense,
5842-
)
5843-
} else if (truncateResult.truncationId) {
5844-
// Sliding window truncation occurred (fallback when condensing fails or is disabled)
5845-
const contextTruncation: ContextTruncation = {
5846-
truncationId: truncateResult.truncationId,
5847-
messagesRemoved: truncateResult.messagesRemoved ?? 0,
5848-
prevContextTokens: truncateResult.prevContextTokens,
5849-
newContextTokens: truncateResult.newContextTokensAfterTruncation ?? 0,
5850-
}
5851-
await this.say(
5852-
"sliding_window_truncation",
5853-
undefined /* text */,
5854-
undefined /* images */,
5855-
false /* partial */,
5856-
undefined /* checkpoint */,
5857-
undefined /* progressStatus */,
5858-
{ isNonInteractive: true } /* options */,
5859-
undefined /* contextCondense */,
5860-
contextTruncation,
5861-
)
5862-
}
5844+
await this.reportContextManagementResult(truncateResult)
58635845
} finally {
58645846
// Notify webview that context management is complete (sets isCondensing = false)
58655847
// This removes the in-progress spinner and allows the completed result to show

‎src/core/task/__tests__/Task.spec.ts‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2547,6 +2547,96 @@ describe("Cline", () => {
25472547
expect(getSystemPromptSpy).toHaveBeenCalledWith(snapshot, ctxModelInfo)
25482548
})
25492549

2550+
describe("emergency condense reporting (#1769)", () => {
2551+
const ctxModelInfo: ModelInfo = { contextWindow: 50_000, maxTokens: 1024, supportsPromptCache: false }
2552+
2553+
// Overflow the 50k window so the real handler reaches manageContext's condense branch.
2554+
const createOverflowingTask = async (state: ProviderState) => {
2555+
vi.spyOn(mockProvider, "getState").mockResolvedValue(state)
2556+
const task = new Task({
2557+
provider: mockProvider,
2558+
apiConfiguration: mockApiConfig,
2559+
task: "test task",
2560+
startTask: false,
2561+
})
2562+
await task.getTaskMode()
2563+
vi.spyOn(task, "getTokenUsage").mockReturnValue({
2564+
totalCost: 0,
2565+
totalTokensIn: 0,
2566+
totalTokensOut: 0,
2567+
contextTokens: 100_000,
2568+
})
2569+
vi.spyOn(task.api, "getModel").mockReturnValue({ id: "ctx-model", info: ctxModelInfo })
2570+
vi.spyOn(getTaskTestAccess(task), "getSystemPrompt").mockResolvedValue("mock system prompt")
2571+
vi.spyOn(task, "overwriteApiConversationHistory").mockResolvedValue(undefined)
2572+
task.apiConversationHistory = [{ role: "user", content: [{ type: "text", text: "x" }], ts: Date.now() }]
2573+
const say = vi.spyOn(task, "say").mockResolvedValue(undefined)
2574+
return { task, say }
2575+
}
2576+
2577+
it("emits the summary's condenseId and summarizes with the task's condense settings", async () => {
2578+
const { task, say } = await createOverflowingTask(
2579+
providerStateWith({ customSupportPrompts: { CONDENSE: "custom condense prompt" } }),
2580+
)
2581+
vi.mocked(summarizeConversation).mockResolvedValueOnce({
2582+
messages: [{ role: "user", content: [{ type: "text", text: "condensed" }], ts: Date.now() }],
2583+
summary: "summary",
2584+
cost: 0,
2585+
newContextTokens: 1,
2586+
condenseId: "emergency-condense-id",
2587+
})
2588+
2589+
await getTaskTestAccess(task).handleContextWindowExceededError(ctxModelInfo)
2590+
2591+
// Rewind cleanup can only remove the summary if the event carries its condenseId.
2592+
const condenseCall = say.mock.calls.find(([type]) => type === "condense_context")
2593+
expect(condenseCall?.[7]).toMatchObject({ condenseId: "emergency-condense-id" })
2594+
const [options] = requireDefined(vi.mocked(summarizeConversation).mock.calls.at(-1))
2595+
expect(options).toMatchObject({ customCondensingPrompt: "custom condense prompt", cwd: task.cwd })
2596+
})
2597+
2598+
it("surfaces a failed emergency condense as condense_context_error", async () => {
2599+
const { task, say } = await createOverflowingTask(providerStateWith())
2600+
// Enough visible messages for the 50% fallback to hide a pair (floor(4 * 0.5) = 2).
2601+
task.apiConversationHistory = ["a", "b", "c", "d", "e"].map((text, index) => ({
2602+
role: index % 2 === 0 ? ("user" as const) : ("assistant" as const),
2603+
content: [{ type: "text" as const, text }],
2604+
ts: index + 1,
2605+
}))
2606+
const overwrite = vi.mocked(task.overwriteApiConversationHistory)
2607+
vi.mocked(summarizeConversation).mockResolvedValueOnce({
2608+
messages: task.apiConversationHistory,
2609+
summary: "",
2610+
cost: 0,
2611+
error: "Condensing failed: rate limited",
2612+
})
2613+
2614+
await getTaskTestAccess(task).handleContextWindowExceededError(ctxModelInfo)
2615+
2616+
expect(say).toHaveBeenCalledWith("condense_context_error", "Condensing failed: rate limited")
2617+
// The sliding-window fallback still reports its truncation after the error row.
2618+
expect(say.mock.calls.map(([type]) => type)).toEqual([
2619+
"condense_context_error",
2620+
"sliding_window_truncation",
2621+
])
2622+
2623+
const truncatedHistory = requireDefined(overwrite.mock.calls.at(-1))[0]
2624+
const marker = requireDefined(truncatedHistory.find((message) => message.isTruncationMarker))
2625+
const truncationCall = requireDefined(
2626+
say.mock.calls.find(([type]) => type === "sliding_window_truncation"),
2627+
)
2628+
const reported = requireDefined(truncationCall[8])
2629+
expect(reported.truncationId).toBe(marker.truncationId)
2630+
expect(reported.messagesRemoved).toBe(2)
2631+
expect(
2632+
truncatedHistory.filter((message) => message.truncationParent === reported.truncationId),
2633+
).toHaveLength(2)
2634+
expect(reported.prevContextTokens).toBeGreaterThanOrEqual(100_000)
2635+
expect(reported.newContextTokens).toBeGreaterThan(0)
2636+
expect(reported.newContextTokens).toBeLessThan(reported.prevContextTokens)
2637+
})
2638+
})
2639+
25502640
it("uses the task mode when manually condensing after focused state changes", async () => {
25512641
vi.spyOn(mockProvider, "getState").mockResolvedValue(providerStateWith({ mode: "architect" }))
25522642
const task = new Task({

0 commit comments

Comments
 (0)