Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 85 additions & 0 deletions apps/vscode-e2e/src/fixtures/subtasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ const SUBTASK_FAST_CHILD_MARKER = "SUBTASK_CHILD_IMMEDIATE_COMPLETION"
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.`
Expand Down Expand Up @@ -54,6 +56,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"
Expand Down Expand Up @@ -122,6 +132,81 @@ const completionAfterAnswer = (followupId: string, completionId: string) => ({
})

export function addSubtaskFixtures(mock: InstanceType<typeof LLMock>) {
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),
Expand Down
72 changes: 72 additions & 0 deletions apps/vscode-e2e/src/suite/subtasks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ 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_PROMPT,
SUBTASK_QUEUED_INPUT_PARENT_RESULT,
SUBTASK_XPROFILE_DIFFERENT_CHILD_RESULT,
SUBTASK_XPROFILE_PARENT_PROMPT,
SUBTASK_XPROFILE_PARENT_RESULT,
Expand Down Expand Up @@ -174,6 +179,73 @@ suite("Roo Code Subtasks", function () {
}
})

test("queued input interrupts child completion before the parent resumes", async () => {
const api = globalThis.api
const says: Record<string, ClineMessage[]> = {}

const messageHandler = ({ taskId, message }: { taskId: string; message: ClineMessage }) => {
if (message.type === "say" && message.partial === false) {
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)

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
Expand Down
53 changes: 29 additions & 24 deletions src/core/task/Task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import {
type ContextTruncation,
type ClineMessage,
type ClineSay,
type ClineSayTool,
type ClineAsk,
type ToolProgressStatus,
type HistoryItem,
Expand Down Expand Up @@ -1150,6 +1151,19 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
return undefined
}

private drainQueuedMessageIntoAskResponse(allowResolvedAskOverride = false): void {
// A synchronous auto-approval may already have resolved the ask before the
// entry queue snapshot is acted on. Never replace that resolved response.
if (this.askResponse !== undefined && !allowResolvedAskOverride) {
return
}

const message = this.messageQueueService.dequeueMessage()
if (message) {
this.handleWebviewAskResponse("messageResponse", message.text, message.images)
}
}

// Note that `partial` has three valid states true (partial message),
// false (completion of partial message), undefined (individual complete
// message).
Expand Down Expand Up @@ -1315,6 +1329,14 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
// Keep queued user messages intact during command_output asks. Those asks
// are terminal flow-control, not conversational turns.
const shouldDrainQueuedMessageForAsk = type !== "command_output"
let isFinishTaskAsk = false
if (type === "tool") {
try {
isFinishTaskAsk = (JSON.parse(text || "{}") as ClineSayTool).tool === "finishTask"
} catch {
// Invalid tool payloads are handled by their caller; they are not finishTask asks.
}
}
const isStatusMutable = !partial && isBlocking && !isMessageQueued && approval.decision === "ask"

if (isStatusMutable) {
Expand Down Expand Up @@ -1359,20 +1381,10 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
)
}
} else if (isMessageQueued && shouldDrainQueuedMessageForAsk) {
const message = this.messageQueueService.dequeueMessage()

if (message) {
// Check if this is a tool approval ask that needs to be handled.
if (type === "tool" || type === "command" || type === "use_mcp_server") {
// For tool approvals, we need to approve first, then send
// the message if there's text/images.
this.handleWebviewAskResponse("yesButtonClicked", message.text, message.images)
} else {
// For other ask types (like followup or command_output), fulfill the ask
// directly.
this.handleWebviewAskResponse("messageResponse", message.text, message.images)
}
}
// This branch acts on the queue state captured when the ask was entered.
// A queued instruction must interrupt finishTask before the child returns
// to its parent, even when subtask completion is otherwise auto-approved.
this.drainQueuedMessageIntoAskResponse(isFinishTaskAsk)
}

// Wait for askResponse to be set
Expand All @@ -1386,16 +1398,9 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
// suggestion click that was incorrectly queued due to UI state), consume it
// immediately so the task doesn't hang.
if (shouldDrainQueuedMessageForAsk && !this.messageQueueService.isEmpty()) {
const message = this.messageQueueService.dequeueMessage()
if (message) {
// If this is a tool approval ask, we need to approve first (yesButtonClicked)
// and include any queued text/images.
if (type === "tool" || type === "command" || type === "use_mcp_server") {
this.handleWebviewAskResponse("yesButtonClicked", message.text, message.images)
} else {
this.handleWebviewAskResponse("messageResponse", message.text, message.images)
}
}
// Unlike the entry snapshot above, this live check handles messages that
// arrive after the ask has begun waiting.
this.drainQueuedMessageIntoAskResponse()
}

return false
Expand Down
Loading
Loading