Skip to content

Commit 036245c

Browse files
easonLiangWorldedtecheasonLiangWorldedtechedelauna
authored
fix(task): stage-independent saveClineMessages + finalize open partial tool ask (split 1/6 of #1066) (#1927)
* fix(task): stage-independent saveClineMessages + finalize open partial tool ask * test(task): stop leaking the fixed-task-id record between save-stage tests The task uuid is mocked to a fixed value, so the ui_messages.json this save writes outlives the test that created it. The sibling test below removes the whole directory and recreates it, which is the only reason the leak has not surfaced: with merge = true, any later save that reads its merged output would fold in a stale record and fail by run order rather than by behavior. The body now runs in try/finally, removing ui_messages.json and restoring both spies whatever the assertions do. The spies moved out of the try so the finally can see them. Local run: 162 passed in Task.spec.ts (the one remaining failure, blocks a truncated write_to_file call instead of executing it, fails identically at cf5abe6 without this change - local artifact), eslint clean, no suppression change. * test(task): check the saved payload in finalizePartialToolAsk test * chore(ci): request a fresh run for the flaky restart-persistence step No code change. This empty commit exists only to obtain a new CI run, because the required e2e-mock check is red at c4ca658 and the failed job cannot be re-run with the token available here (POST /repos/Zoo-Code-Org/Zoo-Code/actions/runs/37880099804/rerun-failed-jobs -> 403 Must have admin rights to Repository). Why the red is not caused by this branch: - In job 113657575830, step 14 'Run mocked E2E tests' = success; only step 15 'Run mocked restart-persistence E2E test' failed. The create phase passed ('persists completed task across a fresh extension host', 1 passing); the verify phase threw TaskMessagesReadError: Failed to read task messages for 01a11ec0-9f7e-72db-9721-1c8b2d4d28f4 at /tmp/roo from readTaskMessages <- Task.resumeTaskFromHistory <- TaskScheduler.schedule, then 'Error: Timeout after 30s' (out/suite/utils.js:15). - The previous head on this same branch, cf9206a, passed both steps (run 37516254245, 2026-10-06). The only commit between cf9206a and c4ca658 changes src/core/task/__tests__/Task.spec.ts (+13/-2), a Vitest unit-test file the mocked E2E suite never loads; no production file changed and the branch base is unchanged (7214352). - The identical signature appears on unrelated branches: run 37762259575 (vps2-f2c), run 37706659841 (feat/chat-input-model-selector, same TaskMessagesReadError), run 37626907243 (feat/dte-v2-3-task-runtime-effort). - Four sibling PRs carrying the same U1 Task.ts content passed this step: #1929 run 37873787271, #1928 run 37854340884, #1931 run 37833581055, #1932 run 37774292614. Evidence note on the PR: #1927 (comment) --------- Co-authored-by: easonLiangWorldedtech <[email protected]> Co-authored-by: Elliott de Launay <[email protected]>
1 parent fc1fc9a commit 036245c

3 files changed

Lines changed: 495 additions & 5 deletions

File tree

‎src/core/assistant-message/__tests__/presentAssistantMessage-custom-tool.spec.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ describe("presentAssistantMessage - Custom Tool Recording", () => {
8989
},
9090
say: vi.fn().mockResolvedValue(undefined),
9191
ask: vi.fn().mockResolvedValue({ response: "yesButtonClicked" }),
92+
finalizePartialToolAsk: vi.fn().mockResolvedValue(undefined),
9293
}
9394

9495
// Add pushToolResultToUserContent method after mockTask is created so it can reference mockTask

‎src/core/task/Task.ts‎

Lines changed: 75 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ import { maybeRemoveImageBlocks } from "../../api/transform/image-cleaning"
6868
import { OutputTokenLimitError } from "../../api/providers/utils/output-token-limit-error"
6969

7070
// shared
71-
import { findLastIndex } from "../../shared/array"
71+
import { findLast, findLastIndex } from "../../shared/array"
7272
import { combineApiRequests } from "../../shared/combineApiRequests"
7373
import { combineCommandSequences } from "../../shared/combineCommandSequences"
7474
import { t } from "../../i18n"
@@ -1719,7 +1719,19 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
17191719
}
17201720
}
17211721

