GeezerVison is showing github.com — fix(acp): stream the parent's reaction to background subagent reports… · drpr/opencode@3039a8b
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: packages/cli/src/acp/translate.ts +41-27Lines changed: 41 additions & 27 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -25,7 +25,7 @@ export type Terminal = "succeeded" | "failed" | "interrupted" | 25 | 25 | export type TurnContext = { | 26 | 26 | readonly sessionID: Session.ID | 27 | 27 | readonly cwd: string | 28 | | - readonly start: TurnStart | | 28 | + readonly start?: TurnStart | 29 | 29 | readonly childUpdates: boolean | 30 | 30 | readonly compaction: boolean | 31 | 31 | } | @@ -44,12 +44,14 @@ type RetryStatus = { | 44 | 44 | readonly error: SessionError.Error | 45 | 45 | } | 46 | 46 |
| | 47 | +type Child = ACPChild.Session & { readonly turnID?: string } | | 48 | + | 47 | 49 | export type TurnState = { | 48 | 50 | readonly started: boolean | 49 | 51 | readonly tools: ReadonlyMap<string, Tool> | 50 | 52 | readonly retries: ReadonlyMap<string, RetryStatus> | 51 | 53 | readonly compactions: ACPCompaction.Tracked | 52 | | - readonly children: ReadonlyMap<string, ACPChild.Session> | | 54 | + readonly children: ReadonlyMap<string, Child> | 53 | 55 | readonly openChildren: ReadonlySet<string> | 54 | 56 | readonly asks: ReadonlySet<string> | 55 | 57 | readonly finish?: SessionMessage.Assistant["finish"] | @@ -69,9 +71,9 @@ export type Output = | 69 | 71 | readonly _tag: "PermissionAsk" | 70 | 72 | readonly event: PermissionEvent | 71 | 73 | readonly tool?: Tool | 72 | | - readonly child?: ACPChild.Session | | 74 | + readonly child?: Child | 73 | 75 | } | 74 | | - | { readonly _tag: "FormAsk"; readonly form: FormEvent["data"]["form"]; readonly child?: ACPChild.Session } | | 76 | + | { readonly _tag: "FormAsk"; readonly form: FormEvent["data"]["form"]; readonly child?: Child } | 75 | 77 | | { readonly _tag: "AskSettled"; readonly id: string } | 76 | 78 |
| 77 | 79 | export type Folded = { | @@ -95,20 +97,21 @@ export function fold(state: TurnState, event: OpenCodeEvent, ctx: TurnContext): | 95 | 97 |
| 96 | 98 | const sessionID = sessionIDFromEvent(event) | 97 | 99 | const child = sessionID ? state.children.get(sessionID) : undefined | | 100 | + const openChild = child && state.openChildren.has(child.id) ? child : undefined | 98 | 101 |
| 99 | | - if (event.type === "permission.asked" && (event.data.sessionID === ctx.sessionID || child)) { | | 102 | + if (event.type === "permission.asked" && (event.data.sessionID === ctx.sessionID || openChild)) { | 100 | 103 | const tool = event.data.source?.id | 101 | 104 | ? state.tools.get(toolKey(event.data.sessionID, event.data.source.id)) | 102 | 105 | : undefined | 103 | 106 | return { | 104 | 107 | state: { ...state, asks: new Set(state.asks).add(event.data.id) }, | 105 | | - outputs: [{ _tag: "PermissionAsk", event, tool, child }], | | 108 | + outputs: [{ _tag: "PermissionAsk", event, tool, child: openChild }], | 106 | 109 | } | 107 | 110 | } | 108 | | - if (event.type === "form.created" && (event.data.form.sessionID === ctx.sessionID || child)) { | | 111 | + if (event.type === "form.created" && (event.data.form.sessionID === ctx.sessionID || openChild)) { | 109 | 112 | return { | 110 | 113 | state: { ...state, asks: new Set(state.asks).add(event.data.form.id) }, | 111 | | - outputs: [{ _tag: "FormAsk", form: event.data.form, child }], | | 114 | + outputs: [{ _tag: "FormAsk", form: event.data.form, child: openChild }], | 112 | 115 | } | 113 | 116 | } | 114 | 117 | const settledID = | @@ -123,15 +126,18 @@ export function fold(state: TurnState, event: OpenCodeEvent, ctx: TurnContext): | 123 | 126 | return { state: { ...state, asks }, outputs: [{ _tag: "AskSettled", id: settledID }] } | 124 | 127 | } | 125 | 128 | if (!sessionID || (sessionID !== ctx.sessionID && !child)) return { state, outputs: [] } | 126 | | - if (event.type === "session.inbox.delivered" && event.data.inboxID === ctx.start.id) | | 129 | + if ( | | 130 | + sessionID === ctx.sessionID && | | 131 | + event.type === "session.inbox.delivered" && | | 132 | + (!ctx.start || event.data.inboxID === ctx.start.id) | | 133 | + ) | 127 | 134 | return { state: { ...state, started: true }, outputs: [] } | 128 | | - if (!state.started) return { state, outputs: [] } | | 135 | + if (!child && !state.started) return { state, outputs: [] } | 129 | 136 | return child ? childEvent(state, event, ctx, child) : rootEvent(state, event, ctx) | 130 | 137 | } | 131 | 138 |
| 132 | | -export function fromTrackedChild(state: TurnState, event: OpenCodeEvent) { | 133 | | - const sessionID = event.type === "session.created" ? event.data.parentID : sessionIDFromEvent(event) | 134 | | - return sessionID !== undefined && state.children.has(sessionID) | | 139 | +export function projectChild(ctx: TurnContext, child: Child) { | | 140 | + return !ctx.childUpdates && ctx.start !== undefined && child.turnID === ctx.start.id | 135 | 141 | } | 136 | 142 |
| 137 | 143 | export function failure(state: TurnState) { | @@ -202,7 +208,13 @@ function childCreated(state: TurnState, event: CreatedEvent, ctx: TurnContext): | 202 | 208 | if (!parentID) return { state, outputs: [] } | 203 | 209 | const parent = parentID === ctx.sessionID ? undefined : state.children.get(parentID) | 204 | 210 | if (!parent && parentID !== ctx.sessionID) return { state, outputs: [] } | 205 | | - const child = { id: event.data.sessionID, parentID, depth: parent ? parent.depth + 1 : 1, title: event.data.title } | | 211 | + const child: Child = { | | 212 | + id: event.data.sessionID, | | 213 | + parentID, | | 214 | + depth: parent ? parent.depth + 1 : 1, | | 215 | + title: event.data.title, | | 216 | + turnID: parent ? parent.turnID : ctx.start?.id, | | 217 | + } | 206 | 218 | return { | 207 | 219 | state: { | 208 | 220 | ...state, | @@ -224,20 +236,27 @@ function rootEvent(state: TurnState, event: OpenCodeEvent, ctx: TurnContext): Fo | 224 | 236 | return { state: { ...recorded, stepError: event.data.error }, outputs: [] } | 225 | 237 | } | 226 | 238 | case "session.execution.succeeded": | 227 | | - return { state, outputs: [], terminal: "succeeded" } | | 239 | + return { state: { ...state, started: Boolean(ctx.start) }, outputs: [], terminal: "succeeded" } | 228 | 240 | case "session.execution.interrupted": | 229 | | - return { state, outputs: [], terminal: "interrupted" } | | 241 | + return { state: { ...state, started: Boolean(ctx.start) }, outputs: [], terminal: "interrupted" } | 230 | 242 | case "session.execution.failed": | 231 | | - return { state: { ...state, executionError: event.data.error }, outputs: [], terminal: "failed" } | | 243 | + return { | | 244 | + state: { ...state, started: Boolean(ctx.start), executionError: event.data.error }, | | 245 | + outputs: [], | | 246 | + terminal: "failed", | | 247 | + } | 232 | 248 | default: | 233 | 249 | return sessionEvent(state, event, ctx, undefined) | 234 | 250 | } | 235 | 251 | } | 236 | 252 |
| 237 | | -function childEvent(state: TurnState, event: OpenCodeEvent, ctx: TurnContext, child: ACPChild.Session): Folded { | | 253 | +function childEvent(state: TurnState, event: OpenCodeEvent, ctx: TurnContext, child: Child): Folded { | 238 | 254 | switch (event.type) { | 239 | 255 | case "session.execution.started": | 240 | | - return { state, outputs: childStatus(ctx, child, { type: "status", status: "running" }) } | | 256 | + return { | | 257 | + state: { ...state, openChildren: new Set(state.openChildren).add(child.id) }, | | 258 | + outputs: childStatus(ctx, child, { type: "status", status: "running" }), | | 259 | + } | 241 | 260 | case "session.execution.succeeded": | 242 | 261 | return childEnded(state, ctx, child, { type: "status", status: "completed" }) | 243 | 262 | case "session.execution.interrupted": | @@ -249,12 +268,7 @@ function childEvent(state: TurnState, event: OpenCodeEvent, ctx: TurnContext, ch | 249 | 268 | } | 250 | 269 | } | 251 | 270 |
| 252 | | -function sessionEvent( | 253 | | - state: TurnState, | 254 | | - event: OpenCodeEvent, | 255 | | - ctx: TurnContext, | 256 | | - child: ACPChild.Session | undefined, | 257 | | -): Folded { | | 271 | +function sessionEvent(state: TurnState, event: OpenCodeEvent, ctx: TurnContext, child: Child | undefined): Folded { | 258 | 272 | const sessionID = child?.id ?? ctx.sessionID | 259 | 273 | const send = (update: SessionUpdate) => route(ctx, child, update) | 260 | 274 | switch (event.type) { | @@ -415,11 +429,11 @@ function newTool(sessionID: string, id: string, name = "tool"): Tool { | 415 | 429 | return { sessionID, id, name, input: {}, metadata: {} } | 416 | 430 | } | 417 | 431 |
| 418 | | -function route(ctx: TurnContext, child: ACPChild.Session | undefined, update: SessionUpdate): Output[] { | | 432 | +function route(ctx: TurnContext, child: Child | undefined, update: SessionUpdate): Output[] { | 419 | 433 | if (!child) return [{ _tag: "SessionUpdate", update }] | 420 | 434 | const projected = ACPChild.project(update, child) | 421 | 435 | if (ctx.childUpdates) return childStatus(ctx, child, { type: "update", update: projected }) | 422 | | - return [{ _tag: "SessionUpdate", update: projected }] | | 436 | + return projectChild(ctx, child) ? [{ _tag: "SessionUpdate", update: projected }] : [] | 423 | 437 | } | 424 | 438 |
| 425 | 439 | function childStatus(ctx: TurnContext, child: ACPChild.Session, event: ACPChild.Event): Output[] { | |
Collapse file Copy file name to clipboardExpand all lines: packages/cli/src/acp/turn.ts +44-18Lines changed: 44 additions & 18 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -21,7 +21,7 @@ import { findModel, type ACPCatalog } from "./catalog" | 21 | 21 | import { ACPChild } from "./child" | 22 | 22 | import { ACPClient } from "./client" | 23 | 23 | import { currentModel } from "./config-option" | 24 | | -import type { ACPConnection } from "./connection" | | 24 | +import { ACPConnection } from "./connection" | 25 | 25 | import { ACPElicitation } from "./elicitation" | 26 | 26 | import { ACPError } from "./error" | 27 | 27 | import { ACPPermission } from "./permission" | @@ -60,7 +60,11 @@ type Turn = { | 60 | 60 | readonly state: Ref.Ref<ACPTranslate.TurnState> | 61 | 61 | readonly subscription: Subscription | 62 | 62 | readonly cancelled: Deferred.Deferred<void> | 63 | | - readonly background: boolean | | 63 | +} | | 64 | + | | 65 | +type Background = { | | 66 | + readonly state: Ref.Ref<ACPTranslate.TurnState> | | 67 | + readonly fiber?: Fiber.Fiber<unknown, unknown> | 64 | 68 | } | 65 | 69 |
| 66 | 70 | export const make = Effect.fnUntraced(function* (input: { | @@ -73,8 +77,24 @@ export const make = Effect.fnUntraced(function* (input: { | 73 | 77 | const scope = yield* Effect.scope | 74 | 78 | const drainTimeout = yield* CancelDrainTimeout | 75 | 79 | const turns = yield* FiberMap.make<string, PromptResponse, ACPError.Failure>() | | 80 | + const backgrounds = new WeakMap<Attached, Background>() | 76 | 81 |
| 77 | | - const open = Effect.fnUntraced(function* (ctx: ACPTranslate.TurnContext, state: Ref.Ref<ACPTranslate.TurnState>) { | | 82 | + const open = Effect.fnUntraced(function* ( | | 83 | + attached: Attached, | | 84 | + ctx: ACPTranslate.TurnContext, | | 85 | + state: Ref.Ref<ACPTranslate.TurnState>, | | 86 | + ) { | | 87 | + const previous = backgrounds.get(attached) | | 88 | + if (previous) { | | 89 | + backgrounds.delete(attached) | | 90 | + if (previous.fiber) yield* Fiber.interrupt(previous.fiber) | | 91 | + const inherited = yield* Ref.get(previous.state) | | 92 | + yield* Ref.set(state, { | | 93 | + ...ACPTranslate.initial, | | 94 | + children: inherited.children, | | 95 | + openChildren: inherited.openChildren, | | 96 | + }) | | 97 | + } | 78 | 98 | // Parented to the service scope; the session scope may already be closed. | 79 | 99 | const subscriptionScope = yield* Scope.fork(scope) | 80 | 100 | const subscription: Subscription = { | @@ -93,7 +113,7 @@ export const make = Effect.fnUntraced(function* (input: { | 93 | 113 | Effect.forever, | 94 | 114 | Effect.forkIn(subscriptionScope), | 95 | 115 | ) | 96 | | - return { ctx, state, subscription, cancelled: yield* Deferred.make<void>(), background: false } satisfies Turn | | 116 | + return { ctx, state, subscription, cancelled: yield* Deferred.make<void>() } satisfies Turn | 97 | 117 | }) | 98 | 118 |
| 99 | 119 | const take = (subscription: Subscription) => | @@ -141,7 +161,6 @@ export const make = Effect.fnUntraced(function* (input: { | 141 | 161 | const interpret = (turn: Turn, output: ACPTranslate.Output) => { | 142 | 162 | switch (output._tag) { | 143 | 163 | case "SessionUpdate": | 144 | | - if (turn.background) return Effect.void | 145 | 164 | return ACPPermission.withCompletedDiffs(output.update, output.diff, turn.ctx.cwd).pipe( | 146 | 165 | Effect.flatMap((update) => input.connection.sessionUpdate({ sessionId: turn.ctx.sessionID, update })), | 147 | 166 | ) | @@ -185,7 +204,7 @@ export const make = Effect.fnUntraced(function* (input: { | 185 | 204 | requestedSchema, | 186 | 205 | clientSessionID: turn.ctx.sessionID, | 187 | 206 | child: output.child, | 188 | | - toolCallSent: !turn.background && (!output.child || !turn.ctx.childUpdates), | | 207 | + toolCallSent: !output.child || ACPTranslate.projectChild(turn.ctx, output.child), | 189 | 208 | } | 190 | 209 | yield* queueAsk(turn, output.form.id, ACPElicitation.ask(elicitation), "cancel", (outcome) => | 191 | 210 | ACPElicitation.respond(elicitation, outcome), | @@ -203,10 +222,7 @@ export const make = Effect.fnUntraced(function* (input: { | 203 | 222 | const advance = Effect.fnUntraced(function* (turn: Turn) { | 204 | 223 | const event = yield* take(turn.subscription) | 205 | 224 | const folded = yield* Ref.modify(turn.state, (current) => { | 206 | | - const next = | 207 | | - turn.background && !ACPTranslate.fromTrackedChild(current, event) | 208 | | - ? { state: current, outputs: [] } | 209 | | - : ACPTranslate.fold(current, event, turn.ctx) | | 225 | + const next = ACPTranslate.fold(current, event, turn.ctx) | 210 | 226 | return [next, next.state] | 211 | 227 | }) | 212 | 228 | yield* Effect.forEach(folded.outputs, (output) => interpret(turn, output), { discard: true }) | @@ -226,7 +242,7 @@ export const make = Effect.fnUntraced(function* (input: { | 226 | 242 | const followChildren = Effect.fnUntraced(function* (turn: Turn) { | 227 | 243 | while (true) { | 228 | 244 | const folded = yield* advance(turn) | 229 | | - if (folded.state.openChildren.size === 0) return yield* asksSettled(turn.subscription) | | 245 | + if (folded.terminal && folded.state.openChildren.size === 0) return yield* asksSettled(turn.subscription) | 230 | 246 | } | 231 | 247 | }) | 232 | 248 |
| @@ -312,13 +328,22 @@ export const make = Effect.fnUntraced(function* (input: { | 312 | 328 | const close = Scope.close(turn.subscription.scope, Exit.void) | 313 | 329 | if (Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause)) return yield* close | 314 | 330 | const state = yield* Ref.get(turn.state) | 315 | | - if (state.openChildren.size === 0) return yield* close | 316 | | - // Children outlive a cancelled turn, so their asks still reach the client. | 317 | | - const background = followChildren({ | 318 | | - ...turn, | 319 | | - state: yield* Ref.make(state), | 320 | | - cancelled: yield* Deferred.make<void>(), | 321 | | - background: true, | | 331 | + if (state.openChildren.size === 0) { | | 332 | + if (state.children.size > 0) backgrounds.set(attached, { state: turn.state }) | | 333 | + return yield* close | | 334 | + } | | 335 | + const responded = yield* ACPConnection.Responded | | 336 | + const nextState = yield* Ref.make({ ...state, started: false }) | | 337 | + const cancelled = yield* Deferred.make<void>() | | 338 | + // Children outlive a cancelled turn, so their asks and report-triggered turns still reach the client. | | 339 | + const background = Effect.withFiber((fiber) => { | | 340 | + backgrounds.set(attached, { state: nextState, fiber }) | | 341 | + return Effect.exit(responded).pipe( | | 342 | + Effect.andThen( | | 343 | + followChildren({ ...turn, ctx: { ...turn.ctx, start: undefined }, state: nextState, cancelled }), | | 344 | + ), | | 345 | + Effect.interruptible, | | 346 | + ) | 322 | 347 | }).pipe(Effect.ignore, Effect.ensuring(close), Effect.withSpan("cli.acp.turn.background")) | 323 | 348 | yield* input.sessions.fork(attached, background).pipe(Effect.catchTag("ACPSessionNotFoundError", () => close)) | 324 | 349 | }) | @@ -368,6 +393,7 @@ export const make = Effect.fnUntraced(function* (input: { | 368 | 393 | const state = yield* Ref.make(ACPTranslate.initial) | 369 | 394 | const exit = yield* Effect.acquireUseRelease( | 370 | 395 | open( | | 396 | + attached, | 371 | 397 | { | 372 | 398 | sessionID: attached.id, | 373 | 399 | cwd: attached.cwd, | |
Collapse file Copy file name to clipboard +48Lines changed: 48 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +import type { PromptResponse } from "@agentclientprotocol/sdk" | | 2 | +import { expect, test } from "bun:test" | | 3 | +import { Schema } from "effect" | | 4 | +import { createAcpFixture, expectOk, initialize, newSession, toolCallStream } from "./subprocess" | | 5 | + | | 6 | +const modelRequest = Schema.decodeUnknownSync(Schema.Struct({ messages: Schema.Array(Schema.Unknown) })) | | 7 | + | | 8 | +test("streams the parent's response to a subagent report after end_turn", async () => { | | 9 | + const child = Promise.withResolvers<string>() | | 10 | + const resumed = Promise.withResolvers<void>() | | 11 | + await using fixture = await createAcpFixture({ | | 12 | + respond(request) { | | 13 | + const last = JSON.stringify(modelRequest(request).messages.at(-1)) | | 14 | + if (last.includes("<subagent") && last.includes("child result")) { | | 15 | + resumed.resolve() | | 16 | + return "parent reaction" | | 17 | + } | | 18 | + if (last.includes("run the child")) | | 19 | + return toolCallStream("call_child", "subagent", { | | 20 | + agent: "general", | | 21 | + description: "Background task", | | 22 | + prompt: "work in child session", | | 23 | + }) | | 24 | + if (last.includes("work in child session")) return child.promise | | 25 | + return "launched" | | 26 | + }, | | 27 | + }) | | 28 | + const acp = fixture.spawn() | | 29 | + await initialize(acp) | | 30 | + const { sessionId } = await newSession(acp, fixture.home) | | 31 | + const response = expectOk( | | 32 | + await acp.request<PromptResponse>("session/prompt", { | | 33 | + sessionId, | | 34 | + prompt: [{ type: "text", text: "run the child" }], | | 35 | + }), | | 36 | + ) | | 37 | + expect(response.stopReason).toBe("end_turn") | | 38 | + child.resolve("child result") | | 39 | + await resumed.promise | | 40 | + const message = await acp.waitForMessage( | | 41 | + (message) => message.method === "session/update" && JSON.stringify(message.params).includes("parent reaction"), | | 42 | + "the resumed parent's agent_message_chunk", | | 43 | + ) | | 44 | + expect(message.params).toMatchObject({ | | 45 | + sessionId, | | 46 | + update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "parent reaction" } }, | | 47 | + }) | | 48 | +}, 60_000) |
Collapse file Copy file name to clipboardExpand all lines: packages/cli/test/acp/subprocess.ts +2Lines changed: 2 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -37,6 +37,7 @@ type AcpProcess = { | 37 | 37 | readonly pid: number | 38 | 38 | readonly exited: Promise<number> | 39 | 39 | readonly request: <T>(method: string, params?: unknown) => Promise<JsonRpcResponse<T>> | | 40 | + readonly waitForMessage: (predicate: Waiter["predicate"], description: string) => Promise<JsonRpcMessage> | 40 | 41 | readonly close: () => Promise<number> | 41 | 42 | readonly stderr: () => string | 42 | 43 | readonly [Symbol.asyncDispose]: () => Promise<void> | @@ -294,6 +295,7 @@ function spawnAcp(input: { readonly env: Record<string, string | undefined> }): | 294 | 295 | pid: child.pid, | 295 | 296 | exited: child.exited, | 296 | 297 | request, | | 298 | + waitForMessage: (predicate, description) => take(predicate, 10_000, description), | 297 | 299 | async close() { | 298 | 300 | if (!inputClosed) { | 299 | 301 | inputClosed = true | |
|