diff --git a/apps/vscode-e2e/src/fixtures/subtasks.ts b/apps/vscode-e2e/src/fixtures/subtasks.ts index ebfd94324e..7ce8122185 100644 --- a/apps/vscode-e2e/src/fixtures/subtasks.ts +++ b/apps/vscode-e2e/src/fixtures/subtasks.ts @@ -16,6 +16,8 @@ const SUBTASK_APPROVAL_RESTORE_CHILD_MARKER = "SUBTASK_CHILD_APPROVAL_RESTORE" const SUBTASK_XPROFILE_PARENT_MARKER = "SUBTASK_PARENT_CROSS_PROFILE" const SUBTASK_XPROFILE_SAME_CHILD_MARKER = "SUBTASK_CHILD_SAME_PROFILE" const SUBTASK_XPROFILE_DIFFERENT_CHILD_MARKER = "SUBTASK_CHILD_DIFFERENT_PROFILE" +export const SUBTASK_QUEUED_INPUT_PARENT_MARKER = "SUBTASK_PARENT_QUEUED_INPUT" +export const SUBTASK_QUEUED_INPUT_CHILD_MARKER = "SUBTASK_CHILD_QUEUED_INPUT" const SUBTASK_CHILD_PROMPT = `${SUBTASK_CHILD_MARKER}: Ask the user exactly this follow-up question: What is the square root of 81? After the user answers, complete with only the answer.` export const SUBTASK_PARENT_PROMPT = `${SUBTASK_PARENT_MARKER}: Use the new_task tool exactly once. Create an ask-mode subtask with this exact message: "${SUBTASK_CHILD_PROMPT}" Do not answer directly.` @@ -59,6 +61,14 @@ export const SUBTASK_XPROFILE_SAME_CHILD_RESULT = "Same-profile child completed" export const SUBTASK_XPROFILE_DIFFERENT_CHILD_RESULT = "Different-profile child completed" export const SUBTASK_XPROFILE_PARENT_RESULT = "Sequential cross-profile parent resumed" +const SUBTASK_QUEUED_INPUT_INITIAL_RESULT = "Child completed before queued input" +export const SUBTASK_QUEUED_INPUT_MESSAGE = "Use the queued instruction before completing." +export const SUBTASK_QUEUED_INPUT_CHILD_RESULT = "Child processed queued input" +export const SUBTASK_QUEUED_INPUT_PARENT_RESULT = "Parent resumed after queued input" +const SUBTASK_QUEUED_INPUT_CHILD_PROMPT = `${SUBTASK_QUEUED_INPUT_CHILD_MARKER}: Complete immediately with the exact result "${SUBTASK_QUEUED_INPUT_INITIAL_RESULT}".` +export const SUBTASK_QUEUED_INPUT_PARENT_PROMPT = `${SUBTASK_QUEUED_INPUT_PARENT_MARKER}: Use the new_task tool exactly once. Create an ask-mode subtask with this exact message: "${SUBTASK_QUEUED_INPUT_CHILD_PROMPT}" Do not answer directly. When the subtask returns, complete with the exact result "${SUBTASK_QUEUED_INPUT_PARENT_RESULT}".` +export const SUBTASK_QUEUED_INPUT_RESPONSE_LATENCY_MS = 2_000 + // Scheduler regression tests — exercises TaskScheduler + run() dispatch post-CodeRabbit fix. // Separate markers to avoid collisions with the other subtask fixtures. const SCHED_STANDALONE_MARKER = "SCHED_STANDALONE_INTERRUPT_RESUME" @@ -179,6 +189,81 @@ export function addSubtaskFixtures(mock: InstanceType) { }, }) + mock.addFixture({ + match: { + userMessage: new RegExp(SUBTASK_QUEUED_INPUT_PARENT_MARKER), + sequenceIndex: 0, + }, + response: { + toolCalls: [ + { + name: "new_task", + arguments: JSON.stringify({ + mode: "ask", + message: SUBTASK_QUEUED_INPUT_CHILD_PROMPT, + }), + id: "call_queued_input_parent_new_task_001", + }, + ], + }, + }) + + mock.addFixture({ + match: { + predicate: (req: ChatCompletionRequest) => + lastUserMessageContains(req, SUBTASK_QUEUED_INPUT_CHILD_MARKER) && + !requestContains(req, [SUBTASK_QUEUED_INPUT_PARENT_MARKER]) && + !requestContains(req, [SUBTASK_QUEUED_INPUT_MESSAGE]), + }, + streamingProfile: { ttft: SUBTASK_QUEUED_INPUT_RESPONSE_LATENCY_MS }, + response: { + toolCalls: [ + { + name: "attempt_completion", + arguments: JSON.stringify({ result: SUBTASK_QUEUED_INPUT_INITIAL_RESULT }), + id: "call_queued_input_child_initial_completion_002", + }, + ], + }, + }) + + mock.addFixture({ + match: { + predicate: (req: ChatCompletionRequest) => + requestContains(req, [SUBTASK_QUEUED_INPUT_CHILD_MARKER, SUBTASK_QUEUED_INPUT_MESSAGE]) && + !requestContains(req, [SUBTASK_QUEUED_INPUT_PARENT_MARKER]), + }, + response: { + toolCalls: [ + { + name: "attempt_completion", + arguments: JSON.stringify({ result: SUBTASK_QUEUED_INPUT_CHILD_RESULT }), + id: "call_queued_input_child_revised_completion_003", + }, + ], + }, + }) + + mock.addFixture({ + match: { + predicate: (req: ChatCompletionRequest) => + requestContains(req, [ + SUBTASK_QUEUED_INPUT_PARENT_MARKER, + SUBTASK_RESULT_INJECTION, + SUBTASK_QUEUED_INPUT_CHILD_RESULT, + ]), + }, + response: { + toolCalls: [ + { + name: "attempt_completion", + arguments: JSON.stringify({ result: SUBTASK_QUEUED_INPUT_PARENT_RESULT }), + id: "call_queued_input_parent_completion_004", + }, + ], + }, + }) + mock.addFixture({ match: { userMessage: new RegExp(SUBTASK_FAST_PARENT_MARKER), diff --git a/apps/vscode-e2e/src/suite/subtasks.test.ts b/apps/vscode-e2e/src/suite/subtasks.test.ts index 857c8accc5..0da28c1aca 100644 --- a/apps/vscode-e2e/src/suite/subtasks.test.ts +++ b/apps/vscode-e2e/src/suite/subtasks.test.ts @@ -27,6 +27,12 @@ import { SUBTASK_INTERRUPT_PARENT_PROMPT, SUBTASK_INTERRUPT_PARENT_RESULT, SUBTASK_PARENT_PROMPT, + SUBTASK_QUEUED_INPUT_CHILD_MARKER, + SUBTASK_QUEUED_INPUT_CHILD_RESULT, + SUBTASK_QUEUED_INPUT_MESSAGE, + SUBTASK_QUEUED_INPUT_PARENT_MARKER, + SUBTASK_QUEUED_INPUT_PARENT_PROMPT, + SUBTASK_QUEUED_INPUT_PARENT_RESULT, SUBTASK_XPROFILE_DIFFERENT_CHILD_RESULT, SUBTASK_XPROFILE_PARENT_PROMPT, SUBTASK_XPROFILE_PARENT_RESULT, @@ -260,6 +266,73 @@ suite("Roo Code Subtasks", function () { } }) + test("queued input interrupts child completion before the parent resumes", async () => { + const api = globalThis.api + const says: Record = {} + + const messageHandler = ({ taskId, message }: { taskId: string; message: ClineMessage }) => { + if (message.type === "say" && message.partial !== true) { + says[taskId] = says[taskId] || [] + says[taskId].push(message) + } + } + + api.on(RooCodeEventName.Message, messageHandler) + + try { + const parentTaskId = await api.startNewTask({ + configuration: { + mode: "ask", + alwaysAllowModeSwitch: true, + alwaysAllowSubtasks: true, + autoApprovalEnabled: true, + enableCheckpoints: false, + }, + text: SUBTASK_QUEUED_INPUT_PARENT_PROMPT, + }) + + let childTaskId: string | undefined + await waitFor(() => { + const current = api.getCurrentTaskStack().at(-1) + if (current && current !== parentTaskId) { + childTaskId = current + return true + } + return false + }) + + await waitForAimockRequestContaining(SUBTASK_QUEUED_INPUT_CHILD_MARKER, SUBTASK_QUEUED_INPUT_PARENT_MARKER) + + const completedParentTaskId = await waitUntilCompleted({ + api, + start: async () => { + await api.sendMessage(SUBTASK_QUEUED_INPUT_MESSAGE) + return parentTaskId + }, + }) + + assert.strictEqual(completedParentTaskId, parentTaskId) + assert.ok( + says[childTaskId!]?.some( + ({ say, text }) => + say === "completion_result" && text?.trim() === SUBTASK_QUEUED_INPUT_CHILD_RESULT, + ), + "Child should process the queued instruction before returning to its parent", + ) + assert.strictEqual( + says[parentTaskId]?.find(({ say }) => say === "completion_result")?.text?.trim(), + SUBTASK_QUEUED_INPUT_PARENT_RESULT, + "Parent should resume only after the child processes the queued instruction", + ) + } finally { + api.off(RooCodeEventName.Message, messageHandler) + while (api.getCurrentTaskStack().length > 0) { + await api.clearCurrentTask() + } + await waitFor(() => api.getCurrentTaskStack().length === 0).catch(() => {}) + } + }) + // Smoke: child completing normally must resume the parent task. test("child task returns to parent after normal completion", async () => { const api = globalThis.api diff --git a/src/extension/__tests__/api.spec.ts b/src/extension/__tests__/api.spec.ts new file mode 100644 index 0000000000..eca673daa2 --- /dev/null +++ b/src/extension/__tests__/api.spec.ts @@ -0,0 +1,141 @@ +import type * as vscode from "vscode" +import { IpcMessageType, TaskCommandName, type ClineMessage, type IpcMessage } from "@roo-code/types" + +import { API } from "../api" +import type { ClineProvider } from "../../core/webview/ClineProvider" +import { MessageQueueService } from "../../core/message-queue/MessageQueueService" +import { Task } from "../../core/task/Task" + +vi.mock("vscode") +vi.mock("../../core/webview/ClineProvider") + +type TaskCommandHandler = ( + clientId: string, + command: Extract["data"], +) => Promise + +let taskCommandHandler: TaskCommandHandler | undefined + +type TaskTestAccess = { + addToClineMessages: (message: ClineMessage) => Promise +} + +const createStreamingTask = (provider: object) => { + const task = Object.create(Task.prototype) as Task + Object.assign(task, { + abort: false, + clineMessages: [], + taskId: "task-1", + instanceId: "instance-1", + isStreaming: true, + messageQueueService: new MessageQueueService(), + providerRef: { deref: () => provider }, + addToClineMessages: vi.fn(async () => {}), + saveClineMessages: vi.fn(async () => true), + updateClineMessage: vi.fn(async () => {}), + cancelAutoApprovalTimeout: vi.fn(), + checkpointSave: vi.fn(async () => {}), + emit: vi.fn(), + }) + vi.spyOn(task as unknown as TaskTestAccess, "addToClineMessages").mockImplementation(async (message) => { + task.clineMessages.push(message) + }) + return task +} + +vi.mock("@roo-code/ipc", () => ({ + IpcServer: class { + listen() {} + on(messageType: IpcMessageType, handler: TaskCommandHandler) { + if (messageType === IpcMessageType.TaskCommand) { + taskCommandHandler = handler + } + } + }, +})) + +describe("API.sendMessage", () => { + it("enqueues directly when the current webview task is streaming", async () => { + const addMessage = vi.fn() + const postMessageToWebview = vi.fn() + const provider = { + viewLaunched: true, + getCurrentTask: vi.fn().mockReturnValue({ + isStreaming: true, + messageQueueService: { addMessage }, + }), + getCurrentTaskStack: vi.fn().mockReturnValue([]), + postMessageToWebview, + on: vi.fn(), + } as unknown as ClineProvider + const api = new API({} as vscode.OutputChannel, provider) + const images = ["data:image/png;base64,image1data"] + + await api.sendMessage("Use this before completing", images) + + expect(addMessage).toHaveBeenCalledWith("Use this before completing", images) + expect(postMessageToWebview).not.toHaveBeenCalled() + + addMessage.mockClear() + await api.sendMessage(undefined, images) + expect(addMessage).toHaveBeenCalledWith("", images) + }) + + it.each([ + ["command", "npm publish"], + ["use_mcp_server", '{"server_name":"filesystem","tool_name":"write_file"}'], + ] as const)("does not approve a protected headless %s ask from queued IPC input", async (askType, askText) => { + const appendLine = vi.fn() + const provider = { + context: {}, + cwd: "/test/cwd", + viewLaunched: false, + getState: vi.fn().mockResolvedValue({ autoApprovalEnabled: false }), + getCurrentTask: vi.fn(), + getCurrentTaskStack: vi.fn().mockReturnValue([]), + on: vi.fn(), + } as unknown as ClineProvider + const task = createStreamingTask(provider) + vi.mocked(provider.getCurrentTask).mockReturnValue(task) + new API({ appendLine } as unknown as vscode.OutputChannel, provider, "/tmp/roo-test.sock", true) + const images = ["data:image/png;base64,image1data"] + const executeProtectedTool = vi.fn() + const ask = task.ask(askType, askText, false) + await vi.waitFor(() => expect(task.clineMessages).toHaveLength(1)) + + await taskCommandHandler?.("client-1", { + commandName: TaskCommandName.SendMessage, + data: { text: "Use this before completing", images }, + }) + const result = await ask + if (result.response === "yesButtonClicked") { + executeProtectedTool() + } + + expect(appendLine).toHaveBeenCalledWith("[API] SendMessage -> Use this before completing") + expect(result).toMatchObject({ response: "messageResponse", text: "Use this before completing", images }) + expect(task.messageQueueService.isEmpty()).toBe(true) + expect(executeProtectedTool).not.toHaveBeenCalled() + }) + + it("logs rejected SendMessage commands without rejecting the IPC handler", async () => { + const appendLine = vi.fn() + const provider = { + context: {}, + cwd: "/test/cwd", + getCurrentTask: vi.fn(), + getCurrentTaskStack: vi.fn().mockReturnValue([]), + on: vi.fn(), + } as unknown as ClineProvider + const api = new API({ appendLine } as unknown as vscode.OutputChannel, provider, "/tmp/roo-test.sock", true) + vi.spyOn(api, "sendMessage").mockRejectedValue(new Error("invalid input")) + + await expect( + taskCommandHandler?.("client-1", { + commandName: TaskCommandName.SendMessage, + data: { text: "" }, + }), + ).resolves.toBeUndefined() + expect(appendLine).toHaveBeenCalledWith("[API] SendMessage failed: invalid input") + }) +}) diff --git a/src/extension/api.ts b/src/extension/api.ts index 316e7a6c9d..23d7cfbf58 100644 --- a/src/extension/api.ts +++ b/src/extension/api.ts @@ -110,7 +110,12 @@ export class API extends EventEmitter implements RooCodeAPI { break case TaskCommandName.SendMessage: this.log(`[API] SendMessage -> ${command.data.text}`) - await this.sendMessage(command.data.text, command.data.images) + try { + await this.sendMessage(command.data.text, command.data.images) + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error) + this.log(`[API] SendMessage failed: ${errorMessage}`) + } break case TaskCommandName.GetCommands: try { @@ -324,8 +329,8 @@ export class API extends EventEmitter implements RooCodeAPI { const currentTask = this.sidebarProvider.getCurrentTask() // In headless/sandbox flows the webview may not be launched, so routing - // through invoke=sendMessage drops the message. Deliver directly to the - // task ask-response channel instead. + // through invoke=sendMessage drops the message. Keep this path on the task + // ask-response channel so queued input cannot approve protected tool asks. if (!this.sidebarProvider.viewLaunched) { if (!currentTask) { this.log("[API#sendMessage] no current task in headless mode; message dropped") @@ -336,6 +341,12 @@ export class API extends EventEmitter implements RooCodeAPI { return } + // Ensure steering input reaches the active task before it can finish. + if (currentTask?.isStreaming) { + currentTask.messageQueueService.addMessage(text ?? "", images) + return + } + await this.sidebarProvider.postMessageToWebview({ type: "invoke", invoke: "sendMessage", text, images }) }