1722-
/** Persists Cline messages and updates task metadata in the history store. Returns false on failure. */
1722+
/**
1723+
* Persist the message array, then refresh the derived metadata / task-history entries.
1724+
*
1725+
* The returned boolean reflects the message write only: `saveTaskMessages` failure
1726+
* leaves the on-disk record stale, so callers gating UI updates on durable state must
1727+
* skip them. Metadata / task-history stage failures are logged and swallowed — the
1728+
* message array is already persisted, and the next save recomputes and re-emits the
1729+
* metadata.
1730+
*
1731+
* `merge` (default `true`) is passed through to `saveTaskMessages`: the in-memory
1732+
* snapshot is merged with the on-disk record. `overwriteClineMessages` passes `false`
1733+
* to replace the stored messages outright.
1734+
*/
17231735
private async saveClineMessages(merge = true): Promise<boolean> {
17241736
try {
17251737
await saveTaskMessages({
@@ -1728,7 +1740,12 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
17281740
globalStoragePath: this.globalStoragePath,
17291741
merge,
17301742
})
1743+
} catch (error) {
1744+
console.error("Failed to save Roo messages:", error)
1745+
return false
1746+
}
17311747

1748+
try {
17321749
if (this._taskApiConfigName === undefined) {
17331750
await this.taskApiConfigReady
17341751
}
@@ -1756,11 +1773,14 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
17561773
const provider = this.providerRef.deref()
17571774
const existingStatus = provider?.taskHistoryStore.get(this.taskId)?.status
17581775
await provider?.updateTaskHistory(existingStatus ? { ...historyItem, status: existingStatus } : historyItem)
1759-
return true
17601776
} catch (error) {
1761-
console.error("Failed to save Roo messages:", error)
1762-
return false
1777+
// The message array was persisted above; a metadata or task-history failure must
1778+
// not mask that write (see the method docs). The next saveClineMessages() call
1779+
// recomputes and re-emits the metadata update.
1780+
console.error("Failed to save task metadata:", error)
17631781
}
1782+
1783+
return true
17641784
}
17651785

17661786
private findMessageByTimestamp(ts: number): ClineMessage | undefined {
@@ -2761,6 +2781,56 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
27612781
return formatResponse.toolError(formatResponse.missingToolParameterError(paramName))
27622782
}
27632783

2784+
/**
2785+
* Finalize a partial "tool" ask message without blocking for user input.
2786+
* Call this in error paths where a partial tool message was opened during streaming
2787+
* but execution failed before the normal approval flow could close it, so the webview
2788+
* spinner does not get stuck in a loading state.
2789+
*
2790+
* The matching partial message may no longer be the final entry if another asynchronous
2791+
* message was inserted between the partial ask and the error handler, so search backward
2792+
* instead of relying on clineMessages.at(-1).
2793+
*
2794+
* Any in-progress `progressStatus` on the message is cleared as well: the ask is being
2795+
* finalized because it will NOT complete, so a stale "in progress" indicator would be
2796+
* misleading (the normal completion path overwrites it with the final status instead).
2797+
*
2798+
* `isAnswered` is stamped true because the ask is resolved by the system rather than
2799+
* by the user: ChatView only shows ask buttons for unanswered messages, so leaving it
2800+
* unset would keep Save/Reject armed for a write that already failed.
2801+
*/
2802+
async finalizePartialToolAsk(text?: string): Promise<void> {
2803+
const partialToolAsk = findLast(
2804+
this.clineMessages,
2805+
(message) =>
2806+
message.partial === true &&
2807+
message.type === "ask" &&
2808+
message.ask === "tool" &&
2809+
(text === undefined || message.text === text),
2810+
)
2811+
2812+
if (!partialToolAsk) {
2813+
return
2814+
}
2815+
2816+
partialToolAsk.partial = false
2817+
partialToolAsk.progressStatus = undefined
2818+
partialToolAsk.isAnswered = true
2819+
const saved = await this.saveClineMessages()
2820+
if (!saved) {
2821+
// The persistence write failed: the on-disk record still carries `partial: true`
2822+
// while the in-memory message is finalized. Skip the webview-only update so the
2823+
// two views do not diverge (a later state resync or restart reload would flip the
2824+
// spinner back on from the stale disk record). The next saveClineMessages() call
2825+
// re-persists the full message array and repairs the disk record.
2826+
console.error("[Task#finalizePartialToolAsk] saveClineMessages failed; skipping webview update")
2827+
return
2828+
}
2829+
await this.updateClineMessage(partialToolAsk).catch((error) => {
2830+
console.error("[Task#finalizePartialToolAsk] updateClineMessage failed:", error)
2831+
})
2832+
}
2833+
27642834
// Lifecycle
27652835
// Start / Resume / Abort / Dispose
27662836

0 commit comments

Comments
 (0)