diff --git a/packages/core/src/flag/flag.ts b/packages/core/src/flag/flag.ts index f76d1aaf9d22..f8b704819b61 100644 --- a/packages/core/src/flag/flag.ts +++ b/packages/core/src/flag/flag.ts @@ -72,6 +72,8 @@ export const Flag = { OPENCODE_EXPERIMENTAL_LSP_TOOL: OPENCODE_EXPERIMENTAL || truthy("OPENCODE_EXPERIMENTAL_LSP_TOOL"), OPENCODE_EXPERIMENTAL_PLAN_MODE: OPENCODE_EXPERIMENTAL || truthy("OPENCODE_EXPERIMENTAL_PLAN_MODE"), OPENCODE_EXPERIMENTAL_SCOUT: OPENCODE_EXPERIMENTAL || truthy("OPENCODE_EXPERIMENTAL_SCOUT"), + OPENCODE_EXPERIMENTAL_BACKGROUND_AGENTS: + OPENCODE_EXPERIMENTAL || truthy("OPENCODE_EXPERIMENTAL_BACKGROUND_AGENTS"), OPENCODE_EXPERIMENTAL_MARKDOWN: !falsy("OPENCODE_EXPERIMENTAL_MARKDOWN"), OPENCODE_ENABLE_PARALLEL: truthy("OPENCODE_ENABLE_PARALLEL") || truthy("OPENCODE_EXPERIMENTAL_PARALLEL"), OPENCODE_MODELS_URL: process.env["OPENCODE_MODELS_URL"], diff --git a/packages/opencode/src/cli/cmd/tui/routes/session/index.tsx b/packages/opencode/src/cli/cmd/tui/routes/session/index.tsx index 95d1b072f1eb..ee6d45de1117 100644 --- a/packages/opencode/src/cli/cmd/tui/routes/session/index.tsx +++ b/packages/opencode/src/cli/cmd/tui/routes/session/index.tsx @@ -2028,7 +2028,9 @@ function Task(props: ToolProps) { const content = createMemo(() => { if (!props.input.description) return "" - let content = [`${Locale.titlecase(props.input.subagent_type ?? "General")} Task — ${props.input.description}`] + const description = + props.metadata.background === true ? `${props.input.description} (background)` : props.input.description + let content = [`${Locale.titlecase(props.input.subagent_type ?? "General")} Task — ${description}`] if (isRunning() && tools().length > 0) { // content[0] += ` · ${tools().length} toolcalls` @@ -2040,7 +2042,11 @@ function Task(props: ToolProps) { } if (props.part.state.status === "completed") { - content.push(`└ ${tools().length} toolcalls · ${Locale.duration(duration())}`) + content.push( + props.metadata.background === true + ? `└ ${tools().length} toolcalls` + : `└ ${tools().length} toolcalls · ${Locale.duration(duration())}`, + ) } return content.join("\n") diff --git a/packages/opencode/src/session/prompt.ts b/packages/opencode/src/session/prompt.ts index 15246dac394d..47381b8d0a90 100644 --- a/packages/opencode/src/session/prompt.ts +++ b/packages/opencode/src/session/prompt.ts @@ -210,6 +210,7 @@ export const layer = Layer.effect( cancel: (sessionID: SessionID) => cancel(sessionID), resolvePromptParts: (template: string) => resolvePromptParts(template), prompt: (input: PromptInput) => prompt(input), + loop: (input: LoopInput) => loop(input), } satisfies TaskPromptOps }) diff --git a/packages/opencode/src/session/run-state.ts b/packages/opencode/src/session/run-state.ts index 9d4986f17436..2983521a9e2b 100644 --- a/packages/opencode/src/session/run-state.ts +++ b/packages/opencode/src/session/run-state.ts @@ -1,5 +1,6 @@ import { InstanceState } from "@/effect/instance-state" import { Runner } from "@/effect/runner" +import { BackgroundJob } from "@/background/job" import { Effect, Latch, Layer, Scope, Context } from "effect" import * as Session from "./session" import { MessageV2 } from "./message-v2" @@ -27,6 +28,7 @@ export class Service extends Context.Service()("@opencode/Se export const layer = Layer.effect( Service, Effect.gen(function* () { + const background = yield* BackgroundJob.Service const status = yield* SessionStatus.Service const state = yield* InstanceState.make( @@ -75,6 +77,7 @@ export const layer = Layer.effect( }) const cancel = Effect.fn("SessionRunState.cancel")(function* (sessionID: SessionID) { + yield* cancelBackgroundJobs(background, sessionID) const data = yield* InstanceState.get(state) const existing = data.runners.get(sessionID) if (!existing || !existing.busy) { @@ -105,6 +108,40 @@ export const layer = Layer.effect( }), ) -export const defaultLayer = layer.pipe(Layer.provide(SessionStatus.defaultLayer)) +export const defaultLayer = layer.pipe(Layer.provide(BackgroundJob.defaultLayer), Layer.provide(SessionStatus.defaultLayer)) + +const cancelBackgroundJobs = Effect.fn("SessionRunState.cancelBackgroundJobs")(function* ( + background: BackgroundJob.Interface, + sessionID: SessionID, +) { + const jobs = yield* background.list() + const pending = new Set([sessionID]) + const cancelled = new Set() + const matches = (job: BackgroundJob.Info) => { + if (job.status !== "running") return false + if (cancelled.has(job.id)) return false + if (pending.has(job.id)) return true + if (typeof job.metadata?.sessionId === "string" && pending.has(job.metadata.sessionId)) return true + return typeof job.metadata?.parentSessionId === "string" && pending.has(job.metadata.parentSessionId) + } + let batch = jobs.filter(matches) + while (batch.length > 0) { + yield* Effect.forEach( + batch, + (job) => + background.cancel(job.id).pipe( + Effect.tap(() => + Effect.sync(() => { + cancelled.add(job.id) + pending.add(job.id) + if (typeof job.metadata?.sessionId === "string") pending.add(job.metadata.sessionId) + }), + ), + ), + { concurrency: "unbounded", discard: true }, + ) + batch = jobs.filter(matches) + } +}) export * as SessionRunState from "./run-state" diff --git a/packages/opencode/src/session/session.ts b/packages/opencode/src/session/session.ts index eff027579abf..2a6a9dc65c51 100644 --- a/packages/opencode/src/session/session.ts +++ b/packages/opencode/src/session/session.ts @@ -1,5 +1,6 @@ import { Slug } from "@opencode-ai/core/util/slug" import path from "path" +import { BackgroundJob } from "@/background/job" import { BusEvent } from "@/bus/bus-event" import { Bus } from "@/bus" import { Decimal } from "decimal.js" @@ -503,9 +504,10 @@ export type Patch = Types.DeepMutable["dat const db = (fn: (d: Parameters[0] extends (trx: infer D) => any ? D : never) => T) => Effect.sync(() => Database.use(fn)) -export const layer: Layer.Layer = Layer.effect( +export const layer: Layer.Layer = Layer.effect( Service, Effect.gen(function* () { + const background = yield* BackgroundJob.Service const bus = yield* Bus.Service const storage = yield* Storage.Service const sync = yield* SyncEvent.Service @@ -583,6 +585,7 @@ export const layer: Layer.Layer { + if (job.status !== "running") return false + if (job.id === sessionID) return true + if (job.metadata?.sessionId === sessionID) return true + return job.metadata?.parentSessionId === sessionID + }), + (job) => background.cancel(job.id), + { concurrency: "unbounded", discard: true }, + ) +}) + function* listByProject( input: ListInput & { projectID: ProjectID diff --git a/packages/opencode/src/tool/registry.ts b/packages/opencode/src/tool/registry.ts index f72f10dd1f74..d28daec5f9bd 100644 --- a/packages/opencode/src/tool/registry.ts +++ b/packages/opencode/src/tool/registry.ts @@ -7,6 +7,7 @@ import { GlobTool } from "./glob" import { GrepTool } from "./grep" import { ReadTool } from "./read" import { TaskTool } from "./task" +import { TaskStatusTool } from "./task_status" import { TodoWriteTool } from "./todo" import { WebFetchTool } from "./webfetch" import { WriteTool } from "./write" @@ -50,6 +51,8 @@ import { Git } from "@/git" import { Skill } from "../skill" import { Permission } from "@/permission" import { Reference } from "@/reference/reference" +import { BackgroundJob } from "@/background/job" +import { SessionStatus } from "@/session/status" const log = Log.create({ service: "tool.registry" }) @@ -89,6 +92,8 @@ export const layer: Layer.Layer< | Agent.Service | Skill.Service | Session.Service + | SessionStatus.Service + | BackgroundJob.Service | Provider.Service | Git.Service | Reference.Service @@ -112,6 +117,7 @@ export const layer: Layer.Layer< const invalid = yield* InvalidTool const task = yield* TaskTool + const taskStatus = yield* TaskStatusTool const read = yield* ReadTool const question = yield* QuestionTool const todo = yield* TodoWriteTool @@ -219,6 +225,7 @@ export const layer: Layer.Layer< edit: Tool.init(edit), write: Tool.init(writetool), task: Tool.init(task), + task_status: Tool.init(taskStatus), fetch: Tool.init(webfetch), todo: Tool.init(todo), search: Tool.init(websearch), @@ -243,6 +250,7 @@ export const layer: Layer.Layer< tool.edit, tool.write, tool.task, + ...(Flag.OPENCODE_EXPERIMENTAL_BACKGROUND_AGENTS ? [tool.task_status] : []), tool.fetch, tool.todo, tool.search, @@ -366,6 +374,7 @@ export const defaultLayer = Layer.suspend(() => Layer.provide(Skill.defaultLayer), Layer.provide(Agent.defaultLayer), Layer.provide(Session.defaultLayer), + Layer.provide(Layer.mergeAll(SessionStatus.defaultLayer, BackgroundJob.defaultLayer)), Layer.provide(Provider.defaultLayer), Layer.provide(Git.defaultLayer), Layer.provide(Reference.defaultLayer), diff --git a/packages/opencode/src/tool/task.ts b/packages/opencode/src/tool/task.ts index c4d5bf7f4aee..0a6800245cd7 100644 --- a/packages/opencode/src/tool/task.ts +++ b/packages/opencode/src/tool/task.ts @@ -1,23 +1,41 @@ import * as Tool from "./tool" import DESCRIPTION from "./task.txt" +import { ToolJsonSchema } from "./json-schema" +import { BackgroundJob } from "@/background/job" +import { Bus } from "@/bus" import { Session } from "@/session/session" import { SessionID, MessageID } from "../session/schema" import { MessageV2 } from "../session/message-v2" import { Agent } from "../agent/agent" import { deriveSubagentSessionPermission } from "../agent/subagent-permissions" import type { SessionPrompt } from "../session/prompt" +import { SessionStatus } from "@/session/status" import { Config } from "@/config/config" -import { Effect, Exit, Schema } from "effect" +import { TuiEvent } from "@/cli/cmd/tui/event" +import { Cause, Effect, Exit, Option, Schema, Scope } from "effect" import { EffectBridge } from "@/effect/bridge" +import { Flag } from "@opencode-ai/core/flag/flag" export interface TaskPromptOps { cancel(sessionID: SessionID): Effect.Effect resolvePromptParts(template: string): Effect.Effect prompt(input: SessionPrompt.PromptInput): Effect.Effect + loop(input: SessionPrompt.LoopInput): Effect.Effect } const id = "task" +const BaseParameters = Schema.Struct({ + description: Schema.String.annotate({ description: "A short (3-5 words) description of the task" }), + prompt: Schema.String.annotate({ description: "The task for the agent to perform" }), + subagent_type: Schema.String.annotate({ description: "The type of specialized agent to use for this task" }), + task_id: Schema.optional(Schema.String).annotate({ + description: + "This should only be set if you mean to resume a previous task (you can pass a prior task_id and the task will continue the same subagent session as before instead of creating a fresh one)", + }), + command: Schema.optional(Schema.String).annotate({ description: "The command that triggered this task" }), +}) + export const Parameters = Schema.Struct({ description: Schema.String.annotate({ description: "A short (3-5 words) description of the task" }), prompt: Schema.String.annotate({ description: "The task for the agent to perform" }), @@ -27,20 +45,68 @@ export const Parameters = Schema.Struct({ "This should only be set if you mean to resume a previous task (you can pass a prior task_id and the task will continue the same subagent session as before instead of creating a fresh one)", }), command: Schema.optional(Schema.String).annotate({ description: "The command that triggered this task" }), + background: Schema.optional(Schema.Boolean).annotate({ + description: "When true, launch the subagent in the background and return immediately", + }), }) +function output(sessionID: SessionID, text: string) { + return [ + `task_id: ${sessionID} (for resuming to continue this task if needed)`, + "", + "", + text, + "", + ].join("\n") +} + +function backgroundOutput(sessionID: SessionID) { + return [ + `task_id: ${sessionID} (for polling this task with task_status)`, + "state: running", + "", + "", + "Background task started. Continue your current work and call task_status when you need the result.", + "", + ].join("\n") +} + +function backgroundMessage(input: { sessionID: SessionID; description: string; state: "completed" | "error"; text: string }) { + const tag = input.state === "completed" ? "task_result" : "task_error" + const title = + input.state === "completed" + ? `Background task completed: ${input.description}` + : `Background task failed: ${input.description}` + return [title, `task_id: ${input.sessionID}`, `state: ${input.state}`, "", `<${tag}>`, input.text, ``].join( + "\n", + ) +} + +function errorText(error: unknown) { + if (error instanceof Error) return error.message + return String(error) +} + export const TaskTool = Tool.define( id, Effect.gen(function* () { const agent = yield* Agent.Service + const background = yield* BackgroundJob.Service + const bus = yield* Bus.Service const config = yield* Config.Service const sessions = yield* Session.Service + const scope = yield* Scope.Scope + const status = yield* SessionStatus.Service const run = Effect.fn("TaskTool.execute")(function* ( params: Schema.Schema.Type, ctx: Tool.Context, ) { const cfg = yield* config.get() + const runInBackground = params.background === true + if (runInBackground && !Flag.OPENCODE_EXPERIMENTAL_BACKGROUND_AGENTS) { + return yield* Effect.fail(new Error("Background agents require OPENCODE_EXPERIMENTAL_BACKGROUND_AGENTS=true")) + } if (!ctx.extra?.bypassAgentCheck) { yield* ctx.ask({ @@ -93,20 +159,125 @@ export const TaskTool = Tool.define( modelID: msg.info.modelID, providerID: msg.info.providerID, } + const metadata = { + parentSessionId: ctx.sessionID, + sessionId: nextSession.id, + model, + ...(runInBackground ? { background: true } : {}), + } yield* ctx.metadata({ title: params.description, - metadata: { - sessionId: nextSession.id, - model, - }, + metadata, }) const ops = ctx.extra?.promptOps as TaskPromptOps if (!ops) return yield* Effect.fail(new Error("TaskTool requires promptOps in ctx.extra")) const runCancel = yield* EffectBridge.make() - const messageID = MessageID.ascending() + const runTask = Effect.fn("TaskTool.runTask")(function* () { + const parts = yield* ops.resolvePromptParts(params.prompt) + const result = yield* ops.prompt({ + messageID: MessageID.ascending(), + sessionID: nextSession.id, + model: { + modelID: model.modelID, + providerID: model.providerID, + }, + agent: next.name, + tools: { + ...(next.permission.some((rule) => rule.permission === "todowrite") ? {} : { todowrite: false }), + ...(next.permission.some((rule) => rule.permission === id) ? {} : { task: false }), + ...Object.fromEntries((cfg.experimental?.primary_tools ?? []).map((item) => [item, false])), + }, + parts, + }) + return result.parts.findLast((item) => item.type === "text")?.text ?? "" + }) + + const resumeWhenIdle: (input: { userID: MessageID; state: "completed" | "error" }) => Effect.Effect = Effect.fn( + "TaskTool.resumeWhenIdle", + )(function* (input: { userID: MessageID; state: "completed" | "error" }) { + const latest = yield* sessions.findMessage(ctx.sessionID, (item) => item.info.role === "user") + if (Option.isNone(latest)) return + if (latest.value.info.id !== input.userID) return + if ((yield* status.get(ctx.sessionID)).type !== "idle") { + yield* Effect.sleep("300 millis") + return yield* resumeWhenIdle(input) + } + yield* bus.publish(TuiEvent.ToastShow, { + title: input.state === "completed" ? "Background task complete" : "Background task failed", + message: + input.state === "completed" + ? `Background task "${params.description}" finished. Resuming the main thread.` + : `Background task "${params.description}" failed. Resuming the main thread.`, + variant: input.state === "completed" ? "success" : "error", + duration: 5000, + }) + yield* ops.loop({ sessionID: ctx.sessionID }).pipe(Effect.ignore, Effect.forkIn(scope, { startImmediately: true })) + }) + + const continueIfIdle = Effect.fn("TaskTool.continueIfIdle")(function* (input: { + userID: MessageID + state: "completed" | "error" + }) { + yield* resumeWhenIdle(input).pipe(Effect.ignore, Effect.forkIn(scope, { startImmediately: true })) + }) + + const inject = Effect.fn("TaskTool.injectBackgroundResult")(function* (state: "completed" | "error", text: string) { + const currentParent = yield* sessions.get(ctx.sessionID) + const message = yield* ops.prompt({ + sessionID: ctx.sessionID, + noReply: true, + agent: currentParent.agent ?? ctx.agent, + parts: [ + { + type: "text", + synthetic: true, + text: backgroundMessage({ + sessionID: nextSession.id, + description: params.description, + state, + text, + }), + }, + ], + }) + yield* continueIfIdle({ userID: message.info.id, state }) + }) + + const existing = yield* background.get(nextSession.id) + if (existing?.status === "running") { + return yield* Effect.fail(new Error(`Task ${nextSession.id} is already running. Use task_status to check progress.`)) + } + + if (runInBackground) { + const info = yield* background.start({ + id: nextSession.id, + type: id, + title: params.description, + metadata, + run: runTask().pipe( + Effect.tap((text) => inject("completed", text).pipe(Effect.ignore)), + Effect.catchCause((cause) => + (Cause.hasInterruptsOnly(cause) + ? Effect.void + : inject("error", errorText(Cause.squash(cause))).pipe(Effect.ignore) + ).pipe(Effect.andThen(Effect.failCause(cause))), + ), + ), + }) + + return { + title: params.description, + metadata: { + ...metadata, + jobId: info.id, + }, + output: backgroundOutput(nextSession.id), + } + } + const cancel = ops.cancel(nextSession.id) function onAbort() { @@ -119,36 +290,11 @@ export const TaskTool = Tool.define( }), () => Effect.gen(function* () { - const parts = yield* ops.resolvePromptParts(params.prompt) - const result = yield* ops.prompt({ - messageID, - sessionID: nextSession.id, - model: { - modelID: model.modelID, - providerID: model.providerID, - }, - agent: next.name, - tools: { - ...(next.permission.some((rule) => rule.permission === "todowrite") ? {} : { todowrite: false }), - ...(next.permission.some((rule) => rule.permission === id) ? {} : { task: false }), - ...Object.fromEntries((cfg.experimental?.primary_tools ?? []).map((item) => [item, false])), - }, - parts, - }) - + const text = yield* runTask() return { title: params.description, - metadata: { - sessionId: nextSession.id, - model, - }, - output: [ - `task_id: ${nextSession.id} (for resuming to continue this task if needed)`, - "", - "", - result.parts.findLast((item) => item.type === "text")?.text ?? "", - "", - ].join("\n"), + metadata, + output: output(nextSession.id, text), } }), (_, exit) => @@ -167,6 +313,7 @@ export const TaskTool = Tool.define( return { description: DESCRIPTION, parameters: Parameters, + jsonSchema: Flag.OPENCODE_EXPERIMENTAL_BACKGROUND_AGENTS ? undefined : ToolJsonSchema.fromSchema(BaseParameters), execute: (params: Schema.Schema.Type, ctx: Tool.Context) => run(params, ctx).pipe(Effect.orDie), } diff --git a/packages/opencode/src/tool/task.txt b/packages/opencode/src/tool/task.txt index fba8470d1b4b..89d3218a8ab8 100644 --- a/packages/opencode/src/tool/task.txt +++ b/packages/opencode/src/tool/task.txt @@ -15,10 +15,11 @@ When NOT to use the Task tool: Usage notes: 1. Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses 2. When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result. The output includes a task_id you can reuse later to continue the same subagent session. -3. Each agent invocation starts with a fresh context unless you provide task_id to resume the same subagent session (which continues with its previous messages and tool outputs). When starting fresh, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you. -4. The agent's outputs should generally be trusted -5. Clearly tell the agent whether you expect it to write code or just to do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent. Tell it how to verify its work if possible (e.g., relevant test commands). -6. If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement. +3. If OPENCODE_EXPERIMENTAL_BACKGROUND_AGENTS is enabled, background=true launches the subagent asynchronously. Use task_status(task_id=..., wait=false) to poll, or wait=true to block until done. +4. Each agent invocation starts with a fresh context unless you provide task_id to resume the same subagent session (which continues with its previous messages and tool outputs). When starting fresh, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you. +5. The agent's outputs should generally be trusted +6. Clearly tell the agent whether you expect it to write code or just to do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent. Tell it how to verify its work if possible (e.g., relevant test commands). +7. If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement. Example usage (NOTE: The agents below are fictional examples for illustration only - use the actual agents listed above): diff --git a/packages/opencode/src/tool/task_status.ts b/packages/opencode/src/tool/task_status.ts new file mode 100644 index 000000000000..23233fbcd2d4 --- /dev/null +++ b/packages/opencode/src/tool/task_status.ts @@ -0,0 +1,166 @@ +import * as Tool from "./tool" +import DESCRIPTION from "./task_status.txt" +import { BackgroundJob } from "@/background/job" +import { Session } from "@/session/session" +import { MessageV2 } from "@/session/message-v2" +import { SessionID } from "@/session/schema" +import { SessionStatus } from "@/session/status" +import { PositiveInt } from "@opencode-ai/core/schema" +import { Flag } from "@opencode-ai/core/flag/flag" +import { Effect, Option, Schema } from "effect" + +const DEFAULT_TIMEOUT = 60_000 +const POLL_MS = 300 + +const Parameters = Schema.Struct({ + task_id: SessionID.annotate({ description: "The task_id returned by the task tool" }), + wait: Schema.optional(Schema.Boolean).annotate({ description: "When true, wait until the task reaches a terminal state or timeout" }), + timeout_ms: Schema.optional(PositiveInt).annotate({ + description: "Maximum milliseconds to wait when wait=true (default: 60000)", + }), +}) + +type State = BackgroundJob.Status +type InspectResult = { state: State; text: string } + +function format(input: { taskID: SessionID; state: State; text: string }) { + const tag = input.state === "completed" || input.state === "running" ? "task_result" : "task_error" + return [`task_id: ${input.taskID}`, `state: ${input.state}`, "", `<${tag}>`, input.text, ``].join("\n") +} + +function errorText(error: NonNullable) { + const data = Reflect.get(error, "data") + const message = data && typeof data === "object" ? Reflect.get(data, "message") : undefined + if (typeof message === "string" && message) return message + return error.name +} + +function inspectMessage(message: MessageV2.WithParts): InspectResult | undefined { + if (message.info.role !== "assistant") return + const text = message.parts.findLast((part) => part.type === "text")?.text ?? "" + if (message.info.error) return { state: "error", text: text || errorText(message.info.error) } + if (message.info.finish && !["tool-calls", "unknown"].includes(message.info.finish)) return { state: "completed", text } + return { state: "running", text: text || "Task is still running." } +} + +export const TaskStatusTool = Tool.define( + "task_status", + Effect.gen(function* () { + const jobs = yield* BackgroundJob.Service + const sessions = yield* Session.Service + const status = yield* SessionStatus.Service + + const inspect: (taskID: SessionID) => Effect.Effect = Effect.fn("TaskStatusTool.inspect")(function* (taskID: SessionID) { + const job = yield* jobs.get(taskID) + if (job) { + return { + state: job.status, + text: + job.output ?? + job.error ?? + (job.status === "running" + ? "Task is still running." + : job.status === "cancelled" + ? "Task was cancelled." + : ""), + } + } + + const current = yield* status.get(taskID) + if (current.type === "busy" || current.type === "retry") { + return { + state: "running", + text: current.type === "retry" ? `Task is retrying: ${current.message}` : "Task is still running.", + } + } + + const latestAssistant = yield* sessions.findMessage(taskID, (item) => item.info.role === "assistant") + if (Option.isSome(latestAssistant)) { + const latest = inspectMessage(latestAssistant.value) + if (!latest) return { state: "error", text: "Task is not running in this process." } + if (latest.state === "running") return { state: "error", text: "Task is not running in this process and has no final output." } + return latest + } + return { state: "error", text: "Task is not running in this process and has not produced output." } + }) + + const waitForTerminal: (taskID: SessionID, timeout: number) => Effect.Effect<{ result: InspectResult; timedOut: boolean }> = Effect.fn( + "TaskStatusTool.waitForTerminal", + )(function* (taskID: SessionID, timeout: number) { + const result = yield* inspect(taskID) + if (result.state !== "running") return { result, timedOut: false } + if (timeout <= 0) return { result, timedOut: true } + const sleep = Math.min(POLL_MS, timeout) + yield* Effect.sleep(`${sleep} millis`) + return yield* waitForTerminal(taskID, timeout - sleep) + }) + + const run = Effect.fn("TaskStatusTool.execute")(function* ( + params: Schema.Schema.Type, + _ctx: Tool.Context, + ) { + if (!Flag.OPENCODE_EXPERIMENTAL_BACKGROUND_AGENTS) { + return yield* Effect.fail(new Error("task_status requires OPENCODE_EXPERIMENTAL_BACKGROUND_AGENTS=true")) + } + + const session = yield* sessions.get(params.task_id).pipe(Effect.catchCause(() => Effect.succeed(undefined))) + if (!session) { + return { + title: "Task status", + metadata: { + task_id: params.task_id, + state: "error" as const, + timed_out: false, + }, + output: format({ + taskID: params.task_id, + state: "error", + text: `Task not found: ${params.task_id}`, + }), + } + } + + const waited = + params.wait === true + ? yield* jobs.wait({ id: params.task_id, timeout: params.timeout_ms ?? DEFAULT_TIMEOUT }) + : { info: yield* jobs.get(params.task_id), timedOut: false } + const inspected = waited.info + ? { + result: { + state: waited.info.status, + text: + waited.info.output ?? + waited.info.error ?? + (waited.info.status === "running" ? "Task is still running." : ""), + }, + timedOut: waited.timedOut, + } + : params.wait === true + ? yield* waitForTerminal(params.task_id, params.timeout_ms ?? DEFAULT_TIMEOUT) + : { result: yield* inspect(params.task_id), timedOut: false } + const text = inspected.timedOut + ? `Timed out after ${params.timeout_ms ?? DEFAULT_TIMEOUT}ms while waiting for task completion.` + : inspected.result.text + + return { + title: "Task status", + metadata: { + task_id: params.task_id, + state: inspected.result.state, + timed_out: inspected.timedOut, + }, + output: format({ + taskID: params.task_id, + state: inspected.result.state, + text, + }), + } + }) + + return { + description: DESCRIPTION, + parameters: Parameters, + execute: (params: Schema.Schema.Type, ctx: Tool.Context) => run(params, ctx).pipe(Effect.orDie), + } + }), +) diff --git a/packages/opencode/src/tool/task_status.txt b/packages/opencode/src/tool/task_status.txt new file mode 100644 index 000000000000..ed6fa727b2a9 --- /dev/null +++ b/packages/opencode/src/tool/task_status.txt @@ -0,0 +1,13 @@ +Poll the status of a background subagent task launched with the task tool. + +Use this for tasks started with `task(background=true)`. + +Parameters: +- `task_id` (required): the task session id returned by the task tool +- `wait` (optional): when true, wait for completion +- `timeout_ms` (optional): max wait duration in milliseconds when `wait=true` + +Returns compact, parseable output: +- `task_id` +- `state` (`running`, `completed`, `error`, or `cancelled`) +- `...` or `...` containing final output, error summary, or current progress text diff --git a/packages/opencode/test/session/prompt.test.ts b/packages/opencode/test/session/prompt.test.ts index 3821954945f5..07615ca5d6b7 100644 --- a/packages/opencode/test/session/prompt.test.ts +++ b/packages/opencode/test/session/prompt.test.ts @@ -7,6 +7,7 @@ import path from "path" import { fileURLToPath, pathToFileURL } from "url" import { NamedError } from "@opencode-ai/core/util/error" import { Agent as AgentSvc } from "../../src/agent/agent" +import { BackgroundJob } from "@/background/job" import { Bus } from "../../src/bus" import { Command } from "../../src/command" import { Config } from "@/config/config" @@ -175,6 +176,7 @@ function makeHttp() { lsp, mcp, AppFileSystem.defaultLayer, + BackgroundJob.defaultLayer, status, SyncEvent.defaultLayer, ).pipe(Layer.provideMerge(infra)) diff --git a/packages/opencode/test/session/snapshot-tool-race.test.ts b/packages/opencode/test/session/snapshot-tool-race.test.ts index 8640612e9825..292f821c424f 100644 --- a/packages/opencode/test/session/snapshot-tool-race.test.ts +++ b/packages/opencode/test/session/snapshot-tool-race.test.ts @@ -30,6 +30,7 @@ import { TestLLMServer } from "../lib/llm-server" // Same layer setup as prompt-effect.test.ts import { NodeFileSystem } from "@effect/platform-node" import { Agent as AgentSvc } from "../../src/agent/agent" +import { BackgroundJob } from "@/background/job" import { Git } from "../../src/git" import { Bus } from "../../src/bus" import { Command } from "../../src/command" @@ -124,6 +125,7 @@ function makeHttp() { lsp, mcp, AppFileSystem.defaultLayer, + BackgroundJob.defaultLayer, status, SyncEvent.defaultLayer, ).pipe(Layer.provideMerge(infra)) diff --git a/packages/opencode/test/tool/__snapshots__/parameters.test.ts.snap b/packages/opencode/test/tool/__snapshots__/parameters.test.ts.snap index d6c1bc45d884..9fede8175929 100644 --- a/packages/opencode/test/tool/__snapshots__/parameters.test.ts.snap +++ b/packages/opencode/test/tool/__snapshots__/parameters.test.ts.snap @@ -319,6 +319,10 @@ exports[`tool parameters JSON Schema (wire shape) task 1`] = ` { "$schema": "https://json-schema.org/draft/2020-12/schema", "properties": { + "background": { + "description": "When true, launch the subagent in the background and return immediately", + "type": "boolean", + }, "command": { "description": "The command that triggered this task", "type": "string", diff --git a/packages/opencode/test/tool/parameters.test.ts b/packages/opencode/test/tool/parameters.test.ts index 8b2dc9a74dd0..3a124be81b0c 100644 --- a/packages/opencode/test/tool/parameters.test.ts +++ b/packages/opencode/test/tool/parameters.test.ts @@ -235,6 +235,10 @@ describe("tool parameters", () => { const parsed = parse(Task, { description: "d", prompt: "p", subagent_type: "general" }) expect(parsed.subagent_type).toBe("general") }) + test("accepts optional background flag", () => { + const parsed = parse(Task, { description: "d", prompt: "p", subagent_type: "general", background: true }) + expect(parsed.background).toBe(true) + }) test("rejects missing prompt", () => { expect(accepts(Task, { description: "d", subagent_type: "general" })).toBe(false) }) diff --git a/packages/opencode/test/tool/registry.test.ts b/packages/opencode/test/tool/registry.test.ts index 5ee56300c454..3720492afee1 100644 --- a/packages/opencode/test/tool/registry.test.ts +++ b/packages/opencode/test/tool/registry.test.ts @@ -15,7 +15,9 @@ import { Question } from "@/question" import { Todo } from "@/session/todo" import { Skill } from "@/skill" import { Agent } from "@/agent/agent" +import { BackgroundJob } from "@/background/job" import { Session } from "@/session/session" +import { SessionStatus } from "@/session/status" import { Provider } from "@/provider/provider" import { Git } from "@/git" import { LSP } from "@/lsp/lsp" @@ -32,6 +34,7 @@ import { ToolJsonSchema } from "@/tool/json-schema" const node = CrossSpawnSpawner.defaultLayer const originalExperimentalScout = Flag.OPENCODE_EXPERIMENTAL_SCOUT +const originalBackgroundAgents = Flag.OPENCODE_EXPERIMENTAL_BACKGROUND_AGENTS const configLayer = TestConfig.layer({ directories: () => InstanceState.directory.pipe(Effect.map((dir) => [path.join(dir, ".opencode")])), }) @@ -44,6 +47,7 @@ const registryLayer = ToolRegistry.layer.pipe( Layer.provide(Skill.defaultLayer), Layer.provide(Agent.defaultLayer), Layer.provide(Session.defaultLayer), + Layer.provide(Layer.mergeAll(SessionStatus.defaultLayer, BackgroundJob.defaultLayer)), Layer.provide(Provider.defaultLayer), Layer.provide(Git.defaultLayer), Layer.provide(Reference.defaultLayer), @@ -62,6 +66,7 @@ const it = testEffect(Layer.mergeAll(registryLayer, node, Agent.defaultLayer)) afterEach(async () => { Flag.OPENCODE_EXPERIMENTAL_SCOUT = originalExperimentalScout + Flag.OPENCODE_EXPERIMENTAL_BACKGROUND_AGENTS = originalBackgroundAgents await disposeAllInstances() }) @@ -88,6 +93,41 @@ describe("tool.registry", () => { }), ) + it.instance("hides task_status unless experimental background agents are enabled", () => + Effect.gen(function* () { + Flag.OPENCODE_EXPERIMENTAL_BACKGROUND_AGENTS = false + const registry = yield* ToolRegistry.Service + const ids = yield* registry.ids() + + expect(ids).not.toContain("task_status") + }), + ) + + it.instance("hides task background parameter unless experimental background agents are enabled", () => + Effect.gen(function* () { + Flag.OPENCODE_EXPERIMENTAL_BACKGROUND_AGENTS = false + const registry = yield* ToolRegistry.Service + const agent = yield* Agent.Service + const build = yield* agent.get("build") + const task = (yield* registry.tools({ providerID: ProviderID.opencode, modelID: ModelID.make("test"), agent: build })).find( + (tool) => tool.id === "task", + ) + + expect(task?.jsonSchema).toBeDefined() + expect((task?.jsonSchema?.properties as Record | undefined)?.background).toBeUndefined() + }), + ) + + it.instance("shows task_status when experimental background agents are enabled", () => + Effect.gen(function* () { + Flag.OPENCODE_EXPERIMENTAL_BACKGROUND_AGENTS = true + const registry = yield* ToolRegistry.Service + const ids = yield* registry.ids() + + expect(ids).toContain("task_status") + }), + ) + it.instance("loads tools from .opencode/tool (singular)", () => Effect.gen(function* () { const test = yield* TestInstance diff --git a/packages/opencode/test/tool/task.test.ts b/packages/opencode/test/tool/task.test.ts index f75fcf84b8a9..5aa6f5f5600b 100644 --- a/packages/opencode/test/tool/task.test.ts +++ b/packages/opencode/test/tool/task.test.ts @@ -1,20 +1,28 @@ import { afterEach, describe, expect } from "bun:test" import { Effect, Exit, Fiber, Layer } from "effect" import { Agent } from "../../src/agent/agent" +import { BackgroundJob } from "@/background/job" +import { Bus } from "@/bus" import { Config } from "@/config/config" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" import { Session } from "@/session/session" import { MessageV2 } from "../../src/session/message-v2" import type { SessionPrompt } from "../../src/session/prompt" import { MessageID, PartID, SessionID } from "../../src/session/schema" +import { SessionRunState } from "@/session/run-state" +import { SessionStatus } from "@/session/status" import { ModelID, ProviderID } from "../../src/provider/schema" import { TaskTool, type TaskPromptOps } from "../../src/tool/task" import { Truncate } from "@/tool/truncate" import { ToolRegistry } from "@/tool/registry" +import { Flag } from "@opencode-ai/core/flag/flag" import { disposeAllInstances } from "../fixture/fixture" import { testEffect } from "../lib/effect" +const originalBackgroundAgents = Flag.OPENCODE_EXPERIMENTAL_BACKGROUND_AGENTS + afterEach(async () => { + Flag.OPENCODE_EXPERIMENTAL_BACKGROUND_AGENTS = originalBackgroundAgents await disposeAllInstances() }) @@ -26,9 +34,13 @@ const ref = { const it = testEffect( Layer.mergeAll( Agent.defaultLayer, + BackgroundJob.defaultLayer, + Bus.defaultLayer, Config.defaultLayer, CrossSpawnSpawner.defaultLayer, Session.defaultLayer, + SessionRunState.defaultLayer, + SessionStatus.defaultLayer, Truncate.defaultLayer, ToolRegistry.defaultLayer, ), @@ -80,6 +92,7 @@ function stubOps(opts?: { onPrompt?: (input: SessionPrompt.PromptInput) => void; opts?.onPrompt?.(input) return reply(input, opts?.text ?? "done") }), + loop: (input) => Effect.succeed(reply({ sessionID: input.sessionID, parts: [] }, opts?.text ?? "done")), } } @@ -294,6 +307,7 @@ describe("tool.task", () => { ready.resolve(input) return cancelled.promise }).pipe(Effect.as(reply(input, "cancelled"))), + loop: (input) => Effect.succeed(reply({ sessionID: input.sessionID, parts: [] }, "done")), } const fiber = yield* def @@ -432,4 +446,318 @@ describe("tool.task", () => { }, }, ) + + it.instance("rejects background execution when the experiment is disabled", () => + Effect.gen(function* () { + Flag.OPENCODE_EXPERIMENTAL_BACKGROUND_AGENTS = false + const { chat, assistant } = yield* seed() + const tool = yield* TaskTool + const def = yield* tool.init() + + const exit = yield* def + .execute( + { + description: "inspect bug", + prompt: "look into the cache key path", + subagent_type: "general", + background: true, + }, + { + sessionID: chat.id, + messageID: assistant.id, + agent: "build", + abort: new AbortController().signal, + extra: { promptOps: stubOps() }, + messages: [], + metadata: () => Effect.void, + ask: () => Effect.void, + }, + ) + .pipe(Effect.exit) + + expect(Exit.isFailure(exit)).toBe(true) + }), + ) + + it.instance("execute launches background tasks without waiting for completion", () => + Effect.gen(function* () { + Flag.OPENCODE_EXPERIMENTAL_BACKGROUND_AGENTS = true + const jobs = yield* BackgroundJob.Service + const { chat, assistant } = yield* seed() + const tool = yield* TaskTool + const def = yield* tool.init() + + const result = yield* def.execute( + { + description: "inspect bug", + prompt: "look into the cache key path", + subagent_type: "general", + background: true, + }, + { + sessionID: chat.id, + messageID: assistant.id, + agent: "build", + abort: new AbortController().signal, + extra: { + promptOps: { + ...stubOps(), + prompt: () => Effect.never, + } satisfies TaskPromptOps, + }, + messages: [], + metadata: () => Effect.void, + ask: () => Effect.void, + }, + ) + + const job = yield* jobs.get(result.metadata.sessionId) + expect(result.metadata.background).toBe(true) + expect(result.output).toContain("state: running") + expect(job?.status).toBe("running") + }), + ) + + it.instance("background tasks complete through the background job service", () => + Effect.gen(function* () { + Flag.OPENCODE_EXPERIMENTAL_BACKGROUND_AGENTS = true + const jobs = yield* BackgroundJob.Service + const { chat, assistant } = yield* seed() + const tool = yield* TaskTool + const def = yield* tool.init() + + const result = yield* def.execute( + { + description: "inspect bug", + prompt: "look into the cache key path", + subagent_type: "general", + background: true, + }, + { + sessionID: chat.id, + messageID: assistant.id, + agent: "build", + abort: new AbortController().signal, + extra: { promptOps: stubOps({ text: "background done" }) }, + messages: [], + metadata: () => Effect.void, + ask: () => Effect.void, + }, + ) + + const waited = yield* jobs.wait({ id: result.metadata.sessionId, timeout: 1_000 }) + expect(waited.timedOut).toBe(false) + expect(waited.info?.status).toBe("completed") + expect(waited.info?.output).toBe("background done") + }), + ) + + it.instance("background task completion does not wait for the parent resume loop", () => + Effect.gen(function* () { + Flag.OPENCODE_EXPERIMENTAL_BACKGROUND_AGENTS = true + const jobs = yield* BackgroundJob.Service + const sessions = yield* Session.Service + const { chat, assistant } = yield* seed() + const tool = yield* TaskTool + const def = yield* tool.init() + + const result = yield* def.execute( + { + description: "inspect bug", + prompt: "look into the cache key path", + subagent_type: "general", + background: true, + }, + { + sessionID: chat.id, + messageID: assistant.id, + agent: "build", + abort: new AbortController().signal, + extra: { + promptOps: { + ...stubOps({ text: "background done" }), + prompt: (input) => + input.noReply + ? Effect.gen(function* () { + const user = yield* sessions.updateMessage({ + id: input.messageID ?? MessageID.ascending(), + role: "user", + sessionID: input.sessionID, + agent: input.agent ?? "build", + model: input.model ?? ref, + time: { created: Date.now() }, + }) + const parts = input.parts.map((part) => ({ + ...part, + id: part.id ?? PartID.ascending(), + messageID: user.id, + sessionID: input.sessionID, + })) + yield* Effect.forEach(parts, (part) => sessions.updatePart(part), { discard: true }) + return { info: user, parts } + }) + : Effect.succeed(reply(input, "background done")), + loop: () => Effect.never, + } satisfies TaskPromptOps, + }, + messages: [], + metadata: () => Effect.void, + ask: () => Effect.void, + }, + ) + + const waited = yield* jobs.wait({ id: result.metadata.sessionId, timeout: 1_000 }) + expect(waited.timedOut).toBe(false) + expect(waited.info?.status).toBe("completed") + }), + ) + + it.instance("removing the parent session cancels running background tasks", () => + Effect.gen(function* () { + Flag.OPENCODE_EXPERIMENTAL_BACKGROUND_AGENTS = true + const jobs = yield* BackgroundJob.Service + const sessions = yield* Session.Service + const { chat, assistant } = yield* seed() + const tool = yield* TaskTool + const def = yield* tool.init() + + const result = yield* def.execute( + { + description: "inspect bug", + prompt: "look into the cache key path", + subagent_type: "general", + background: true, + }, + { + sessionID: chat.id, + messageID: assistant.id, + agent: "build", + abort: new AbortController().signal, + extra: { + promptOps: { + ...stubOps(), + prompt: () => Effect.never, + } satisfies TaskPromptOps, + }, + messages: [], + metadata: () => Effect.void, + ask: () => Effect.void, + }, + ) + + yield* sessions.remove(chat.id) + const waited = yield* jobs.wait({ id: result.metadata.sessionId, timeout: 1_000 }) + expect(waited.timedOut).toBe(false) + expect(waited.info?.status).toBe("cancelled") + }), + ) + + it.instance("removing the child task session cancels its running background task", () => + Effect.gen(function* () { + Flag.OPENCODE_EXPERIMENTAL_BACKGROUND_AGENTS = true + const jobs = yield* BackgroundJob.Service + const sessions = yield* Session.Service + const { chat, assistant } = yield* seed() + const tool = yield* TaskTool + const def = yield* tool.init() + + const result = yield* def.execute( + { + description: "inspect bug", + prompt: "look into the cache key path", + subagent_type: "general", + background: true, + }, + { + sessionID: chat.id, + messageID: assistant.id, + agent: "build", + abort: new AbortController().signal, + extra: { + promptOps: { + ...stubOps(), + prompt: () => Effect.never, + } satisfies TaskPromptOps, + }, + messages: [], + metadata: () => Effect.void, + ask: () => Effect.void, + }, + ) + + yield* sessions.remove(result.metadata.sessionId) + const waited = yield* jobs.wait({ id: result.metadata.sessionId, timeout: 1_000 }) + expect(waited.timedOut).toBe(false) + expect(waited.info?.status).toBe("cancelled") + }), + ) + + it.instance("cancelling the parent run cancels running background tasks", () => + Effect.gen(function* () { + Flag.OPENCODE_EXPERIMENTAL_BACKGROUND_AGENTS = true + const jobs = yield* BackgroundJob.Service + const runState = yield* SessionRunState.Service + const { chat, assistant } = yield* seed() + const tool = yield* TaskTool + const def = yield* tool.init() + + const result = yield* def.execute( + { + description: "inspect bug", + prompt: "look into the cache key path", + subagent_type: "general", + background: true, + }, + { + sessionID: chat.id, + messageID: assistant.id, + agent: "build", + abort: new AbortController().signal, + extra: { + promptOps: { + ...stubOps(), + prompt: () => Effect.never, + } satisfies TaskPromptOps, + }, + messages: [], + metadata: () => Effect.void, + ask: () => Effect.void, + }, + ) + + yield* runState.cancel(chat.id) + const waited = yield* jobs.wait({ id: result.metadata.sessionId, timeout: 1_000 }) + expect(waited.timedOut).toBe(false) + expect(waited.info?.status).toBe("cancelled") + }), + ) + + it.instance("cancelling a parent run recursively cancels descendant background tasks", () => + Effect.gen(function* () { + const jobs = yield* BackgroundJob.Service + const runState = yield* SessionRunState.Service + const sessions = yield* Session.Service + const { chat } = yield* seed() + const child = yield* sessions.create({ parentID: chat.id, title: "child" }) + const grandchild = yield* sessions.create({ parentID: child.id, title: "grandchild" }) + + yield* jobs.start({ + id: child.id, + type: "task", + metadata: { parentSessionId: chat.id, sessionId: child.id }, + run: Effect.never, + }) + yield* jobs.start({ + id: grandchild.id, + type: "task", + metadata: { parentSessionId: child.id, sessionId: grandchild.id }, + run: Effect.never, + }) + + yield* runState.cancel(chat.id) + + expect((yield* jobs.get(child.id))?.status).toBe("cancelled") + expect((yield* jobs.get(grandchild.id))?.status).toBe("cancelled") + }), + ) }) diff --git a/packages/opencode/test/tool/task_status.test.ts b/packages/opencode/test/tool/task_status.test.ts new file mode 100644 index 000000000000..448f24e76680 --- /dev/null +++ b/packages/opencode/test/tool/task_status.test.ts @@ -0,0 +1,95 @@ +import { afterEach, describe, expect } from "bun:test" +import { Effect, Layer } from "effect" +import { Agent } from "@/agent/agent" +import { BackgroundJob } from "@/background/job" +import { Bus } from "@/bus" +import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" +import { Session } from "@/session/session" +import { MessageID } from "@/session/schema" +import { SessionStatus } from "@/session/status" +import { TaskStatusTool } from "@/tool/task_status" +import { Truncate } from "@/tool/truncate" +import { Flag } from "@opencode-ai/core/flag/flag" +import { disposeAllInstances } from "../fixture/fixture" +import { testEffect } from "../lib/effect" + +const originalBackgroundAgents = Flag.OPENCODE_EXPERIMENTAL_BACKGROUND_AGENTS + +afterEach(async () => { + Flag.OPENCODE_EXPERIMENTAL_BACKGROUND_AGENTS = originalBackgroundAgents + await disposeAllInstances() +}) + +const it = testEffect( + Layer.mergeAll( + Agent.defaultLayer, + BackgroundJob.defaultLayer, + Bus.defaultLayer, + CrossSpawnSpawner.defaultLayer, + Session.defaultLayer, + SessionStatus.defaultLayer, + Truncate.defaultLayer, + ), +) + +describe("tool.task_status", () => { + it.instance("returns completed background job output", () => + Effect.gen(function* () { + Flag.OPENCODE_EXPERIMENTAL_BACKGROUND_AGENTS = true + const jobs = yield* BackgroundJob.Service + const sessions = yield* Session.Service + const tool = yield* TaskStatusTool + const def = yield* tool.init() + const chat = yield* sessions.create({}) + + yield* jobs.start({ id: chat.id, type: "task", run: Effect.succeed("all done") }) + + const result = yield* def.execute( + { task_id: chat.id, wait: true, timeout_ms: 1_000 }, + { + sessionID: chat.id, + messageID: MessageID.ascending(), + agent: "build", + abort: new AbortController().signal, + messages: [], + metadata: () => Effect.void, + ask: () => Effect.void, + }, + ) + + expect(result.output).toContain("state: completed") + expect(result.output).toContain("all done") + expect(result.metadata.timed_out).toBe(false) + }), + ) + + it.instance("wait=true times out while the background job is running", () => + Effect.gen(function* () { + Flag.OPENCODE_EXPERIMENTAL_BACKGROUND_AGENTS = true + const jobs = yield* BackgroundJob.Service + const sessions = yield* Session.Service + const tool = yield* TaskStatusTool + const def = yield* tool.init() + const chat = yield* sessions.create({}) + + yield* jobs.start({ id: chat.id, type: "task", run: Effect.never }) + + const result = yield* def.execute( + { task_id: chat.id, wait: true, timeout_ms: 50 }, + { + sessionID: chat.id, + messageID: MessageID.ascending(), + agent: "build", + abort: new AbortController().signal, + messages: [], + metadata: () => Effect.void, + ask: () => Effect.void, + }, + ) + + expect(result.output).toContain("state: running") + expect(result.output).toContain("Timed out after 50ms") + expect(result.metadata.timed_out).toBe(true) + }), + ) +}) diff --git a/packages/ui/src/components/message-part.tsx b/packages/ui/src/components/message-part.tsx index 35598a170c3e..d347af646012 100644 --- a/packages/ui/src/components/message-part.tsx +++ b/packages/ui/src/components/message-part.tsx @@ -1738,9 +1738,10 @@ ToolRegistry.register({ const title = createMemo(() => agent().name ?? i18n.t("ui.tool.agent.default")) const tone = createMemo(() => agent().color) const subtitle = createMemo(() => { - const value = props.input.description - if (typeof value === "string" && value) return value - return childSessionId() + const value = typeof props.input.description === "string" && props.input.description ? props.input.description : childSessionId() + if (!value) return value + if (props.metadata.background === true) return `${value} (background)` + return value }) const running = createMemo(() => props.status === "pending" || props.status === "running")