Skip to content

Commit 0952a89

Browse files
simurg79Bertan Ari
andauthored
[Fix] Preserve subtask link identities (#2228)
* fix(chat): preserve subtask link identities * test: re-enable subtask-links provider tests * fix(subtask-links): stamp only the ask matching the current delegation * fix(chat): do not link earlier subtask results to the latest completed child * test(subtask-links): kill surviving mutants and simplify stamping guards * test(subtask-links): cover differing result text and mark equivalent type-check mutants * refactor(subtask-links): drop redundant message type checks and keep taskMessages mock complete * test(task-persistence): cover childTaskId surviving merge when incoming omits it --------- Co-authored-by: Bertan Ari <[email protected]>
1 parent 545e4d5 commit 0952a89

6 files changed

Lines changed: 524 additions & 152 deletions

File tree

‎packages/types/src/message.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,8 @@ export const clineMessageSchema = z.object({
272272
* Present when `say: "sliding_window_truncation"`.
273273
*/
274274
contextTruncation: contextTruncationSchema.optional(),
275+
// Older delegation messages lack this stamp and require positional link resolution.
276+
childTaskId: z.string().optional(),
275277
isProtected: z.boolean().optional(),
276278
apiProtocol: z.union([z.literal("openai"), z.literal("anthropic")]).optional(),
277279
isAnswered: z.boolean().optional(),
Lines changed: 254 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,254 @@
1+
import { beforeEach, describe, expect, it, vi } from "vitest"
2+
import { clineMessageSchema, type ClineMessage, type HistoryItem } from "@roo-code/types"
3+
4+
vi.mock("../core/task-persistence/taskMessages", async (importOriginal) => ({
5+
...(await importOriginal<typeof import("../core/task-persistence/taskMessages")>()),
6+
readTaskMessages: vi.fn(),
7+
}))
8+
vi.mock("../core/task-persistence", async (importOriginal) => ({
9+
...(await importOriginal<typeof import("../core/task-persistence")>()),
10+
readApiMessages: vi.fn().mockResolvedValue([]),
11+
saveApiMessages: vi.fn(async ({ messages }: { messages: unknown[] }) => messages),
12+
saveTaskMessages: vi.fn(async ({ messages }: { messages: ClineMessage[] }) => messages),
13+
}))
14+
15+
import { ClineProvider } from "../core/webview/ClineProvider"
16+
import { readTaskMessages } from "../core/task-persistence/taskMessages"
17+
import { saveTaskMessages } from "../core/task-persistence"
18+
import { makeProviderStub } from "./helpers/provider-stub"
19+
20+
function newTask(ts: number, childTaskId?: string, content = "Do work"): ClineMessage {
21+
return {
22+
ts,
23+
type: "ask",
24+
ask: "tool",
25+
text: JSON.stringify({ tool: "newTask", mode: "code", content }),
26+
...(childTaskId ? { childTaskId } : {}),
27+
}
28+
}
29+
30+
function makeLinkProvider() {
31+
const parentHistory: HistoryItem = {
32+
id: "parent",
33+
number: 1,
34+
ts: 1,
35+
task: "Parent",
36+
tokensIn: 0,
37+
tokensOut: 0,
38+
totalCost: 0,
39+
status: "active",
40+
}
41+
const records = new Map<string, HistoryItem>([["parent", parentHistory]])
42+
const taskHistoryStore = {
43+
get: vi.fn((taskId: string) => records.get(taskId)),
44+
invalidate: vi.fn().mockResolvedValue(undefined),
45+
atomicReadAndUpdate: vi.fn(async (taskId: string, update: (item: HistoryItem) => HistoryItem) => {
46+
records.set(taskId, update(records.get(taskId)!))
47+
}),
48+
atomicUpdatePair: vi.fn(
49+
async (
50+
firstId: string,
51+
secondId: string,
52+
firstUpdate: (item: HistoryItem) => HistoryItem,
53+
secondUpdate: (item: HistoryItem) => HistoryItem,
54+
) => {
55+
records.set(firstId, firstUpdate(records.get(firstId)!))
56+
records.set(secondId, secondUpdate(records.get(secondId)!))
57+
},
58+
),
59+
}
60+
const parent = {
61+
taskId: "parent",
62+
apiConfiguration: {},
63+
getTaskApiConfigName: vi.fn().mockResolvedValue("default"),
64+
getTaskMode: vi.fn().mockResolvedValue("code"),
65+
flushPendingToolResultsToHistory: vi.fn().mockResolvedValue(true),
66+
}
67+
const child = { taskId: "child", run: vi.fn().mockResolvedValue(undefined) }
68+
const reopenedParent = {
69+
taskId: "parent",
70+
resumeAfterDelegation: vi.fn().mockResolvedValue(undefined),
71+
overwriteClineMessages: vi.fn().mockResolvedValue(undefined),
72+
overwriteApiConversationHistory: vi.fn().mockResolvedValue(undefined),
73+
}
74+
const provider = makeProviderStub({
75+
contextProxy: { globalStorageUri: { fsPath: "/storage" } },
76+
getCurrentTask: vi.fn(() => parent),
77+
getTaskWithId: vi.fn(async (taskId: string) => ({ historyItem: records.get(taskId) })),
78+
removeClineFromStack: vi.fn().mockResolvedValue(undefined),
79+
createTask: vi.fn().mockResolvedValue(child),
80+
createTaskWithHistoryItem: vi.fn().mockResolvedValue(reopenedParent),
81+
deleteTaskWithId: vi.fn().mockResolvedValue(undefined),
82+
emit: vi.fn(),
83+
log: vi.fn(),
84+
taskHistoryStore,
85+
})
86+
return { provider, records, taskHistoryStore, child, reopenedParent }
87+
}
88+
89+
const delegation = { parentTaskId: "parent", message: "Do work", initialTodos: [], mode: "code" }
90+
91+
describe("persisted subtask links", () => {
92+
beforeEach(() => {
93+
vi.clearAllMocks()
94+
vi.mocked(readTaskMessages).mockResolvedValue([])
95+
})
96+
97+
it.each([undefined, "child"])("keeps optional child identity through schema validation: %s", (childTaskId) => {
98+
expect(clineMessageSchema.parse(newTask(1, childTaskId)).childTaskId).toBe(childTaskId)
99+
})
100+
101+
it("stamps only the latest ask after commit and before the child runs", async () => {
102+
const messages: ClineMessage[] = [
103+
newTask(1),
104+
newTask(2),
105+
{ ts: 3, type: "say", say: "text", text: "Working" },
106+
{ ts: 4, type: "ask", ask: "tool", text: "invalid JSON" },
107+
{ ts: 5, type: "ask", ask: "tool", text: JSON.stringify({ tool: "readFile" }) },
108+
]
109+
vi.mocked(readTaskMessages).mockResolvedValue(messages)
110+
const { provider, taskHistoryStore, child } = makeLinkProvider()
111+
await ClineProvider.prototype.delegateParentAndOpenChild.call(provider, delegation)
112+
113+
expect(messages[0].childTaskId).toBeUndefined()
114+
expect(messages[1].childTaskId).toBe("child")
115+
expect(saveTaskMessages).toHaveBeenCalledWith({
116+
messages,
117+
taskId: "parent",
118+
globalStoragePath: "/storage",
119+
merge: true,
120+
})
121+
const saveOrder = vi.mocked(saveTaskMessages).mock.invocationCallOrder[0]
122+
expect(taskHistoryStore.atomicReadAndUpdate.mock.invocationCallOrder[0]).toBeLessThan(saveOrder)
123+
expect(saveOrder).toBeLessThan(child.run.mock.invocationCallOrder[0])
124+
expect(readTaskMessages).toHaveBeenCalledWith({ taskId: "parent", globalStoragePath: "/storage" })
125+
})
126+
127+
it.each<ClineMessage>([
128+
{ ts: 3, type: "say", say: "text", text: newTask(0).text },
129+
{ ts: 3, type: "ask", ask: "followup", text: newTask(0).text },
130+
{ ts: 3, type: "ask", ask: "tool", text: "null" },
131+
{ ts: 3, type: "ask", ask: "tool", text: JSON.stringify({ tool: "readFile", content: "Do work" }) },
132+
])("skips a newer non-delegation message and stamps the delegation ask: %j", async (newer) => {
133+
const messages = [newTask(1), newer]
134+
vi.mocked(readTaskMessages).mockResolvedValue(messages)
135+
const { provider } = makeLinkProvider()
136+
await ClineProvider.prototype.delegateParentAndOpenChild.call(provider, delegation)
137+
expect(messages[0].childTaskId).toBe("child")
138+
expect(newer.childTaskId).toBeUndefined()
139+
})
140+
141+
it.each([{ tool: "newTask" }, { tool: "newTask", content: 42 }])(
142+
"does not stamp or log a newest ask without string content: %j",
143+
async (tool) => {
144+
const messages: ClineMessage[] = [{ ts: 1, type: "ask", ask: "tool", text: JSON.stringify(tool) }]
145+
vi.mocked(readTaskMessages).mockResolvedValue(messages)
146+
const { provider } = makeLinkProvider()
147+
await ClineProvider.prototype.delegateParentAndOpenChild.call(provider, delegation)
148+
expect(messages[0].childTaskId).toBeUndefined()
149+
expect(provider.log).not.toHaveBeenCalledWith(expect.stringContaining("Failed to save child link"))
150+
},
151+
)
152+
153+
it.each([{ messages: [] }, { messages: [newTask(1), newTask(2, "existing-child")] }])(
154+
"does not write or stamp older asks when no pending delegation exists: %j",
155+
async ({ messages }) => {
156+
vi.mocked(readTaskMessages).mockResolvedValue(messages)
157+
const { provider } = makeLinkProvider()
158+
await ClineProvider.prototype.delegateParentAndOpenChild.call(provider, delegation)
159+
expect(saveTaskMessages).not.toHaveBeenCalled()
160+
expect(messages[0]?.childTaskId).toBeUndefined()
161+
},
162+
)
163+
164+
it.each([
165+
{ askContent: "Do work", delegatedMessage: "Do work", stamped: true },
166+
{ askContent: "See \\\\@file", delegatedMessage: "See \\@file", stamped: true },
167+
{ askContent: "Other work", delegatedMessage: "Do work", stamped: false },
168+
])("stamps the newest ask only when it matches the delegation: %j", async (scenario) => {
169+
const { askContent, delegatedMessage, stamped } = scenario
170+
const messages = [newTask(1, undefined, delegatedMessage), newTask(2, undefined, askContent)]
171+
vi.mocked(readTaskMessages).mockResolvedValue(messages)
172+
const { provider, child } = makeLinkProvider()
173+
await ClineProvider.prototype.delegateParentAndOpenChild.call(provider, {
174+
...delegation,
175+
message: delegatedMessage,
176+
})
177+
178+
expect(messages[0].childTaskId).toBeUndefined()
179+
expect(messages[1].childTaskId).toBe(stamped ? "child" : undefined)
180+
expect(vi.mocked(saveTaskMessages).mock.calls).toHaveLength(stamped ? 1 : 0)
181+
expect(child.run).toHaveBeenCalledOnce()
182+
})
183+
184+
it("does not stamp a rejected delegation", async () => {
185+
const { provider, taskHistoryStore } = makeLinkProvider()
186+
taskHistoryStore.atomicReadAndUpdate.mockRejectedValueOnce(new Error("commit rejected"))
187+
await expect(ClineProvider.prototype.delegateParentAndOpenChild.call(provider, delegation)).rejects.toThrow(
188+
"commit rejected",
189+
)
190+
expect(readTaskMessages).not.toHaveBeenCalled()
191+
expect(saveTaskMessages).not.toHaveBeenCalled()
192+
})
193+
194+
it.each(["read", "write"])("starts the committed child even if link %s fails", async (operation) => {
195+
vi.mocked(readTaskMessages).mockResolvedValue([newTask(1)])
196+
if (operation === "read") vi.mocked(readTaskMessages).mockRejectedValueOnce(new Error("read failed"))
197+
else vi.mocked(saveTaskMessages).mockRejectedValueOnce(new Error("write failed"))
198+
const { provider, child } = makeLinkProvider()
199+
await ClineProvider.prototype.delegateParentAndOpenChild.call(provider, delegation)
200+
expect(child.run).toHaveBeenCalledOnce()
201+
expect(provider.log).toHaveBeenCalledWith(expect.stringContaining("Failed to save child link"))
202+
})
203+
204+
it.each([undefined, "child", "earlier-child"])(
205+
"stamps resumed results without conflating identical summaries from child %s",
206+
async (previousChildId) => {
207+
const { provider, records, reopenedParent } = makeLinkProvider()
208+
const parent = records.get("parent")!
209+
records.set("parent", { ...parent, status: "delegated", awaitingChildId: "child", childIds: ["child"] })
210+
records.set("child", { ...parent, id: "child", parentTaskId: "parent" })
211+
const previous: ClineMessage = {
212+
ts: 1,
213+
type: "say",
214+
say: "subtask_result",
215+
text: "Done",
216+
childTaskId: previousChildId,
217+
}
218+
vi.mocked(readTaskMessages).mockResolvedValue([previous])
219+
220+
await ClineProvider.prototype.reopenParentFromDelegation.call(provider, {
221+
parentTaskId: "parent",
222+
childTaskId: "child",
223+
completionResultSummary: "Done",
224+
})
225+
226+
const saved = vi.mocked(saveTaskMessages).mock.calls[0][0].messages
227+
expect(saved).toHaveLength(previousChildId === "earlier-child" ? 2 : 1)
228+
expect(saved.at(-1)).toMatchObject({ say: "subtask_result", childTaskId: "child" })
229+
if (previousChildId === "earlier-child") expect(saved[0].childTaskId).toBe("earlier-child")
230+
expect(reopenedParent.overwriteClineMessages).toHaveBeenCalledWith(saved, false)
231+
},
232+
)
233+
234+
it.each<ClineMessage>([
235+
{ ts: 1, type: "say", say: "text", text: "Done" },
236+
{ ts: 1, type: "say", say: "subtask_result", text: "Earlier result", childTaskId: "child" },
237+
])("appends the result after a non-duplicate last message: %j", async (previous) => {
238+
const { provider, records } = makeLinkProvider()
239+
const parent = records.get("parent")!
240+
records.set("parent", { ...parent, status: "delegated", awaitingChildId: "child", childIds: ["child"] })
241+
records.set("child", { ...parent, id: "child", parentTaskId: "parent" })
242+
vi.mocked(readTaskMessages).mockResolvedValue([previous])
243+
244+
await ClineProvider.prototype.reopenParentFromDelegation.call(provider, {
245+
parentTaskId: "parent",
246+
childTaskId: "child",
247+
completionResultSummary: "Done",
248+
})
249+
250+
const saved = vi.mocked(saveTaskMessages).mock.calls[0][0].messages
251+
expect(saved).toHaveLength(2)
252+
expect(saved.at(-1)).toMatchObject({ say: "subtask_result", childTaskId: "child" })
253+
})
254+
})

‎src/core/task-persistence/__tests__/mergeMessageSnapshots.spec.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,15 @@ describe("mergeClineMessageSnapshots", () => {
121121
])
122122
})
123123

124+
it("keeps a disk childTaskId when the matching incoming message omits the key", () => {
125+
const result = mergeClineMessageSnapshots(
126+
[{ messageId: "msg-1", ts: 1, type: "say", say: "subtask_result", text: "done", childTaskId: "child-1" }],
127+
[{ messageId: "msg-1", ts: 1, type: "say", say: "subtask_result", text: "done (updated)" }],
128+
)
129+
130+
expect(result).toEqual([expect.objectContaining({ ts: 1, text: "done (updated)", childTaskId: "child-1" })])
131+
})
132+
124133
it("returns incoming data when either snapshot is not an array", () => {
125134
expect(mergeClineMessageSnapshots(null, [{ ts: 1 }])).toEqual([{ ts: 1 }])
126135
expect(mergeClineMessageSnapshots([], "invalid")).toBe("invalid")

‎src/core/webview/ClineProvider.ts‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4259,6 +4259,44 @@ export class ClineProvider
42594259
throw err
42604260
}
42614261

4262+
// Stamp only committed delegations; rejected ones must not link to a rolled-back child.
4263+
try {
4264+
const globalStoragePath = this.contextProxy.globalStorageUri.fsPath
4265+
const parentMessages = await readTaskMessages({ taskId: parentTaskId, globalStoragePath })
4266+
for (let messageIndex = parentMessages.length - 1; messageIndex >= 0; messageIndex--) {
4267+
const candidate = parentMessages[messageIndex]
4268+
if (candidate.ask !== "tool" || !candidate.text) continue
4269+
4270+
let tool: { tool?: unknown; content?: unknown } | null
4271+
try {
4272+
tool = JSON.parse(candidate.text) as { tool?: unknown; content?: unknown } | null
4273+
} catch {
4274+
continue
4275+
}
4276+
if (tool?.tool !== "newTask") continue
4277+
4278+
// Never walk past the newest delegation and stamp an earlier rejected ask.
4279+
// startSubtask delegates without an ask, so the newest ask may belong to another delegation.
4280+
// NewTaskTool shows the raw content but delegates with one level of "\\@" unescaped.
4281+
const matchesDelegation =
4282+
typeof tool.content === "string" && tool.content.replace(/\\\\@/g, "\\@") === message
4283+
if (matchesDelegation && !candidate.childTaskId) {
4284+
candidate.childTaskId = child.taskId
4285+
await saveTaskMessages({
4286+
messages: parentMessages,
4287+
taskId: parentTaskId,
4288+
globalStoragePath,
4289+
merge: true,
4290+
})
4291+
}
4292+
break
4293+
}
4294+
} catch (error) {
4295+
this.log(
4296+
`[delegateParentAndOpenChild] Failed to save child link for parent ${parentTaskId}: ${error instanceof Error ? error.message : String(error)}`,
4297+
)
4298+
}
4299+
42624300
// 6) Start the child task now that parent metadata is safely persisted.
42634301
scheduleTask(this.taskScheduler, child, "delegateParentAndOpenChild")
42644302

@@ -4351,14 +4389,18 @@ export class ClineProvider
43514389
say: "subtask_result",
43524390
text: completionResultSummary,
43534391
ts,
4392+
childTaskId,
43544393
}
43554394
const lastParentClineMessage = parentClineMessages.at(-1)
43564395
if (
43574396
lastParentClineMessage?.type !== "say" ||
43584397
lastParentClineMessage.say !== "subtask_result" ||
4359-
lastParentClineMessage.text !== completionResultSummary
4398+
lastParentClineMessage.text !== completionResultSummary ||
4399+
(lastParentClineMessage.childTaskId !== undefined && lastParentClineMessage.childTaskId !== childTaskId)
43604400
) {
43614401
parentClineMessages.push(subtaskUiMessage)
4402+
} else {
4403+
lastParentClineMessage.childTaskId = childTaskId
43624404
}
43634405
parentClineMessages = await saveTaskMessages({
43644406
messages: parentClineMessages,

0 commit comments

Comments
 (0)