Skip to content

Commit d7a98bc

Browse files
committed
fix(AttempCompletionTool): allow completion of active parents
1 parent 77efcde commit d7a98bc

6 files changed

Lines changed: 280 additions & 14 deletions

File tree

‎apps/vscode-e2e/src/fixtures/subtasks.ts‎

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,23 @@ const SUBTASK_PARENT_MARKER = "SUBTASK_PARENT_CANCELLATION_SMOKE"
77
const SUBTASK_CHILD_MARKER = "SUBTASK_CHILD_CALCULATOR_SMOKE"
88
const SUBTASK_FAST_PARENT_MARKER = "SUBTASK_PARENT_IMMEDIATE_COMPLETION"
99
const SUBTASK_FAST_CHILD_MARKER = "SUBTASK_CHILD_IMMEDIATE_COMPLETION"
10+
const SUBTASK_XPROFILE_PARENT_MARKER = "SUBTASK_PARENT_CROSS_PROFILE"
11+
const SUBTASK_XPROFILE_SAME_CHILD_MARKER = "SUBTASK_CHILD_SAME_PROFILE"
12+
const SUBTASK_XPROFILE_DIFFERENT_CHILD_MARKER = "SUBTASK_CHILD_DIFFERENT_PROFILE"
1013

1114
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.`
1215
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.`
1316
export const SUBTASK_CHILD_FOLLOWUP_ANSWER = "9"
1417
const SUBTASK_FAST_CHILD_PROMPT = `${SUBTASK_FAST_CHILD_MARKER}: Complete immediately with the exact result "Fast child completed".`
1518
export const SUBTASK_FAST_PARENT_PROMPT = `${SUBTASK_FAST_PARENT_MARKER}: Use the new_task tool exactly once. Create an ask-mode subtask with this exact message: "${SUBTASK_FAST_CHILD_PROMPT}" Do not answer directly.`
1619

