Skip to content

Commit 423d83b

Browse files
committed
fix(task): restore interrupted text bubbles as finalized rows on resume
What: resumeTaskFromHistory() now collects the trailing partial `reasoning` and `text` bubbles instead of dropping them outright, and after reading API history re-adds each partial `text` bubble whose complete text already appears in the last assistant turn, with `partial` cleared. Partial `reasoning` and unmatched `text` bubbles are still discarded. Why: CodeRabbit flagged that the strip discards text the model still retains. The claim is reachable: recursivelyMakeRooRequests appends the assistant turn to API history before it releases the streaming presenter that clears the bubble's `partial` flag, so an abort landing between those two steps leaves a partial bubble and a complete turn coexisting. Dropping the row erased text that is still in the model's context. The recommendation as written would have reintroduced Zoo-Code-Org#257: ChatView's streaming memo returns true for any trailing `partial === true` row, so retaining the row unchanged re-locks the resumed chat on "API Request..." with a queuing input. Clearing `partial` keeps the text visible as finalized content and leaves the input enabled, which is strictly better than dropping the row. The comparison re-applies the streaming-time `<thinking>` strip, because presentAssistantMessage strips that markup from the bubble but the API turn is built from the raw accumulator. Impact: an interrupted answer that already reached API history survives resume as finalized text instead of vanishing. Orphaned partial text, partial reasoning, and the Zoo-Code-Org#257 lock behavior are unchanged. The adjacent comment now states that partial text can already have an API-history entry.
1 parent 7f665f1 commit 423d83b

3 files changed

Lines changed: 322 additions & 7 deletions

File tree

‎src/core/task/Task.ts‎

Lines changed: 52 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,35 @@ function queuedResponseForAsk(type: ClineAsk, text?: string): QueuedAskResolutio
236236
return { response: "messageResponse", requiresDurableAck: type === "completion_result" }
237237
}
238238

239+
/**
240+
* Whether an assistant API turn already carries the complete text of a streamed
241+
* `say("text")` bubble that was interrupted before its UI finalize.
242+
*
243+
* `recursivelyMakeRooRequests` appends the assistant turn to API history before it
244+
* releases the streaming presenter that clears the bubble's `partial` flag, so an
245+
* abort landing between those two steps leaves a partial bubble and a complete
246+
* turn coexisting. The bubble's text is then not orphaned and must not be
247+
* discarded.
248+
*
249+
* The comparison re-applies the streaming-time `<thinking>` strip that
250+
* `presentAssistantMessage` applies to the bubble but not to the raw accumulator
251+
* the API turn is built from.
252+
*/
253+
function hasAssistantTextTurnFor(apiMessages: ApiMessage[], partialText: string): boolean {
254+
const expected = partialText.replace(/<thinking>\s?/g, "").replace(/\s?<\/thinking>/g, "")
255+
const lastAssistantTurn = findLast(apiMessages, (message) => message.role === "assistant")
256+
257+
if (!lastAssistantTurn || !Array.isArray(lastAssistantTurn.content)) {
258+
return false
259+
}
260+
261+
return lastAssistantTurn.content.some(
262+
(block) =>
263+
block.type === "text" &&
264+
block.text.replace(/<thinking>\s?/g, "").replace(/\s?<\/thinking>/g, "") === expected,
265+
)
266+
}
267+
239268
const FORCED_CONTEXT_REDUCTION_PERCENT = 75 // Keep 75% of context (remove 25%) on context window errors
240269
const MAX_CONTEXT_WINDOW_RETRIES = 3 // Maximum retries for context window errors
241270

@@ -3145,12 +3174,20 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
31453174
}
31463175
}
31473176

3148-
// Partial reasoning and text have no API-history entry, since the assistant
3149-
// message is only written once the stream completes, so an interrupted stream
3150-
// leaves them orphaned. A trailing partial bubble also keeps the webview in its
3177+
// A trailing partial `reasoning` or `text` bubble keeps the webview in its
31513178
// streaming state, which leaves the resumed chat stuck on "API Request..." with
31523179
// an input that only queues (see #257). Other partial say types (e.g. command
31533180
// output) record work that already ran, so they are kept.
3181+
//
3182+
// The two types are not equally orphaned, though. `recursivelyMakeRooRequests`
3183+
// appends the assistant turn to API history before it releases the streaming
3184+
// presenter that clears the bubble's `partial` flag, so an abort landing between
3185+
// those two steps leaves a partial text bubble whose complete text is already in
3186+
// API history. Those are restored below as finalized rows instead of being
3187+
// discarded; reasoning keeps the plain drop because it is never re-rendered
3188+
// from API history.
3189+
const trailingPartialStreamBubbles: ClineMessage[] = []
3190+
31543191
while (modifiedClineMessages.length > 0) {
31553192
const lastMessage = modifiedClineMessages[modifiedClineMessages.length - 1]
31563193
const isPartialStreamBubble =
@@ -3162,7 +3199,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
31623199
break
31633200
}
31643201

