From 6cb8aba19aa5b54d18ba81a0bbf7eb4557ad6fdc Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Wed, 4 Nov 2026 14:07:28 -0800 Subject: [PATCH] feat(core): thread a subagent notify preference and job foreground visibility --- packages/core/src/config/plugin/command.ts | 4 +- packages/core/src/job.ts | 9 ++ packages/core/src/session/subagent-job.ts | 66 ++++++++--- .../core/src/session/subagent-metadata.ts | 18 +++ packages/core/src/tool/plugin/subagent.ts | 15 ++- packages/core/test/job.test.ts | 28 +++++ packages/core/test/tool-subagent.test.ts | 111 ++++++++++++++++++ 7 files changed, 231 insertions(+), 20 deletions(-) create mode 100644 packages/core/src/session/subagent-metadata.ts diff --git a/packages/core/src/config/plugin/command.ts b/packages/core/src/config/plugin/command.ts index 32f59f222ef..ff19890edcc 100644 --- a/packages/core/src/config/plugin/command.ts +++ b/packages/core/src/config/plugin/command.ts @@ -92,8 +92,8 @@ export const Plugin = define({ agent: selected.id, description: command.description ?? name, } - yield* subagents.start(recovery) - yield* subagents.background(recovery) + yield* subagents.start({ recovery, notify: true }) + yield* subagents.background({ recovery, notify: true }) return } if (agent !== undefined) { diff --git a/packages/core/src/job.ts b/packages/core/src/job.ts index fd5d391b396..066fe26abc7 100644 --- a/packages/core/src/job.ts +++ b/packages/core/src/job.ts @@ -116,6 +116,9 @@ export type BackgroundAllInput = { export interface Interface { readonly get: (id: string) => Effect.Effect + // True only while a foreground caller holds a block registration for this job. Settlement, + // cancellation and backgrounding clear it, so read it before awaiting anything else. + readonly isBlocked: (id: string) => Effect.Effect readonly start: (input: StartInput) => Effect.Effect readonly wait: (input: WaitInput) => Effect.Effect readonly block: (input: BlockInput) => Effect.Effect @@ -281,6 +284,11 @@ export const make = Effect.gen(function* () { return snapshot(job) }) + const isBlocked: Interface["isBlocked"] = Effect.fn("Job.isBlocked")(function* (id) { + const job = (yield* SynchronizedRef.get(state.jobs)).get(id) + return job !== undefined && job.blockingSessions.size > 0 + }) + const start: Interface["start"] = Effect.fnUntraced(function* (input) { return yield* Effect.uninterruptibleMask((restore) => Effect.gen(function* () { @@ -535,6 +543,7 @@ export const make = Effect.gen(function* () { return Service.of({ get, + isBlocked, start, wait, block, diff --git a/packages/core/src/session/subagent-job.ts b/packages/core/src/session/subagent-job.ts index c64cb047324..780f7b7a7c1 100644 --- a/packages/core/src/session/subagent-job.ts +++ b/packages/core/src/session/subagent-job.ts @@ -6,12 +6,18 @@ import type { LayerNode } from "@opencode/util/effect/layer-node" import { Job } from "../job.js" import { Session } from "../session.js" import { SubagentCompletion } from "./subagent-completion.js" +import { SubagentMetadata } from "./subagent-metadata.js" type Recovery = Extract +export type Input = { + readonly recovery: Recovery + readonly notify: boolean +} + export interface Interface { - start: (recovery: Recovery) => Effect.Effect - background: (recovery: Recovery) => Effect.Effect + start: (input: Input) => Effect.Effect + background: (input: Input) => Effect.Effect notify: (recovery: Recovery, startedAt: number) => Effect.Effect } @@ -27,13 +33,37 @@ const make: Effect.Effect() + // Children inherit their parent's metadata (Session.create), so the per-spawn preference is + // always written explicitly, merged over whatever the child already carries. This must run + // before jobs.start, because that forks the child's run. A vanished child keeps the + // never-error channel; jobs.start and the run surface a genuinely missing one. + const writeNotify = Effect.fnUntraced(function* (recovery: Recovery, notify: boolean) { + yield* Effect.gen(function* () { + const session = yield* sessions.get(recovery.childSessionID) + const metadata = SubagentMetadata.withNotify(session.metadata, notify) + if (metadata) yield* sessions.setMetadata({ sessionID: recovery.childSessionID, metadata }) + }).pipe(Effect.catchTag("Session.NotFoundError", () => Effect.void)) + }) + const notify = Effect.fn("SubagentJob.notify")(function* (recovery: Recovery, startedAt: number) { const key = `${recovery.childSessionID}:${startedAt}` if (notifications.has(key)) return notifications.add(key) yield* Effect.gen(function* () { const info = (yield* jobs.wait({ id: recovery.childSessionID })).info - if (info) yield* SubagentCompletion.deliver(sessions, jobs, { ...info, recovery }) + if (!info) return + // The preference belongs to the spawn call, so read it after the child settles. A silent + // child still clears its durable marker rather than leave a row that restart recovery + // would replay as a report the parent asked not to receive. + const metadata = yield* sessions.get(recovery.childSessionID).pipe( + Effect.map((session) => session.metadata), + Effect.catchTag("Session.NotFoundError", () => Effect.succeed(undefined)), + ) + if (!SubagentMetadata.notify(metadata)) { + if (info.notificationID) yield* jobs.completeBackground(info.notificationID) + return + } + yield* SubagentCompletion.deliver(sessions, jobs, { ...info, recovery }) }).pipe( Effect.ensuring(Effect.sync(() => notifications.delete(key))), Effect.forkIn(scope, { startImmediately: true }), @@ -42,17 +72,22 @@ const make: Effect.Effect - jobs - .start({ - id: recovery.childSessionID, + start: (input: Input) => + Effect.gen(function* () { + yield* writeNotify(input.recovery, input.notify) + return yield* jobs.start({ + id: input.recovery.childSessionID, type: "subagent", - title: recovery.description, + title: input.recovery.description, metadata: {}, - recovery, + recovery: input.recovery, run: Effect.gen(function* () { - yield* sessions.resume(recovery.childSessionID) - const messages = yield* sessions.messages({ sessionID: recovery.childSessionID, order: "desc", limit: 20 }) + yield* sessions.resume(input.recovery.childSessionID) + const messages = yield* sessions.messages({ + sessionID: input.recovery.childSessionID, + order: "desc", + limit: 20, + }) const assistant = messages.find( (message) => message.type === "assistant" && message.time.completed !== undefined && message.error === undefined, @@ -60,10 +95,11 @@ const make: Effect.Effect { }), ) + it.live("reports foreground visibility only while a session blocks on the job", () => + Effect.gen(function* () { + const jobs = yield* Job.Service + const latch = yield* Deferred.make() + const job = yield* jobs.start({ + id: "job_visibility", + type: "test", + run: Deferred.await(latch).pipe(Effect.as("done")), + }) + + expect(yield* jobs.isBlocked(job.id)).toBe(false) + expect(yield* jobs.isBlocked("job_missing")).toBe(false) + + const waiting = yield* jobs + .block({ id: job.id, sessionID: SessionSchema.ID.make("ses_visible") }) + .pipe(Effect.forkIn(yield* Scope.Scope, { startImmediately: true })) + // The registration happens in the forked fiber; yield until it is visible, never sleep. + yield* Effect.gen(function* () { + while (!(yield* jobs.isBlocked(job.id))) yield* Effect.yieldNow + }).pipe(Effect.timeout("1 second")) + expect(yield* jobs.isBlocked(job.id)).toBe(true) + + yield* Deferred.succeed(latch, undefined) + expect(yield* Fiber.join(waiting)).toMatchObject({ type: "finished" }) + expect(yield* jobs.isBlocked(job.id)).toBe(false) + }), + ) + it.live("returns backgrounded from a blocking wait when background wins", () => Effect.gen(function* () { const jobs = yield* Job.Service diff --git a/packages/core/test/tool-subagent.test.ts b/packages/core/test/tool-subagent.test.ts index ff3041b565f..e8e28b54385 100644 --- a/packages/core/test/tool-subagent.test.ts +++ b/packages/core/test/tool-subagent.test.ts @@ -877,4 +877,115 @@ describe("SubagentTool", () => { ), ), ) + + it.live("records the notify preference explicitly instead of inheriting it", () => + tmpdirScoped().pipe( + Effect.flatMap((dir) => + Effect.gen(function* () { + const location = Location.Ref.make({ directory: AbsolutePath.make(dir.path) }) + const sessions = yield* Session.Service + const parent = yield* sessions.create({ + location, + metadata: { "subagent.notify": false, host: "keep" }, + }) + yield* withSubagent(parent.location) + const locations = yield* LocationServiceMap.Service + const registry = yield* Tool.Service.pipe(Effect.provide(locations.get(parent.location))) + + const spawn = (id: string, input: Record) => + executeTool(registry, { + sessionID: parent.id, + ...toolIdentity, + call: { type: "tool-call", id, name: SubagentTool.name, input }, + }) + + const loud = yield* spawn("call-notify-default", { + agent: "reviewer", + description: "loud review", + prompt: "review", + background: true, + }) + const quiet = yield* spawn("call-notify-false", { + agent: "reviewer", + description: "quiet review", + prompt: "review", + background: true, + notify: false, + }) + + // The inherited false is rewritten by default, and the host key survives the merge. + expect((yield* sessions.get(outputSessionID(loud.metadata))).metadata).toEqual({ + "subagent.notify": true, + host: "keep", + }) + expect((yield* sessions.get(outputSessionID(quiet.metadata))).metadata).toEqual({ + "subagent.notify": false, + host: "keep", + }) + }), + ), + ), + ) + + it.live("reports only the children whose spawn asked for it", () => + tmpdirScoped().pipe( + Effect.flatMap((dir) => + Effect.gen(function* () { + const location = Location.Ref.make({ directory: AbsolutePath.make(dir.path) }) + const sessions = yield* Session.Service + const parent = yield* sessions.create({ location }) + yield* withSubagent(parent.location) + const locations = yield* LocationServiceMap.Service + const registry = yield* Tool.Service.pipe(Effect.provide(locations.get(parent.location))) + const jobs = yield* Job.Service + const bus = yield* Bus.Service + const database = yield* Database.Service + const admitted = yield* bus.subscribe(SessionEvent.InboxEnqueued).pipe( + Stream.filter((event) => event.data.sessionID === parent.id && event.data.item.type === "synthetic"), + Stream.take(1), + Stream.runCollect, + Effect.forkScoped({ startImmediately: true }), + ) + + const spawn = (id: string, input: Record) => + executeTool(registry, { + sessionID: parent.id, + ...toolIdentity, + call: { type: "tool-call", id, name: SubagentTool.name, input }, + }) + + const quiet = yield* spawn("call-silent-subagent", { + agent: "reviewer", + description: "quiet review", + prompt: "review", + background: true, + notify: false, + }) + const loud = yield* spawn("call-loud-subagent", { + agent: "reviewer", + description: "loud review", + prompt: "review", + background: true, + }) + const loudID = outputSessionID(loud.metadata) + + const admission = Array.from(yield* Fiber.join(admitted))[0] + if (admission?.data.item.type !== "synthetic") return yield* Effect.die("Expected synthetic inbox item") + expect(admission.data.item.payload.metadata).toMatchObject({ childID: loudID }) + + // The silent child settles without a report but still clears its durable marker. + yield* jobs.wait({ id: outputSessionID(quiet.metadata) }) + yield* jobs.wait({ id: loudID }) + yield* jobs.pendingBackground.pipe( + Effect.repeat({ until: (pending) => pending.length === 0 }), + Effect.timeout("2 seconds"), + ) + yield* SessionInbox.promote(database.db, bus, parent.id, "steer") + const synthetic = (yield* sessions.context(parent.id)).filter((message) => message.type === "synthetic") + expect(synthetic).toHaveLength(1) + expect(synthetic[0]?.text).toContain(`