GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(acp): stream the parent's reaction to background subagent reports… · drpr/opencode@3039a8b

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • packages/cli
    • src/acp
      • translate.ts
      • turn.ts
    • test/acp
      • background-turn.subprocess.test.ts
      • subprocess.ts
      • turn.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎packages/cli/src/acp/translate.ts‎

Copy file name to clipboardExpand all lines: packages/cli/src/acp/translate.ts
+41-27Lines changed: 41 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ export type Terminal = "succeeded" | "failed" | "interrupted"
2525
export type TurnContext = {
2626
readonly sessionID: Session.ID
2727
readonly cwd: string
28-
readonly start: TurnStart
28+
readonly start?: TurnStart
2929
readonly childUpdates: boolean
3030
readonly compaction: boolean
3131
}
@@ -44,12 +44,14 @@ type RetryStatus = {
4444
readonly error: SessionError.Error
4545
}
4646

47+
type Child = ACPChild.Session & { readonly turnID?: string }
48+
4749
export type TurnState = {
4850
readonly started: boolean
4951
readonly tools: ReadonlyMap<string, Tool>
5052
readonly retries: ReadonlyMap<string, RetryStatus>
5153
readonly compactions: ACPCompaction.Tracked
52-
readonly children: ReadonlyMap<string, ACPChild.Session>
54+
readonly children: ReadonlyMap<string, Child>
5355
readonly openChildren: ReadonlySet<string>
5456
readonly asks: ReadonlySet<string>
5557
readonly finish?: SessionMessage.Assistant["finish"]
@@ -69,9 +71,9 @@ export type Output =
6971
readonly _tag: "PermissionAsk"
7072
readonly event: PermissionEvent
7173
readonly tool?: Tool
72-
readonly child?: ACPChild.Session
74+
readonly child?: Child
7375
}
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 }
7577
| { readonly _tag: "AskSettled"; readonly id: string }
7678

7779
export type Folded = {
@@ -95,20 +97,21 @@ export function fold(state: TurnState, event: OpenCodeEvent, ctx: TurnContext):
9597

9698
const sessionID = sessionIDFromEvent(event)
9799
const child = sessionID ? state.children.get(sessionID) : undefined
100+
const openChild = child && state.openChildren.has(child.id) ? child : undefined
98101

99-
if (event.type === "permission.asked" && (event.data.sessionID === ctx.sessionID || child)) {
102+
if (event.type === "permission.asked" && (event.data.sessionID === ctx.sessionID || openChild)) {
100103
const tool = event.data.source?.id
101104
? state.tools.get(toolKey(event.data.sessionID, event.data.source.id))
102105
: undefined
103106
return {
104107
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 }],
106109
}
107110
}
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)) {
109112
return {
110113
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 }],
112115
}
113116
}
114117
const settledID =
@@ -123,15 +126,18 @@ export function fold(state: TurnState, event: OpenCodeEvent, ctx: TurnContext):
123126
return { state: { ...state, asks }, outputs: [{ _tag: "AskSettled", id: settledID }] }
124127
}
125128
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+
)
127134
return { state: { ...state, started: true }, outputs: [] }
128-
if (!state.started) return { state, outputs: [] }
135+
if (!child && !state.started) return { state, outputs: [] }
129136
return child ? childEvent(state, event, ctx, child) : rootEvent(state, event, ctx)
130137
}
131138

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
135141
}
136142