20+
const SUBTASK_XPROFILE_SAME_CHILD_PROMPT = `${SUBTASK_XPROFILE_SAME_CHILD_MARKER}: Complete immediately with the exact result "Same-profile child completed".`
21+
const SUBTASK_XPROFILE_DIFFERENT_CHILD_PROMPT = `${SUBTASK_XPROFILE_DIFFERENT_CHILD_MARKER}: Complete immediately with the exact result "Different-profile child completed".`
22+
export const SUBTASK_XPROFILE_PARENT_PROMPT = `${SUBTASK_XPROFILE_PARENT_MARKER}: First use new_task to create a code-mode subtask with this exact message: "${SUBTASK_XPROFILE_SAME_CHILD_PROMPT}" After it returns, create an ask-mode subtask with the next instructions you receive.`
23+
export const SUBTASK_XPROFILE_SAME_CHILD_RESULT = "Same-profile child completed"
24+
export const SUBTASK_XPROFILE_DIFFERENT_CHILD_RESULT = "Different-profile child completed"
25+
export const SUBTASK_XPROFILE_PARENT_RESULT = "Sequential cross-profile parent resumed"
26+
1727
const requestContains = (req: ChatCompletionRequest, expected: string[]) => {
1828
const rawRequest = JSON.stringify(req)
1929
return expected.every((text) => rawRequest.includes(text))
@@ -144,4 +154,94 @@ export function addSubtaskFixtures(mock: InstanceType<typeof LLMock>) {
144154
],
145155
},
146156
})
157+
158+
// Issue #457 sequence: a same-profile child returns first, then the resumed
159+
// parent delegates to a child whose mode uses a different API profile.
160+
mock.addFixture({
161+
match: {
162+
userMessage: new RegExp(SUBTASK_XPROFILE_PARENT_MARKER),
163+
},
164+
response: {
165+
toolCalls: [
166+
{
167+
name: "new_task",
168+
arguments: JSON.stringify({
169+
mode: "code",
170+
message: SUBTASK_XPROFILE_SAME_CHILD_PROMPT,
171+
}),
172+
id: "call_subtasks_xprofile_parent_same_child_001",
173+
},
174+
],
175+
},
176+
})
177+
178+
mock.addFixture({
179+
match: {
180+
userMessage: new RegExp(SUBTASK_XPROFILE_SAME_CHILD_MARKER),
181+
},
182+
response: {
183+
toolCalls: [
184+
{
185+
name: "attempt_completion",
186+
arguments: JSON.stringify({ result: SUBTASK_XPROFILE_SAME_CHILD_RESULT }),
187+
id: "call_subtasks_xprofile_same_child_completion_002",
188+
},
189+
],
190+
},
191+
})
192+
193+
mock.addFixture({
194+
match: {
195+
predicate: (req: ChatCompletionRequest) =>
196+
requestContains(req, [SUBTASK_XPROFILE_PARENT_MARKER, SUBTASK_XPROFILE_SAME_CHILD_RESULT]) &&
197+
!requestContains(req, [SUBTASK_XPROFILE_DIFFERENT_CHILD_RESULT]),
198+
},
199+
response: {
200+
toolCalls: [
201+
{
202+
name: "new_task",
203+
arguments: JSON.stringify({
204+
mode: "ask",
205+
message: SUBTASK_XPROFILE_DIFFERENT_CHILD_PROMPT,
206+
}),
207+
id: "call_subtasks_xprofile_parent_different_child_003",
208+
},
209+
],
210+
},
211+
})
212+
213+
mock.addFixture({
214+
match: {
215+
userMessage: new RegExp(SUBTASK_XPROFILE_DIFFERENT_CHILD_MARKER),
216+
},
217+
response: {
218+
toolCalls: [
219+
{
220+
name: "attempt_completion",
221+
arguments: JSON.stringify({ result: SUBTASK_XPROFILE_DIFFERENT_CHILD_RESULT }),
222+
id: "call_subtasks_xprofile_different_child_completion_004",
223+
},
224+
],
225+
},
226+
})
227+
228+
mock.addFixture({
229+
match: {
230+
predicate: (req: ChatCompletionRequest) =>
231+
requestContains(req, [
232+
SUBTASK_XPROFILE_PARENT_MARKER,
233+
SUBTASK_XPROFILE_SAME_CHILD_RESULT,
234+
SUBTASK_XPROFILE_DIFFERENT_CHILD_RESULT,
235+
]),
236+
},
237+
response: {
238+
toolCalls: [
239+
{
240+
name: "attempt_completion",
241+
arguments: JSON.stringify({ result: SUBTASK_XPROFILE_PARENT_RESULT }),
242+
id: "call_subtasks_xprofile_parent_completion_005",
243+
},
244+
],
245+
},
246+
})
147247
}

‎apps/vscode-e2e/src/suite/subtasks.test.ts‎

Lines changed: 117 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,15 @@ import { RooCodeEventName, type ClineMessage } from "@roo-code/types"
44

55
import { setDefaultSuiteTimeout } from "./test-utils"
66
import { waitFor, waitUntilCompleted } from "./utils"
7-
import { SUBTASK_CHILD_FOLLOWUP_ANSWER, SUBTASK_FAST_PARENT_PROMPT, SUBTASK_PARENT_PROMPT } from "../fixtures/subtasks"
7+
import {
8+
SUBTASK_CHILD_FOLLOWUP_ANSWER,
9+
SUBTASK_FAST_PARENT_PROMPT,
10+
SUBTASK_PARENT_PROMPT,
11+
SUBTASK_XPROFILE_DIFFERENT_CHILD_RESULT,
12+
SUBTASK_XPROFILE_PARENT_PROMPT,
13+
SUBTASK_XPROFILE_PARENT_RESULT,
14+
SUBTASK_XPROFILE_SAME_CHILD_RESULT,
15+
} from "../fixtures/subtasks"
816

