Skip to content

Commit e1c7d99

Browse files
committed
feat(opencode): add list_tasks tool to query all background tasks (#184)
1 parent fa91b4a commit e1c7d99

5 files changed

Lines changed: 241 additions & 5 deletions

File tree

‎.fork-features/manifest.json‎

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,23 +17,35 @@
1717
"packages/opencode/src/tool/task.ts",
1818
"packages/opencode/src/tool/task.txt",
1919
"packages/opencode/src/tool/check_task.ts",
20-
"packages/opencode/src/tool/check_task.txt"
20+
"packages/opencode/src/tool/check_task.txt",
21+
"packages/opencode/src/tool/list_tasks.ts",
22+
"packages/opencode/src/tool/list_tasks.txt"
23+
],
24+
"modifiedFiles": [
25+
"packages/opencode/src/session/index.ts",
26+
"packages/opencode/src/session/prompt.ts",
27+
"packages/opencode/src/tool/registry.ts"
2128
],
22-
"modifiedFiles": ["packages/opencode/src/session/index.ts", "packages/opencode/src/session/prompt.ts"],
2329
"criticalCode": [
2430
"backgroundTaskResults",
2531
"trackBackgroundTask",
2632
"cleanupSessionMaps",
2733
"formatCompletedTasksForInjection",
2834
"TaskTool",
2935
"CheckTaskTool",
30-
"Agent.get(task.agent)",
36+
"ListTasksTool",
3137
"parent_session_id",
38+
"session ownership",
39+
"filter to caller's session",
3240
"sync",
3341
"sync mode execution",
3442
"parameters.sync"
3543
],
36-
"tests": ["packages/opencode/test/tool/check_task.test.ts", "packages/opencode/test/session/async-tasks.test.ts"],
44+
"tests": [
45+
"packages/opencode/test/tool/check_task.test.ts",
46+
"packages/opencode/test/tool/list_tasks.test.ts",
47+
"packages/opencode/test/session/async-tasks.test.ts"
48+
],
3749
"upstreamTracking": {
3850
"relatedPRs": ["anomalyco/opencode#7206"],
3951
"relatedIssues": ["anomalyco/opencode#5887"],
@@ -129,7 +141,7 @@
129141
"modifiedFiles": [],
130142
"criticalCode": [],
131143
"tests": [],
132-
"upstreamTracking": {
144+
"upstream": {
133145
"absorptionSignals": []
134146
}
135147
},
@@ -189,6 +201,24 @@
189201
"task.*delegation.*restrict"
190202
]
191203
}
204+
},
205+
"list-tasks": {
206+
"status": "active",
207+
"description": "New tool to list all background tasks with their status. Exposes the internal listBackgroundTasks() function as a user-facing tool. Supports filtering by limit and including/excluding completed tasks.",
208+
"issue": "https://github.com/randomm/opencode/issues/184",
209+
"newFiles": [
210+
"packages/opencode/src/tool/list_tasks.ts",
211+
"packages/opencode/src/tool/list_tasks.txt",
212+
"packages/opencode/test/tool/list_tasks.test.ts"
213+
],
214+
"modifiedFiles": ["packages/opencode/src/tool/registry.ts"],
215+
"criticalCode": ["ListTasksTool", "listBackgroundTasks", "list_tasks"],
216+
"tests": ["packages/opencode/test/tool/list_tasks.test.ts"],
217+
"upstreamTracking": {
218+
"relatedPRs": [],
219+
"relatedIssues": [],
220+
"absorptionSignals": ["list.*tasks", "ListTasksTool", "listBackgroundTasks"]
221+
}
192222
}
193223
}
194224
}
Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
import { Tool } from "./tool"
2+
import DESCRIPTION from "./list_tasks.txt"
3+
import z from "zod"
4+
import { listBackgroundTasks, getBackgroundTaskResult, getBackgroundTaskMetadata } from "../session/async-tasks"
5+
6+
interface TaskInfo {
7+
task_id: string
8+
status: "running" | "completed" | "failed"
9+
agent?: string
10+
description?: string
11+
started_at?: string
12+
completed_at?: string
13+
}
14+
15+
interface ListTasksResult {
16+
pending: TaskInfo[]
17+
completed: TaskInfo[]
18+
total_count: number
19+
}
20+
21+
// Helper: Timestamp validation (>= 2000-01-01, sane range)
22+
function isValidTimestamp(timestamp: number): boolean {
23+
if (!timestamp || !Number.isFinite(timestamp)) {
24+
return false
25+
}
26+
const date = new Date(timestamp)
27+
return date.getFullYear() >= 2000 && date.getFullYear() <= 2100
28+
}
29+
30+
export const ListTasksTool = Tool.define("list_tasks", {
31+
description: DESCRIPTION,
32+
parameters: z.object({
33+
limit: z.number().optional().describe("Maximum number of tasks to return (default: 50)"),
34+
include_completed: z.boolean().optional().describe("Include completed tasks (default: true)"),
35+
}),
36+
async execute(params, ctx) {
37+
// CRITICAL #1: Session ownership filtering - only return tasks owned by caller's session
38+
const callerSessionId = ctx.sessionID!
39+
40+
const tasks = listBackgroundTasks()
41+
const limit = params.limit ?? 50
42+
43+
// Filter and map pending tasks
44+
const pending: TaskInfo[] = []
45+
for (const id of tasks.pending.slice(0, limit)) {
46+
const metadata = getBackgroundTaskMetadata(id)
47+
const result = getBackgroundTaskResult(id)
48+
49+
// Ownership check: filter to caller's session
50+
const ownedByCaller =
51+
metadata?.parent_session_id === callerSessionId || result?.metadata?.parent_session_id === callerSessionId
52+
53+
if (!ownedByCaller) {
54+
continue
55+
}
56+
57+
// CRITICAL #2: Timestamp validation before Date() calls
58+
let started_at: string | undefined
59+
if (metadata?.start_time && isValidTimestamp(metadata.start_time)) {
60+
started_at = new Date(metadata.start_time).toISOString()
61+
} else if (result?.time.started && isValidTimestamp(result.time.started)) {
62+
started_at = new Date(result.time.started).toISOString()
63+
}
64+
65+
pending.push({
66+
task_id: id,
67+
status: "running",
68+
agent: metadata?.agent_type,
69+
description: metadata?.description,
70+
started_at,
71+
})
72+
73+
if (pending.length >= limit) {
74+
break
75+
}
76+
}
77+
78+
// Filter and map completed tasks
79+
const completed: TaskInfo[] = []
80+
if (params.include_completed !== false) {
81+
// CRITICAL #4: Clamp slice end to prevent negative values (limit=0 case)
82+
const completedLimit = Math.max(0, limit - pending.length)
83+
84+
// CRITICAL #3: Guard against undefined values from Object.entries
85+
for (const [id, result] of Object.entries(tasks.results)) {
86+
if (!result) {
87+
continue
88+
}
89+
90+
// Ownership check: only return tasks owned by caller's session
91+
if (result.metadata?.parent_session_id !== callerSessionId) {
92+
continue
93+
}
94+
95+
// CRITICAL #5: Timestamp validation before Date() calls
96+
const has_valid_started = isValidTimestamp(result.time.started)
97+
const has_valid_completed = result.time.completed && isValidTimestamp(result.time.completed)
98+
99+
completed.push({
100+
task_id: id,
101+
status: result.status,
102+
agent: result.metadata?.agent_type,
103+
description: result.metadata?.description,
104+
started_at: has_valid_started ? new Date(result.time.started).toISOString() : undefined,
105+
completed_at: has_valid_completed ? new Date(result.time.completed).toISOString() : undefined,
106+
})
107+
108+
if (completed.length >= completedLimit) {
109+
break
110+
}
111+
}
112+
}
113+
114+
const taskResult: ListTasksResult = {
115+
pending,
116+
completed,
117+
total_count: pending.length + completed.length,
118+
}
119+
120+
return {
121+
title: `List tasks: ${taskResult.total_count} total`,
122+
output: JSON.stringify(taskResult, null, 2),
123+
metadata: {
124+
pending_count: pending.length,
125+
completed_count: completed.length,
126+
},
127+
}
128+
},
129+
})
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
List all background tasks with their status.
2+
3+
Use this tool to get an overview of all running and completed tasks without needing to know their individual IDs.
4+
5+
Parameters:
6+
- limit: Maximum number of tasks to return (default: 50)
7+
- include_completed: Whether to include completed tasks (default: true)
8+
9+
Returns:
10+
- pending: Array of running tasks with task_id, status, agent, description, started_at
11+
- completed: Array of completed/failed tasks with task_id, status, agent, description, started_at, completed_at
12+
- total_count: Total number of tasks returned
13+
14+
Example usage:
15+
List all tasks: /list_tasks
16+
List only pending tasks: /list_tasks {"include_completed": false}
17+
List up to 10 tasks: /list_tasks {"limit": 10}