137143
export function failure(state: TurnState) {
@@ -202,7 +208,13 @@ function childCreated(state: TurnState, event: CreatedEvent, ctx: TurnContext):
202208
if (!parentID) return { state, outputs: [] }
203209
const parent = parentID === ctx.sessionID ? undefined : state.children.get(parentID)
204210
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+
}
206218
return {
207219
state: {
208220
...state,
@@ -224,20 +236,27 @@ function rootEvent(state: TurnState, event: OpenCodeEvent, ctx: TurnContext): Fo
224236
return { state: { ...recorded, stepError: event.data.error }, outputs: [] }
225237
}
226238
case "session.execution.succeeded":
227-
return { state, outputs: [], terminal: "succeeded" }
239+
return { state: { ...state, started: Boolean(ctx.start) }, outputs: [], terminal: "succeeded" }
228240
case "session.execution.interrupted":
229-
return { state, outputs: [], terminal: "interrupted" }
241+
return { state: { ...state, started: Boolean(ctx.start) }, outputs: [], terminal: "interrupted" }
230242
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+
}
232248
default:
233249
return sessionEvent(state, event, ctx, undefined)
234250
}
235251
}
236252

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 {
238254
switch (event.type) {
239255
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+
}
241260
case "session.execution.succeeded":
242261
return childEnded(state, ctx, child, { type: "status", status: "completed" })
243262
case "session.execution.interrupted":
@@ -249,12 +268,7 @@ function childEvent(state: TurnState, event: OpenCodeEvent, ctx: TurnContext, ch
249268
}
250269
}
251270

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 {
258272
const sessionID = child?.id ?? ctx.sessionID
259273
const send = (update: SessionUpdate) => route(ctx, child, update)
260274
switch (event.type) {
@@ -415,11 +429,11 @@ function newTool(sessionID: string, id: string, name = "tool"): Tool {
415429
return { sessionID, id, name, input: {}, metadata: {} }
416430
}
417431

418-
function route(ctx: TurnContext, child: ACPChild.Session | undefined, update: SessionUpdate): Output[] {
432+
function route(ctx: TurnContext, child: Child | undefined, update: SessionUpdate): Output[] {
419433
if (!child) return [{ _tag: "SessionUpdate", update }]
420434
const projected = ACPChild.project(update, child)
421435
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 }] : []
423437
}
424438

425439
function childStatus(ctx: TurnContext, child: ACPChild.Session, event: ACPChild.Event): Output[] {
Collapse file

‎packages/cli/src/acp/turn.ts‎

Copy file name to clipboardExpand all lines: packages/cli/src/acp/turn.ts
+44-18Lines changed: 44 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ import { findModel, type ACPCatalog } from "./catalog"
2121
import { ACPChild } from "./child"
2222
import { ACPClient } from "./client"
2323
import { currentModel } from "./config-option"
24-
import type { ACPConnection } from "./connection"
24+
import { ACPConnection } from "./connection"
2525
import { ACPElicitation } from "./elicitation"
2626
import { ACPError } from "./error"
2727
import { ACPPermission } from "./permission"
@@ -60,7 +60,11 @@ type Turn = {
6060
readonly state: Ref.Ref<ACPTranslate.TurnState>
6161
readonly subscription: Subscription
6262
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>
6468
}
6569

6670
export const make = Effect.fnUntraced(function* (input: {
@@ -73,8 +77,24 @@ export const make = Effect.fnUntraced(function* (input: {
7377
const scope = yield* Effect.scope
7478
const drainTimeout = yield* CancelDrainTimeout
7579
const turns = yield* FiberMap.make<string, PromptResponse, ACPError.Failure>()
80+
const backgrounds = new WeakMap<Attached, Background>()
7681

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+
}
7898
// Parented to the service scope; the session scope may already be closed.
7999
const subscriptionScope = yield* Scope.fork(scope)
80100
const subscription: Subscription = {
@@ -93,7 +113,7 @@ export const make = Effect.fnUntraced(function* (input: {
93113
Effect.forever,
94114
Effect.forkIn(subscriptionScope),
95115
)
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
97117
})
98118

99119
const take = (subscription: Subscription) =>
@@ -141,7 +161,6 @@ export const make = Effect.fnUntraced(function* (input: {
141161
const interpret = (turn: Turn, output: ACPTranslate.Output) => {
142162
switch (output._tag) {
143163
case "SessionUpdate":
144-
if (turn.background) return Effect.void
145164
return ACPPermission.withCompletedDiffs(output.update, output.diff, turn.ctx.cwd).pipe(
146165
Effect.flatMap((update) => input.connection.sessionUpdate({ sessionId: turn.ctx.sessionID, update })),
147166
)
@@ -185,7 +204,7 @@ export const make = Effect.fnUntraced(function* (input: {
185204
requestedSchema,
186205
clientSessionID: turn.ctx.sessionID,
187206
child: output.child,
188-
toolCallSent: !turn.background && (!output.child || !turn.ctx.childUpdates),
207+
toolCallSent: !output.child || ACPTranslate.projectChild(turn.ctx, output.child),
189208
}
190209
yield* queueAsk(turn, output.form.id, ACPElicitation.ask(elicitation), "cancel", (outcome) =>
191210
ACPElicitation.respond(elicitation, outcome),
@@ -203,10 +222,7 @@ export const make = Effect.fnUntraced(function* (input: {
203222
const advance = Effect.fnUntraced(function* (turn: Turn) {
204223
const event = yield* take(turn.subscription)
205224
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)
210226
return [next, next.state]
211227
})
212228
yield* Effect.forEach(folded.outputs, (output) => interpret(turn, output), { discard: true })
@@ -226,7 +242,7 @@ export const make = Effect.fnUntraced(function* (input: {
226242
const followChildren = Effect.fnUntraced(function* (turn: Turn) {
227243
while (true) {
228244
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)
230246
}
231247
})
232248

@@ -312,13 +328,22 @@ export const make = Effect.fnUntraced(function* (input: {
312328
const close = Scope.close(turn.subscription.scope, Exit.void)
313329
if (Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause)) return yield* close
314330
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+
)
322347
}).pipe(Effect.ignore, Effect.ensuring(close), Effect.withSpan("cli.acp.turn.background"))
323348
yield* input.sessions.fork(attached, background).pipe(Effect.catchTag("ACPSessionNotFoundError", () => close))
324349
})
@@ -368,6 +393,7 @@ export const make = Effect.fnUntraced(function* (input: {
368393
const state = yield* Ref.make(ACPTranslate.initial)
369394
const exit = yield* Effect.acquireUseRelease(
370395
open(
396+
attached,
371397
{
372398
sessionID: attached.id,
373399
cwd: attached.cwd,
Collapse file

‎packages/cli/test/acp/background-turn.subprocess.test.ts‎

Copy file name to clipboard
+48Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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

‎packages/cli/test/acp/subprocess.ts‎

Copy file name to clipboardExpand all lines: packages/cli/test/acp/subprocess.ts
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ type AcpProcess = {
3737
readonly pid: number
3838
readonly exited: Promise<number>
3939
readonly request: <T>(method: string, params?: unknown) => Promise<JsonRpcResponse<T>>
40+
readonly waitForMessage: (predicate: Waiter["predicate"], description: string) => Promise<JsonRpcMessage>
4041
readonly close: () => Promise<number>
4142
readonly stderr: () => string
4243
readonly [Symbol.asyncDispose]: () => Promise<void>
@@ -294,6 +295,7 @@ function spawnAcp(input: { readonly env: Record<string, string | undefined> }):
294295
pid: child.pid,
295296
exited: child.exited,
296297
request,
298+
waitForMessage: (predicate, description) => take(predicate, 10_000, description),
297299
async close() {
298300
if (!inputClosed) {
299301
inputClosed = true

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.