From c802418efc69b29f6064c1cf7483ed00bb47fac7 Mon Sep 17 00:00:00 2001 From: cartridgebasic <68982521+cartridgebasic@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:34:50 -0700 Subject: [PATCH 1/2] Restore checkpoints by stable message ID A timestamp can target the wrong message when several rows share it. Carry the stable ID through the delete confirmation and rewind path. Refs #2737 --- packages/types/src/vscode-extension-host.ts | 1 + .../checkpoints/__tests__/checkpoint.test.ts | 36 ++++++++++++++++++ src/core/checkpoints/index.ts | 15 +++++--- src/core/message-manager/index.ts | 4 +- src/core/task/Task.ts | 2 +- src/core/task/__tests__/Task.spec.ts | 15 ++++++++ .../webviewMessageHandler.checkpoint.spec.ts | 29 +++++++++++++++ src/core/webview/checkpointRestoreHandler.ts | 4 +- src/core/webview/webviewMessageHandler.ts | 37 ++++++++++++++----- webview-ui/src/App.tsx | 4 ++ webview-ui/src/__tests__/App.spec.tsx | 25 ++++++++++++- webview-ui/src/components/chat/ChatRow.tsx | 6 ++- .../chat/__tests__/ChatRow.timestamp.spec.tsx | 11 ++++++ 13 files changed, 169 insertions(+), 20 deletions(-) diff --git a/packages/types/src/vscode-extension-host.ts b/packages/types/src/vscode-extension-host.ts index 4e7efff57fc..38a61b6445c 100644 --- a/packages/types/src/vscode-extension-host.ts +++ b/packages/types/src/vscode-extension-host.ts @@ -228,6 +228,7 @@ export interface ExtensionMessage { rulesFolderPath?: string settings?: any // eslint-disable-line @typescript-eslint/no-explicit-any messageTs?: number + messageId?: string hasCheckpoint?: boolean context?: string commands?: Command[] diff --git a/src/core/checkpoints/__tests__/checkpoint.test.ts b/src/core/checkpoints/__tests__/checkpoint.test.ts index 1d56126f0a4..f717531fdb6 100644 --- a/src/core/checkpoints/__tests__/checkpoint.test.ts +++ b/src/core/checkpoints/__tests__/checkpoint.test.ts @@ -237,6 +237,42 @@ describe("Checkpoint functionality", () => { expect(mockProvider.cancelTask).toHaveBeenCalled() }) + it("restores the selected message when two UI messages share a timestamp", async () => { + mockTask.clineMessages[1].ts = 3 + mockTask.clineMessages[1].messageId = "earlier" + mockTask.clineMessages[2].messageId = "selected" + + await checkpointRestore(mockTask, { + ts: 3, + messageId: "selected", + commitHash: RESTORE_HASH, + mode: "restore", + operation: "delete", + }) + + expect(mockTask.overwriteClineMessages).toHaveBeenCalledWith(mockTask.clineMessages.slice(0, 2)) + }) + + it("retains the edited UI row but removes its API turn when selected by ID", async () => { + mockTask.clineMessages[1].ts = 3 + mockTask.clineMessages[1].messageId = "earlier" + mockTask.clineMessages[2].messageId = "selected" + + await checkpointRestore(mockTask, { + ts: 3, + messageId: "selected", + commitHash: RESTORE_HASH, + mode: "restore", + operation: "edit", + }) + + expect(mockTask.overwriteClineMessages).toHaveBeenCalledWith(mockTask.clineMessages.slice(0, 3)) + expect(mockTask.overwriteApiConversationHistory).toHaveBeenCalledWith([ + { ts: 1, role: "user", content: [{ type: "text", text: "Message 1" }] }, + { ts: 2, role: "assistant", content: [{ type: "text", text: "Message 2" }] }, + ]) + }) + it("should restore checkpoint for edit operation", async () => { await checkpointRestore(mockTask, { ts: 2, diff --git a/src/core/checkpoints/index.ts b/src/core/checkpoints/index.ts index 0bf73a726e4..79740bbd433 100644 --- a/src/core/checkpoints/index.ts +++ b/src/core/checkpoints/index.ts @@ -231,6 +231,7 @@ export async function checkpointSave(task: Task, force = false, suppressMessage export type CheckpointRestoreOptions = { ts: number + messageId?: string commitHash: string mode: "preview" | "restore" operation?: "delete" | "edit" // Optional to maintain backward compatibility @@ -238,7 +239,7 @@ export type CheckpointRestoreOptions = { export async function checkpointRestore( task: Task, - { ts, commitHash, mode, operation = "delete" }: CheckpointRestoreOptions, + { ts, messageId, commitHash, mode, operation = "delete" }: CheckpointRestoreOptions, ) { assertRecordedCheckpoint(task, commitHash) @@ -248,7 +249,7 @@ export async function checkpointRestore( return } - const index = task.clineMessages.findIndex((m) => m.ts === ts) + const index = task.clineMessages.findIndex((m) => (messageId ? m.messageId === messageId : m.ts === ts)) if (index === -1) { return @@ -271,9 +272,13 @@ export async function checkpointRestore( // Use MessageManager to properly handle context-management events // This ensures orphaned Summary messages and truncation markers are cleaned up - await task.messageManager.rewindToTimestamp(ts, { - includeTargetMessage: operation === "edit", - }) + if (messageId) { + await task.messageManager.rewindToIndex(index + (operation === "edit" ? 1 : 0), { + apiCutoffTs: ts, + }) + } else { + await task.messageManager.rewindToTimestamp(ts, { includeTargetMessage: operation === "edit" }) + } // Report the deleted API request metrics await task.say( diff --git a/src/core/message-manager/index.ts b/src/core/message-manager/index.ts index 2d4666e9eec..88131e93906 100644 --- a/src/core/message-manager/index.ts +++ b/src/core/message-manager/index.ts @@ -9,6 +9,8 @@ export interface RewindOptions { includeTargetMessage?: boolean /** Skip cleanup for special cases (default: false) */ skipCleanup?: boolean + /** API history boundary when the UI target is resolved by ID/index. */ + apiCutoffTs?: number } interface ContextEventIds { @@ -66,7 +68,7 @@ export class MessageManager { * @param options - Rewind options */ async rewindToIndex(toIndex: number, options: RewindOptions = {}): Promise { - const cutoffTs = this.task.clineMessages[toIndex]?.ts ?? Date.now() + const cutoffTs = options.apiCutoffTs ?? this.task.clineMessages[toIndex]?.ts ?? Date.now() await this.performRewind(toIndex, cutoffTs, options) } diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index 3b2771ddfa7..fa0306fc17c 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -2850,7 +2850,7 @@ export class Task extends EventEmitter implements TaskLike { contextCondense?: ContextCondense, contextTruncation?: ContextTruncation, ): Promise { - if (this.abort) { + if (this.abort && type !== "api_req_deleted") { throw new Error(`[RooCode#say] task ${this.taskId}.${this.instanceId} aborted`) } diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index cea34e05d1c..427c3c4584c 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -2694,6 +2694,21 @@ describe("Cline", () => { expect(metadata?.mode).toBe("ask") }) + it("records checkpoint deletion metrics after the task has been stopped", async () => { + const task = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + task: "test task", + startTask: false, + }) + task.requestAbort(false) + await expect(task.say("api_req_deleted", "{}")).resolves.toBeUndefined() + expect(task.clineMessages.at(-1)).toMatchObject({ say: "api_req_deleted", text: "{}" }) + await expect(task.say("text", "must not resume")).rejects.toThrow( + `[RooCode#say] task ${task.taskId}.${task.instanceId} aborted`, + ) + }) + it("condenses with an undefined state snapshot when the provider is gone", async () => { const task = new Task({ provider: mockProvider, diff --git a/src/core/webview/__tests__/webviewMessageHandler.checkpoint.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.checkpoint.spec.ts index 5cb791026b5..eeeed1663ca 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.checkpoint.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.checkpoint.spec.ts @@ -269,6 +269,35 @@ describe("webviewMessageHandler - checkpoint operations", () => { expect(fixture.taskDouble.checkpointRestore).not.toHaveBeenCalled() }) + it("uses the steering message ID through delete confirmation and checkpoint restore", async () => { + fixture.task.clineMessages[1].ts = 3 + fixture.task.clineMessages[1].messageId = "other" + fixture.task.clineMessages[2].messageId = "steering" + + await webviewMessageHandler(fixture.provider, { + type: "deleteMessage", + value: 3, + messageId: "steering", + }) + expect(fixture.providerDouble.postMessageToWebview).toHaveBeenCalledWith( + expect.objectContaining({ type: "showDeleteMessageDialog", messageId: "steering" }), + ) + + await webviewMessageHandler(fixture.provider, { + type: "deleteMessageConfirm", + messageTs: 3, + messageId: "steering", + restoreCheckpoint: true, + }) + expect(fixture.taskDouble.checkpointRestore).toHaveBeenCalledWith({ + ts: 3, + messageId: "steering", + commitHash: LATEST_CHECKPOINT, + mode: "restore", + operation: "delete", + }) + }) + it.each([ { type: "checkpointRestore", diff --git a/src/core/webview/checkpointRestoreHandler.ts b/src/core/webview/checkpointRestoreHandler.ts index d8b1acb4b31..c2b6c51522d 100644 --- a/src/core/webview/checkpointRestoreHandler.ts +++ b/src/core/webview/checkpointRestoreHandler.ts @@ -10,6 +10,7 @@ export interface CheckpointRestoreConfig { provider: ClineProvider currentCline: Task messageTs: number + messageId?: string messageIndex: number checkpoint: { hash: string } operation: "delete" | "edit" @@ -25,7 +26,7 @@ export interface CheckpointRestoreConfig { * This consolidates the common logic while handling operation-specific behavior. */ export async function handleCheckpointRestoreOperation(config: CheckpointRestoreConfig): Promise { - const { provider, currentCline, messageTs, checkpoint, operation, editData } = config + const { provider, currentCline, messageTs, messageId, checkpoint, operation, editData } = config let checkpointRestored = false let pendingEditOwner: object | undefined @@ -60,6 +61,7 @@ export async function handleCheckpointRestoreOperation(config: CheckpointRestore // Perform the checkpoint restoration await currentCline.checkpointRestore({ ts: messageTs, + ...(messageId ? { messageId } : {}), commitHash: checkpoint.hash, mode: "restore", operation, diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index 6641ff259f1..15eebe83f99 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -254,9 +254,11 @@ export const webviewMessageHandler = async ( * this function prefers non-summary messages to ensure user operations * target the intended message rather than the summary. */ - const findMessageIndices = (messageTs: number, currentCline: any) => { + const findMessageIndices = (messageTs: number, currentCline: any, messageId?: string) => { // Find the exact message by timestamp, not the first one after a cutoff - const messageIndex = currentCline.clineMessages.findIndex((msg: ClineMessage) => msg.ts === messageTs) + const messageIndex = currentCline.clineMessages.findIndex((msg: ClineMessage) => + messageId ? msg.messageId === messageId : msg.ts === messageTs, + ) // Find all matching API messages by timestamp const allApiMatches = currentCline.apiConversationHistory @@ -284,7 +286,7 @@ export const webviewMessageHandler = async ( /** * Handles message deletion operations with user confirmation */ - const handleDeleteOperation = async (messageTs: number): Promise => { + const handleDeleteOperation = async (messageTs: number, messageId?: string): Promise => { // Check if there's a checkpoint before this message const currentCline = provider.getCurrentTask() let hasCheckpoint = false @@ -294,7 +296,7 @@ export const webviewMessageHandler = async ( return } - const { messageIndex } = findMessageIndices(messageTs, currentCline) + const { messageIndex } = findMessageIndices(messageTs, currentCline, messageId) if (messageIndex !== -1) { // Find the last checkpoint before this message @@ -308,6 +310,9 @@ export const webviewMessageHandler = async ( await provider.postMessageToWebview({ type: "showDeleteMessageDialog", messageTs, + ...(currentCline.clineMessages[messageIndex]?.messageId + ? { messageId: currentCline.clineMessages[messageIndex].messageId } + : {}), hasCheckpoint, }) } @@ -315,14 +320,18 @@ export const webviewMessageHandler = async ( /** * Handles confirmed message deletion from webview dialog */ - const handleDeleteMessageConfirm = async (messageTs: number, restoreCheckpoint?: boolean): Promise => { + const handleDeleteMessageConfirm = async ( + messageTs: number, + restoreCheckpoint?: boolean, + messageId?: string, + ): Promise => { const currentCline = provider.getCurrentTask() if (!currentCline) { console.error("[handleDeleteMessageConfirm] No current cline available") return } - const { messageIndex, apiConversationHistoryIndex } = findMessageIndices(messageTs, currentCline) + const { messageIndex, apiConversationHistoryIndex } = findMessageIndices(messageTs, currentCline, messageId) // Determine API truncation index with timestamp fallback if exact match not found let apiIndexToUse = apiConversationHistoryIndex const tsThreshold = currentCline.clineMessages[messageIndex]?.ts @@ -352,6 +361,7 @@ export const webviewMessageHandler = async ( provider, currentCline, messageTs: targetMessage.ts!, + messageId: targetMessage.messageId, messageIndex, checkpoint: { hash: nextCheckpoint.text }, operation: "delete", @@ -373,7 +383,13 @@ export const webviewMessageHandler = async ( } // Delete this message and all subsequent messages using MessageManager - await currentCline.messageManager.rewindToTimestamp(targetMessage.ts!, { includeTargetMessage: false }) + if (targetMessage.messageId) { + await currentCline.messageManager.rewindToIndex(messageIndex, { apiCutoffTs: targetMessage.ts }) + } else { + await currentCline.messageManager.rewindToTimestamp(targetMessage.ts!, { + includeTargetMessage: false, + }) + } // Restore checkpoint associations for preserved messages for (const [ts, checkpoint] of preservedCheckpoints) { @@ -587,9 +603,10 @@ export const webviewMessageHandler = async ( operation: "delete" | "edit", editedContent?: string, images?: string[], + messageId?: string, ): Promise => { if (operation === "delete") { - await handleDeleteOperation(messageTs) + await handleDeleteOperation(messageTs, messageId) } else if (operation === "edit" && editedContent) { await handleEditOperation(messageTs, editedContent, images) } @@ -2240,7 +2257,7 @@ export const webviewMessageHandler = async ( break } - await handleMessageModificationsOperation(message.value, "delete") + await handleMessageModificationsOperation(message.value, "delete", undefined, undefined, message.messageId) break } case "submitEditedMessage": { @@ -2614,7 +2631,7 @@ export const webviewMessageHandler = async ( break } - await handleDeleteMessageConfirm(message.messageTs, message.restoreCheckpoint) + await handleDeleteMessageConfirm(message.messageTs, message.restoreCheckpoint, message.messageId) break case "editMessageConfirm": if (message.messageTs && message.text) { diff --git a/webview-ui/src/App.tsx b/webview-ui/src/App.tsx index 583479020a0..8e7f15233db 100644 --- a/webview-ui/src/App.tsx +++ b/webview-ui/src/App.tsx @@ -30,6 +30,7 @@ type Tab = "settings" | "history" | "chat" | "marketplace" interface DeleteMessageDialogState { isOpen: boolean messageTs: number + messageId?: string hasCheckpoint: boolean } @@ -146,6 +147,7 @@ const App = () => { setDeleteMessageDialogState({ isOpen: true, messageTs: message.messageTs, + messageId: message.messageId, hasCheckpoint: message.hasCheckpoint || false, }) } @@ -298,6 +300,7 @@ const App = () => { vscode.postMessage({ type: "deleteMessageConfirm", messageTs: deleteMessageDialogState.messageTs, + messageId: deleteMessageDialogState.messageId, restoreCheckpoint, }) setDeleteMessageDialogState((prev) => ({ ...prev, isOpen: false })) @@ -311,6 +314,7 @@ const App = () => { vscode.postMessage({ type: "deleteMessageConfirm", messageTs: deleteMessageDialogState.messageTs, + messageId: deleteMessageDialogState.messageId, }) setDeleteMessageDialogState((prev) => ({ ...prev, isOpen: false })) }} diff --git a/webview-ui/src/__tests__/App.spec.tsx b/webview-ui/src/__tests__/App.spec.tsx index e0b0238dd31..fe33301582c 100644 --- a/webview-ui/src/__tests__/App.spec.tsx +++ b/webview-ui/src/__tests__/App.spec.tsx @@ -1,7 +1,7 @@ // npx vitest run src/__tests__/App.spec.tsx import React from "react" -import { render, screen, act, cleanup } from "@/utils/test-utils" +import { render, screen, act, cleanup, fireEvent } from "@/utils/test-utils" import AppWithProviders from "../App" import { vscode } from "../utils/vscode" @@ -210,6 +210,29 @@ describe("App", () => { expect(chatView.getAttribute("data-hidden")).toBe("false") }, 10000) + it("forwards the saved message ID when restoring a deleted steering message", () => { + render() + act(() => { + window.dispatchEvent( + new MessageEvent("message", { + data: { + type: "showDeleteMessageDialog", + messageTs: 1234, + messageId: "steer-id", + hasCheckpoint: true, + }, + }), + ) + }) + fireEvent.click(screen.getByText("common:confirmation.restoreToCheckpoint")) + expect(vscode.postMessage).toHaveBeenCalledWith({ + type: "deleteMessageConfirm", + messageTs: 1234, + messageId: "steer-id", + restoreCheckpoint: true, + }) + }) + it("preserves chat state across task and tab changes", async () => { const state = { didHydrateState: true, diff --git a/webview-ui/src/components/chat/ChatRow.tsx b/webview-ui/src/components/chat/ChatRow.tsx index 47e8bf1f783..cb96dc57504 100644 --- a/webview-ui/src/components/chat/ChatRow.tsx +++ b/webview-ui/src/components/chat/ChatRow.tsx @@ -1329,7 +1329,11 @@ export const ChatRowContent = ({ style={{ visibility: isStreaming ? "hidden" : "visible" }} onClick={(e) => { e.stopPropagation() - vscode.postMessage({ type: "deleteMessage", value: message.ts }) + vscode.postMessage({ + type: "deleteMessage", + value: message.ts, + messageId: message.messageId, + }) }}> { expect(screen.getByTestId("message-timestamp").textContent).toContain("Today") }) + it("sends the stable ID when deleting a steering message", () => { + renderRow({ ts: 1234, messageId: "steer-id", type: "say", say: "user_feedback", text: "steer" }) + fireEvent.click(screen.getByLabelText("common:confirmation.deleteMessage")) + expect(vscode.postMessage).toHaveBeenCalledWith({ + type: "deleteMessage", + value: 1234, + messageId: "steer-id", + }) + }) + it("uses the message's own timestamp, not the current time", () => { const d = new Date() d.setDate(d.getDate() - 1) From 92d35bbda207eff3054c162d94e3bf72bcd8cbb7 Mon Sep 17 00:00:00 2001 From: cartridgebasic <68982521+cartridgebasic@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:01:28 -0700 Subject: [PATCH 2/2] fix: preserve earlier messages when rollback timestamps collide --- src/core/checkpoints/index.ts | 1 + src/core/message-manager/index.spec.ts | 25 ++++++++++++ src/core/message-manager/index.ts | 38 +++++++++++++++++-- .../webviewMessageHandler.checkpoint.spec.ts | 12 ++++++ src/core/webview/webviewMessageHandler.ts | 9 ++++- 5 files changed, 80 insertions(+), 5 deletions(-) diff --git a/src/core/checkpoints/index.ts b/src/core/checkpoints/index.ts index 79740bbd433..ba6ba0dbb38 100644 --- a/src/core/checkpoints/index.ts +++ b/src/core/checkpoints/index.ts @@ -275,6 +275,7 @@ export async function checkpointRestore( if (messageId) { await task.messageManager.rewindToIndex(index + (operation === "edit" ? 1 : 0), { apiCutoffTs: ts, + apiCutoffMessageId: messageId, }) } else { await task.messageManager.rewindToTimestamp(ts, { includeTargetMessage: operation === "edit" }) diff --git a/src/core/message-manager/index.spec.ts b/src/core/message-manager/index.spec.ts index 770b8347cff..f11b70e7f46 100644 --- a/src/core/message-manager/index.spec.ts +++ b/src/core/message-manager/index.spec.ts @@ -27,6 +27,31 @@ describe("MessageManager", () => { }) describe("Basic rewind operations", () => { + it.each([false, true])( + "keeps the earlier API turn on a timestamp collision (shared ID=%s)", + async (sharedId) => { + const earlierUi = { ts: 300, type: "say", say: "user_feedback", messageId: "earlier-ui" } + const targetUi = { ts: 300, type: "say", say: "user_feedback", messageId: "target-ui" } + const earlierApi = { ts: 300, role: "user", content: "earlier prompt", messageId: "earlier-api" } + const targetApi = { + ts: 300, + role: "user", + content: "target prompt", + messageId: sharedId ? "target-ui" : "target-api", + } + mockTask.clineMessages = [earlierUi, targetUi] + mockTask.apiConversationHistory = [ + earlierApi, + targetApi, + { ts: 301, role: "assistant", content: "response" }, + ] + + await manager.rewindToIndex(1, { apiCutoffTs: 300, apiCutoffMessageId: "target-ui", skipCleanup: true }) + + expect(mockTask.overwriteClineMessages).toHaveBeenCalledExactlyOnceWith([earlierUi]) + expect(mockTask.overwriteApiConversationHistory).toHaveBeenCalledExactlyOnceWith([earlierApi]) + }, + ) it("should remove messages at and after the target timestamp", async () => { mockTask.clineMessages = [ { ts: 100, say: "user", text: "First" }, diff --git a/src/core/message-manager/index.ts b/src/core/message-manager/index.ts index 88131e93906..e89944834ee 100644 --- a/src/core/message-manager/index.ts +++ b/src/core/message-manager/index.ts @@ -11,6 +11,8 @@ export interface RewindOptions { skipCleanup?: boolean /** API history boundary when the UI target is resolved by ID/index. */ apiCutoffTs?: number + /** Stable identity of the UI turn at the API cutoff, if available. */ + apiCutoffMessageId?: string } interface ContextEventIds { @@ -76,7 +78,9 @@ export class MessageManager { * Internal method that performs the actual rewind operation. */ private async performRewind(toIndex: number, cutoffTs: number, options: RewindOptions): Promise { - const { skipCleanup = false } = options + const { skipCleanup = false, apiCutoffMessageId } = options + const apiCutoffIndex = + apiCutoffMessageId === undefined ? undefined : this.resolveApiCutoffIndex(apiCutoffMessageId, cutoffTs) // Step 1: Collect context event IDs from messages being removed const removedIds = this.collectRemovedContextEventIds(toIndex) @@ -85,7 +89,30 @@ export class MessageManager { await this.truncateClineMessages(toIndex) // Step 3: Truncate and clean API history (combined with cleanup for efficiency) - await this.truncateApiHistoryWithCleanup(cutoffTs, removedIds, skipCleanup) + await this.truncateApiHistoryWithCleanup(cutoffTs, removedIds, skipCleanup, apiCutoffIndex) + } + + private resolveApiCutoffIndex(messageId: string, cutoffTs: number): number | undefined { + const history = this.task.apiConversationHistory + const exact = history.findIndex((message) => message.messageId === messageId && !message.isSummary) + if (exact !== -1) return exact + + // Older transcripts give the UI and API rows different IDs. Only align by + // ordinal when both sides have the same number of matching user turns. + const matchingUi = this.task.clineMessages.filter( + (message, index) => + message.ts === cutoffTs && + message.type === "say" && + (message.say === "user_feedback" || (index === 0 && message.say === "text")), + ) + const ordinal = matchingUi.findIndex((message) => message.messageId === messageId) + if (ordinal <= 0) return undefined + const matchingApi: number[] = [] + for (const [index, message] of history.entries()) { + if (message.ts === cutoffTs && message.role === "user" && !message.isSummary && !message.isTruncationMarker) + matchingApi.push(index) + } + return matchingApi.length === matchingUi.length ? matchingApi[ordinal] : undefined } /** @@ -149,9 +176,10 @@ export class MessageManager { cutoffTs: number, removedIds: ContextEventIds, skipCleanup: boolean, + apiCutoffIndex?: number, ): Promise { const originalHistory = this.task.apiConversationHistory - let apiHistory = [...originalHistory] + let apiHistory = apiCutoffIndex === undefined ? [...originalHistory] : originalHistory.slice(0, apiCutoffIndex) // Step 1: Determine the actual cutoff timestamp // Check if there's an API message with an exact timestamp match @@ -179,7 +207,9 @@ export class MessageManager { } // Step 2: Filter by the actual cutoff timestamp - apiHistory = apiHistory.filter((m) => !m.ts || m.ts < actualCutoff) + if (apiCutoffIndex === undefined) { + apiHistory = apiHistory.filter((m) => !m.ts || m.ts < actualCutoff) + } // Step 3: Remove Summaries whose condense_context was removed if (removedIds.condenseIds.size > 0) { diff --git a/src/core/webview/__tests__/webviewMessageHandler.checkpoint.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.checkpoint.spec.ts index eeeed1663ca..d76ad1654e7 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.checkpoint.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.checkpoint.spec.ts @@ -269,6 +269,18 @@ describe("webviewMessageHandler - checkpoint operations", () => { expect(fixture.taskDouble.checkpointRestore).not.toHaveBeenCalled() }) + it("rejects an unknown delete ID even if another row has the same timestamp", async () => { + await webviewMessageHandler(fixture.provider, { + type: "deleteMessage", + value: 3, + messageId: "removed-message", + }) + expect(fixture.providerDouble.postMessageToWebview).not.toHaveBeenCalledWith( + expect.objectContaining({ type: "showDeleteMessageDialog" }), + ) + expect(fixture.taskDouble.checkpointRestore).not.toHaveBeenCalled() + }) + it("uses the steering message ID through delete confirmation and checkpoint restore", async () => { fixture.task.clineMessages[1].ts = 3 fixture.task.clineMessages[1].messageId = "other" diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index 15eebe83f99..d5326384ed2 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -297,6 +297,10 @@ export const webviewMessageHandler = async ( } const { messageIndex } = findMessageIndices(messageTs, currentCline, messageId) + if (messageId && messageIndex === -1) { + await vscode.window.showErrorMessage(t("common:errors.message.message_not_found", { messageTs })) + return + } if (messageIndex !== -1) { // Find the last checkpoint before this message @@ -384,7 +388,10 @@ export const webviewMessageHandler = async ( // Delete this message and all subsequent messages using MessageManager if (targetMessage.messageId) { - await currentCline.messageManager.rewindToIndex(messageIndex, { apiCutoffTs: targetMessage.ts }) + await currentCline.messageManager.rewindToIndex(messageIndex, { + apiCutoffTs: targetMessage.ts, + apiCutoffMessageId: targetMessage.messageId, + }) } else { await currentCline.messageManager.rewindToTimestamp(targetMessage.ts!, { includeTargetMessage: false,