917
suite("Roo Code Subtasks", function () {
1018
setDefaultSuiteTimeout(this)
@@ -322,4 +330,112 @@ suite("Roo Code Subtasks", function () {
322330
api.off(RooCodeEventName.Message, messageHandler)
323331
}
324332
})
333+
334+
test("same-profile child returns before a different-profile child", async () => {
335+
const api = globalThis.api
336+
const says: Record<string, ClineMessage[]> = {}
337+
338+
const messageHandler = ({ taskId, message }: { taskId: string; message: ClineMessage }) => {
339+
if (message.type === "say" && message.partial === false) {
340+
says[taskId] = says[taskId] || []
341+
says[taskId].push(message)
342+
}
343+
}
344+
345+
api.on(RooCodeEventName.Message, messageHandler)
346+
347+
const aimockUrl = process.env.AIMOCK_URL
348+
const parentProfile = {
349+
apiProvider: "openrouter" as const,
350+
openRouterApiKey: "mock-key",
351+
openRouterModelId: "openai/gpt-4.1",
352+
rateLimitSeconds: 0,
353+
...(aimockUrl && { openRouterBaseUrl: `${aimockUrl}/v1` }),
354+
}
355+
const childProfile = {
356+
...parentProfile,
357+
openRouterModelId: "openai/gpt-4.1-mini",
358+
}
359+
const parentProfileId = await api.upsertProfile("subtask-parent-profile", parentProfile, true)
360+
const childProfileId = await api.upsertProfile("subtask-child-profile", childProfile, false)
361+
await api.setConfiguration({
362+
modeApiConfigs: {
363+
code: parentProfileId!,
364+
ask: childProfileId!,
365+
},
366+
})
367+
368+
try {
369+
let parentTaskId: string
370+
try {
371+
parentTaskId = await waitUntilCompleted({
372+
api,
373+
start: () =>
374+
api.startNewTask({
375+
configuration: {
376+
mode: "code",
377+
alwaysAllowModeSwitch: true,
378+
alwaysAllowSubtasks: true,
379+
autoApprovalEnabled: true,
380+
enableCheckpoints: false,
381+
},
382+
text: SUBTASK_XPROFILE_PARENT_PROMPT,
383+
}),
384+
})
385+
} catch (error) {
386+
const messageSummary = Object.fromEntries(
387+
Object.entries(says).map(([taskId, messages]) => [
388+
taskId,
389+
messages.map(({ say, text }) => ({ say, text: text?.slice(0, 200) })),
390+
]),
391+
)
392+
throw new Error(
393+
`Sequential cross-profile subtasks did not complete. Stack: ${JSON.stringify(api.getCurrentTaskStack())}; ` +
394+
`messages: ${JSON.stringify(messageSummary)}`,
395+
{ cause: error },
396+
)
397+
}
398+
399+
const sameProfileChildId = Object.entries(says).find(
400+
([taskId, messages]) =>
401+
taskId !== parentTaskId &&
402+
messages.some(
403+
({ say, text }) =>
404+
say === "completion_result" && text?.trim() === SUBTASK_XPROFILE_SAME_CHILD_RESULT,
405+
),
406+
)?.[0]
407+
const differentProfileChildId = Object.entries(says).find(
408+
([taskId, messages]) =>
409+
taskId !== parentTaskId &&
410+
messages.some(
411+
({ say, text }) =>
412+
say === "completion_result" && text?.trim() === SUBTASK_XPROFILE_DIFFERENT_CHILD_RESULT,
413+
),
414+
)?.[0]
415+
416+
assert.ok(sameProfileChildId, "Same-profile child should return to the parent")
417+
assert.ok(differentProfileChildId, "Different-profile child should return to the parent")
418+
assert.notStrictEqual(
419+
sameProfileChildId,
420+
differentProfileChildId,
421+
"Parent should delegate to two distinct child tasks",
422+
)
423+
assert.strictEqual(
424+
says[parentTaskId]
425+
?.filter(({ say }) => say === "completion_result")
426+
.map(({ text }) => text?.trim())
427+
.find((text): text is string => !!text),
428+
SUBTASK_XPROFILE_PARENT_RESULT,
429+
"Parent should resume after both sequential children complete",
430+
)
431+
} finally {
432+
api.off(RooCodeEventName.Message, messageHandler)
433+
await api.setConfiguration({ modeApiConfigs: {} })
434+
await api.deleteProfile("subtask-child-profile").catch(() => {})
435+
await api.deleteProfile("subtask-parent-profile").catch(() => {})
436+
while (api.getCurrentTaskStack().length > 0) {
437+
await api.clearCurrentTask()
438+
}
439+
}
440+
})
325441
})