3165-
modifiedClineMessages.pop()
3202+
trailingPartialStreamBubbles.unshift(modifiedClineMessages.pop()!)
31663203
}
31673204

31683205
// Since we don't use `api_req_finished` anymore, we need to check if the
@@ -3191,6 +3228,17 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
31913228
return
31923229
}
31933230

3231+
// Restore the interrupted text bubbles whose complete text already reached API
3232+
// history, as finalized rows. Clearing `partial` is what keeps the retention from
3233+
// re-locking the chat: ChatView's streaming memo returns true for any trailing
3234+
// `partial === true` row (ChatView.tsx:583-587), so a retained partial would
3235+
// reintroduce exactly the #257 lock this cleanup exists to remove.
3236+
for (const bubble of trailingPartialStreamBubbles) {
3237+
if (bubble.say === "text" && hasAssistantTextTurnFor(savedApiConversationHistory, bubble.text ?? "")) {
3238+
modifiedClineMessages.push({ ...bubble, partial: false })
3239+
}
3240+
}
3241+
31943242
// Avoid a standalone write during hydration. The resume ask will persist only
31953243
// after all history reads succeed and the task is still active.
31963244
this.hydrateClineMessages(modifiedClineMessages)

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

Lines changed: 221 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2440,6 +2440,227 @@ describe("Task persistence", () => {
24402440
expect(mockSaveTaskMessages).not.toHaveBeenCalled()
24412441
})
24422442

