From 4a326cb44ef311c922147a2104965d7061dc7261 Mon Sep 17 00:00:00 2001 From: cartridgebasic <68982521+cartridgebasic@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:35:38 -0700 Subject: [PATCH 1/3] Validate and preserve task to-do lists Reject malformed inputs without clearing accepted lists. Keep approval edits task-scoped and seed delegated reminders from durable history. Refs #2743 --- packages/types/src/__tests__/message.test.ts | 6 + packages/types/src/message.ts | 3 + .../__tests__/getEnvironmentDetails.spec.ts | 45 +++- src/core/environment/getEnvironmentDetails.ts | 9 +- src/core/environment/reminder.ts | 18 +- .../prompts/tools/native-tools/new_task.ts | 2 +- .../tools/native-tools/update_todo_list.ts | 39 +--- .../__tests__/todoHistory.spec.ts | 34 +++ src/core/task/Task.ts | 7 +- .../task/__tests__/Task.persistence.spec.ts | 18 ++ src/core/tools/NewTaskTool.ts | 12 +- src/core/tools/UpdateTodoListTool.ts | 116 ++++------- .../tools/__tests__/todoInputContract.spec.ts | 197 ++++++++++++++++++ .../__tests__/updateTodoListTool.spec.ts | 27 ++- .../ClineProvider.sticky-mode.spec.ts | 12 ++ src/core/webview/webviewMessageHandler.ts | 7 +- src/eslint-suppressions.json | 12 +- src/shared/__tests__/todo.spec.ts | 51 +++++ src/shared/__tests__/todoChecklist.spec.ts | 58 ++++++ src/shared/todo.ts | 48 +++-- src/shared/todoChecklist.ts | 82 ++++++++ 21 files changed, 634 insertions(+), 169 deletions(-) create mode 100644 src/core/task-persistence/__tests__/todoHistory.spec.ts create mode 100644 src/core/tools/__tests__/todoInputContract.spec.ts create mode 100644 src/shared/__tests__/todo.spec.ts create mode 100644 src/shared/__tests__/todoChecklist.spec.ts create mode 100644 src/shared/todoChecklist.ts diff --git a/packages/types/src/__tests__/message.test.ts b/packages/types/src/__tests__/message.test.ts index 9bd108e6b39..047017e9b96 100644 --- a/packages/types/src/__tests__/message.test.ts +++ b/packages/types/src/__tests__/message.test.ts @@ -23,6 +23,12 @@ describe("ask messages", () => { }) describe("clineMessageSchema autoApprovalDecision", () => { + it("preserves initial task todos through persisted message validation", () => { + const initialTodos = [{ id: "first", content: "Initial task", status: "pending" }] + expect(clineMessageSchema.parse({ ts: 1, type: "say", say: "text", initialTodos }).initialTodos).toEqual( + initialTodos, + ) + }) it.each(["approve", "deny"] as const)("accepts %s", (autoApprovalDecision) => { expect(clineMessageSchema.safeParse({ ts: 1, type: "ask", ask: "command", autoApprovalDecision }).success).toBe( true, diff --git a/packages/types/src/message.ts b/packages/types/src/message.ts index 25cae2c0209..104698b15c2 100644 --- a/packages/types/src/message.ts +++ b/packages/types/src/message.ts @@ -1,4 +1,5 @@ import { z } from "zod" +import { todoItemSchema } from "./todo.js" /** * ClineAsk @@ -259,6 +260,8 @@ export const clineMessageSchema = z.object({ text: z.string().optional(), images: z.array(z.string()).optional(), partial: z.boolean().optional(), + /** Initial delegated-task checklist, stored with its first message before model updates. */ + initialTodos: z.array(todoItemSchema).optional(), reasoning: z.string().optional(), conversationHistoryIndex: z.number().optional(), checkpoint: z.record(z.string(), z.unknown()).optional(), diff --git a/src/core/environment/__tests__/getEnvironmentDetails.spec.ts b/src/core/environment/__tests__/getEnvironmentDetails.spec.ts index 9711b2a1b24..5d2430f2caa 100644 --- a/src/core/environment/__tests__/getEnvironmentDetails.spec.ts +++ b/src/core/environment/__tests__/getEnvironmentDetails.spec.ts @@ -368,14 +368,57 @@ describe("getEnvironmentDetails", () => { expect(result).toContain("REMINDERS") }) - it("should NOT include REMINDERS section when todoListEnabled is false", async () => { + it("does not advertise the update tool when todoListEnabled is false", async () => { mockProvider.getState.mockResolvedValue({ ...mockState, apiConfiguration: { todoListEnabled: false }, }) const cline = { ...mockCline, todoList: [{ content: "test", status: "pending" }] } const result = await getEnvironmentDetails(cline as Task) + expect(result).toContain("REMINDERS") + expect(result).not.toContain("call the `update_todo_list` tool") + }) + + it("omits empty-list instructions when the update tool is disabled", async () => { + mockProvider.getState.mockResolvedValue({ + ...mockState, + apiConfiguration: { todoListEnabled: false }, + }) + const cline = { ...mockCline, todoList: [] as NonNullable } + const result = await getEnvironmentDetails(cline as Task) expect(result).not.toContain("REMINDERS") + expect(result).not.toContain("update_todo_list") + }) + + it("keeps an existing task list visible after switching to a profile without the update tool", async () => { + mockProvider.getState.mockResolvedValue({ + ...mockState, + apiConfiguration: { todoListEnabled: false }, + }) + const cline = { + ...mockCline, + apiConfiguration: { todoListEnabled: false }, + todoList: [{ content: "Finish the active task", status: "in_progress" }], + } + const result = await getEnvironmentDetails(cline as Task) + expect(result).toContain("Finish the active task") + expect(result).toContain("In Progress") + expect(result).not.toContain("call the `update_todo_list` tool") + }) + + it("uses task-local tool availability when another profile is selected globally", async () => { + mockProvider.getState.mockResolvedValue({ + ...mockState, + apiConfiguration: { todoListEnabled: false }, + }) + const cline = { + ...mockCline, + apiConfiguration: { todoListEnabled: true }, + todoList: [{ content: "Keep task progress", status: "pending" }], + } + const result = await getEnvironmentDetails(cline as Task) + expect(result).toContain("Keep task progress") + expect(result).toContain("call the `update_todo_list` tool") }) it("should include REMINDERS section when todoListEnabled is undefined", async () => { diff --git a/src/core/environment/getEnvironmentDetails.ts b/src/core/environment/getEnvironmentDetails.ts index 89406906790..bf998b679e5 100644 --- a/src/core/environment/getEnvironmentDetails.ts +++ b/src/core/environment/getEnvironmentDetails.ts @@ -254,10 +254,9 @@ export async function getEnvironmentDetails(cline: Task, includeFileDetails: boo } } - const todoListEnabled = - state && typeof state.apiConfiguration?.todoListEnabled === "boolean" - ? state.apiConfiguration.todoListEnabled - : true - const reminderSection = todoListEnabled ? formatReminderSection(cline.todoList) : "" + const todoListEnabled = cline.apiConfiguration?.todoListEnabled ?? state?.apiConfiguration?.todoListEnabled ?? true + // A mode's profile can disable the update tool without clearing the task's list. + // Keep an existing list in the next request so superseded environment blocks can be removed safely. + const reminderSection = formatReminderSection(cline.todoList, todoListEnabled) return `\n${details.trim()}\n${reminderSection}\n` } diff --git a/src/core/environment/reminder.ts b/src/core/environment/reminder.ts index 6edb24364df..dda82916c28 100644 --- a/src/core/environment/reminder.ts +++ b/src/core/environment/reminder.ts @@ -3,9 +3,11 @@ import { TodoItem, TodoStatus } from "@roo-code/types" /** * Format the reminders section as a markdown block in English, with basic instructions. */ -export function formatReminderSection(todoList?: TodoItem[]): string { +export function formatReminderSection(todoList?: TodoItem[], canUpdate = true): string { if (!todoList || todoList.length === 0) { - return "You have not created a todo list yet. Create one with `update_todo_list` if your task is complicated or involves multiple steps." + return canUpdate + ? "You have not created a todo list yet. Create one with `update_todo_list` if your task is complicated or involves multiple steps." + : "" } const statusMap: Record = { pending: "Pending", @@ -29,10 +31,12 @@ export function formatReminderSection(todoList?: TodoItem[]): string { }) lines.push("") - lines.push( - "", - "IMPORTANT: When task status changes, remember to call the `update_todo_list` tool to update your progress.", - "", - ) + if (canUpdate) { + lines.push( + "", + "IMPORTANT: When task status changes, remember to call the `update_todo_list` tool to update your progress.", + "", + ) + } return lines.join("\n") } diff --git a/src/core/prompts/tools/native-tools/new_task.ts b/src/core/prompts/tools/native-tools/new_task.ts index f8e29e549d9..7bad0be4e15 100644 --- a/src/core/prompts/tools/native-tools/new_task.ts +++ b/src/core/prompts/tools/native-tools/new_task.ts @@ -8,7 +8,7 @@ const MODE_PARAMETER_DESCRIPTION = `Slug of the mode to begin the new task in (e const MESSAGE_PARAMETER_DESCRIPTION = `Initial user instructions or context for the new task` -const TODOS_PARAMETER_DESCRIPTION = `Optional initial todo list written as a markdown checklist; required when the workspace mandates todos` +const TODOS_PARAMETER_DESCRIPTION = `Optional string containing the full Markdown checklist, e.g. "[ ] First task\\n[-] Current task". Use [ ], [-], or [x] for status. Required when the workspace mandates todos; otherwise use null to omit.` export default { type: "function", diff --git a/src/core/prompts/tools/native-tools/update_todo_list.ts b/src/core/prompts/tools/native-tools/update_todo_list.ts index bad8e56e959..d885bc7b977 100644 --- a/src/core/prompts/tools/native-tools/update_todo_list.ts +++ b/src/core/prompts/tools/native-tools/update_todo_list.ts @@ -1,37 +1,20 @@ import type OpenAI from "openai" +import { TODO_ARGUMENT_EXAMPLE } from "../../../../shared/todoChecklist" -const UPDATE_TODO_LIST_DESCRIPTION = `Replace the entire TODO list with an updated checklist reflecting the current state. Always provide the full list; the system will overwrite the previous one. This tool is designed for step-by-step task tracking, allowing you to confirm completion of each step before updating, update multiple task statuses at once (e.g., mark one as completed and start the next), and dynamically add new todos discovered during long or complex tasks. +const UPDATE_TODO_LIST_DESCRIPTION = `Replace the entire task TODO list. Include all unfinished tasks and any completed tasks you want to retain; this is a replacement, not an append. -Checklist Format: -- Use a single-level markdown checklist (no nesting or subtasks) -- List todos in the intended execution order -- Status options: [ ] (pending), [x] (completed), [-] (in progress) +Call this native tool with JSON arguments. The todos field is a STRING containing a single-level Markdown checklist. Escape line breaks as \\n inside the JSON string. +- [ ] means pending, [-] means in progress, [x] means completed. +- Put tasks in execution order. Mark completed only when fully accomplished. +- Add newly discovered work and update several statuses in one call when useful. +- Use an empty string only to intentionally clear the entire list. -Core Principles: -- Before updating, always confirm which todos have been completed -- You may update multiple statuses in a single update -- Add new actionable items as they're discovered -- Only mark a task as completed when fully accomplished -- Keep all unfinished tasks unless explicitly instructed to remove +Example JSON arguments: +${TODO_ARGUMENT_EXAMPLE} -Example: Initial task list -{ "todos": "[x] Analyze requirements\\n[x] Design architecture\\n[-] Implement core logic\\n[ ] Write tests\\n[ ] Update documentation" } +Use this for multi-step work that needs progress tracking; skip it for trivial tasks or purely conversational replies.` -Example: After completing implementation -{ "todos": "[x] Analyze requirements\\n[x] Design architecture\\n[x] Implement core logic\\n[-] Write tests\\n[ ] Update documentation\\n[ ] Add performance benchmarks" } - -When to Use: -- Task involves multiple steps or requires ongoing tracking -- Need to update status of several todos at once -- New actionable items are discovered during execution -- Task is complex and benefits from stepwise progress tracking - -When NOT to Use: -- Only a single, trivial task -- Task can be completed in one or two simple steps -- Request is purely conversational or informational` - -const TODOS_PARAMETER_DESCRIPTION = `Full markdown checklist in execution order, using [ ] for pending, [x] for completed, and [-] for in progress` +const TODOS_PARAMETER_DESCRIPTION = `String containing the full checklist in execution order, using [ ] for pending, [x] for completed, and [-] for in progress. JSON arguments example: ${TODO_ARGUMENT_EXAMPLE}` export default { type: "function", diff --git a/src/core/task-persistence/__tests__/todoHistory.spec.ts b/src/core/task-persistence/__tests__/todoHistory.spec.ts new file mode 100644 index 00000000000..3f9554fc166 --- /dev/null +++ b/src/core/task-persistence/__tests__/todoHistory.spec.ts @@ -0,0 +1,34 @@ +import * as fs from "node:fs/promises" +import * as path from "node:path" +import * as os from "node:os" +import type { ClineMessage } from "@roo-code/types" + +import { readTaskMessages, saveTaskMessages } from "../taskMessages" +import { getLatestTodo } from "../../../shared/todo" +import { parseTodoListInput } from "../../../shared/todoChecklist" + +describe("TODO disk history round trip", () => { + let storage: string + beforeEach(async () => { + storage = await fs.mkdtemp(path.join(os.tmpdir(), "zoo-todo-history-")) + }) + afterEach(async () => { + await fs.rm(storage, { recursive: true, force: true }) + }) + it("preserves initial seeds and later approved JSON updates through actual file writes", async () => { + const seed = parseTodoListInput("[ ] Initial delegated task") + const messages: ClineMessage[] = [{ ts: 1, type: "say", say: "text", text: "Task", initialTodos: seed }] + await saveTaskMessages({ taskId: "todo", globalStoragePath: storage, messages }) + expect(getLatestTodo(await readTaskMessages({ taskId: "todo", globalStoragePath: storage }))).toEqual(seed) + const edited = parseTodoListInput([{ content: "#17: clickable https://example.com/link", status: "completed" }]) + messages.push({ + ts: 2, + type: "ask", + ask: "tool", + isAnswered: true, + text: JSON.stringify({ tool: "updateTodoList", todos: edited }), + }) + await saveTaskMessages({ taskId: "todo", globalStoragePath: storage, messages, merge: true }) + expect(getLatestTodo(await readTaskMessages({ taskId: "todo", globalStoragePath: storage }))).toEqual(edited) + }) +}) diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index 3b2771ddfa7..3687bae2968 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -1707,6 +1707,11 @@ export class Task extends EventEmitter implements TaskLike { private async addToClineMessages(message: ClineMessage) { message.messageId ??= crypto.randomUUID() + // A delegated task can restart before its first update_todo_list call. Keep + // the supplied list in the same durable history as subsequent accepted edits. + if (this.clineMessages.length === 0 && this.todoList?.length) { + message.initialTodos = this.todoList.map((todo) => ({ ...todo })) + } this.clineMessages.push(message) const provider = this.providerRef.deref() // Unanswered asks must reach the webview before Message listeners can respond against its state. @@ -3116,7 +3121,7 @@ export class Task extends EventEmitter implements TaskLike { this.apiConversationHistory = [] // The todo list is already set in the constructor if initialTodos were provided - // No need to add any messages - the todoList property is already set + // addToClineMessages saves it with the first message below. await this.providerRef.deref()?.postStateToWebviewWithoutTaskHistory() diff --git a/src/core/task/__tests__/Task.persistence.spec.ts b/src/core/task/__tests__/Task.persistence.spec.ts index 86df5615db1..9d6315f9596 100644 --- a/src/core/task/__tests__/Task.persistence.spec.ts +++ b/src/core/task/__tests__/Task.persistence.spec.ts @@ -976,6 +976,24 @@ describe("Task persistence", () => { // ── saveClineMessages ──────────────────────────────────────────────── describe("saveClineMessages", () => { + it("restores initial child-task todos from its first saved message before any model update", async () => { + const initialTodos = [{ id: "initial", content: "Delegated task", status: "in_progress" as const }] + const task = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + task: "child", + initialTodos, + startTask: false, + }) + await task.say("text", "child task request") + const saved = JSON.parse(JSON.stringify(task.clineMessages)) as ClineMessage[] + const restored = new Task({ provider: mockProvider, apiConfiguration: mockApiConfig, startTask: false }) + await restored.overwriteClineMessages(saved, false) + expect(restored.todoList).toEqual(initialTodos) + initialTodos[0].content = "Changed elsewhere" + expect(task.clineMessages[0]?.initialTodos?.[0]?.content).toBe("Delegated task") + expect(saved[0]?.initialTodos?.[0]?.content).toBe("Delegated task") + }) it("returns true on success", async () => { mockSaveTaskMessages.mockResolvedValueOnce([]) diff --git a/src/core/tools/NewTaskTool.ts b/src/core/tools/NewTaskTool.ts index 2e70cefb13d..a95cd57f5ce 100644 --- a/src/core/tools/NewTaskTool.ts +++ b/src/core/tools/NewTaskTool.ts @@ -5,7 +5,7 @@ import type { PendingTaskAction, TodoItem } from "@roo-code/types" import { Task } from "../task/Task" import { getModeBySlug } from "../../shared/modes" import { formatResponse } from "../prompts/responses" -import { parseMarkdownChecklist } from "./UpdateTodoListTool" +import { parseTodoListInput } from "../../shared/todoChecklist" import { Package } from "../../shared/package" import { BaseTool, ToolCallbacks } from "./BaseTool" import type { ToolUse } from "../../shared/tools" @@ -59,7 +59,7 @@ export class NewTaskTool extends BaseTool<"new_task"> { // Check if todos are required based on VSCode setting. // Note: `undefined` means not provided, empty string is valid. - if (requireTodos && todos === undefined) { + if (requireTodos && todos == null) { task.consecutiveMistakeCount++ task.recordToolError("new_task") task.didToolFailInCurrentTurn = true @@ -69,14 +69,14 @@ export class NewTaskTool extends BaseTool<"new_task"> { // Parse todos if provided, otherwise use empty array let todoItems: TodoItem[] = [] - if (todos) { + if (todos != null) { try { - todoItems = parseMarkdownChecklist(todos) - } catch { + todoItems = parseTodoListInput(todos) + } catch (error) { task.consecutiveMistakeCount++ task.recordToolError("new_task") task.didToolFailInCurrentTurn = true - pushToolResult(formatResponse.toolError("Invalid todos format: must be a markdown checklist")) + pushToolResult(formatResponse.toolError(error instanceof Error ? error.message : String(error))) return } } diff --git a/src/core/tools/UpdateTodoListTool.ts b/src/core/tools/UpdateTodoListTool.ts index 08edec2ed5c..3b9b3f1a1d3 100644 --- a/src/core/tools/UpdateTodoListTool.ts +++ b/src/core/tools/UpdateTodoListTool.ts @@ -2,68 +2,56 @@ import { Task } from "../task/Task" import { formatResponse } from "../prompts/responses" import { BaseTool, ToolCallbacks } from "./BaseTool" import type { ToolUse } from "../../shared/tools" -import cloneDeep from "clone-deep" -import crypto from "crypto" -import { TodoItem, TodoStatus, todoStatusSchema } from "@roo-code/types" +import { TodoItem } from "@roo-code/types" +import { parseMarkdownChecklist, parseTodoListInput } from "../../shared/todoChecklist" import { getLatestTodo } from "../../shared/todo" +export { parseMarkdownChecklist } from "../../shared/todoChecklist" + interface UpdateTodoListParams { - todos: string + todos: unknown } -let approvedTodoList: TodoItem[] | undefined = undefined +interface PendingTodoApproval { + todos: TodoItem[] +} +const pendingTodoLists = new WeakMap() export class UpdateTodoListTool extends BaseTool<"update_todo_list"> { readonly name = "update_todo_list" as const async execute(params: UpdateTodoListParams, task: Task, callbacks: ToolCallbacks): Promise { const { pushToolResult, handleError, askApproval } = callbacks + let pending: PendingTodoApproval | undefined try { - const todosRaw = params.todos - - let todos: TodoItem[] + let normalizedTodos: TodoItem[] try { - todos = parseMarkdownChecklist(todosRaw || "") - } catch { - task.consecutiveMistakeCount++ - task.recordToolError("update_todo_list") - task.didToolFailInCurrentTurn = true - pushToolResult(formatResponse.toolError("The todos parameter is not valid markdown checklist or JSON")) - return - } - - const { valid, error } = validateTodos(todos) - if (!valid) { + normalizedTodos = parseTodoListInput(params?.todos) + } catch (error) { task.consecutiveMistakeCount++ task.recordToolError("update_todo_list") task.didToolFailInCurrentTurn = true - pushToolResult(formatResponse.toolError(error || "todos parameter validation failed")) + pushToolResult(formatResponse.toolError(error instanceof Error ? error.message : String(error))) return } - let normalizedTodos: TodoItem[] = todos.map((t) => ({ - id: t.id, - content: t.content, - status: normalizeStatus(t.status), - })) - const approvalMsg = JSON.stringify({ tool: "updateTodoList", todos: normalizedTodos, }) - approvedTodoList = cloneDeep(normalizedTodos) + pending = { todos: normalizedTodos.map((todo) => ({ ...todo })) } + pendingTodoLists.set(task, pending) const didApprove = await askApproval("tool", approvalMsg) if (!didApprove) { pushToolResult("User declined to update the todoList.") return } - const isTodoListChanged = - approvedTodoList !== undefined && JSON.stringify(normalizedTodos) !== JSON.stringify(approvedTodoList) + const isTodoListChanged = JSON.stringify(normalizedTodos) !== JSON.stringify(pending.todos) if (isTodoListChanged) { - normalizedTodos = approvedTodoList ?? [] + normalizedTodos = pending.todos // Non-blocking: a failed notification must not abort persisting the edited list. void task .say( @@ -79,6 +67,7 @@ export class UpdateTodoListTool extends BaseTool<"update_todo_list"> { } await setTodoListForTask(task, normalizedTodos) + task.consecutiveMistakeCount = 0 if (isTodoListChanged) { const md = todoListToMarkdown(normalizedTodos) @@ -87,20 +76,22 @@ export class UpdateTodoListTool extends BaseTool<"update_todo_list"> { pushToolResult(formatResponse.toolResult("Todo list updated successfully.")) } } catch (error) { - await handleError("update todo list", error as Error) + await handleError("update todo list", error instanceof Error ? error : new Error(String(error))) + } finally { + if (pending && pendingTodoLists.get(task) === pending) pendingTodoLists.delete(task) } } override async handlePartial(task: Task, block: ToolUse<"update_todo_list">): Promise { - const todosRaw = block.params.todos + const todosRaw = block.nativeArgs?.todos ?? block.params.todos // Parse the markdown checklist to maintain consistent format with execute() let todos: TodoItem[] try { - todos = parseMarkdownChecklist(todosRaw || "") + todos = parseTodoListInput(todosRaw) } catch { - // If parsing fails during partial, send empty array - todos = [] + // An incomplete streamed checklist may still contain completed lines. + todos = parseMarkdownChecklist(todosRaw) } const approvalMsg = JSON.stringify({ @@ -135,53 +126,16 @@ function todoListToMarkdown(todos: TodoItem[]): string { .join("\n") } -function normalizeStatus(status: string | undefined): TodoStatus { - if (status === "completed") return "completed" - if (status === "in_progress") return "in_progress" - return "pending" -} - -export function parseMarkdownChecklist(md: string): TodoItem[] { - if (typeof md !== "string") return [] - const lines = md - .split(/\r?\n/) - .map((l) => l.trim()) - .filter(Boolean) - const todos: TodoItem[] = [] - for (const line of lines) { - const match = line.match(/^(?:-\s*)?\[\s*([ xX\-~])\s*\]\s+(.+)$/) - if (!match) continue - let status: TodoStatus = "pending" - if (match[1] === "x" || match[1] === "X") status = "completed" - else if (match[1] === "-" || match[1] === "~") status = "in_progress" - const id = crypto - .createHash("md5") - .update(match[2] + status) - .digest("hex") - todos.push({ - id, - content: match[2], - status, - }) - } - return todos -} - -export function setPendingTodoList(todos: TodoItem[]) { - approvedTodoList = todos -} - -function validateTodos(todos: any[]): { valid: boolean; error?: string } { - if (!Array.isArray(todos)) return { valid: false, error: "todos must be an array" } - for (const [i, t] of todos.entries()) { - if (!t || typeof t !== "object") return { valid: false, error: `Item ${i + 1} is not an object` } - if (!t.id || typeof t.id !== "string") return { valid: false, error: `Item ${i + 1} is missing id` } - if (!t.content || typeof t.content !== "string") - return { valid: false, error: `Item ${i + 1} is missing content` } - if (t.status && !todoStatusSchema.options.includes(t.status as TodoStatus)) - return { valid: false, error: `Item ${i + 1} has invalid status` } +/** Apply edits only to this Task's currently pending approval. */ +export function setPendingTodoList(task: Task, todos: unknown): boolean { + const pending = pendingTodoLists.get(task) + if (!pending || !Array.isArray(todos)) return false + try { + pending.todos = parseTodoListInput(todos) + return true + } catch { + return false } - return { valid: true } } export const updateTodoListTool = new UpdateTodoListTool() diff --git a/src/core/tools/__tests__/todoInputContract.spec.ts b/src/core/tools/__tests__/todoInputContract.spec.ts new file mode 100644 index 00000000000..5d9e225655c --- /dev/null +++ b/src/core/tools/__tests__/todoInputContract.spec.ts @@ -0,0 +1,197 @@ +import type { ClineMessage, TodoItem } from "@roo-code/types" +import type { Task } from "../../task/Task" +import type { ToolCallbacks } from "../BaseTool" +import { NativeToolCallParser } from "../../assistant-message/NativeToolCallParser" +import { restoreTodoListForTask, setPendingTodoList, updateTodoListTool } from "../UpdateTodoListTool" +import { newTaskTool } from "../NewTaskTool" +import { webviewMessageHandler } from "../../webview/webviewMessageHandler" +import type { ClineProvider } from "../../webview/ClineProvider" + +function fixture(taskId = "task") { + const state = { + taskId, + consecutiveMistakeCount: 0, + didToolFailInCurrentTurn: false, + recordToolError: vi.fn(), + todoList: [{ id: "existing", content: "Keep working", status: "in_progress" }] as TodoItem[], + clineMessages: [] as ClineMessage[], + say: vi.fn().mockResolvedValue(undefined), + ask: vi.fn().mockResolvedValue({ response: "yesButtonClicked" }), + } + // The tools under test use only these in-memory fields, notifications and error counters. + const task = state as unknown as Task + const callbacks = { + toolCallId: "call", + pushToolResult: vi.fn(), + handleError: vi.fn().mockResolvedValue(undefined), + askApproval: vi.fn().mockResolvedValue(true), + } + return { state, task, callbacks } +} + +describe("native TODO calls", () => { + it.each([ + "[-] #17: add https://example.com/link\n[ ] Tests", + [{ content: "#17: add https://example.com/link", status: "in_progress" }, { content: "Tests" }], + JSON.stringify([{ content: "#17: add https://example.com/link", status: "in_progress" }, { content: "Tests" }]), + ])("passes supported JSON arguments through the real parser and tool (%j)", async (todos) => { + const { state, task, callbacks } = fixture() + state.consecutiveMistakeCount = 2 + const block = NativeToolCallParser.parseToolCall({ + name: "update_todo_list", + id: "call", + arguments: JSON.stringify({ todos }), + }) + if (!block || block.type !== "tool_use") throw new Error("native JSON arguments did not parse") + await updateTodoListTool.handle(task, block, callbacks) + expect(state.todoList.map(({ content, status }) => ({ content, status }))).toEqual([ + { content: "#17: add https://example.com/link", status: "in_progress" }, + { content: "Tests", status: "pending" }, + ]) + expect(callbacks.handleError).not.toHaveBeenCalled() + expect(state.consecutiveMistakeCount).toBe(0) + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("updated successfully")) + }) + + it.each([ + null, + undefined, + {}, + "[ ] Valid\ninvalid item", + [{ content: "Valid" }, { content: "Bad status", status: "done" }], + ])("preserves the existing list and gives actionable feedback for invalid input (%j)", async (todos) => { + const { state, task, callbacks } = fixture() + const previous = state.todoList + await updateTodoListTool.execute({ todos }, task, callbacks) + expect(state.todoList).toBe(previous) + expect(callbacks.askApproval).not.toHaveBeenCalled() + expect(callbacks.pushToolResult).toHaveBeenCalledWith( + expect.stringContaining("Call the tool with JSON arguments"), + ) + expect(state.didToolFailInCurrentTurn).toBe(true) + }) + + it("isolates pending approval edits across concurrent tasks and releases them afterwards", async () => { + const a = fixture("a"), + b = fixture("b") + let approveA!: (approved: boolean) => void + let approveB!: (approved: boolean) => void + a.callbacks.askApproval.mockReturnValueOnce( + new Promise((resolve) => { + approveA = resolve + }), + ) + b.callbacks.askApproval.mockReturnValueOnce( + new Promise((resolve) => { + approveB = resolve + }), + ) + const first = updateTodoListTool.execute({ todos: "[ ] Task A" }, a.task, a.callbacks) + const second = updateTodoListTool.execute({ todos: "[ ] Task B" }, b.task, b.callbacks) + expect(setPendingTodoList(a.task, [{ id: "edit", content: "Edited A", status: "in_progress" }])).toBe(true) + approveB(true) + await second + approveA(true) + await first + expect(a.state.todoList[0]?.content).toBe("Edited A") + expect(b.state.todoList[0]?.content).toBe("Task B") + expect(setPendingTodoList(a.task, [])).toBe(false) + expect(setPendingTodoList(b.task, [])).toBe(false) + }) + + it("keeps the list when approval is declined or throws, and rejects invalid approval edits", async () => { + const { state, task, callbacks } = fixture() + callbacks.askApproval.mockImplementationOnce(async () => { + expect(setPendingTodoList(task, [{ content: "bad", status: "done" }])).toBe(false) + return false + }) + await updateTodoListTool.execute({ todos: "[ ] Replacement" }, task, callbacks) + expect(state.todoList[0]?.id).toBe("existing") + expect(setPendingTodoList(task, [])).toBe(false) + callbacks.askApproval.mockRejectedValueOnce(new Error("approval failed")) + await updateTodoListTool.execute({ todos: "[ ] Replacement" }, task, callbacks) + expect(state.todoList[0]?.id).toBe("existing") + expect(setPendingTodoList(task, [])).toBe(false) + }) + + it.each([ + { taskId: "old-task", expected: "Original" }, + { taskId: "active", expected: "Edited" }, + ])("routes approval edits for $taskId without applying them to another task", async ({ taskId, expected }) => { + const { task, state, callbacks } = fixture("active") + let approve!: (accepted: boolean) => void + callbacks.askApproval.mockReturnValueOnce( + new Promise((resolve) => { + approve = resolve + }), + ) + const update = updateTodoListTool.execute({ todos: "[ ] Original" }, task, callbacks) + // This handler branch only reads the current Task; it needs no VS Code surface. + const host = { getCurrentTask: () => task } as unknown as ClineProvider + await webviewMessageHandler(host, { + type: "updateTodoList", + taskId, + payload: { todos: [{ content: "Edited", status: "pending" }] }, + }) + approve(true) + await update + expect(state.todoList[0]?.content).toBe(expected) + }) + + it("previews native arguments without changing accepted state", async () => { + const { state, task } = fixture() + await updateTodoListTool.handlePartial(task, { + type: "tool_use", + name: "update_todo_list", + params: {}, + nativeArgs: { todos: "[ ] Preview" }, + partial: true, + }) + expect(state.ask).toHaveBeenCalledWith("tool", expect.stringContaining("Preview"), true) + expect(state.todoList[0]?.id).toBe("existing") + }) + + it("restores the accepted JSON-format update from saved UI history", async () => { + const { state, task, callbacks } = fixture() + callbacks.askApproval.mockImplementationOnce(async (_type, text) => { + state.clineMessages.push({ ts: 1, type: "ask", ask: "tool", text, isAnswered: true }) + return true + }) + await updateTodoListTool.execute( + { todos: [{ content: "Saved JSON task", status: "in_progress" }] }, + task, + callbacks, + ) + const accepted = state.todoList + state.clineMessages = JSON.parse(JSON.stringify(state.clineMessages)) + state.todoList = [] + restoreTodoListForTask(task) + expect(state.todoList).toEqual(accepted) + }) + + it("requires approval before an intentional empty replacement", async () => { + const { state, task, callbacks } = fixture() + await updateTodoListTool.execute({ todos: "" }, task, callbacks) + expect(callbacks.askApproval).toHaveBeenCalledOnce() + expect(state.todoList).toEqual([]) + }) + + it("rejects invalid initial todos before delegating a new task", async () => { + const { task, callbacks } = fixture() + const delegate = vi.fn() + // NewTask validation additionally reads this provider state before delegation. + task.providerRef = new WeakRef({ + getState: vi.fn().mockResolvedValue({}), + delegateParentAndOpenChild: delegate, + } as unknown as import("../../webview/ClineProvider").ClineProvider) + await newTaskTool.execute( + { mode: "code", message: "Work", todos: '[{"content":"Task","status":"done"}]' }, + task, + callbacks, + ) + expect(delegate).not.toHaveBeenCalled() + expect(callbacks.pushToolResult).toHaveBeenCalledWith( + expect.stringContaining("status must be pending, in_progress, or completed"), + ) + }) +}) diff --git a/src/core/tools/__tests__/updateTodoListTool.spec.ts b/src/core/tools/__tests__/updateTodoListTool.spec.ts index 0e6e0302cc1..044de688178 100644 --- a/src/core/tools/__tests__/updateTodoListTool.spec.ts +++ b/src/core/tools/__tests__/updateTodoListTool.spec.ts @@ -5,6 +5,27 @@ import type { Task } from "../../task/Task" import type { ToolCallbacks } from "../BaseTool" describe("UpdateTodoListTool", () => { + it("rejects non-checklist text instead of clearing a saved list and reporting success", async () => { + const existing: TodoItem[] = [{ id: "existing", content: "Continue work", status: "in_progress" }] + const task = { + consecutiveMistakeCount: 0, + recordToolError: vi.fn(), + didToolFailInCurrentTurn: false, + todoList: existing, + } as unknown as Task + const callbacks = { + pushToolResult: vi.fn(), + handleError: vi.fn(), + askApproval: vi.fn(), + } as unknown as ToolCallbacks + + await updateTodoListTool.execute({ todos: "I updated the plan" }, task, callbacks) + + expect(task.todoList).toEqual(existing) + expect(callbacks.askApproval).not.toHaveBeenCalled() + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("Checklist line 1")) + }) + it("persists the edited todo list even if the say notification fails", async () => { const editedTodos: TodoItem[] = [{ id: "edited", content: "Edited task", status: "in_progress" }] const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined) @@ -19,7 +40,7 @@ describe("UpdateTodoListTool", () => { pushToolResult: vi.fn(), handleError: vi.fn(), askApproval: vi.fn().mockImplementation(async () => { - setPendingTodoList(editedTodos) + setPendingTodoList(task, editedTodos) return true }), } as unknown as ToolCallbacks @@ -192,12 +213,12 @@ describe("parseMarkdownChecklist", () => { }) it("should handle non-string input", () => { - const result = parseMarkdownChecklist(null as any) + const result = parseMarkdownChecklist(null) expect(result).toEqual([]) }) it("should handle undefined input", () => { - const result = parseMarkdownChecklist(undefined as any) + const result = parseMarkdownChecklist(undefined) expect(result).toEqual([]) }) diff --git a/src/core/webview/__tests__/ClineProvider.sticky-mode.spec.ts b/src/core/webview/__tests__/ClineProvider.sticky-mode.spec.ts index f73101d4eeb..0d332b232eb 100644 --- a/src/core/webview/__tests__/ClineProvider.sticky-mode.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.sticky-mode.spec.ts @@ -335,6 +335,18 @@ describe("ClineProvider - Sticky Mode", () => { await provider.resolveWebviewView(mockWebviewView) }) + it("preserves the active task's to-do list and posts it after a mode switch", async () => { + const todos = [{ id: "todo-1", content: "Continue this task", status: "in_progress" as const }] + const task = new Task({ provider, apiConfiguration: { apiProvider: providerIdentifiers.openrouter } }) + task.todoList = todos + await provider.addClineToStack(task) + + await provider.handleModeSwitch("architect") + + expect(task.todoList).toBe(todos) + expect((await provider.getStateToPostToWebview()).currentTaskTodos).toEqual(todos) + }) + it("should save mode to task metadata when switching modes", async () => { // Create a mock task const mockTask = new Task({ diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index 6641ff259f1..3212b35809f 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -2455,10 +2455,11 @@ export const webviewMessageHandler = async ( break } case "updateTodoList": { - const payload = message.payload as { todos?: any[] } + const payload = message.payload as { todos?: unknown } | undefined const todos = payload?.todos - if (Array.isArray(todos)) { - await setPendingTodoList(todos) + const task = provider.getCurrentTask() + if (task && (!message.taskId || message.taskId === task.taskId)) { + setPendingTodoList(task, todos) } break } diff --git a/src/eslint-suppressions.json b/src/eslint-suppressions.json index e07b00bd6a9..0e2086fe7a8 100644 --- a/src/eslint-suppressions.json +++ b/src/eslint-suppressions.json @@ -774,11 +774,6 @@ "count": 1 } }, - "core/tools/UpdateTodoListTool.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, "core/tools/UseMcpToolTool.ts": { "@typescript-eslint/no-explicit-any": { "count": 3 @@ -859,11 +854,6 @@ "count": 3 } }, - "core/tools/__tests__/updateTodoListTool.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, "core/tools/__tests__/useMcpToolTool.spec.ts": { "@typescript-eslint/no-explicit-any": { "count": 21 @@ -986,7 +976,7 @@ }, "core/webview/webviewMessageHandler.ts": { "@typescript-eslint/no-explicit-any": { - "count": 5 + "count": 4 } }, "services/__tests__/zoo-code-auth.test.ts": { diff --git a/src/shared/__tests__/todo.spec.ts b/src/shared/__tests__/todo.spec.ts new file mode 100644 index 00000000000..b9841e51dfa --- /dev/null +++ b/src/shared/__tests__/todo.spec.ts @@ -0,0 +1,51 @@ +import type { ClineMessage, TodoItem } from "@roo-code/types" + +import { getLatestTodo } from "../todo" + +const original: TodoItem[] = [{ id: "a", content: "Keep this task", status: "in_progress" }] + +function todoAsk(ts: number, todos: TodoItem[], overrides: Partial = {}): ClineMessage { + return { + ts, + type: "ask", + ask: "tool", + text: JSON.stringify({ tool: "updateTodoList", todos }), + ...overrides, + } +} + +describe("getLatestTodo", () => { + it("restores initial todos while allowing later accepted updates and clears to take precedence", () => { + const seed: ClineMessage = { ts: 1, type: "say", say: "text", text: "Task", initialTodos: original } + expect(getLatestTodo([seed, todoAsk(2, [], { partial: true })])).toEqual(original) + expect(getLatestTodo([seed, todoAsk(2, [], { isAnswered: true })])).toEqual([]) + const restored = getLatestTodo([seed]) + restored[0].content = "Modified in memory" + expect(seed.initialTodos?.[0]?.content).toBe("Keep this task") + }) + it("restores the last accepted list instead of a later partial or unanswered request", () => { + expect( + getLatestTodo([ + todoAsk(1, original, { isAnswered: true }), + todoAsk(2, [], { partial: true }), + todoAsk(3, [], { isAnswered: false }), + ]), + ).toEqual(original) + }) + + it("ignores an automatically denied list but accepts an intentional empty approved list", () => { + expect( + getLatestTodo([ + todoAsk(1, original, { isAnswered: true }), + todoAsk(2, [], { isAnswered: true, autoApprovalDecision: "deny" }), + ]), + ).toEqual(original) + expect( + getLatestTodo([todoAsk(1, original, { isAnswered: true }), todoAsk(2, [], { isAnswered: true })]), + ).toEqual([]) + }) + + it("retains a legacy saved list when no answered list is available", () => { + expect(getLatestTodo([todoAsk(1, original), todoAsk(2, [], { partial: true })])).toEqual(original) + }) +}) diff --git a/src/shared/__tests__/todoChecklist.spec.ts b/src/shared/__tests__/todoChecklist.spec.ts new file mode 100644 index 00000000000..2bcb2c0190a --- /dev/null +++ b/src/shared/__tests__/todoChecklist.spec.ts @@ -0,0 +1,58 @@ +import { parseMarkdownChecklist, parseTodoListInput, TODO_ARGUMENT_EXAMPLE } from "../todoChecklist" +import updateTodoTool from "../../core/prompts/tools/native-tools/update_todo_list" + +describe("TODO input contract", () => { + it("accepts the exact JSON example advertised in the native schema", () => { + const args: unknown = JSON.parse(TODO_ARGUMENT_EXAMPLE) + if (!args || typeof args !== "object" || !("todos" in args)) throw new Error("invalid example") + expect(parseTodoListInput(args.todos).map((todo) => todo.status)).toEqual([ + "completed", + "in_progress", + "pending", + ]) + expect(updateTodoTool.function.parameters.properties.todos.type).toBe("string") + expect(updateTodoTool.function.description).toContain(TODO_ARGUMENT_EXAMPLE) + }) + + it("accepts long checklist text, issue numbers, URLs, Unicode and standard bullet prefixes", () => { + const content = "#17: clickable Apply/Listing URLs https://example.com/?a=1&b=2 — 日本語 ".repeat(1_000) + const todos = parseTodoListInput(`- [x] Prior work\n* [-] ${content}\n+ [ ] Run tests`) + expect(todos).toHaveLength(3) + expect(todos[1]?.content).toBe(content.trim()) + expect(todos.map((todo) => todo.status)).toEqual(["completed", "in_progress", "pending"]) + }) + + it.each([false, true])( + "accepts JSON task objects (serialized=%s) without requiring model-generated IDs", + (serialized) => { + const list = [ + { content: "#17: add link", status: "in_progress" }, + { id: "done", content: "Tests", status: "completed" }, + ] + const todos = parseTodoListInput(serialized ? JSON.stringify(list) : list) + expect(todos[0]).toMatchObject({ content: "#17: add link", status: "in_progress", id: expect.any(String) }) + expect(todos[1]?.id).toBe("done") + expect(todos[0]?.id).toBe(parseMarkdownChecklist("[-] #17: add link")[0]?.id) + }, + ) + + it("accepts JSON arrays of checklist lines and explicit empty replacements", () => { + expect(parseTodoListInput(JSON.stringify(["[ ] One", "[x] Two"]))).toHaveLength(2) + for (const value of ["", " ", [], "[]"]) expect(parseTodoListInput(value)).toEqual([]) + }) + + it.each([ + undefined, + null, + 0, + {}, + { todos: "[ ] One" }, + [null], + [""], + '[{"content":"One","status":"done"}]', + "[ ] Good\nnot a checklist", + [{ content: " " }], + ])("rejects malformed input without returning a partial or empty replacement (%j)", (value) => { + expect(() => parseTodoListInput(value)).toThrow(/todos|Todo|Checklist/) + }) +}) diff --git a/src/shared/todo.ts b/src/shared/todo.ts index d20539049b0..01ad5e8a453 100644 --- a/src/shared/todo.ts +++ b/src/shared/todo.ts @@ -1,25 +1,29 @@ -import { ClineMessage } from "@roo-code/types" +import { todoItemSchema, type ClineMessage, type TodoItem } from "@roo-code/types" -export function getLatestTodo(clineMessages: ClineMessage[]) { - const todos = clineMessages - .filter( - (msg) => - (msg.type === "ask" && msg.ask === "tool") || (msg.type === "say" && msg.say === "user_edit_todos"), - ) - .map((msg) => { - try { - return JSON.parse(msg.text ?? "{}") - } catch { - return null - } - }) - .filter((item) => item && item.tool === "updateTodoList" && Array.isArray(item.todos)) - .map((item) => item.todos) - .pop() - - if (todos) { - return todos - } else { - return [] +export function getLatestTodo(clineMessages: ClineMessage[]): TodoItem[] { + let legacyList: TodoItem[] | undefined + for (let i = clineMessages.length - 1; i >= 0; i--) { + const msg = clineMessages[i] + if (msg.initialTodos !== undefined) { + const seed = todoItemSchema.array().safeParse(msg.initialTodos) + if (seed.success) return legacyList ?? seed.data + } + const isEdit = msg.type === "say" && msg.say === "user_edit_todos" + const isAsk = msg.type === "ask" && msg.ask === "tool" + if (!isEdit && !isAsk) continue + if (msg.partial === true || msg.autoApprovalDecision === "deny" || (isAsk && msg.isAnswered === false)) { + continue + } + try { + const item = JSON.parse(msg.text ?? "{}") as { tool?: unknown; todos?: unknown } + if (item.tool !== "updateTodoList" || !Array.isArray(item.todos)) continue + if (isEdit || msg.isAnswered === true) return item.todos as TodoItem[] + // Older saved tasks did not always stamp isAnswered. Use one only if + // no accepted list can be found, so a new pending ask cannot clear it. + legacyList ??= item.todos as TodoItem[] + } catch { + // Ignore malformed tool text and continue to the previous accepted list. + } } + return legacyList ?? [] } diff --git a/src/shared/todoChecklist.ts b/src/shared/todoChecklist.ts new file mode 100644 index 00000000000..292f03cbe63 --- /dev/null +++ b/src/shared/todoChecklist.ts @@ -0,0 +1,82 @@ +import crypto from "crypto" +import { todoStatusSchema, type TodoItem, type TodoStatus } from "@roo-code/types" + +export const TODO_ARGUMENT_EXAMPLE = '{"todos":"[x] Finished task\\n[-] Current task\\n[ ] Next task"}' +export const TODO_FORMAT_HELP = `Call the tool with JSON arguments, for example ${TODO_ARGUMENT_EXAMPLE}. The todos field should be a string containing the full checklist. Use [ ], [-], or [x] for each item. Use an empty string only to intentionally clear the list.` + +const checklistLine = /^(?:[-*+]\s*)?\[\s*([ xX\-~])\s*\]\s+(.+)$/ + +function todoItem(content: string, status: TodoStatus, id?: string): TodoItem { + return { + id: + id ?? + crypto + .createHash("md5") + .update(content + status) + .digest("hex"), + content, + status, + } +} + +/** Lenient preview/legacy reader; completed tool calls use parseTodoListInput instead. */ +export function parseMarkdownChecklist(md: unknown): TodoItem[] { + if (typeof md !== "string") return [] + return md.split(/\r?\n/).flatMap((line) => { + const match = line.trim().match(checklistLine) + if (!match) return [] + const status = /[xX]/.test(match[1]) ? "completed" : /[-~]/.test(match[1]) ? "in_progress" : "pending" + return [todoItem(match[2], status)] + }) +} + +/** Validate the entire replacement before touching the saved list. */ +export function parseTodoListInput(value: unknown): TodoItem[] { + if (typeof value === "string") { + const text = value.trim() + if (!text) return [] + // Some local providers do not enforce the native schema, and models also + // serialize JSON task arrays inside the string field. Accept either without + // requiring a different tool schema on strict providers. + if (text.startsWith("[")) { + let decoded: unknown + try { + decoded = JSON.parse(text) + } catch { + /* A Markdown checkbox also starts with [. */ + } + if (Array.isArray(decoded)) return parseTodoListInput(decoded) + } + const lines = text.split(/\r?\n/).filter((line) => line.trim()) + const todos = parseMarkdownChecklist(text) + const invalidLine = lines.findIndex((line) => !checklistLine.test(line.trim())) + if (invalidLine !== -1) + throw new Error(`Checklist line ${invalidLine + 1} must start with [ ], [-], or [x]. ${TODO_FORMAT_HELP}`) + return todos + } + if (!Array.isArray(value)) throw new Error(`The todos field is missing or has the wrong type. ${TODO_FORMAT_HELP}`) + if (value.every((item) => typeof item === "string")) { + if (value.some((item) => !item.trim())) + throw new Error(`Checklist entries must not be empty. ${TODO_FORMAT_HELP}`) + return parseTodoListInput(value.join("\n")) + } + return value.map((item: unknown, index) => { + const fail = (detail: string): never => { + throw new Error(`Todo item ${index + 1}: ${detail}. ${TODO_FORMAT_HELP}`) + } + if (!item || typeof item !== "object" || Array.isArray(item)) + return fail("expected an object with content and status") + if (!("content" in item) || typeof item.content !== "string" || !item.content.trim()) + return fail("content must be nonempty text") + if (/[\r\n]/.test(item.content)) return fail("content must fit on one line") + const status = todoStatusSchema.safeParse("status" in item ? item.status : "pending") + if (!status.success) return fail("status must be pending, in_progress, or completed") + if ("id" in item && (typeof item.id !== "string" || !item.id.trim())) + return fail("id must be nonempty text when provided") + return todoItem( + item.content.trim(), + status.data, + "id" in item && typeof item.id === "string" ? item.id : undefined, + ) + }) +} From ebbe35f72d86a5a5098aa92d71a32a64d08c6ba5 Mon Sep 17 00:00:00 2001 From: cartridgebasic <68982521+cartridgebasic@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:40:56 -0700 Subject: [PATCH 2/3] Remove obsolete checklist clone dependencies --- pnpm-lock.yaml | 43 ------------------------------------------- src/package.json | 2 -- 2 files changed, 45 deletions(-) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8ed8534efc4..bbcab9b9a17 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -505,9 +505,6 @@ importers: chokidar: specifier: ^4.0.1 version: 4.0.3 - clone-deep: - specifier: ^4.0.1 - version: 4.0.1 delay: specifier: ^6.0.0 version: 6.0.0 @@ -662,9 +659,6 @@ importers: '@roo-code/config-typescript': specifier: workspace:^ version: link:../packages/config-typescript - '@types/clone-deep': - specifier: 4.0.4 - version: 4.0.4 '@types/diff': specifier: 5.2.3 version: 5.2.3 @@ -3340,9 +3334,6 @@ packages: '@types/chai@5.2.3': resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} - '@types/clone-deep@4.0.4': - resolution: {integrity: sha512-vXh6JuuaAha6sqEbJueYdh5zNBPPgG1OYumuz2UvLvriN6ABHDSW8ludREGWJb1MLIzbwZn4q4zUbUCerJTJfA==} - '@types/d3-array@3.2.2': resolution: {integrity: sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==} @@ -4316,10 +4307,6 @@ packages: resolution: {integrity: sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==} engines: {node: '>=12'} - clone-deep@4.0.1: - resolution: {integrity: sha512-neHB9xuzh/wk0dIHweyAXv2aPGZIVk3pLMe+/RNzINf17fe0OG96QroktYAUm7SM1PBnzTabaLboqqxDyMU+SQ==} - engines: {node: '>=6'} - clone@2.1.2: resolution: {integrity: sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==} engines: {node: '>=0.8'} @@ -5907,10 +5894,6 @@ packages: resolution: {integrity: sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==} engines: {node: '>=12'} - is-plain-object@2.0.4: - resolution: {integrity: sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==} - engines: {node: '>=0.10.0'} - is-potential-custom-element-name@1.0.1: resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==} @@ -6001,10 +5984,6 @@ packages: isexe@2.0.0: resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} - isobject@3.0.1: - resolution: {integrity: sha512-WhB9zCku7EGTj/HQQRz5aUQEUeoQZH2bWcltRErOpymJ4boYE6wL9Tbr23krRPSZ+C5zqNSrSw+Cc7sZZ4b7vg==} - engines: {node: '>=0.10.0'} - istanbul-lib-coverage@3.2.2: resolution: {integrity: sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==} engines: {node: '>=8'} @@ -7921,10 +7900,6 @@ packages: setprototypeof@1.2.0: resolution: {integrity: sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==} - shallow-clone@3.0.1: - resolution: {integrity: sha512-/6KqX+GVUdqPuPPd2LxDDxzX6CAbjJehAAOKlNpqqUpAqPM6HeL8f+o3a+JsyGjn2lv0WY8UsTgUJjU9Ok55NA==} - engines: {node: '>=8'} - shebang-command@2.0.0: resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} engines: {node: '>=8'} @@ -11705,8 +11680,6 @@ snapshots: '@types/deep-eql': 4.0.2 assertion-error: 2.0.1 - '@types/clone-deep@4.0.4': {} - '@types/d3-array@3.2.2': {} '@types/d3-axis@3.0.6': @@ -12803,12 +12776,6 @@ snapshots: strip-ansi: 6.0.1 wrap-ansi: 7.0.0 - clone-deep@4.0.1: - dependencies: - is-plain-object: 2.0.4 - kind-of: 6.0.3 - shallow-clone: 3.0.1 - clone@2.1.2: {} clsx@2.1.1: {} @@ -14614,10 +14581,6 @@ snapshots: is-plain-obj@4.1.0: {} - is-plain-object@2.0.4: - dependencies: - isobject: 3.0.1 - is-potential-custom-element-name@1.0.1: {} is-promise@4.0.0: {} @@ -14691,8 +14654,6 @@ snapshots: isexe@2.0.0: {} - isobject@3.0.1: {} - istanbul-lib-coverage@3.2.2: {} istanbul-lib-report@3.0.1: @@ -17091,10 +17052,6 @@ snapshots: setprototypeof@1.2.0: {} - shallow-clone@3.0.1: - dependencies: - kind-of: 6.0.3 - shebang-command@2.0.0: dependencies: shebang-regex: 3.0.0 diff --git a/src/package.json b/src/package.json index c006b3fb766..e594c060f89 100644 --- a/src/package.json +++ b/src/package.json @@ -503,7 +503,6 @@ "async-mutex": "^0.5.0", "axios": "^1.18.1", "chokidar": "^4.0.1", - "clone-deep": "^4.0.1", "delay": "^6.0.0", "diff": "^5.2.0", "dotenv": "^17.4.2", @@ -557,7 +556,6 @@ "@roo-code/build": "workspace:^", "@roo-code/config-eslint": "workspace:^", "@roo-code/config-typescript": "workspace:^", - "@types/clone-deep": "4.0.4", "@types/diff": "5.2.3", "@types/lodash.debounce": "4.0.9", "@types/node": "catalog:", From 0ada5859139d7cf26dd1cd84a9332ea913db4508 Mon Sep 17 00:00:00 2001 From: cartridgebasic <68982521+cartridgebasic@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:01:13 -0700 Subject: [PATCH 3/3] fix: retain delegated todos until a replacement is approved --- packages/types/src/__tests__/message.test.ts | 14 ++++++ .../__tests__/getEnvironmentDetails.spec.ts | 43 ++++++++++++------- src/core/environment/getEnvironmentDetails.ts | 2 +- src/core/task/Task.ts | 9 ++-- .../task/__tests__/Task.persistence.spec.ts | 35 +++++++++++++++ src/shared/__tests__/todoChecklist.spec.ts | 5 ++- 6 files changed, 86 insertions(+), 22 deletions(-) diff --git a/packages/types/src/__tests__/message.test.ts b/packages/types/src/__tests__/message.test.ts index 047017e9b96..247afceadaa 100644 --- a/packages/types/src/__tests__/message.test.ts +++ b/packages/types/src/__tests__/message.test.ts @@ -29,6 +29,20 @@ describe("clineMessageSchema autoApprovalDecision", () => { initialTodos, ) }) + it.each([ + { content: "Missing ID", status: "pending" }, + { id: "bad", content: "Invalid status", status: "unknown" }, + ])("rejects an invalid initial todo (%j)", (todo) => { + expect(clineMessageSchema.safeParse({ ts: 1, type: "say", say: "text", initialTodos: [todo] }).success).toBe( + false, + ) + }) + + it("accepts older messages with no initial todos", () => { + const message = { ts: 1, type: "say", say: "text" } + expect(clineMessageSchema.parse(message)).toEqual(message) + }) + it.each(["approve", "deny"] as const)("accepts %s", (autoApprovalDecision) => { expect(clineMessageSchema.safeParse({ ts: 1, type: "ask", ask: "command", autoApprovalDecision }).success).toBe( true, diff --git a/src/core/environment/__tests__/getEnvironmentDetails.spec.ts b/src/core/environment/__tests__/getEnvironmentDetails.spec.ts index 5d2430f2caa..86349e9ab30 100644 --- a/src/core/environment/__tests__/getEnvironmentDetails.spec.ts +++ b/src/core/environment/__tests__/getEnvironmentDetails.spec.ts @@ -373,7 +373,11 @@ describe("getEnvironmentDetails", () => { ...mockState, apiConfiguration: { todoListEnabled: false }, }) - const cline = { ...mockCline, todoList: [{ content: "test", status: "pending" }] } + const cline = { + ...mockCline, + apiConfiguration: { todoListEnabled: false }, + todoList: [{ content: "test", status: "pending" }], + } const result = await getEnvironmentDetails(cline as Task) expect(result).toContain("REMINDERS") expect(result).not.toContain("call the `update_todo_list` tool") @@ -384,7 +388,11 @@ describe("getEnvironmentDetails", () => { ...mockState, apiConfiguration: { todoListEnabled: false }, }) - const cline = { ...mockCline, todoList: [] as NonNullable } + const cline = { + ...mockCline, + apiConfiguration: { todoListEnabled: false }, + todoList: [] as NonNullable, + } const result = await getEnvironmentDetails(cline as Task) expect(result).not.toContain("REMINDERS") expect(result).not.toContain("update_todo_list") @@ -406,20 +414,23 @@ describe("getEnvironmentDetails", () => { expect(result).not.toContain("call the `update_todo_list` tool") }) - it("uses task-local tool availability when another profile is selected globally", async () => { - mockProvider.getState.mockResolvedValue({ - ...mockState, - apiConfiguration: { todoListEnabled: false }, - }) - const cline = { - ...mockCline, - apiConfiguration: { todoListEnabled: true }, - todoList: [{ content: "Keep task progress", status: "pending" }], - } - const result = await getEnvironmentDetails(cline as Task) - expect(result).toContain("Keep task progress") - expect(result).toContain("call the `update_todo_list` tool") - }) + it.each([true, undefined])( + "uses the task-local default or setting (%s) when a different profile is selected globally", + async (todoListEnabled) => { + mockProvider.getState.mockResolvedValue({ + ...mockState, + apiConfiguration: { todoListEnabled: false }, + }) + const cline = { + ...mockCline, + apiConfiguration: { todoListEnabled }, + todoList: [{ content: "Keep task progress", status: "pending" }], + } + const result = await getEnvironmentDetails(cline as Task) + expect(result).toContain("Keep task progress") + expect(result).toContain("call the `update_todo_list` tool") + }, + ) it("should include REMINDERS section when todoListEnabled is undefined", async () => { mockProvider.getState.mockResolvedValue({ diff --git a/src/core/environment/getEnvironmentDetails.ts b/src/core/environment/getEnvironmentDetails.ts index bf998b679e5..4b1fde26caf 100644 --- a/src/core/environment/getEnvironmentDetails.ts +++ b/src/core/environment/getEnvironmentDetails.ts @@ -254,7 +254,7 @@ export async function getEnvironmentDetails(cline: Task, includeFileDetails: boo } } - const todoListEnabled = cline.apiConfiguration?.todoListEnabled ?? state?.apiConfiguration?.todoListEnabled ?? true + const todoListEnabled = cline.apiConfiguration?.todoListEnabled ?? true // A mode's profile can disable the update tool without clearing the task's list. // Keep an existing list in the next request so superseded environment blocks can be removed safely. const reminderSection = formatReminderSection(cline.todoList, todoListEnabled) diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index 3687bae2968..42f77f66aef 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -2000,6 +2000,7 @@ export class Task extends EventEmitter implements TaskLike { }) const isAutoAnswered = approval.decision === "approve" || approval.decision === "deny" const autoApprovalDecision = isAutoAnswered ? approval.decision : undefined + const isAnswered = isAutoAnswered ? true : type === "tool" ? false : undefined // Re-check: an abort during the getState/checkAutoApproval awaits must not post an ask row. if (this.abort) { @@ -2063,8 +2064,8 @@ export class Task extends EventEmitter implements TaskLike { lastMessage.partial = false lastMessage.progressStatus = progressStatus lastMessage.isProtected = isProtected - if (isAutoAnswered) { - lastMessage.isAnswered = true + if (isAnswered !== undefined) { + lastMessage.isAnswered = isAnswered lastMessage.autoApprovalDecision = autoApprovalDecision } this.cancelPendingPartialMessageUpdate() @@ -2086,7 +2087,7 @@ export class Task extends EventEmitter implements TaskLike { ask: type, text, isProtected, - isAnswered: isAutoAnswered || undefined, + isAnswered, autoApprovalDecision, }) } @@ -2104,7 +2105,7 @@ export class Task extends EventEmitter implements TaskLike { ask: type, text, isProtected, - isAnswered: isAutoAnswered || undefined, + isAnswered, autoApprovalDecision, }) } diff --git a/src/core/task/__tests__/Task.persistence.spec.ts b/src/core/task/__tests__/Task.persistence.spec.ts index 9d6315f9596..225039f1f81 100644 --- a/src/core/task/__tests__/Task.persistence.spec.ts +++ b/src/core/task/__tests__/Task.persistence.spec.ts @@ -1,3 +1,4 @@ +import { getLatestTodo } from "../../../shared/todo" import { WebviewFocusTracker } from "../../webview/WebviewFocusTracker" // cd src && npx vitest run core/task/__tests__/Task.persistence.spec.ts @@ -976,6 +977,40 @@ describe("Task persistence", () => { // ── saveClineMessages ──────────────────────────────────────────────── describe("saveClineMessages", () => { + it.each([undefined, false, true])( + "keeps a delegated checklist while a replacement is pending or rejected (partial=%s)", + async (partial) => { + const seed = [{ id: "seed", content: "Keep the original", status: "pending" as const }] + const task = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + task: "child", + initialTodos: seed, + startTask: false, + }) + await task.say("text", "child request") + const text = JSON.stringify({ tool: "updateTodoList", todos: [] }) + if (partial) await expect(task.ask("tool", text, true)).rejects.toThrow() + const pending = task.ask("tool", text, partial === undefined ? undefined : false) + try { + await vi.waitFor(() => + expect(mockSaveTaskMessages).toHaveBeenCalledWith( + expect.objectContaining({ + messages: expect.arrayContaining([ + expect.objectContaining({ ask: "tool", text, isAnswered: false }), + ]), + }), + ), + ) + expect(getLatestTodo(task.clineMessages)).toEqual(seed) + } finally { + task.handleWebviewAskResponse("noButtonClicked") + await pending + } + expect(getLatestTodo(task.clineMessages)).toEqual(seed) + }, + ) + it("restores initial child-task todos from its first saved message before any model update", async () => { const initialTodos = [{ id: "initial", content: "Delegated task", status: "in_progress" as const }] const task = new Task({ diff --git a/src/shared/__tests__/todoChecklist.spec.ts b/src/shared/__tests__/todoChecklist.spec.ts index 2bcb2c0190a..0ab3f17e4e8 100644 --- a/src/shared/__tests__/todoChecklist.spec.ts +++ b/src/shared/__tests__/todoChecklist.spec.ts @@ -37,7 +37,10 @@ describe("TODO input contract", () => { ) it("accepts JSON arrays of checklist lines and explicit empty replacements", () => { - expect(parseTodoListInput(JSON.stringify(["[ ] One", "[x] Two"]))).toHaveLength(2) + expect(parseTodoListInput(JSON.stringify(["[ ] One", "[x] Two"]))).toEqual([ + { id: expect.any(String), content: "One", status: "pending" }, + { id: expect.any(String), content: "Two", status: "completed" }, + ]) for (const value of ["", " ", [], "[]"]) expect(parseTodoListInput(value)).toEqual([]) })