‎src/__tests__/history-resume-delegation.spec.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,12 +45,12 @@ describe("History resume delegation - parent metadata transitions", () => {
4545
vi.clearAllMocks()
4646
})
4747

48-
it("reopenParentFromDelegation persists parent metadata (delegated → active) before reopen", async () => {
48+
it("reopenParentFromDelegation accepts an active parent awaiting the returning child", async () => {
4949
const providerEmit = vi.fn()
5050
const getTaskWithId = vi.fn().mockResolvedValue({
5151
historyItem: {
5252
id: "parent-1",
53-
status: "delegated",
53+
status: "active",
5454
delegatedToId: "child-1",
5555
awaitingChildId: "child-1",
5656
childIds: ["child-1"],

‎src/core/tools/AttemptCompletionTool.ts‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ export class AttemptCompletionTool extends BaseTool<"attempt_completion"> {
102102
const { historyItem: parentHistory } = await provider.getTaskWithId(task.parentTaskId)
103103

104104
if (
105-
parentHistory?.status === "delegated" &&
105+
(parentHistory?.status === "delegated" || parentHistory?.status === "active") &&
106106
parentHistory?.awaitingChildId === task.taskId
107107
) {
108108
const delegation = await this.delegateToParent(
@@ -119,11 +119,12 @@ export class AttemptCompletionTool extends BaseTool<"attempt_completion"> {
119119
} else {
120120
// Parent already detached, such as when the user cancelled this child.
121121
// Fall through to the normal completion ask flow.
122-
provider.log(
122+
const msg =
123123
`[AttemptCompletionTool] Skipping delegation for child ${task.taskId}: ` +
124-
`parent ${task.parentTaskId} is not awaiting this child. ` +
125-
`Diagnostic: { childStatus: "${status}", parentStatus: "${parentHistory?.status}", awaitingChildId: "${parentHistory?.awaitingChildId}" }`,
126-
)
124+
`parent ${task.parentTaskId} is not awaiting this child. ` +
125+
`Diagnostic: { childStatus: "${status}", parentStatus: "${parentHistory?.status}", awaitingChildId: "${parentHistory?.awaitingChildId}" }`
126+
provider.log(msg)
127+
console.warn(msg)
127128
}
128129
} else {
129130
// Unexpected status (undefined or "delegated") - log error and skip delegation

‎src/core/tools/__tests__/attemptCompletionTool.spec.ts‎

Lines changed: 50 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -484,7 +484,7 @@ describe("attemptCompletionTool", () => {
484484
})
485485

486486
describe("completion lifecycle", () => {
487-
it("delegates an active subtask completion only when the parent is awaiting that child", async () => {
487+
it("delegates an active subtask completion when the active parent awaits that child", async () => {
488488
const block: AttemptCompletionToolUse = {
489489
type: "tool_use",
490490
name: "attempt_completion",
@@ -500,7 +500,7 @@ describe("attemptCompletionTool", () => {
500500
}
501501
if (id === "parent-1") {
502502
return Promise.resolve({
503-
historyItem: { id, status: "delegated", awaitingChildId: "child-1" },
503+
historyItem: { id, status: "active", awaitingChildId: "child-1" },
504504
})
505505
}
506506
throw new Error(`unexpected task id ${id}`)
@@ -635,6 +635,54 @@ describe("attemptCompletionTool", () => {
635635
expect(mockCaptureTaskCompleted).toHaveBeenCalledWith("child-1")
636636
})
637637

638+
it("does not resume the parent when the parent is active but awaiting a different child", async () => {
639+
const block: AttemptCompletionToolUse = {
640+
type: "tool_use",
641+
name: "attempt_completion",
642+
params: { result: "9" },
643+
nativeArgs: { result: "9" },
644+
partial: false,
645+
}
646+
const mockProvider = {
647+
log: vi.fn(),
648+
getTaskWithId: vi.fn().mockImplementation((id: string) => {
649+
if (id === "child-1") {
650+
return Promise.resolve({ historyItem: { id, status: "active" } })
651+
}
652+
if (id === "parent-1") {
653+
return Promise.resolve({
654+
historyItem: { id, status: "active", awaitingChildId: "different-child" },
655+
})
656+
}
657+
throw new Error(`unexpected task id ${id}`)
658+
}),
659+
reopenParentFromDelegation: vi.fn().mockResolvedValue(undefined),
660+
}
661+
662+
Object.assign(mockTask, {
663+
taskId: "child-1",
664+
parentTaskId: "parent-1",
665+
providerRef: { deref: () => mockProvider },
666+
})
667+
mockAskFinishSubTaskApproval.mockResolvedValue(true)
668+
669+
const callbacks: AttemptCompletionCallbacks = {
670+
askApproval: mockAskApproval,
671+
handleError: mockHandleError,
672+
pushToolResult: mockPushToolResult,
673+
askFinishSubTaskApproval: mockAskFinishSubTaskApproval,
674+
toolDescription: mockToolDescription,
675+
}
676+
677+
await attemptCompletionTool.handle(mockTask as Task, block, callbacks)
678+
679+
expect(mockAskFinishSubTaskApproval).not.toHaveBeenCalled()
680+
expect(mockProvider.reopenParentFromDelegation).not.toHaveBeenCalled()
681+
expect(mockProvider.log).toHaveBeenCalledWith(expect.stringContaining("Skipping delegation"))
682+
expect(mockTask.ask).toHaveBeenCalledWith("completion_result", "", false)
683+
expect(mockCaptureTaskCompleted).toHaveBeenCalledWith("child-1")
684+
})
685+
638686
it("emits TaskCompleted only when completion is accepted", async () => {
639687
const block: AttemptCompletionToolUse = {
640688
type: "tool_use",

‎src/core/webview/ClineProvider.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -526,10 +526,11 @@ export class ClineProvider
526526
status: "active",
527527
awaitingChildId: undefined,
528528
})
529-
this.log(
529+
const repairMsg =
530530
`[ClineProvider#removeClineFromStack] Repaired parent ${parentTaskId} metadata: delegated → active (child ${childTaskId} removed). ` +
531-
`Caller stack: ${callerStack?.split("\n").slice(1, 5).join(" | ")}`,
532-
)
531+
`Caller stack: ${callerStack?.split("\n").slice(1, 5).join(" | ")}`
532+
this.log(repairMsg)
533+
console.warn(repairMsg)
533534
}
534535
})
535536
} catch (err) {
@@ -3541,7 +3542,7 @@ export class ClineProvider
35413542
// routing output back would corrupt an unrelated task.
35423543
if (
35433544
this.cancelledDelegationChildIds.has(childTaskId) ||
3544-
historyItem.status !== "delegated" ||
3545+
(historyItem.status !== "delegated" && historyItem.status !== "active") ||
35453546
historyItem.awaitingChildId !== childTaskId
35463547
) {
35473548
this.log(

0 commit comments

Comments
 (0)