2443+
// The assistant turn is appended to API history before the presenter that
2444+
// clears `partial` runs, so an abort between them leaves a partial text bubble
2445+
// whose complete text is already persisted. Dropping it would erase text the
2446+
// model can still see; keeping it partial would re-lock the resumed chat on
2447+
// ChatView's `partial === true` heuristic. Restore it as a finalized row.
2448+
it("restores a partial text bubble as finalized when the complete turn is in API history", async () => {
2449+
mockReadTaskMessages.mockResolvedValue([
2450+
{ ts: 1, type: "say", say: "text", text: "Original task" },
2451+
{ ts: 2, type: "say", say: "text", text: "Half a sentence", partial: true },
2452+
])
2453+
mockReadApiMessages.mockResolvedValue([
2454+
{ role: "user", content: [{ type: "text", text: "Original task" }] },
2455+
{ role: "assistant", content: [{ type: "text", text: "Half a sentence" }] },
2456+
])
2457+
2458+
const task = new Task({
2459+
provider: mockProvider,
2460+
apiConfiguration: mockApiConfig,
2461+
historyItem: {
2462+
id: "issue-257-restore-partial-text",
2463+
number: 1,
2464+
ts: 1,
2465+
task: "Original task",
2466+
tokensIn: 10,
2467+
tokensOut: 5,
2468+
totalCost: 0.001,
2469+
},
2470+
startTask: false,
2471+
})
2472+
vi.spyOn(task, "ask").mockImplementation(async () => {
2473+
// Retained, but finalized: the text survives and the row no longer reads as
2474+
// streaming, so the resumed chat keeps its input enabled.
2475+
expect(task.clineMessages).toContainEqual(
2476+
expect.objectContaining({ say: "text", text: "Half a sentence", partial: false }),
2477+
)
2478+
expect(task.clineMessages).not.toContainEqual(expect.objectContaining({ partial: true }))
2479+
throw new Error("stop after hydration")
2480+
})
2481+
2482+
await expect(getTaskPersistenceAccess(task).resumeTaskFromHistory()).rejects.toThrow("stop after hydration")
2483+
expect(mockSaveTaskMessages).not.toHaveBeenCalled()
2484+
})
2485+
2486+
it("compares the partial text against API history after the streaming thinking-tag strip", async () => {
2487+
// presentAssistantMessage strips `<thinking>` from the bubble but the API turn is
2488+
// built from the raw accumulator, so the two texts differ by exactly that markup.
2489+
mockReadTaskMessages.mockResolvedValue([
2490+
{ ts: 1, type: "say", say: "text", text: "Original task" },
2491+
{ ts: 2, type: "say", say: "text", text: "Answer in progress", partial: true },
2492+
])
2493+
mockReadApiMessages.mockResolvedValue([
2494+
{ role: "user", content: [{ type: "text", text: "Original task" }] },
2495+
{ role: "assistant", content: [{ type: "text", text: "<thinking>\nAnswer in progress" }] },
2496+
])
2497+
2498+
const task = new Task({
2499+
provider: mockProvider,
2500+
apiConfiguration: mockApiConfig,
2501+
historyItem: {
2502+
id: "issue-257-restore-thinking-strip",
2503+
number: 1,
2504+
ts: 1,
2505+
task: "Original task",
2506+
tokensIn: 10,
2507+
tokensOut: 5,
2508+
totalCost: 0.001,
2509+
},
2510+
startTask: false,
2511+
})
2512+
vi.spyOn(task, "ask").mockImplementation(async () => {
2513+
expect(task.clineMessages).toContainEqual(
2514+
expect.objectContaining({ say: "text", text: "Answer in progress", partial: false }),
2515+
)
2516+
throw new Error("stop after hydration")
2517+
})
2518+
2519+
await expect(getTaskPersistenceAccess(task).resumeTaskFromHistory()).rejects.toThrow("stop after hydration")
2520+
expect(mockSaveTaskMessages).not.toHaveBeenCalled()
2521+
})
2522+
2523+
it.each([
2524+
{
2525+
name: "the last assistant turn holds different text",
2526+
apiHistory: [
2527+
{ role: "assistant" as const, content: [{ type: "text" as const, text: "An older answer" }] },
2528+
],
2529+
},
2530+
{
2531+
name: "the last assistant turn has no text block",
2532+
apiHistory: [
2533+
{
2534+
role: "assistant" as const,
2535+
content: [{ type: "tool_use" as const, id: "toolu_1", name: "read_file", input: {} }],
2536+
},
2537+
],
2538+
},
2539+
{
2540+
name: "API history holds no assistant turn at all",
2541+
apiHistory: [] as Array<{ role: "assistant"; content: Array<{ type: "text"; text: string }> }>,
2542+
},
2543+
{
2544+
// Pins the comparison to the LAST assistant turn: an older turn that happens
2545+
// to match must not resurrect a bubble the newest turn does not account for.
2546+
name: "only an older assistant turn holds the text",
2547+
apiHistory: [
2548+
{ role: "assistant" as const, content: [{ type: "text" as const, text: "Half a sentence" }] },
2549+
{ role: "user" as const, content: [{ type: "text" as const, text: "Follow up" }] },
2550+
{ role: "assistant" as const, content: [{ type: "text" as const, text: "A newer answer" }] },
2551+
],
2552+
},
2553+
])("strips the partial text bubble when $name", async ({ apiHistory }) => {
2554+
// No matching turn means the text exists nowhere else, so the orphaned bubble is
2555+
// dropped exactly as before this change.
2556+
mockReadTaskMessages.mockResolvedValue([
2557+
{ ts: 1, type: "say", say: "text", text: "Original task" },
2558+
{ ts: 2, type: "say", say: "text", text: "Half a sentence", partial: true },
2559+
])
2560+
mockReadApiMessages.mockResolvedValue([
2561+
{ role: "user", content: [{ type: "text", text: "Original task" }] },
2562+
...apiHistory,
2563+
])
2564+
2565+
const task = new Task({
2566+
provider: mockProvider,
2567+
apiConfiguration: mockApiConfig,
2568+
historyItem: {
2569+
id: "issue-257-orphaned-partial-text",
2570+
number: 1,
2571+
ts: 1,
2572+
task: "Original task",
2573+
tokensIn: 10,
2574+
tokensOut: 5,
2575+
totalCost: 0.001,
2576+
},
2577+
startTask: false,
2578+
})
2579+
vi.spyOn(task, "ask").mockImplementation(async () => {
2580+
expect(task.clineMessages).toContainEqual(
2581+
expect.objectContaining({ say: "text", text: "Original task" }),
2582+
)
2583+
expect(task.clineMessages).not.toContainEqual(expect.objectContaining({ text: "Half a sentence" }))
2584+
throw new Error("stop after hydration")
2585+
})
2586+
2587+
await expect(getTaskPersistenceAccess(task).resumeTaskFromHistory()).rejects.toThrow("stop after hydration")
2588+
expect(mockSaveTaskMessages).not.toHaveBeenCalled()
2589+
})
2590+
2591+
it("keeps dropping a partial reasoning bubble even when an assistant turn exists", async () => {
2592+
// Reasoning is never re-rendered from API history, so a matching assistant turn
2593+
// must not resurrect the bubble. This pins the CR-requested split.
2594+
mockReadTaskMessages.mockResolvedValue([
2595+
{ ts: 1, type: "say", say: "text", text: "Original task" },
2596+
{ ts: 2, type: "say", say: "reasoning", text: "Thinking about it", partial: true },
2597+
])
2598+
mockReadApiMessages.mockResolvedValue([
2599+
{ role: "user", content: [{ type: "text", text: "Original task" }] },
2600+
{ role: "assistant", content: [{ type: "text", text: "Thinking about it" }] },
2601+
])
2602+
2603+
const task = new Task({
2604+
provider: mockProvider,
2605+
apiConfiguration: mockApiConfig,
2606+
historyItem: {
2607+
id: "issue-257-reasoning-still-dropped",
2608+
number: 1,
2609+
ts: 1,
2610+
task: "Original task",
2611+
tokensIn: 10,
2612+
tokensOut: 5,
2613+
totalCost: 0.001,
2614+
},
2615+
startTask: false,
2616+
})
2617+
vi.spyOn(task, "ask").mockImplementation(async () => {
2618+
expect(task.clineMessages).not.toContainEqual(expect.objectContaining({ say: "reasoning" }))
2619+
throw new Error("stop after hydration")
2620+
})
2621+
2622+
await expect(getTaskPersistenceAccess(task).resumeTaskFromHistory()).rejects.toThrow("stop after hydration")
2623+
expect(mockSaveTaskMessages).not.toHaveBeenCalled()
2624+
})
2625+
2626+
it("does not restore a partial text bubble when the task is evicted during the API read", async () => {
2627+
// The restore sits after the abort guard, so an evicted task must not resurrect
2628+
// the row into a history it is about to discard.
2629+
const apiMessagesDeferred =
2630+
createDeferred<Array<{ role: "assistant"; content: Array<{ type: "text"; text: string }> }>>()
2631+
mockReadTaskMessages.mockResolvedValue([
2632+
{ ts: 1, type: "say", say: "text", text: "Original task" },
2633+
{ ts: 2, type: "say", say: "text", text: "Half a sentence", partial: true },
2634+
])
2635+
mockReadApiMessages.mockReturnValue(apiMessagesDeferred.promise)
2636+
2637+
const task = new Task({
2638+
provider: mockProvider,
2639+
apiConfiguration: mockApiConfig,
2640+
historyItem: {
2641+
id: "issue-257-restore-evicted",
2642+
number: 1,
2643+
ts: 1,
2644+
task: "Original task",
2645+
tokensIn: 10,
2646+
tokensOut: 5,
2647+
totalCost: 0.001,
2648+
},
2649+
startTask: false,
2650+
})
2651+
const resumePromise = getTaskPersistenceAccess(task).resumeTaskFromHistory()
2652+
await vi.waitFor(() => expect(mockReadApiMessages).toHaveBeenCalled())
2653+
2654+
await task.abortTask(true)
2655+
mockSaveTaskMessages.mockClear()
2656+
vi.mocked(mockProvider.updateTaskHistory).mockClear()
2657+
apiMessagesDeferred.resolve([{ role: "assistant", content: [{ type: "text", text: "Half a sentence" }] }])
2658+
await resumePromise
2659+
2660+
expect(task.clineMessages).toHaveLength(0)
2661+
expect(mockSaveTaskMessages).not.toHaveBeenCalled()
2662+
})
2663+
24432664
it("stops before hydrating either history when the task is evicted during the API read", async () => {
24442665
const apiMessagesDeferred =
24452666
createDeferred<Array<{ role: "user"; content: Array<{ type: "text"; text: string }> }>>()

0 commit comments

Comments
 (0)