Skip to content

Commit 50ff042

Browse files
committed
feat(tool): add cancel_task for stopping background tasks (#54)
1 parent 75ddfd0 commit 50ff042

5 files changed

Lines changed: 187 additions & 1 deletion

File tree

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { Tool } from "./tool"
2+
import DESCRIPTION from "./cancel_task.txt"
3+
import z from "zod"
4+
import { Session } from "../session"
5+
6+
type CancellationStatus = "cancelled" | "not_found" | "already_completed"
7+
8+
interface CancelTaskResult {
9+
task_id: string
10+
status: CancellationStatus
11+
message?: string
12+
}
13+
14+
interface CancelTaskMetadata {
15+
status: CancellationStatus
16+
taskId?: string
17+
}
18+
19+
export const CancelTaskTool = Tool.define<z.ZodObject<{ task_id: z.ZodString }>, CancelTaskMetadata>("cancel_task", {
20+
description: DESCRIPTION,
21+
parameters: z.object({
22+
task_id: z
23+
.string()
24+
.min(1)
25+
.max(100)
26+
.regex(/^[a-zA-Z0-9_-]+$/)
27+
.describe("The ID of the background task to cancel"),
28+
}),
29+
async execute(params) {
30+
const result = Session.tryCancel(params.task_id)
31+
32+
const response: CancelTaskResult = {
33+
task_id: params.task_id,
34+
status: result.status,
35+
message: result.message,
36+
}
37+
38+
return {
39+
title: `Cancel task: ${params.task_id}`,
40+
output: JSON.stringify(response, null, 2),
41+
metadata: {
42+
status: result.status,
43+
taskId: params.task_id,
44+
},
45+
}
46+
},
47+
})
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
- Stop a running background task by its ID
2+
- Returns the cancellation status: "cancelled", "not_found", or "already_completed"
3+
- Use this tool to cancel tasks that are taking too long or are no longer needed
4+
- Note: Only running tasks can be cancelled; completed or failed tasks cannot be cancelled

‎packages/opencode/src/tool/check_task.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { Instance } from "../project/instance"
66
import { SessionStatus } from "../session/status"
77
import { MessageV2 } from "../session/message-v2"
88

9-
type TaskStatus = "running" | "completed" | "failed" | "not_found"
9+
type TaskStatus = "running" | "completed" | "failed" | "not_found" | "cancelled"
1010

1111
interface TaskResult {
1212
task_id: string

‎packages/opencode/src/tool/registry.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import { Truncate } from "./truncation"
2727
import { PlanExitTool, PlanEnterTool } from "./plan"
2828
import { ApplyPatchTool } from "./apply_patch"
2929
import { CheckTaskTool } from "./check_task"
30+
import { CancelTaskTool } from "./cancel_task"
3031

3132
export namespace ToolRegistry {
3233
const log = Log.create({ service: "tool.registry" })
@@ -103,6 +104,7 @@ export namespace ToolRegistry {
103104
WriteTool,
104105
TaskTool,
105106
CheckTaskTool,
107+
CancelTaskTool,
106108
WebFetchTool,
107109
TodoWriteTool,
108110
TodoReadTool,
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
import { describe, expect, test } from "bun:test"
2+
import { CancelTaskTool } from "../../src/tool/cancel_task"
3+
import { Instance } from "../../src/project/instance"
4+
import { Session } from "../../src/session"
5+
import { tmpdir } from "../fixture/fixture"
6+
7+
const ctx = {
8+
sessionID: "test",
9+
messageID: "",
10+
callID: "",
11+
agent: "build",
12+
abort: AbortSignal.any([]),
13+
metadata: () => {},
14+
ask: async () => {},
15+
}
16+
17+
describe("tool.cancel_task", () => {
18+
test("returns not_found for non-existent task", async () => {
19+
await Instance.provide({
20+
directory: "/tmp/test",
21+
fn: async () => {
22+
const tool = await CancelTaskTool.init()
23+
const result = await tool.execute({ task_id: "non-existent" }, ctx)
24+
25+
const output = JSON.parse(result.output)
26+
expect(output.status).toBe("not_found")
27+
expect(output.task_id).toBe("non-existent")
28+
expect(output.message).toContain("not found")
29+
expect(result.metadata.status).toBe("not_found")
30+
},
31+
})
32+
})
33+
34+
test("returns already_completed for completed task", async () => {
35+
await using tmp = await tmpdir({ git: true })
36+
await Instance.provide({
37+
directory: tmp.path,
38+
fn: async () => {
39+
const tool = await CancelTaskTool.init()
40+
const taskId = "test-task-completed"
41+
42+
Session.trackBackgroundTask(taskId, Promise.resolve("Task result"), undefined, {
43+
agent_type: "test",
44+
description: "Test task",
45+
session_id: ctx.sessionID,
46+
start_time: Date.now(),
47+
})
48+
49+
await new Promise((r) => setTimeout(r, 100))
50+
51+
const result = await tool.execute({ task_id: taskId }, ctx)
52+
53+
const output = JSON.parse(result.output)
54+
expect(output.status).toBe("already_completed")
55+
expect(output.task_id).toBe(taskId)
56+
expect(output.message).toContain("cannot be cancelled")
57+
expect(result.metadata.status).toBe("already_completed")
58+
},
59+
})
60+
})
61+
62+
test("cancels a running task", async () => {
63+
await using tmp = await tmpdir({ git: true })
64+
await Instance.provide({
65+
directory: tmp.path,
66+
fn: async () => {
67+
const tool = await CancelTaskTool.init()
68+
const taskId = "test-task-running"
69+
let taskStarted = false
70+
71+
const promise = new Promise<string>((resolve) => {
72+
taskStarted = true
73+
setTimeout(() => resolve("Should not complete"), 10000)
74+
})
75+
76+
Session.trackBackgroundTask(taskId, promise, undefined, {
77+
agent_type: "test",
78+
description: "Test task",
79+
session_id: ctx.sessionID,
80+
start_time: Date.now(),
81+
})
82+
83+
await new Promise((r) => setTimeout(r, 50))
84+
85+
const result = await tool.execute({ task_id: taskId }, ctx)
86+
87+
const output = JSON.parse(result.output)
88+
expect(output.status).toBe("cancelled")
89+
expect(output.task_id).toBe(taskId)
90+
expect(output.message).toContain("cancelled")
91+
expect(result.metadata.status).toBe("cancelled")
92+
},
93+
})
94+
})
95+
96+
test("validates input with Zod schema", async () => {
97+
await Instance.provide({
98+
directory: "/tmp/test",
99+
fn: async () => {
100+
const tool = await CancelTaskTool.init()
101+
102+
const parameters = tool.parameters
103+
expect(parameters).toBeDefined()
104+
105+
const valid = parameters.safeParse({ task_id: "test-id" })
106+
expect(valid.success).toBe(true)
107+
108+
const invalidEmpty = parameters.safeParse({ task_id: "" })
109+
expect(invalidEmpty.success).toBe(false)
110+
111+
const invalidSpecialChars = parameters.safeParse({ task_id: "test@id" })
112+
expect(invalidSpecialChars.success).toBe(false)
113+
114+
const validWithHyphen = parameters.safeParse({ task_id: "test-id-123" })
115+
expect(validWithHyphen.success).toBe(true)
116+
117+
const validWithUnderscore = parameters.safeParse({ task_id: "test_id_123" })
118+
expect(validWithUnderscore.success).toBe(true)
119+
},
120+
})
121+
})
122+
123+
test("has correct tool description", async () => {
124+
await Instance.provide({
125+
directory: "/tmp/test",
126+
fn: async () => {
127+
const tool = await CancelTaskTool.init()
128+
expect(tool.description).toContain("Stop a running background task")
129+
expect(tool.description).toContain("cancelled")
130+
},
131+
})
132+
})
133+
})

0 commit comments

Comments
 (0)