‎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 { ListTasksTool } from "./list_tasks"
3031

3132
export namespace ToolRegistry {
3233
const log = Log.create({ service: "tool.registry" })
@@ -109,6 +110,7 @@ export namespace ToolRegistry {
109110
WriteTool,
110111
TaskTool,
111112
CheckTaskTool,
113+
ListTasksTool,
112114
WebFetchTool,
113115
TodoWriteTool,
114116
// TodoReadTool,
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import { describe, expect, test } from "bun:test"
2+
import { ListTasksTool } from "../../src/tool/list_tasks"
3+
import { Instance } from "../../src/project/instance"
4+
5+
describe("tool.list_tasks", () => {
6+
const ctx = {
7+
sessionID: "test-session",
8+
messageID: "",
9+
callID: "",
10+
agent: "test",
11+
abort: AbortSignal.any([]),
12+
messages: [],
13+
metadata: () => {},
14+
ask: async () => {},
15+
extra: { bypassAgentCheck: true },
16+
}
17+
18+
test("returns empty list when no tasks", async () => {
19+
await Instance.provide({
20+
directory: "/tmp/test",
21+
fn: async () => {
22+
const tool = await ListTasksTool.init()
23+
const result = await tool.execute({}, ctx)
24+
25+
const output = JSON.parse(result.output)
26+
expect(output.pending).toEqual([])
27+
expect(output.completed).toEqual([])
28+
expect(output.total_count).toBe(0)
29+
},
30+
})
31+
})
32+
33+
test("respects limit parameter", async () => {
34+
await Instance.provide({
35+
directory: "/tmp/test",
36+
fn: async () => {
37+
const tool = await ListTasksTool.init()
38+
const result = await tool.execute({ limit: 5 }, ctx)
39+
40+
const output = JSON.parse(result.output)
41+
expect(output.total_count).toBeLessThanOrEqual(5)
42+
},
43+
})
44+
})
45+
46+
test("can exclude completed tasks", async () => {
47+
await Instance.provide({
48+
directory: "/tmp/test",
49+
fn: async () => {
50+
const tool = await ListTasksTool.init()
51+
const result = await tool.execute({ include_completed: false }, ctx)
52+
53+
const output = JSON.parse(result.output)
54+
expect(output.completed).toEqual([])
55+
},
56+
})
57+
})
58+
})

0 commit comments

Comments
 (0)