Skip to content

Commit 1867dbb

Browse files
committed
1 parent 72e1216 commit 1867dbb

4 files changed

Lines changed: 146 additions & 30 deletions

File tree

‎src/__tests__/ClineProvider.delegation.spec.ts‎

Lines changed: 78 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,41 @@ const makeParentTask = () =>
5454
}) as any
5555

5656
describe("ClineProvider.delegateParentAndOpenChild()", () => {
57+
it("stops before delegation when refreshing the interrupted task's owner fails", async () => {
58+
const parentTask = makeParentTask()
59+
const historyItem: HistoryItem = {
60+
...parentHistoryItem,
61+
status: "interrupted",
62+
parentTaskId: "root",
63+
rootTaskId: "root",
64+
}
65+
const taskHistoryStore = makeStoreStub({ get: vi.fn().mockReturnValue(historyItem) })
66+
taskHistoryStore.invalidate.mockImplementation(async (id: string) => {
67+
if (id === "root") throw new Error("owner read failed")
68+
})
69+
const provider = {
70+
getCurrentTask: vi.fn(() => parentTask),
71+
createTask: vi.fn(),
72+
removeClineFromStack: vi.fn(),
73+
taskHistoryStore,
74+
// Only the boundaries reached before delegation are needed for this failure.
75+
} as unknown as ClineProvider
76+
77+
await expect(
78+
ClineProvider.prototype.delegateParentAndOpenChild.call(provider, {
79+
parentTaskId: "parent-1",
80+
message: "Do something",
81+
initialTodos: [],
82+
mode: "code",
83+
}),
84+
).rejects.toThrow("owner read failed")
85+
expect(taskHistoryStore.invalidate).toHaveBeenNthCalledWith(2, "root")
86+
expect(taskHistoryStore.atomicReadAndUpdate).not.toHaveBeenCalled()
87+
expect(provider.createTask).not.toHaveBeenCalled()
88+
expect(provider.removeClineFromStack).not.toHaveBeenCalled()
89+
expect(historyItem).toMatchObject({ status: "interrupted", parentTaskId: "root", rootTaskId: "root" })
90+
})
91+
5792
it("rejects a stale restored action before delegation side effects", async () => {
5893
const parentTask = makeParentTask()
5994
const removeClineFromStack = vi.fn()
@@ -727,7 +762,7 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
727762
expect(durableParent.awaitingChildId).toBe("child-1")
728763
})
729764

730-
it.each(["legacy", "pending", "resolved", "read-failure", "write-failure"] as const)(
765+
it.each(["legacy", "pending", "flushed", "resolved", "read-failure", "write-failure"] as const)(
731766
"rolls back without automatic action replay after a metadata failure (%s)",
732767
async (scenario) => {
733768
const persistError = new Error("parent metadata persist failed")
@@ -753,6 +788,21 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
753788
content: [{ type: "tool_use", id: "failed-action", name: "new_task", input: {} }],
754789
},
755790
]
791+
if (scenario === "flushed") {
792+
durableMessages[0].content = [
793+
{ type: "tool_use", id: "earlier-action", name: "read_file", input: {} },
794+
{ type: "tool_use", id: "failed-action", name: "new_task", input: {} },
795+
]
796+
durableMessages.push({
797+
role: "user",
798+
ts: 123,
799+
messageId: "flushed-turn",
800+
content: [
801+
{ type: "tool_result", tool_use_id: "earlier-action", content: "File contents" },
802+
{ type: "text", text: "Continue with the subtask" },
803+
],
804+
})
805+
}
756806
if (scenario === "resolved") {
757807
durableMessages.push({
758808
role: "user",
@@ -784,7 +834,14 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
784834
// A rehydrated Task must find a durable result before it can replay the action.
785835
expect(durableMessages.at(-1)).toMatchObject({
786836
role: "user",
787-
content: [{ type: "tool_result", tool_use_id: pendingAction.actionId, is_error: true }],
837+
content: expect.arrayContaining([
838+
{
839+
type: "tool_result",
840+
tool_use_id: pendingAction.actionId,
841+
is_error: true,
842+
content: expect.any(String),
843+
},
844+
]),
788845
})
789846
}
790847
})
@@ -842,8 +899,26 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
842899
expect(createTaskWithHistoryItem).toHaveBeenCalledExactlyOnceWith(historyItem)
843900
}
844901
expect(saveApiMessages).toHaveBeenCalledTimes(
845-
scenario === "pending" || scenario === "write-failure" ? 1 : 0,
902+
scenario === "pending" || scenario === "flushed" || scenario === "write-failure" ? 1 : 0,
846903
)
904+
if (scenario === "flushed") {
905+
expect(durableMessages).toHaveLength(2)
906+
expect(durableMessages[1]).toEqual({
907+
role: "user",
908+
ts: 123,
909+
messageId: "flushed-turn",
910+
content: [
911+
{ type: "tool_result", tool_use_id: "earlier-action", content: "File contents" },
912+
{
913+
type: "tool_result",
914+
tool_use_id: "failed-action",
915+
content: "Subtask creation failed: parent metadata persist failed",
916+
is_error: true,
917+
},
918+
{ type: "text", text: "Continue with the subtask" },
919+
],
920+
})
921+
}
847922
if (scenario === "pending") {
848923
expect(durableMessages).toHaveLength(2)
849924
expect(durableMessages[1]).toMatchObject({

‎src/core/task-persistence/TaskHistoryStore.ts‎

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -756,17 +756,13 @@ export class TaskHistoryStore {
756756
*/
757757
async invalidate(taskId: string): Promise<void> {
758758
return this.withLock(async () => {
759-
try {
760-
const item = await this.readTaskFile(taskId)
761-
if (item) {
762-
this.cache.set(taskId, item)
763-
} else {
764-
this.cache.delete(taskId)
765-
}
766-
this.taskFileMtimes.delete(taskId)
767-
} catch {
759+
const item = await this.readTaskFile(taskId)
760+
if (item) {
761+
this.cache.set(taskId, item)
762+
} else {
768763
this.cache.delete(taskId)
769764
}
765+
this.taskFileMtimes.delete(taskId)
770766
})
771767
}
772768

@@ -877,9 +873,11 @@ export class TaskHistoryStore {
877873
try {
878874
const raw = await fs.readFile(filePath, "utf8")
879875
const item: HistoryItem = JSON.parse(raw)
880-
return item.id ? item : null
881-
} catch {
882-
return null
876+
if (!item?.id) throw new Error(`Invalid task history record: ${filePath}`)
877+
return item
878+
} catch (error) {
879+
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") return null
880+
throw error
883881
}
884882
}
885883

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

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,33 @@ describe("TaskHistoryStore", () => {
9393
})
9494
})
9595

96+
describe("invalidate()", () => {
97+
it.each(["malformed", "invalid-record", "read-error", "missing"] as const)(
98+
"preserves cached ownership unless the record is missing (%s)",
99+
async (scenario) => {
100+
await store.initialize()
101+
store.dispose() // Keep filesystem watcher reconciliation out of this explicit refresh test.
102+
const owner = makeHistoryItem({ id: "owner", status: "delegated", awaitingChildId: "child" })
103+
await store.upsert(owner)
104+
const filePath = path.join(tmpDir, "tasks", "owner", GlobalFileNames.historyItem)
105+
if (scenario === "malformed" || scenario === "invalid-record") {
106+
await fs.writeFile(filePath, scenario === "malformed" ? "{" : "{}")
107+
} else {
108+
await fs.unlink(filePath)
109+
if (scenario === "read-error") await fs.mkdir(filePath)
110+
}
111+
112+
if (scenario === "missing") {
113+
await expect(store.invalidate("owner")).resolves.toBeUndefined()
114+
expect(store.get("owner")).toBeUndefined()
115+
} else {
116+
await expect(store.invalidate("owner")).rejects.toThrow()
117+
expect(store.get("owner")).toEqual(owner)
118+
}
119+
},
120+
)
121+
})
122+
96123
describe("pending action persistence", () => {
97124
it("persists set and clear operations across store reinitialization", async () => {
98125
await store.initialize()

‎src/core/webview/ClineProvider.ts‎

Lines changed: 31 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4089,25 +4089,41 @@ export class ClineProvider
40894089
),
40904090
)
40914091
if (!hasResult) {
4092+
const result: Anthropic.ToolResultBlockParam = {
4093+
type: "tool_result",
4094+
tool_use_id: pendingActionId,
4095+
content: `Subtask creation failed: ${err instanceof Error ? err.message : String(err)}`,
4096+
is_error: true,
4097+
}
4098+
const toolUseIndex = messages.findIndex(
4099+
(message) =>
4100+
message.role === "assistant" &&
4101+
Array.isArray(message.content) &&
4102+
message.content.some(
4103+
(block) => block.type === "tool_use" && block.id === pendingActionId,
4104+
),
4105+
)
4106+
const nextMessage = toolUseIndex === -1 ? undefined : messages[toolUseIndex + 1]
4107+
if (nextMessage?.role === "user") {
4108+
const content =
4109+
typeof nextMessage.content === "string"
4110+
? [{ type: "text" as const, text: nextMessage.content }]
4111+
: [...nextMessage.content]
4112+
const firstNonTool = content.findIndex((block) => block.type !== "tool_result")
4113+
content.splice(firstNonTool === -1 ? content.length : firstNonTool, 0, result)
4114+
messages[toolUseIndex + 1] = { ...nextMessage, content }
4115+
} else {
4116+
messages.splice(toolUseIndex === -1 ? messages.length : toolUseIndex + 1, 0, {
4117+
role: "user",
4118+
ts: Date.now(),
4119+
content: [result],
4120+
})
4121+
}
40924122
await saveApiMessages({
40934123
taskId: parentTaskId,
40944124
globalStoragePath,
40954125
merge: true,
4096-
messages: [
4097-
...messages,
4098-
{
4099-
role: "user",
4100-
ts: Date.now(),
4101-
content: [
4102-
{
4103-
type: "tool_result",
4104-
tool_use_id: pendingActionId,
4105-
content: `Subtask creation failed: ${err instanceof Error ? err.message : String(err)}`,
4106-
is_error: true,
4107-
},
4108-
],
4109-
},
4110-
],
4126+
messages,
41114127
})
41124128
}
41134129
}

0 commit comments

Comments
 (0)