From a7bfbc5ea042d2f27b42d4d93cd9bbf7f5f2bdaa Mon Sep 17 00:00:00 2001 From: James Long Date: Tue, 17 Nov 2026 02:03:53 +0000 Subject: [PATCH 1/5] feat(core): background slow Code Mode scripts behind full_codemode User decisions: - Background a Code Mode script as a job after about 10 seconds - Not durable across restarts yet - Deliver its result the same way background subagents and shells do - No status, wait or cancel APIs yet - Leave permission prompts and client display for later --- packages/cli/src/run/noninteractive.ts | 5 +- .../client/src/promise/generated/types.ts | 13 +- packages/core/src/codemode/job.ts | 131 ++++++++++++++++++ packages/core/src/job.ts | 17 ++- packages/core/src/job/list.ts | 9 ++ packages/core/src/job/recovery.ts | 9 +- packages/core/src/permission.ts | 33 ++++- packages/core/src/plugin/goal.ts | 7 +- packages/core/src/session/background.ts | 1 + packages/core/src/session/execution.ts | 10 +- .../core/src/session/execution/restart.ts | 2 + packages/core/src/session/session.ts | 55 +------- .../core/src/session/subagent-completion.ts | 1 + packages/core/src/session/synthetic.ts | 49 +++++++ packages/core/src/tool.ts | 8 +- packages/core/test/subagent-idle-e2e.test.ts | 100 ++++++++++++- packages/plugin/src/effect/session.ts | 1 + packages/plugin/src/promise/session.ts | 1 + packages/protocol/openapi.json | 33 ++++- packages/protocol/src/groups/job.ts | 2 +- packages/schema/src/job.ts | 9 +- 21 files changed, 420 insertions(+), 76 deletions(-) create mode 100644 packages/core/src/codemode/job.ts create mode 100644 packages/core/src/session/synthetic.ts diff --git a/packages/cli/src/run/noninteractive.ts b/packages/cli/src/run/noninteractive.ts index ee8db3ee71cb..7e30b34e9f14 100644 --- a/packages/cli/src/run/noninteractive.ts +++ b/packages/cli/src/run/noninteractive.ts @@ -277,8 +277,9 @@ export async function runNonInteractivePrompt(input: Input) { const ended = state.ended.promise await input.client.experimental.session.wait({ sessionID: input.sessionID }) const pending = await background() - // Image jobs can't be cancelled through the API, so waiting on them would only hold the exit. - if (!pending || (pending.length > 0 && pending.every((job) => job.kind === "image"))) return + // Wait only for work this client can stop. + if (!pending || (pending.length > 0 && pending.every((job) => job.kind !== "shell" && job.kind !== "subagent"))) + return await ended } } diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index 17578146c2bd..a6a62e36cc2a 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -996,6 +996,15 @@ export type JobImage = { model: string } +export type JobCodeMode = { + kind: "codemode" + id: string + sessionID: SessionID + status: JobStatus + title?: string + time: JobTime +} + export type VcsInfo = { provider?: string; branch: VcsBranch } export type WebSearchProvider = { id: WebSearchID; name: string } @@ -2294,7 +2303,7 @@ export type AutomationTrigger = export type ArtifactContent = { info: ArtifactInfo; files: { [x: string]: string } } -export type JobInfo = JobShell | JobSubagent | JobImage +export type JobInfo = JobShell | JobSubagent | JobImage | JobCodeMode export type SessionInboxMove = { id: SessionMessageID @@ -4778,7 +4787,7 @@ export type ExperimentalArtifactsViewOutput = globalThis.Uint8Array export type ExperimentalJobListInput = { readonly sessionID?: string | undefined - readonly kind?: ("shell" | "subagent" | "image") | undefined + readonly kind?: ("shell" | "subagent" | "image" | "codemode") | undefined readonly status?: ("running" | "completed" | "error" | "cancelled") | undefined readonly descendants?: boolean | undefined } diff --git a/packages/core/src/codemode/job.ts b/packages/core/src/codemode/job.ts new file mode 100644 index 000000000000..cbb124628f95 --- /dev/null +++ b/packages/core/src/codemode/job.ts @@ -0,0 +1,131 @@ +export * as CodeModeJob from "./job.js" + +import { Identifier } from "@opencode/schema/identifier" +import { Cause, Context, Deferred, Effect, Exit, Option, type Scope, Semaphore } from "effect" +import { extension } from "mime-types" +import { Flag } from "../flag.js" +import { Job } from "../job.js" +import { Permission } from "../permission.js" +import type { Session } from "../session.js" +import type { Tool } from "../tool.js" +import { ToolOutput } from "../tool-output.js" + +export function notice(job: Pick) { + const state = job.status === "running" ? "cancelled" : job.status + const body = job.status === "running" ? "Interrupted by server restart." : (job.output ?? job.error ?? state) + return { + description: "Code Mode script", + text: `\n${body}\n`, + metadata: { source: "codemode", jobID: job.id, state }, + } +} + +type Execute = (context: Tool.Context) => Effect.Effect +type Run = (context: Tool.Context, execute: Execute) => ReturnType + +/** Only a session drain can hand off work and report its result. */ +export const Current = Context.Reference("@opencode/CodeModeJob", { defaultValue: () => undefined }) + +export const make = Effect.fnUntraced(function* ( + jobs: Job.Interface, + synthetic: Session.Interface["synthetic"], + scope: Scope.Scope, +) { + const location = Context.pick( + Flag.Service, + ToolOutput.Service, + )(yield* Effect.context()) + + return Effect.fn("CodeModeJob.execute")(function* (context: Tool.Context, execute: Execute) { + if (!(yield* Flag.enabled("full_codemode"))) return yield* execute(context) + const output = yield* ToolOutput.Service + const id = `cm_${Identifier.ascending()}` + const sessionID = context.sessionID + const result = yield* Deferred.make() + const detached = yield* Deferred.make() + const progress = Semaphore.makeUnsafe(1) + return yield* Effect.uninterruptibleMask((restore) => + Effect.gen(function* () { + yield* jobs.start({ + id, + type: "codemode", + title: "Code Mode script", + recovery: { kind: "codemode", sessionID, jobID: id }, + run: Effect.gen(function* () { + const exit = yield* execute({ + ...context, + progress: (update) => + progress.withPermit( + Deferred.isDone(detached).pipe( + Effect.flatMap((done) => (done ? Effect.void : context.progress(update))), + ), + ), + }).pipe( + Effect.provideService(Job.BlockingParent, id), + Effect.provideService(Permission.PromptUntil, detached), + Effect.interruptible, + Effect.exit, + ) + yield* Deferred.done(result, exit) + if (Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)) return yield* Effect.failCause(exit.cause) + const text = Exit.isFailure(exit) + ? Cause.pretty(exit.cause) + : exit.value.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n") + const bounded = yield* output.truncate({ content: [{ type: "text", text }] }) + const body = bounded.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n") + if (Exit.isFailure(exit) || exit.value.metadata?.error === true) return yield* Effect.fail(new Error(body)) + return body + }), + }) + const blocked = yield* restore(jobs.block({ id, sessionID }).pipe(Effect.timeoutOption("10 seconds"))).pipe( + Effect.onInterrupt(() => jobs.cancel(id)), + ) + if (Option.isSome(blocked) && blocked.value?.type === "finished") return yield* Deferred.await(result) + const job = yield* jobs.background(id) + if (!job?.notificationID) return yield* Effect.interrupt + const notificationID = job.notificationID + // Drain the last progress publication before the tool row becomes terminal. + yield* progress.withPermit(Deferred.succeed(detached, undefined)) + yield* Effect.gen(function* () { + const { info } = yield* jobs.wait({ id }) + // Session removal cancels the job and removes its outbox row. + if (!info || info.status === "cancelled") return + // Synthetic messages carry text. Keep the script's file results accessible without putting base64 in its inbox. + const exit = yield* Deferred.await(result).pipe(Effect.exit) + const files = Exit.isSuccess(exit) ? exit.value.content.filter((part) => part.type === "file") : [] + const paths = yield* Effect.forEach(files, (file) => { + const prefix = `data:${file.mime};base64,` + if (!file.uri.startsWith(prefix)) return Effect.succeed(file.uri) + const ext = extension(file.mime) + return output + .save(Buffer.from(file.uri.slice(prefix.length), "base64"), ext ? `.${ext}` : "") + .pipe(Effect.catchDefect(() => Effect.succeed(`Could not save ${file.mime} attachment.`))) + }) + const body = paths.length + ? yield* output.truncate({ + content: [{ type: "text", text: [info.output ?? info.error, ...paths].join("\n") }], + }) + : undefined + const message = notice( + body + ? { + ...info, + output: body.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n"), + } + : info, + ) + yield* synthetic({ id: notificationID, sessionID, ...message }).pipe( + Effect.catchTag("Session.NotFoundError", () => Effect.void), + ) + yield* jobs.completeBackground(notificationID) + }).pipe(Effect.interruptible, Effect.forkIn(scope)) + const text = `Script ${id} is still running; its result will arrive in this session.` + return { + content: [{ type: "text" as const, text }], + output: { output: text, toolCalls: [], files: [] }, + metadata: { jobID: id }, + } + }), + ) + }, Effect.provide(location)) satisfies Run +}) diff --git a/packages/core/src/job.ts b/packages/core/src/job.ts index 94252e3fa6d1..4b68a38d5df2 100644 --- a/packages/core/src/job.ts +++ b/packages/core/src/job.ts @@ -25,6 +25,11 @@ import { SessionSchema } from "./session/schema.js" export type { Recovery } +/** A session-wide background request releases the outer blocker; its nested waits keep their own deadlines. */ +export const BlockingParent = Context.Reference("@opencode/Job/BlockingParent", { + defaultValue: () => undefined, +}) + const Background = Schema.Struct({ id: Schema.String, notificationID: SessionMessage.ID, @@ -196,6 +201,7 @@ function recoveryTitle(job: Active, recovery: Recovery): string | null { if (job.info.title !== undefined) return job.info.title if (recovery.kind === "shell") return recovery.command if (recovery.kind === "subagent") return recovery.description + if (recovery.kind === "codemode") return "Code Mode script" return recovery.path } @@ -440,6 +446,7 @@ export const make = Effect.gen(function* () { }) const block: Interface["block"] = Effect.fnUntraced(function* (input) { + const parent = yield* BlockingParent const result = yield* SynchronizedRef.modify(state.jobs, (jobs): readonly [BlockStart, Map] => { const job = jobs.get(input.id) if (!job) return [{ type: "missing" }, jobs] @@ -447,10 +454,12 @@ export const make = Effect.gen(function* () { if (job.isBackgrounded) return [{ type: "backgrounded", info: snapshot(job) }, jobs] return [ { type: "wait", wait: { done: job.done, backgrounded: job.backgrounded, generation: job.scope } }, - new Map(jobs).set(input.id, { - ...job, - blockingSessions: incrementSession(job.blockingSessions, input.sessionID), - }), + parent && parent !== input.id + ? jobs + : new Map(jobs).set(input.id, { + ...job, + blockingSessions: incrementSession(job.blockingSessions, input.sessionID), + }), ] }) if (result.type === "missing") return undefined diff --git a/packages/core/src/job/list.ts b/packages/core/src/job/list.ts index 5a95ddf5a4cc..d340a1037d29 100644 --- a/packages/core/src/job/list.ts +++ b/packages/core/src/job/list.ts @@ -32,6 +32,15 @@ function toItem(input: { ...(input.completed !== undefined ? { completed: input.completed } : {}), } const recovery = input.recovery + if (recovery.kind === "codemode") + return { + kind: "codemode", + id: input.id, + sessionID: recovery.sessionID, + status: input.status, + time, + ...(title !== undefined ? { title } : {}), + } if (recovery.kind === "shell") { return { kind: "shell", diff --git a/packages/core/src/job/recovery.ts b/packages/core/src/job/recovery.ts index cfe144bb74e6..9ccfcb71bf9f 100644 --- a/packages/core/src/job/recovery.ts +++ b/packages/core/src/job/recovery.ts @@ -20,10 +20,17 @@ const subagent = { description: Schema.String, } -const OutstandingItem = Schema.Union([Shell, Image, Schema.Struct({ ...subagent, sessionID: SessionSchema.ID })]) +const CodeMode = Schema.Struct({ kind: Schema.Literal("codemode"), sessionID: SessionSchema.ID, jobID: Schema.String }) +const OutstandingItem = Schema.Union([ + Shell, + Image, + CodeMode, + Schema.Struct({ ...subagent, sessionID: SessionSchema.ID }), +]) export type OutstandingItem = typeof OutstandingItem.Type export const RecoverySchema = Schema.Union([ + CodeMode, Shell, Image, Schema.Struct({ diff --git a/packages/core/src/permission.ts b/packages/core/src/permission.ts index 319a8b2075d7..102a3b95794b 100644 --- a/packages/core/src/permission.ts +++ b/packages/core/src/permission.ts @@ -64,6 +64,11 @@ export const Unattended = Context.Reference("@op defaultValue: () => undefined, }) +/** A caller that leaves the foreground can no longer host an interactive approval. */ +export const PromptUntil = Context.Reference | undefined>("@opencode/Permission/PromptUntil", { + defaultValue: () => undefined, +}) + export class DeclinedError extends Schema.TaggedError()("Permission.DeclinedError", {}) {} export class CorrectedError extends Schema.TaggedError()("Permission.CorrectedError", { @@ -285,8 +290,34 @@ const layer = Layer.effect( }) } if (result.effect === "allow") return + const until = yield* PromptUntil + const background = () => + new BlockedError({ + rules: relevant(input, result.rules), + permission: input.action, + resources: input.resources, + reason: `Permission ${input.action} needs approval in the foreground`, + }) + if (until && (yield* Deferred.isDone(until))) return yield* background() const item = yield* create(request(input, result.message), input.agent) - return yield* restore(Deferred.await(item.deferred)).pipe( + const wait = Deferred.await(item.deferred) + return yield* restore( + until + ? Effect.raceFirst( + wait, + Deferred.await(until).pipe( + Effect.andThen( + bus.publish(Permission.Event.Replied, { + sessionID: input.sessionID, + requestID: item.request.id, + reply: "reject", + }), + ), + Effect.andThen(Effect.fail(background())), + ), + ) + : wait, + ).pipe( // Deliberate defect tunnel: leaves wrap execution in blanket `mapError`, which // must not convert a user's decline into model-facing tool output. The decline // resurfaces as a typed failure at SessionModelRequest.executeTool. A decline diff --git a/packages/core/src/plugin/goal.ts b/packages/core/src/plugin/goal.ts index 67b3daff8ff5..95ae6c2fa580 100644 --- a/packages/core/src/plugin/goal.ts +++ b/packages/core/src/plugin/goal.ts @@ -145,12 +145,9 @@ export const Plugin = define({ if (goal?.status !== "active") return if (goal.boot !== boot()) return yield* settle(sessionID, goal, "paused", "The server restarted while the goal was active") - // The Session's own running subagent or image job wakes it with its notice, and the hook runs again then. A + // The Session's own running subagent, image or script wakes it with its notice, and the hook runs again then. A // grandchild reports to its own parent, so it would never wake this Session. - if ( - background.some((work) => (work.kind === "subagent" || work.kind === "image") && work.sessionID === sessionID) - ) - return + if (background.some((work) => work.kind !== "shell" && work.sessionID === sessionID)) return if (goal.rounds >= goal.maxRounds) return yield* settle(sessionID, goal, "paused", `Reached the limit of ${goal.maxRounds} rounds`) diff --git a/packages/core/src/session/background.ts b/packages/core/src/session/background.ts index 3ba5b2bc0eb5..fe2dc924b5a4 100644 --- a/packages/core/src/session/background.ts +++ b/packages/core/src/session/background.ts @@ -43,6 +43,7 @@ export const outstanding = Effect.fnUntraced(function* ( descends(store, parents, recovery.kind === "subagent" ? recovery.parentSessionID : recovery.sessionID, sessionID), ) const items: OutstandingItem[] = owned.map((recovery) => { + if (recovery.kind === "codemode") return recovery if (recovery.kind === "shell") return { kind: "shell" as const, diff --git a/packages/core/src/session/execution.ts b/packages/core/src/session/execution.ts index 382f1f9db358..5e99b7ee54c8 100644 --- a/packages/core/src/session/execution.ts +++ b/packages/core/src/session/execution.ts @@ -2,6 +2,7 @@ export * as SessionExecution from "./execution.js" import { Cause, Context, Effect, Exit, Layer } from "effect" import { Bus } from "../bus.js" +import { CodeModeJob } from "../codemode/job.js" import { Database } from "../database/database.js" import { Job } from "../job.js" import { Instance } from "../instance/service.js" @@ -13,6 +14,7 @@ import { SessionRunCoordinator } from "./run-coordinator.js" import { SessionRunner } from "./runner/index.js" import { SessionSchema } from "./schema.js" import { SessionStore } from "./store.js" +import { SessionSynthetic } from "./synthetic.js" import { toSessionError } from "./to-session-error.js" export interface Interface { @@ -60,6 +62,7 @@ export const layer = Layer.effect( const bus = yield* Bus.Service const jobs = yield* Job.Service const inbox = yield* SessionInbox.Service + const scope = yield* Effect.scope const db = (yield* Database.Service).db const reportLifecycle = (sessionID: SessionSchema.ID, effect: Effect.Effect) => effect.pipe( @@ -85,12 +88,14 @@ export const layer = Layer.effect( const holder: { coordinator?: SessionRunCoordinator.Coordinator } = {} + const wake = (sessionID: SessionSchema.ID) => + Effect.suspend(() => (holder.coordinator ? holder.coordinator.wake(sessionID) : Effect.void)) + const background = CodeModeJob.make(jobs, SessionSynthetic.make(store, inbox, wake), scope) const subagentReport = SubagentReport.make({ store, jobs, inbox, - wake: (sessionID) => - Effect.suspend(() => (holder.coordinator ? holder.coordinator.wake(sessionID) : Effect.void)), + wake, draining: Effect.suspend, never, never>(() => holder.coordinator ? holder.coordinator.draining : Effect.succeed(new Set()), ), @@ -116,6 +121,7 @@ export const layer = Layer.effect( interruption: () => interruption(sessionID), }), ).pipe( + Effect.provideServiceEffect(CodeModeJob.Current, background), instances.provide(session), Effect.tapCause((cause) => Cause.hasInterruptsOnly(cause) diff --git a/packages/core/src/session/execution/restart.ts b/packages/core/src/session/execution/restart.ts index ef3497295d70..7ed05e0f3fc2 100644 --- a/packages/core/src/session/execution/restart.ts +++ b/packages/core/src/session/execution/restart.ts @@ -8,6 +8,7 @@ import { Bus } from "../../bus.js" import { Database } from "../../database/database.js" import { Instance } from "../../instance/service.js" import { Job } from "../../job.js" +import { CodeModeJob } from "../../codemode/job.js" import { Session } from "../../session.js" import { Shell } from "../../shell.js" import { ShellTool } from "../../tool/plugin/shell.js" @@ -117,6 +118,7 @@ export const layer = (options?: Options) => }) const restartMessage = (background: Job.Background, recovery: Exclude) => { + if (recovery.kind === "codemode") return CodeModeJob.notice(background) const state = background.status === "running" ? "cancelled" : background.status if (recovery.kind === "shell") { const text = diff --git a/packages/core/src/session/session.ts b/packages/core/src/session/session.ts index 278bd9d05519..696462314a81 100644 --- a/packages/core/src/session/session.ts +++ b/packages/core/src/session/session.ts @@ -11,14 +11,7 @@ import { Database } from "../database/database.js" import { Instance } from "../instance/service.js" import { ShellResult } from "../shell/result.js" import type { Skill } from "../skill.js" -import { - BusyError, - CompactionConflictError, - InboxConflictError, - NotFoundError, - PromptConflictError, - SyntheticConflictError, -} from "./error.js" +import { BusyError, CompactionConflictError, InboxConflictError, NotFoundError, PromptConflictError } from "./error.js" import { SessionEvent } from "./event.js" import { SessionExecution } from "./execution.js" import { SessionInbox } from "./inbox.js" @@ -29,6 +22,7 @@ import { SessionShell } from "./shell.js" import { SessionSkill } from "./skill.js" import { SessionSchema } from "./schema.js" import { SessionStore } from "./store.js" +import { SessionSynthetic } from "./synthetic.js" type PromptRequest = SessionPrompt.Input & { id?: SessionMessage.ID @@ -286,48 +280,9 @@ export const make = Effect.fn("Session.make")(function* () { yield* get(sessionID) yield* execution.resume(sessionID) }) - const synthetic = Effect.fn("Session.synthetic")( - ( - sessionID: SessionSchema.ID, - input: { - id?: SessionMessage.ID - text: string - description?: string - metadata?: Record - delivery?: SessionInbox.Delivery - resume?: boolean - }, - ) => - Effect.uninterruptible( - Effect.gen(function* () { - yield* get(sessionID) - const inputID = input.id ?? SessionMessage.ID.create() - const admittedInput = { - type: "synthetic", - payload: SessionInbox.SyntheticPayload.make({ - text: input.text, - description: input.description, - metadata: input.metadata, - }), - delivery: input.delivery ?? "steer", - } satisfies SessionInbox.Item - const admitted = yield* admission - .admit({ - id: inputID, - sessionID, - item: admittedInput, - }) - .pipe( - Effect.catchTag( - "SessionInbox.LifecycleConflict", - () => new SyntheticConflictError({ sessionID, inputID }), - ), - ) - if (input.resume !== false && !(yield* get(sessionID)).revert) yield* execution.wake(sessionID) - return admitted - }), - ), - ) + const admitSynthetic = SessionSynthetic.make(store, admission, execution.wake) + const synthetic = (sessionID: SessionSchema.ID, input: Omit[0], "sessionID">) => + admitSynthetic({ ...input, sessionID }) const interrupt = Effect.fn("Session.interrupt")( (sessionID: SessionSchema.ID, options?: { readonly resume?: boolean }) => Effect.uninterruptible(execution.interrupt(sessionID, options)), diff --git a/packages/core/src/session/subagent-completion.ts b/packages/core/src/session/subagent-completion.ts index f4a1790ae3d1..d69ed75ea984 100644 --- a/packages/core/src/session/subagent-completion.ts +++ b/packages/core/src/session/subagent-completion.ts @@ -43,6 +43,7 @@ export function formatBody( ): string { if (!background || background.length === 0) return body const lines = background.map((item) => { + if (item.kind === "codemode") return `- Code Mode script (${item.jobID})` if (item.kind === "shell") return `- shell (${item.shellID}${item.sessionID !== childSessionID ? `, in ${item.sessionID}` : ""}): ${clean(item.command)}` if (item.kind === "image") diff --git a/packages/core/src/session/synthetic.ts b/packages/core/src/session/synthetic.ts new file mode 100644 index 000000000000..d732bf43b640 --- /dev/null +++ b/packages/core/src/session/synthetic.ts @@ -0,0 +1,49 @@ +export * as SessionSynthetic from "./synthetic.js" + +import { Effect } from "effect" +import { NotFoundError, SyntheticConflictError } from "./error.js" +import { SessionInbox } from "./inbox.js" +import { SessionMessage } from "./message.js" +import type { SessionSchema } from "./schema.js" +import type { SessionStore } from "./store.js" + +export const make = ( + store: SessionStore.Interface, + inbox: SessionInbox.Interface, + wake: (id: SessionSchema.ID) => Effect.Effect, +) => + Effect.fn("Session.synthetic")(function* (input: { + sessionID: SessionSchema.ID + id?: SessionMessage.ID + text: string + description?: string + metadata?: Record + delivery?: SessionInbox.Delivery + resume?: boolean + }) { + const sessionID = input.sessionID + const get = store + .get(sessionID) + .pipe(Effect.flatMap((session) => (session ? Effect.succeed(session) : new NotFoundError({ sessionID })))) + yield* get + const id = input.id ?? SessionMessage.ID.create() + const admitted = yield* inbox + .admit({ + id, + sessionID, + item: { + type: "synthetic", + delivery: input.delivery ?? "steer", + payload: SessionInbox.SyntheticPayload.make({ + text: input.text, + description: input.description, + metadata: input.metadata, + }), + }, + }) + .pipe( + Effect.catchTag("SessionInbox.LifecycleConflict", () => new SyntheticConflictError({ sessionID, inputID: id })), + ) + if (input.resume !== false && !(yield* get).revert) yield* wake(sessionID) + return admitted + }, Effect.uninterruptible) diff --git a/packages/core/src/tool.ts b/packages/core/src/tool.ts index 9238cb81bf5a..1dd64796bfb5 100644 --- a/packages/core/src/tool.ts +++ b/packages/core/src/tool.ts @@ -9,6 +9,7 @@ import { Context, Effect, Layer, Ref, Result, Schema, SchemaIssue, Types } from import { makeLocationNode } from "@opencode/util/effect/app-node" import type { Agent } from "./agent.js" import { CodeModeCatalog } from "./codemode/catalog.js" +import { CodeModeJob } from "./codemode/job.js" import { CodeModeTool } from "./codemode/tool.js" import { Image } from "./image.js" import { Permission } from "./permission.js" @@ -325,8 +326,11 @@ const layer = Layer.effect( if (!requested && input.definitions && (direct.has(event.tool) || codeModeTool?.name === event.tool)) return yield* new Tool.Error({ message: `Tool is not available for this request: ${event.tool}` }) const name = requested?.name ?? event.tool - if (name === "execute" && codeModeTool) - return yield* executeTool(codeModeTool, name, event.input, context) + if (name === "execute" && codeModeTool) { + const run = (ctx: Tool.Context) => executeTool(codeModeTool, name, event.input, ctx) + const background = yield* CodeModeJob.Current + return yield* background ? background(context, run) : run(context) + } const tool = direct.get(name) if (tool) return yield* executeTool(tool, name, event.input, context) return yield* new Tool.Error({ diff --git a/packages/core/test/subagent-idle-e2e.test.ts b/packages/core/test/subagent-idle-e2e.test.ts index 2a1ce3fe10d9..6eb7b7a530f4 100644 --- a/packages/core/test/subagent-idle-e2e.test.ts +++ b/packages/core/test/subagent-idle-e2e.test.ts @@ -20,6 +20,7 @@ import { Provider } from "@opencode/core/provider" import { AbsolutePath } from "@opencode/core/schema" import { Session } from "@opencode/core/session" import { SessionExecution } from "@opencode/core/session/execution" +import { SessionEvent } from "@opencode/core/session/event" import { SessionRestart } from "@opencode/core/session/execution/restart" import { SessionInbox } from "@opencode/core/session/inbox" import { SessionMessage } from "@opencode/core/session/message" @@ -42,7 +43,8 @@ import { ShellSelect } from "@opencode/core/shell/select" import { makeGlobalNode, makeLocationNode } from "@opencode/util/effect/app-node" import { LayerNode } from "@opencode/util/effect/layer-node" import { Global } from "@opencode/util/global" -import { Context, Deferred, Effect, Exit, Layer, Logger, Ref, Schedule, Schema, Scope } from "effect" +import { Context, Deferred, Effect, Exit, Fiber, Layer, Logger, Ref, Schedule, Schema, Scope, Stream } from "effect" +import { TestClock } from "effect/testing" import { tempGlobalLayer } from "./fixture/global" import { offlineModels } from "./fixture/models" import { tmpdirScoped } from "./fixture/tmpdir" @@ -305,6 +307,98 @@ const waitForReports = Effect.fnUntraced(function* ( yield* app.sessions.wait(sessionID) }) +describe("Code Mode session jobs", () => { + const launch = Effect.fnUntraced(function* (enabled: boolean) { + const h = yield* harness({ config: { experimental: { full_codemode: enabled } } }) + const started = yield* Deferred.make() + const release = yield* Deferred.make() + yield* h.registry.transform((editor) => + editor.add({ + name: "hold", + description: "Wait for release", + input: Schema.Struct({}), + execute: () => + Deferred.succeed(started, undefined).pipe( + Effect.andThen(Deferred.await(release)), + Effect.as({ content: "done" }), + ), + }), + ) + yield* h.llm.push( + TestLLM.toolCall("call-execute", "execute", { + code: 'const prefix = "result: "; return prefix + await tools.hold({})', + }), + TestLLM.text("Finished the step", "receipt"), + TestLLM.text("Received the result", "ack"), + ) + yield* h.sessions.prompt({ sessionID: h.parent.id, text: "Run the script" }) + yield* Deferred.await(started) + const state = h.sessions + .context(h.parent.id) + .pipe( + Effect.map((messages) => + messages + .flatMap((message) => (message.type === "assistant" ? message.content : [])) + .find((part) => part.type === "tool" && part.id === "call-execute"), + ), + ) + return { h, state, release: Deferred.succeed(release, undefined), idle: h.sessions.wait(h.parent.id) } + }) + + for (const [name, enabled] of [ + ["a fast script returns normally", true], + ["a slow script stays in the foreground with the flag off", false], + ] as const) { + e2e.effect(name, () => + Effect.gen(function* () { + const s = yield* launch(enabled) + if (!enabled) { + yield* TestClock.adjust("11 seconds") + expect(yield* s.state).toMatchObject({ state: { status: "running" } }) + } + yield* s.release + yield* s.idle + expect(yield* s.state).toMatchObject({ + state: { status: "completed", content: [{ type: "text", text: "result: done" }] }, + }) + expect(yield* s.h.jobs.pendingBackground).toEqual([]) + }), + ) + } + + e2e.effect("a slow script returns a receipt, then wakes its session with the result", () => + Effect.gen(function* () { + const s = yield* launch(true) + yield* TestClock.adjust("10 seconds") + yield* s.idle + const [job] = yield* s.h.jobs.pendingBackground + expect(job).toMatchObject({ status: "running", recovery: { kind: "codemode", sessionID: s.h.parent.id } }) + expect(yield* s.state).toMatchObject({ + state: { + status: "completed", + content: [ + { type: "text", text: `Script ${job.id} is still running; its result will arrive in this session.` }, + ], + }, + }) + const delivered = yield* Context.get(s.h.context, Bus.Service) + .subscribe(SessionEvent.InboxDelivered) + .pipe( + Stream.filter((event) => event.data.inboxID === job.notificationID), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ) + yield* s.release + yield* Fiber.join(delivered) + yield* s.idle + const text = `\nresult: done\n` + expect((yield* s.h.llm.requests()).at(-1)?.messages).toContainEqual( + expect.objectContaining({ content: expect.arrayContaining([expect.objectContaining({ type: "text", text })]) }), + ) + }), + ) +}) + describe("subagent idle reports end to end", () => { e2e.live( "reports immediately with running background work and again after the shell exits", @@ -380,7 +474,9 @@ describe("subagent idle reports end to end", () => { }) const parent = (yield* h.llm.requests()).find((request) => request.model.id === "build") expect(parent?.messages).toContainEqual( - expect.objectContaining({ content: expect.arrayContaining([expect.objectContaining({ type: "text", text })]) }), + expect.objectContaining({ + content: expect.arrayContaining([expect.objectContaining({ type: "text", text })]), + }), ) yield* h.sessions.wait(childID) yield* h.jobs.wait({ id: childID }) diff --git a/packages/plugin/src/effect/session.ts b/packages/plugin/src/effect/session.ts index 4761f7c50f8f..6d0429b429fd 100644 --- a/packages/plugin/src/effect/session.ts +++ b/packages/plugin/src/effect/session.ts @@ -161,6 +161,7 @@ export interface SessionRetry { * the Session that owns the job: the idle Session itself, or a descendant such as a subagent child. */ export type SessionIdleBackground = + | { readonly kind: "codemode"; readonly sessionID: Session.ID; readonly jobID: string } | { readonly kind: "shell" readonly sessionID: Session.ID diff --git a/packages/plugin/src/promise/session.ts b/packages/plugin/src/promise/session.ts index 93f7a0d69df3..4fd80c187730 100644 --- a/packages/plugin/src/promise/session.ts +++ b/packages/plugin/src/promise/session.ts @@ -161,6 +161,7 @@ export interface SessionRetry { * the Session that owns the job: the idle Session itself, or a descendant such as a subagent child. */ export type SessionIdleBackground = + | { readonly kind: "codemode"; readonly sessionID: Session.ID; readonly jobID: string } | { readonly kind: "shell" readonly sessionID: Session.ID diff --git a/packages/protocol/openapi.json b/packages/protocol/openapi.json index 7f738dfc2c04..1e241a9bfa20 100644 --- a/packages/protocol/openapi.json +++ b/packages/protocol/openapi.json @@ -13659,7 +13659,7 @@ "$ref": "#/components/schemas/Job.Kind" } ], - "description": "Filter by background job kind (shell, subagent, or image)." + "description": "Filter by background job kind." }, "required": false }, @@ -20812,6 +20812,32 @@ "required": ["_tag", "message"], "additionalProperties": false }, + "Job.CodeMode": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": ["codemode"] + }, + "id": { + "type": "string" + }, + "sessionID": { + "$ref": "#/components/schemas/Session.ID" + }, + "status": { + "$ref": "#/components/schemas/Job.Status" + }, + "title": { + "type": "string" + }, + "time": { + "$ref": "#/components/schemas/Job.Time" + } + }, + "required": ["kind", "id", "sessionID", "status", "time"], + "additionalProperties": false + }, "Job.Image": { "type": "object", "properties": { @@ -20854,12 +20880,15 @@ }, { "$ref": "#/components/schemas/Job.Image" + }, + { + "$ref": "#/components/schemas/Job.CodeMode" } ] }, "Job.Kind": { "type": "string", - "enum": ["shell", "subagent", "image"] + "enum": ["shell", "subagent", "image", "codemode"] }, "Job.Shell": { "type": "object", diff --git a/packages/protocol/src/groups/job.ts b/packages/protocol/src/groups/job.ts index 0981ef3f48b9..3d9f65ff01d5 100644 --- a/packages/protocol/src/groups/job.ts +++ b/packages/protocol/src/groups/job.ts @@ -16,7 +16,7 @@ export const ListQuery = Schema.Struct({ description: "Filter to background jobs owned by this session.", }), kind: Schema.optional(Job.Kind).annotate({ - description: "Filter by background job kind (shell, subagent, or image).", + description: "Filter by background job kind.", }), status: Schema.optional(Job.Status).annotate({ description: "Filter by job status (running, completed, error, or cancelled).", diff --git a/packages/schema/src/job.ts b/packages/schema/src/job.ts index 4587906dcaf7..bfaecd686992 100644 --- a/packages/schema/src/job.ts +++ b/packages/schema/src/job.ts @@ -4,7 +4,7 @@ import { Schema } from "effect" import { optional } from "./schema.js" import { SessionID } from "./session-id.js" -export const Kind = Schema.Literals(["shell", "subagent", "image"]).annotate({ identifier: "Job.Kind" }) +export const Kind = Schema.Literals(["shell", "subagent", "image", "codemode"]).annotate({ identifier: "Job.Kind" }) export type Kind = typeof Kind.Type export const Status = Schema.Literals(["running", "completed", "error", "cancelled"]).annotate({ @@ -53,7 +53,12 @@ export const Image = Schema.Struct({ model: Schema.String, }).annotate({ identifier: "Job.Image" }) -export const Info = Schema.Union([Shell, Subagent, Image]).pipe( +export interface CodeMode extends Schema.Schema.Type {} +export const CodeMode = Schema.Struct({ kind: Schema.tag("codemode"), ...Base }).annotate({ + identifier: "Job.CodeMode", +}) + +export const Info = Schema.Union([Shell, Subagent, Image, CodeMode]).pipe( Schema.toTaggedUnion("kind"), Schema.annotate({ identifier: "Job.Info" }), ) From d652dd97eeb76a121fdf5e8b2fbdc3816c57fbc3 Mon Sep 17 00:00:00 2001 From: James Long Date: Tue, 17 Nov 2026 04:02:26 +0000 Subject: [PATCH 2/5] fix(core): let background Code Mode scripts prompt like subagents User decisions: - Let a backgrounded Code Mode script ask for permission like a subagent does - Drop the foreground-only permission cutoff - Show the permission prompt on screen and pause the script until answered --- packages/core/src/codemode/job.ts | 43 ++++++++----------- packages/core/src/job.ts | 11 ++--- packages/core/src/permission.ts | 33 +------------- .../core/src/session/subagent-completion.ts | 9 ++-- packages/core/test/subagent-idle-e2e.test.ts | 1 + packages/tui/src/routes/session/index.tsx | 8 ++-- 6 files changed, 34 insertions(+), 71 deletions(-) diff --git a/packages/core/src/codemode/job.ts b/packages/core/src/codemode/job.ts index cbb124628f95..0ceb919abe06 100644 --- a/packages/core/src/codemode/job.ts +++ b/packages/core/src/codemode/job.ts @@ -5,7 +5,6 @@ import { Cause, Context, Deferred, Effect, Exit, Option, type Scope, Semaphore } import { extension } from "mime-types" import { Flag } from "../flag.js" import { Job } from "../job.js" -import { Permission } from "../permission.js" import type { Session } from "../session.js" import type { Tool } from "../tool.js" import { ToolOutput } from "../tool-output.js" @@ -31,14 +30,20 @@ export const make = Effect.fnUntraced(function* ( synthetic: Session.Interface["synthetic"], scope: Scope.Scope, ) { - const location = Context.pick( - Flag.Service, - ToolOutput.Service, - )(yield* Effect.context()) + // A custom session runner can drain without installing the Location's tool services. + const services = Option.all({ + flags: yield* Effect.serviceOption(Flag.Service), + output: yield* Effect.serviceOption(ToolOutput.Service), + }) + if (Option.isNone(services)) return + const { flags, output } = services.value + const truncate = Effect.fnUntraced(function* (text: string) { + const bounded = yield* output.truncate({ content: [{ type: "text", text }] }) + return bounded.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n") + }) return Effect.fn("CodeModeJob.execute")(function* (context: Tool.Context, execute: Execute) { - if (!(yield* Flag.enabled("full_codemode"))) return yield* execute(context) - const output = yield* ToolOutput.Service + if (!(yield* flags.enabled("full_codemode"))) return yield* execute(context) const id = `cm_${Identifier.ascending()}` const sessionID = context.sessionID const result = yield* Deferred.make() @@ -60,19 +65,13 @@ export const make = Effect.fnUntraced(function* ( Effect.flatMap((done) => (done ? Effect.void : context.progress(update))), ), ), - }).pipe( - Effect.provideService(Job.BlockingParent, id), - Effect.provideService(Permission.PromptUntil, detached), - Effect.interruptible, - Effect.exit, - ) + }).pipe(Effect.provideService(Job.BlockingParent, id), Effect.interruptible, Effect.exit) yield* Deferred.done(result, exit) if (Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)) return yield* Effect.failCause(exit.cause) const text = Exit.isFailure(exit) ? Cause.pretty(exit.cause) : exit.value.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n") - const bounded = yield* output.truncate({ content: [{ type: "text", text }] }) - const body = bounded.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n") + const body = yield* truncate(text) if (Exit.isFailure(exit) || exit.value.metadata?.error === true) return yield* Effect.fail(new Error(body)) return body }), @@ -101,17 +100,9 @@ export const make = Effect.fnUntraced(function* ( .save(Buffer.from(file.uri.slice(prefix.length), "base64"), ext ? `.${ext}` : "") .pipe(Effect.catchDefect(() => Effect.succeed(`Could not save ${file.mime} attachment.`))) }) - const body = paths.length - ? yield* output.truncate({ - content: [{ type: "text", text: [info.output ?? info.error, ...paths].join("\n") }], - }) - : undefined const message = notice( - body - ? { - ...info, - output: body.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n"), - } + paths.length + ? { ...info, output: yield* truncate([info.output ?? info.error, ...paths].join("\n")) } : info, ) yield* synthetic({ id: notificationID, sessionID, ...message }).pipe( @@ -127,5 +118,5 @@ export const make = Effect.fnUntraced(function* ( } }), ) - }, Effect.provide(location)) satisfies Run + }) satisfies Run }) diff --git a/packages/core/src/job.ts b/packages/core/src/job.ts index 4b68a38d5df2..93510fcd8925 100644 --- a/packages/core/src/job.ts +++ b/packages/core/src/job.ts @@ -447,6 +447,7 @@ export const make = Effect.gen(function* () { const block: Interface["block"] = Effect.fnUntraced(function* (input) { const parent = yield* BlockingParent + const tracksSession = parent === undefined || parent === input.id const result = yield* SynchronizedRef.modify(state.jobs, (jobs): readonly [BlockStart, Map] => { const job = jobs.get(input.id) if (!job) return [{ type: "missing" }, jobs] @@ -454,12 +455,12 @@ export const make = Effect.gen(function* () { if (job.isBackgrounded) return [{ type: "backgrounded", info: snapshot(job) }, jobs] return [ { type: "wait", wait: { done: job.done, backgrounded: job.backgrounded, generation: job.scope } }, - parent && parent !== input.id - ? jobs - : new Map(jobs).set(input.id, { + tracksSession + ? new Map(jobs).set(input.id, { ...job, blockingSessions: incrementSession(job.blockingSessions, input.sessionID), - }), + }) + : jobs, ] }) if (result.type === "missing") return undefined @@ -473,7 +474,7 @@ export const make = Effect.gen(function* () { Deferred.await(result.wait.backgrounded).pipe(Effect.map((info) => ({ type: "backgrounded" as const, info }))), ).pipe( Effect.tap((outcome) => (outcome.type === "finished" ? consume(input.id, result.wait.generation) : Effect.void)), - Effect.ensuring(removeBlock(input)), + Effect.ensuring(tracksSession ? removeBlock(input) : Effect.void), ) }) diff --git a/packages/core/src/permission.ts b/packages/core/src/permission.ts index 102a3b95794b..319a8b2075d7 100644 --- a/packages/core/src/permission.ts +++ b/packages/core/src/permission.ts @@ -64,11 +64,6 @@ export const Unattended = Context.Reference("@op defaultValue: () => undefined, }) -/** A caller that leaves the foreground can no longer host an interactive approval. */ -export const PromptUntil = Context.Reference | undefined>("@opencode/Permission/PromptUntil", { - defaultValue: () => undefined, -}) - export class DeclinedError extends Schema.TaggedError()("Permission.DeclinedError", {}) {} export class CorrectedError extends Schema.TaggedError()("Permission.CorrectedError", { @@ -290,34 +285,8 @@ const layer = Layer.effect( }) } if (result.effect === "allow") return - const until = yield* PromptUntil - const background = () => - new BlockedError({ - rules: relevant(input, result.rules), - permission: input.action, - resources: input.resources, - reason: `Permission ${input.action} needs approval in the foreground`, - }) - if (until && (yield* Deferred.isDone(until))) return yield* background() const item = yield* create(request(input, result.message), input.agent) - const wait = Deferred.await(item.deferred) - return yield* restore( - until - ? Effect.raceFirst( - wait, - Deferred.await(until).pipe( - Effect.andThen( - bus.publish(Permission.Event.Replied, { - sessionID: input.sessionID, - requestID: item.request.id, - reply: "reject", - }), - ), - Effect.andThen(Effect.fail(background())), - ), - ) - : wait, - ).pipe( + return yield* restore(Deferred.await(item.deferred)).pipe( // Deliberate defect tunnel: leaves wrap execution in blanket `mapError`, which // must not convert a user's decline into model-facing tool output. The decline // resurfaces as a typed failure at SessionModelRequest.executeTool. A decline diff --git a/packages/core/src/session/subagent-completion.ts b/packages/core/src/session/subagent-completion.ts index d69ed75ea984..db1daa04d9bc 100644 --- a/packages/core/src/session/subagent-completion.ts +++ b/packages/core/src/session/subagent-completion.ts @@ -43,11 +43,10 @@ export function formatBody( ): string { if (!background || background.length === 0) return body const lines = background.map((item) => { - if (item.kind === "codemode") return `- Code Mode script (${item.jobID})` - if (item.kind === "shell") - return `- shell (${item.shellID}${item.sessionID !== childSessionID ? `, in ${item.sessionID}` : ""}): ${clean(item.command)}` - if (item.kind === "image") - return `- image (${item.model}${item.sessionID !== childSessionID ? `, in ${item.sessionID}` : ""}): ${item.path}` + const location = item.sessionID !== childSessionID ? `, in ${item.sessionID}` : "" + if (item.kind === "codemode") return `- Code Mode script (${item.jobID}${location})` + if (item.kind === "shell") return `- shell (${item.shellID}${location}): ${clean(item.command)}` + if (item.kind === "image") return `- image (${item.model}${location}): ${item.path}` return `- subagent (${item.agent}, sessionID: ${item.childSessionID}): ${clean(item.description)}` }) return `${body}${STILL_RUNNING}${lines.join("\n")}` diff --git a/packages/core/test/subagent-idle-e2e.test.ts b/packages/core/test/subagent-idle-e2e.test.ts index 6eb7b7a530f4..ff062bb62543 100644 --- a/packages/core/test/subagent-idle-e2e.test.ts +++ b/packages/core/test/subagent-idle-e2e.test.ts @@ -391,6 +391,7 @@ describe("Code Mode session jobs", () => { yield* s.release yield* Fiber.join(delivered) yield* s.idle + expect(yield* s.h.jobs.pendingBackground).toEqual([]) const text = `\nresult: done\n` expect((yield* s.h.llm.requests()).at(-1)?.messages).toContainEqual( expect.objectContaining({ content: expect.arrayContaining([expect.objectContaining({ type: "text", text })]) }), diff --git a/packages/tui/src/routes/session/index.tsx b/packages/tui/src/routes/session/index.tsx index 09a7bea6de9a..cd04436f459d 100644 --- a/packages/tui/src/routes/session/index.tsx +++ b/packages/tui/src/routes/session/index.tsx @@ -208,7 +208,6 @@ export function Session(props: { return data.session.family(route.sessionID).filter((id) => id !== route.sessionID) }) const permissions = createMemo(() => { - if (session()?.parentID) return [] return [route.sessionID, ...descendantSessionIDs()].flatMap( (sessionID) => data.session.permission.list(sessionID) ?? [], ) @@ -234,6 +233,9 @@ export function Session(props: { open: false, tab: undefined as string | undefined, }) + const composerVisible = createMemo( + () => promptedPermissions().length === 0 && (composer.open || (!!session()?.parentID && forms().length === 0)), + ) props.onTerminalPicker?.(() => setComposer({ open: true, tab: "terminals" })) onCleanup(() => props.onTerminalPicker?.(undefined)) createEffect(() => { @@ -1602,7 +1604,7 @@ export function Session(props: { { const parent = session()?.parentID @@ -1616,7 +1618,7 @@ export function Session(props: { visibleTerminalID={props.visibleTerminalID} /> - {null} + {null} 0}> {(_) => { From e101376701bbf230ab7d0c65ea0d1a35832ea68d Mon Sep 17 00:00:00 2001 From: James Long Date: Tue, 17 Nov 2026 14:16:59 +0000 Subject: [PATCH 3/5] fix(core): keep a permission reject within its own step User decisions: - Rejecting a prompt only cancels other prompts from the same step, like subagents --- packages/core/src/permission.ts | 1 + packages/core/test/permission.test.ts | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/packages/core/src/permission.ts b/packages/core/src/permission.ts index 319a8b2075d7..3314c1b91888 100644 --- a/packages/core/src/permission.ts +++ b/packages/core/src/permission.ts @@ -339,6 +339,7 @@ const layer = Layer.effect( pending.delete(input.requestID) for (const [id, item] of pending) { if (item.request.sessionID !== existing.request.sessionID) continue + if (item.request.source?.messageID !== existing.request.source?.messageID) continue yield* bus.publish(Permission.Event.Replied, { sessionID: item.request.sessionID, requestID: item.request.id, diff --git a/packages/core/test/permission.test.ts b/packages/core/test/permission.test.ts index 49db52d59172..d2a8f3b57906 100644 --- a/packages/core/test/permission.test.ts +++ b/packages/core/test/permission.test.ts @@ -381,6 +381,25 @@ describe("Permission", () => { }), ) + it.effect("rejects sibling requests in the same step and leaves another step's request pending", () => + Effect.gen(function* () { + yield* setup() + const service = yield* Permission.Service + const ask = (call: string, messageID: string) => + service.ask( + assertion({ + id: Permission.ID.create(`per_${call}`), + source: { type: "tool", messageID, id: `call_${call}` }, + }), + ) + const first = yield* ask("first", "msg_one") + yield* ask("sibling", "msg_one") + const other = yield* ask("other", "msg_two") + yield* service.reply({ requestID: first.id, reply: "reject" }) + expect((yield* service.list()).map((request) => request.id)).toEqual([other.id]) + }), + ) + it.effect("stores and removes saved resources for a project", () => Effect.gen(function* () { yield* setup() From d4efb591d15e4cc7ced7d7943921eb36a331b591 Mon Sep 17 00:00:00 2001 From: James Long Date: Tue, 17 Nov 2026 15:26:14 +0000 Subject: [PATCH 4/5] fix(cli): keep waiting for background Code Mode scripts in run User decisions: - Keep run's original background-job wait logic instead of an allowlist --- packages/cli/src/run/noninteractive.ts | 5 ++--- packages/core/src/plugin/goal.ts | 9 ++++++++- packages/core/test/subagent-idle-e2e.test.ts | 4 +--- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/packages/cli/src/run/noninteractive.ts b/packages/cli/src/run/noninteractive.ts index 7e30b34e9f14..ee8db3ee71cb 100644 --- a/packages/cli/src/run/noninteractive.ts +++ b/packages/cli/src/run/noninteractive.ts @@ -277,9 +277,8 @@ export async function runNonInteractivePrompt(input: Input) { const ended = state.ended.promise await input.client.experimental.session.wait({ sessionID: input.sessionID }) const pending = await background() - // Wait only for work this client can stop. - if (!pending || (pending.length > 0 && pending.every((job) => job.kind !== "shell" && job.kind !== "subagent"))) - return + // Image jobs can't be cancelled through the API, so waiting on them would only hold the exit. + if (!pending || (pending.length > 0 && pending.every((job) => job.kind === "image"))) return await ended } } diff --git a/packages/core/src/plugin/goal.ts b/packages/core/src/plugin/goal.ts index 95ae6c2fa580..f48abc188da9 100644 --- a/packages/core/src/plugin/goal.ts +++ b/packages/core/src/plugin/goal.ts @@ -147,7 +147,14 @@ export const Plugin = define({ return yield* settle(sessionID, goal, "paused", "The server restarted while the goal was active") // The Session's own running subagent, image or script wakes it with its notice, and the hook runs again then. A // grandchild reports to its own parent, so it would never wake this Session. - if (background.some((work) => work.kind !== "shell" && work.sessionID === sessionID)) return + if ( + background.some( + (work) => + (work.kind === "subagent" || work.kind === "image" || work.kind === "codemode") && + work.sessionID === sessionID, + ) + ) + return if (goal.rounds >= goal.maxRounds) return yield* settle(sessionID, goal, "paused", `Reached the limit of ${goal.maxRounds} rounds`) diff --git a/packages/core/test/subagent-idle-e2e.test.ts b/packages/core/test/subagent-idle-e2e.test.ts index ff062bb62543..57462dd498b8 100644 --- a/packages/core/test/subagent-idle-e2e.test.ts +++ b/packages/core/test/subagent-idle-e2e.test.ts @@ -475,9 +475,7 @@ describe("subagent idle reports end to end", () => { }) const parent = (yield* h.llm.requests()).find((request) => request.model.id === "build") expect(parent?.messages).toContainEqual( - expect.objectContaining({ - content: expect.arrayContaining([expect.objectContaining({ type: "text", text })]), - }), + expect.objectContaining({ content: expect.arrayContaining([expect.objectContaining({ type: "text", text })]) }), ) yield* h.sessions.wait(childID) yield* h.jobs.wait({ id: childID }) From 9e5611a80ed173dfb39eb74ff708abc85ffeb1ce Mon Sep 17 00:00:00 2001 From: James Long Date: Tue, 17 Nov 2026 15:28:35 +0000 Subject: [PATCH 5/5] fix(cli): let Ctrl+C in run skip waiting on background Code Mode scripts User decisions: - On Ctrl+C, don't wait for background Code Mode scripts, like image jobs - A normal run still waits for them --- packages/cli/src/run/noninteractive.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/cli/src/run/noninteractive.ts b/packages/cli/src/run/noninteractive.ts index ee8db3ee71cb..a297c6984401 100644 --- a/packages/cli/src/run/noninteractive.ts +++ b/packages/cli/src/run/noninteractive.ts @@ -277,8 +277,9 @@ export async function runNonInteractivePrompt(input: Input) { const ended = state.ended.promise await input.client.experimental.session.wait({ sessionID: input.sessionID }) const pending = await background() - // Image jobs can't be cancelled through the API, so waiting on them would only hold the exit. - if (!pending || (pending.length > 0 && pending.every((job) => job.kind === "image"))) return + // Image and Code Mode jobs can't be cancelled through the API, so waiting on them would only hold the exit. + if (!pending || (pending.length > 0 && pending.every((job) => job.kind === "image" || job.kind === "codemode"))) + return await ended } }