mirror of
https://github.com/stablyai/orca.git
synced 2026-11-16 10:58:10 +00:00
fix(native-chat): a Stop also ends running OpenCode subagents, and each subagent can be stopped from the strip
Co-authored-by: SeaBee <85791528+seabee33@users.noreply.github.com>
This commit is contained in:
@@ -122,6 +122,8 @@ export type AcpDialect = {
|
||||
request(sessionId: string, id: string): { method: string; params: unknown }
|
||||
response(value: unknown, id: string): { cancelled: boolean; state?: NativeChatSubagentState }
|
||||
}
|
||||
/** Subagents are child sessions that `session/close` interrupts; a user's Stop also ends them. */
|
||||
childSessionStop?: { supported(initialized: InitializeResponse): boolean }
|
||||
backgroundTaskStop?: {
|
||||
/** Probe without a target to establish support without killing a task. */
|
||||
probe: { method: string; params: unknown }
|
||||
|
||||
@@ -107,6 +107,9 @@ export const OPENCODE_ACP_DIALECT: AcpDialect = {
|
||||
elicitation: { form: {} },
|
||||
_meta: { [OPENCODE_CHILD_SESSION_CAPABILITY]: true }
|
||||
},
|
||||
childSessionStop: {
|
||||
supported: (initialized) => initialized.agentCapabilities?.sessionCapabilities?.close != null
|
||||
},
|
||||
effortChangesModel: true,
|
||||
normalizeToolUpdate,
|
||||
notification: openCodeChildUpdate,
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
{"direction":"out","process":"p1","message":{"jsonrpc":"2.0","id":3,"method":"session/prompt","params":{"sessionId":"session-1","prompt":[{"type":"text","text":"Use the subagent tool with background set to true to launch exactly one general subagent. The subagent must run the shell command 'sleep 120' and then reply with exactly: DONE. Do not run anything yourself and do not wait for it: reply 'launched' right after starting it."}]}}}
|
||||
{"direction":"in","process":"p1","message":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-1","update":{"sessionUpdate":"agent_thought_chunk","messageId":"msg_1befc629e001BtckkrEabxBVf7:reasoning:0","content":{"type":"text","text":"**Making the call**\n\nI shouldn't wait too long, so"}}}}}
|
||||
{"direction":"in","process":"p1","message":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-1","update":{"sessionUpdate":"agent_thought_chunk","messageId":"msg_1befc629e001BtckkrEabxBVf7:reasoning:0","content":{"type":"text","text":" I\u2019ll go ahead and make the call now. I think it's best to act"}}}}}
|
||||
{"direction":"in","process":"p1","message":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-1","update":{"sessionUpdate":"agent_thought_chunk","messageId":"msg_1befc629e001BtckkrEabxBVf7:reasoning:0","content":{"type":"text","text":" quickly and reply with \"launched\" right after. That way, I can"}}}}}
|
||||
{"direction":"in","process":"p1","message":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-1","update":{"sessionUpdate":"agent_thought_chunk","messageId":"msg_1befc629e001BtckkrEabxBVf7:reasoning:0","content":{"type":"text","text":" keep things moving smoothly and avoid any unnecessary delays."}}}}}
|
||||
{"direction":"in","process":"p1","message":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-1","update":{"sessionUpdate":"tool_call","toolCallId":"3ad8324f-4876-4f90-b0ae-1273427d1d7f","title":"subagent","kind":"think","status":"pending","locations":[],"rawInput":{}}}}}
|
||||
{"direction":"in","process":"p1","message":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-1","update":{"sessionUpdate":"tool_call_update","toolCallId":"3ad8324f-4876-4f90-b0ae-1273427d1d7f","status":"in_progress","kind":"think","title":"subagent","locations":[],"rawInput":{"agent":"general","description":"Run sleep command","prompt":"Run the shell command `sleep 120`, then reply with exactly: DONE","background":true}}}}}
|
||||
{"direction":"in","process":"p1","message":{"jsonrpc":"2.0","method":"opencode/session/child_update","params":{"rootSessionId":"session-1","childSessionId":"session-2","parentSessionId":"session-1","depth":1,"title":"Run sleep command","type":"status","status":"created"}}}
|
||||
{"direction":"in","process":"p1","message":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-1","update":{"sessionUpdate":"tool_call_update","toolCallId":"3ad8324f-4876-4f90-b0ae-1273427d1d7f","status":"in_progress","kind":"think","title":"subagent","locations":[],"rawInput":{"agent":"general","description":"Run sleep command","prompt":"Run the shell command `sleep 120`, then reply with exactly: DONE","background":true}}}}}
|
||||
{"direction":"in","process":"p1","message":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-1","update":{"sessionUpdate":"tool_call_update","toolCallId":"3ad8324f-4876-4f90-b0ae-1273427d1d7f","status":"completed","content":[{"type":"content","content":{"type":"text","text":"The subagent is working in the background (sessionID: session-2). You will be notified automatically when it finishes.\nDO NOT sleep, poll for progress, ask the subagent for status, or duplicate this subagent's work; avoid working with the same files or topics it is using.\nWork on non-overlapping tasks, or briefly tell the user what you launched and end your response."}}],"rawOutput":{"metadata":{"sessionID":"session-2","status":"running","truncated":false}}}}}}
|
||||
{"direction":"in","process":"p1","message":{"jsonrpc":"2.0","method":"opencode/session/child_update","params":{"rootSessionId":"session-1","childSessionId":"session-2","parentSessionId":"session-1","depth":1,"title":"Run sleep command","type":"status","status":"running"}}}
|
||||
{"direction":"in","process":"p1","message":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-1","update":{"sessionUpdate":"agent_message_chunk","messageId":"msg_1befc912d001mbRu2ZMleT1Flv","content":{"type":"text","text":"launched"}}}}}
|
||||
{"direction":"in","process":"p1","message":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session-1","update":{"sessionUpdate":"usage_update","used":6284,"size":262144,"cost":{"amount":0,"currency":"USD"}}}}}
|
||||
{"direction":"in","process":"p1","message":{"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn","usage":{"inputTokens":6244,"outputTokens":13,"totalTokens":6284,"thoughtTokens":27},"_meta":{}}}}
|
||||
{"direction":"in","process":"p1","message":{"jsonrpc":"2.0","method":"opencode/session/child_update","params":{"rootSessionId":"session-1","childSessionId":"session-2","parentSessionId":"session-1","depth":1,"title":"Run sleep command","type":"update","update":{"sessionUpdate":"tool_call","toolCallId":"session-2:0bcac73a-71c8-45cf-a7c4-100872ad385a","title":"Run sleep command: shell","kind":"execute","status":"pending","locations":[{"path":"/workspace/project"}],"rawInput":{"cwd":"/workspace/project"},"_meta":{"opencode/child-session":{"id":"session-2","parentID":"session-1","depth":1,"title":"Run sleep command"}}}}}}
|
||||
{"direction":"in","process":"p1","message":{"jsonrpc":"2.0","method":"opencode/session/child_update","params":{"rootSessionId":"session-1","childSessionId":"session-2","parentSessionId":"session-1","depth":1,"title":"Run sleep command","type":"update","update":{"sessionUpdate":"tool_call_update","toolCallId":"session-2:0bcac73a-71c8-45cf-a7c4-100872ad385a","status":"in_progress","kind":"execute","title":"Run sleep command: sleep 120","locations":[{"path":"/workspace/project"}],"rawInput":{"command":"sleep 120","timeout":150000,"cwd":"/workspace/project"},"_meta":{"opencode/child-session":{"id":"session-2","parentID":"session-1","depth":1,"title":"Run sleep command"}}}}}}
|
||||
{"direction":"in","process":"p1","message":{"jsonrpc":"2.0","method":"opencode/session/child_update","params":{"rootSessionId":"session-1","childSessionId":"session-2","parentSessionId":"session-1","depth":1,"title":"Run sleep command","type":"update","update":{"sessionUpdate":"tool_call_update","toolCallId":"session-2:0bcac73a-71c8-45cf-a7c4-100872ad385a","status":"in_progress","kind":"execute","title":"Run sleep command: sleep 120","locations":[{"path":"/workspace/project"}],"rawInput":{"command":"sleep 120","timeout":150000,"cwd":"/workspace/project"},"_meta":{"opencode/child-session":{"id":"session-2","parentID":"session-1","depth":1,"title":"Run sleep command"}}}}}}
|
||||
{"direction":"out","process":"p1","message":{"jsonrpc":"2.0","id":4,"method":"session/close","params":{"sessionId":"session-2"}}}
|
||||
{"direction":"in","process":"p1","message":{"jsonrpc":"2.0","id":4,"result":{}}}
|
||||
{"direction":"in","process":"p1","message":{"jsonrpc":"2.0","method":"opencode/session/child_update","params":{"rootSessionId":"session-1","childSessionId":"session-2","parentSessionId":"session-1","depth":1,"title":"Run sleep command","type":"update","update":{"sessionUpdate":"tool_call_update","toolCallId":"session-2:0bcac73a-71c8-45cf-a7c4-100872ad385a","status":"failed","kind":"execute","title":"Run sleep command: sleep 120","locations":[{"path":"/workspace/project"}],"rawInput":{"command":"sleep 120","timeout":150000,"cwd":"/workspace/project"},"content":[{"type":"content","content":{"type":"text","text":"Tool execution interrupted"}}],"rawOutput":{"metadata":{"shellID":"sh_1befc9b29001Mn4kU1bJGd2uL4"},"error":"Tool execution interrupted"},"_meta":{"opencode/child-session":{"id":"session-2","parentID":"session-1","depth":1,"title":"Run sleep command"}}}}}}
|
||||
{"direction":"in","process":"p1","message":{"jsonrpc":"2.0","method":"opencode/session/child_update","params":{"rootSessionId":"session-1","childSessionId":"session-2","parentSessionId":"session-1","depth":1,"title":"Run sleep command","type":"status","status":"interrupted"}}}
|
||||
@@ -13,6 +13,7 @@ export type AcpStructuredConnection = Pick<
|
||||
| 'setConfigOption'
|
||||
| 'setModel'
|
||||
| 'requestExtension'
|
||||
| 'closeSession'
|
||||
| 'subscribe'
|
||||
| 'closed'
|
||||
| 'spawned'
|
||||
|
||||
@@ -145,6 +145,9 @@ export class AcpSessionRuntime {
|
||||
/** Requires advertised session deletion support. */
|
||||
deleteSession = (sessionId: string) => this.call('session/delete', { sessionId }, z.unknown())
|
||||
|
||||
/** Any session the agent reports on this connection, including a subagent's child session. */
|
||||
closeSession = (sessionId: string) => this.call('session/close', { sessionId }, z.unknown())
|
||||
|
||||
start(
|
||||
options: AcpSessionStartOptions,
|
||||
received?: (started: AcpSessionStarted) => void
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
import { acpLaunchSpecFor } from '../launch/acp-launch-registry'
|
||||
import {
|
||||
openAcpAdapterRig,
|
||||
PROVIDER_SESSION,
|
||||
waitFor,
|
||||
type AcpAdapterRig
|
||||
} from './testing/acp-structured-adapter.test-support'
|
||||
@@ -172,4 +173,49 @@ describe('OpenCode 2 recordings through the adapter', () => {
|
||||
)
|
||||
expect((await rowsOf(rig, 'tool-call')).at(-1)?.body).toMatchObject({ state: 'failed' })
|
||||
})
|
||||
|
||||
it('a Stop also ends a background subagent the finished turn left running', async () => {
|
||||
// OpenCode 2.0.21 shapes (opencode-v2-subagent-close): the child reports itself interrupted.
|
||||
const child = {
|
||||
rootSessionId: PROVIDER_SESSION,
|
||||
childSessionId: 'child-1',
|
||||
parentSessionId: PROVIDER_SESSION,
|
||||
depth: 1,
|
||||
title: 'Run sleep command'
|
||||
}
|
||||
const closed: unknown[] = []
|
||||
const rig = await openAcpAdapterRig({
|
||||
spec: acpLaunchSpecFor('opencode2')!,
|
||||
initialize: { agentCapabilities: { loadSession: true, sessionCapabilities: { close: {} } } },
|
||||
script: (agent) => {
|
||||
agent.on('session/prompt', (frame) => {
|
||||
agent.notify('opencode/session/child_update', {
|
||||
...child,
|
||||
type: 'status',
|
||||
status: 'running'
|
||||
})
|
||||
agent.reply(frame, { stopReason: 'end_turn' })
|
||||
})
|
||||
agent.on('session/close', (frame) => {
|
||||
closed.push(frame.params)
|
||||
agent.reply(frame, {})
|
||||
agent.notify('opencode/session/child_update', {
|
||||
...child,
|
||||
type: 'status',
|
||||
status: 'interrupted'
|
||||
})
|
||||
})
|
||||
}
|
||||
})
|
||||
await rig.acquire()
|
||||
await rig.adapter.dispatch({
|
||||
sessionId: SESSION,
|
||||
clientMessageId: 'send-1',
|
||||
body: ask,
|
||||
fence: 1
|
||||
})
|
||||
await waitFor(async () => expect(await turns(rig)).toMatchObject([{ state: 'completed' }]))
|
||||
await rig.adapter.cancelTurn({ sessionId: SESSION, fence: 1 })
|
||||
await waitFor(() => expect(closed).toEqual([{ sessionId: 'child-1' }]))
|
||||
})
|
||||
})
|
||||
|
||||
@@ -25,7 +25,11 @@ import {
|
||||
import { readAcpLiveOptions } from '../options/acp-live-options'
|
||||
import { writeAcpSessionOption } from '../options/acp-session-option-write'
|
||||
import { acpOptionWriteBound, withAcpModelFallback } from '../turns/acp-model-command'
|
||||
import { stopAcpChildren, acpChildStopCapabilities } from '../turns/acp-structured-child-stop'
|
||||
import {
|
||||
acpChildStopCapabilities,
|
||||
closeAcpChildSessions,
|
||||
stopAcpChildren
|
||||
} from '../turns/acp-structured-child-stop'
|
||||
import * as childState from './children/acp-structured-child'
|
||||
import { AcpStructuredChildren } from './children/acp-structured-child-lifecycle'
|
||||
import { AcpConversationCopies } from '../conversation-copy/acp-conversation-copies'
|
||||
@@ -151,6 +155,8 @@ export class AcpStructuredSessionAdapter implements SessionAdapter {
|
||||
if (input.turnId !== undefined && liveTurnId !== null && input.turnId !== liveTurnId) {
|
||||
return { cancelled: false, refusal: { turnNotRunning: true } }
|
||||
}
|
||||
// A user's Stop ends subagents too, even when the root turn ended just before it arrived.
|
||||
closeAcpChildSessions(session)
|
||||
if (!stop.acpStopHasWork(session)) {
|
||||
return { cancelled: false, refusal: { turnNotRunning: true } }
|
||||
}
|
||||
|
||||
@@ -147,7 +147,7 @@ export async function initializeAcpStructuredSession(
|
||||
})
|
||||
assertStarting()
|
||||
}
|
||||
const childStops = await probeAcpChildStops(connection, spec.dialect)
|
||||
const childStops = await probeAcpChildStops(connection, spec.dialect, initialized)
|
||||
assertStarting()
|
||||
liveLane.apply(liveLane.translator.contextModels(started.response.models, now()))
|
||||
const mode = spec.permissionModeConfig
|
||||
|
||||
@@ -21,11 +21,15 @@ import { acpSubagentOutcome, type AcpSubagents } from './acp-subagents'
|
||||
import type { AcpToolTimeline } from './acp-tool-timeline'
|
||||
import { acpNamedTextKey } from './acp-turn-messages'
|
||||
|
||||
const textKey = (item: ProviderTimelineTextItem): string => ('id' in item ? item.id : item.stream)
|
||||
|
||||
const sessionSchema = z.object({ sessionId: z.string() })
|
||||
|
||||
export class AcpChildSessions {
|
||||
/** ACP has no message end, so each child's text stays open until the child ends. */
|
||||
private readonly openText = new Map<string, Map<string, ProviderTimelineTextItem>>()
|
||||
/** ACP has no message end; a child's text closes at the next message on its channel, or when it ends. */
|
||||
private readonly openText = new Map<string, ProviderTimelineTextItem>()
|
||||
/** Children that have not reported an ending, which a user's Stop also ends. */
|
||||
private readonly running = new Set<string>()
|
||||
|
||||
constructor(
|
||||
private readonly rootSessionId: string,
|
||||
@@ -34,6 +38,10 @@ export class AcpChildSessions {
|
||||
private readonly tools: AcpToolTimeline
|
||||
) {}
|
||||
|
||||
live(): readonly string[] {
|
||||
return [...this.running]
|
||||
}
|
||||
|
||||
/** A child session's events, or undefined when the notification is the root's own. */
|
||||
notification(
|
||||
method: string,
|
||||
@@ -70,9 +78,10 @@ export class AcpChildSessions {
|
||||
if (child.rootSessionId !== rootSessionId) {
|
||||
return []
|
||||
}
|
||||
const known = subagents.has(child.agentId)
|
||||
// Plain frames for a known child carry no lifecycle, so they publish no evidence.
|
||||
const events =
|
||||
subagents.has(child.agentId) && child.state === undefined
|
||||
known && child.state === undefined
|
||||
? []
|
||||
: subagents.translate(
|
||||
[
|
||||
@@ -96,8 +105,16 @@ export class AcpChildSessions {
|
||||
})
|
||||
)
|
||||
}
|
||||
if (child.state !== undefined && acpSubagentOutcome(child.state) !== undefined) {
|
||||
events.push(...this.closeText(child.agentId))
|
||||
if (child.state === undefined || acpSubagentOutcome(child.state) === undefined) {
|
||||
if (child.state !== undefined || !known) {
|
||||
this.running.add(child.agentId)
|
||||
}
|
||||
} else {
|
||||
this.running.delete(child.agentId)
|
||||
events.push(
|
||||
...this.closeText(`${child.agentId}:assistant`),
|
||||
...this.closeText(`${child.agentId}:reasoning`)
|
||||
)
|
||||
}
|
||||
return events
|
||||
}
|
||||
@@ -123,10 +140,14 @@ export class AcpChildSessions {
|
||||
const item = update.messageId
|
||||
? { id: acpNamedTextKey(update.messageId, channel) }
|
||||
: { stream: `${producer.agentId}:${update.sessionUpdate}` }
|
||||
const open = this.openText.get(producer.agentId) ?? new Map()
|
||||
open.set('id' in item ? item.id : item.stream, item)
|
||||
this.openText.set(producer.agentId, open)
|
||||
events = [{ type: 'text.delta', item, channel, text: update.content.text }]
|
||||
// OpenCode keeps one fragment per channel open, so only a new message on the same channel ends one.
|
||||
const slot = `${producer.agentId}:${channel}`
|
||||
const open = this.openText.get(slot)
|
||||
events = [
|
||||
...(open === undefined || textKey(open) === textKey(item) ? [] : this.closeText(slot)),
|
||||
{ type: 'text.delta', item, channel, text: update.content.text }
|
||||
]
|
||||
this.openText.set(slot, item)
|
||||
} else if (
|
||||
update.sessionUpdate === 'tool_call' ||
|
||||
update.sessionUpdate === 'tool_call_update'
|
||||
@@ -148,10 +169,10 @@ export class AcpChildSessions {
|
||||
)
|
||||
}
|
||||
|
||||
private closeText(agentId: string): ProviderTimelineEvent[] {
|
||||
const open = this.openText.get(agentId)
|
||||
this.openText.delete(agentId)
|
||||
private closeText(slot: string): ProviderTimelineEvent[] {
|
||||
const item = this.openText.get(slot)
|
||||
this.openText.delete(slot)
|
||||
const join = { thread: this.rootSessionId, scope: AGENT_JOURNAL_THREAD_SCOPE }
|
||||
return [...(open?.values() ?? [])].map((item) => ({ type: 'text.close', item, join }))
|
||||
return item ? [{ type: 'text.close', item, join }] : []
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it } from 'vitest'
|
||||
import type { AgentJournalRenderItem } from '../../../shared/agent-session/journal/agent-session-journal-types'
|
||||
import { closeProviderTimelineRigs } from '../../native-chat/agent-session-timeline/provider-timeline-assembler-test-support'
|
||||
import { OPENCODE_ACP_DIALECT } from '../acp-dialects/opencode-dialect'
|
||||
import { AcpTimelineTranslator } from './acp-timeline-translator'
|
||||
import {
|
||||
openAcpFixtureRig,
|
||||
readAcpFixture,
|
||||
@@ -73,7 +74,11 @@ describe('OpenCode subagents through the shared timeline', () => {
|
||||
const turn = through(frames, (text) => text.includes('"stopReason"'))
|
||||
await fixture.feed(turn)
|
||||
expect(subagents(fixture)).toMatchObject([{ id: 'session-2', membership: 'live' }])
|
||||
const rows = await fixture.feed(frames.slice(turn.length))
|
||||
// Commit each frame before the next, so later tool updates read their placement back.
|
||||
for (const frame of frames.slice(turn.length)) {
|
||||
await fixture.feed([frame])
|
||||
}
|
||||
const rows = await fixture.rig.rows()
|
||||
expect(subagents(fixture)).toMatchObject([
|
||||
{ id: 'session-2', membership: 'settled', outcome: 'succeeded' }
|
||||
])
|
||||
@@ -115,6 +120,22 @@ describe('OpenCode subagents through the shared timeline', () => {
|
||||
).toEqual([])
|
||||
})
|
||||
|
||||
it('closing a background subagent after the turn ends interrupts it and leaves nothing running', async () => {
|
||||
const fixture = await opened()
|
||||
const frames = await readAcpFixture('opencode-v2-subagent-close')
|
||||
const closing = frames.findIndex((frame) => frame.message.method === 'session/close')
|
||||
await fixture.feed(frames.slice(0, closing))
|
||||
expect(fixture.lane().children.live()).toEqual(['session-2'])
|
||||
const rows = await fixture.feed(frames.slice(closing))
|
||||
expect(subagents(fixture)).toMatchObject([
|
||||
{ id: 'session-2', membership: 'settled', outcome: 'cancelled' }
|
||||
])
|
||||
expect(fixture.lane().children.live()).toEqual([])
|
||||
expect(
|
||||
tools(rows).filter((tool) => tool.agentId === 'session-2' && tool.state === 'running')
|
||||
).toEqual([])
|
||||
})
|
||||
|
||||
it('a follow-up to a finished subagent reopens it until its second run ends', async () => {
|
||||
const fixture = await opened()
|
||||
const frames = await readAcpFixture('opencode-v2-subagent-rerun')
|
||||
@@ -128,4 +149,75 @@ describe('OpenCode subagents through the shared timeline', () => {
|
||||
])
|
||||
expect(texts(rows, 'session-2')).toEqual(['FIRST', 'SECOND'])
|
||||
})
|
||||
|
||||
it('a long-running subagent keeps one message open per channel, however many steps it takes', () => {
|
||||
// OpenCode starts new message ids each step and never appends to an earlier step's.
|
||||
const mostOpen = (steps: number) => {
|
||||
const lane = new AcpTimelineTranslator({
|
||||
sessionId: 'session-1',
|
||||
dialect: OPENCODE_ACP_DIALECT
|
||||
})
|
||||
const open = new Set<string>()
|
||||
let most = 0
|
||||
const report = (body: Record<string, unknown>) => {
|
||||
for (const event of lane.notification(
|
||||
'opencode/session/child_update',
|
||||
{ ...CHILD, ...body },
|
||||
1000
|
||||
)) {
|
||||
const key = 'item' in event ? JSON.stringify(event.item) : ''
|
||||
if (event.type === 'text.delta') {
|
||||
open.add(key)
|
||||
} else if (event.type === 'text.close') {
|
||||
open.delete(key)
|
||||
}
|
||||
most = Math.max(most, open.size)
|
||||
}
|
||||
}
|
||||
report({ type: 'status', status: 'running' })
|
||||
for (let step = 0; step < steps; step++) {
|
||||
report(chunk('agent_thought_chunk', `msg-${step}:reasoning:0`, 'thinking'))
|
||||
report(chunk('agent_message_chunk', `msg-${step}`, `step ${step}`))
|
||||
}
|
||||
report({ type: 'status', status: 'completed' })
|
||||
return { most, left: open.size }
|
||||
}
|
||||
expect(mostOpen(10)).toEqual({ most: 2, left: 0 })
|
||||
expect(mostOpen(100)).toEqual({ most: 2, left: 0 })
|
||||
})
|
||||
|
||||
it('a reply that resumes after the subagent thinks or runs a tool keeps all of its text', async () => {
|
||||
const fixture = await opened()
|
||||
const lane = fixture.lane()
|
||||
const report = (body: Record<string, unknown>) =>
|
||||
fixture.apply(lane.notification('opencode/session/child_update', { ...CHILD, ...body }, 1000))
|
||||
report({ type: 'status', status: 'created', title: 'Helper' })
|
||||
report(chunk('agent_message_chunk', 'msg-1', 'A'))
|
||||
report(chunk('agent_thought_chunk', 'msg-1:reasoning:0', 'R'))
|
||||
report({
|
||||
type: 'update',
|
||||
update: {
|
||||
sessionUpdate: 'tool_call',
|
||||
toolCallId: 'session-2:t1',
|
||||
title: 'shell',
|
||||
status: 'pending'
|
||||
}
|
||||
})
|
||||
report(chunk('agent_message_chunk', 'msg-1', 'B'))
|
||||
report({ type: 'status', status: 'completed' })
|
||||
expect(texts(await fixture.rig.rows(), 'session-2')).toEqual(['AB', 'R'])
|
||||
})
|
||||
})
|
||||
|
||||
const CHILD = {
|
||||
rootSessionId: 'session-1',
|
||||
childSessionId: 'session-2',
|
||||
parentSessionId: 'session-1'
|
||||
}
|
||||
|
||||
function chunk(sessionUpdate: string, messageId: string, text: string) {
|
||||
return {
|
||||
type: 'update',
|
||||
update: { sessionUpdate, messageId, content: { type: 'text', text } }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ export class AcpTimelineTranslator {
|
||||
private readonly backgroundTasks: AcpBackgroundTaskTimeline
|
||||
/** Drained by the lane in journal order. */
|
||||
readonly subagents = new AcpSubagents()
|
||||
private readonly children: AcpChildSessions
|
||||
readonly children: AcpChildSessions
|
||||
private readonly ownership: AcpTimelineOwnership
|
||||
private readonly started = new BoundedMap<string, true>({ maxEntries: 128 })
|
||||
private readonly failures: AcpTurnFailures
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
import type { ProviderTimelineEvent } from '../../../native-chat/agent-session-timeline/provider-timeline-event'
|
||||
import {
|
||||
AGENT,
|
||||
NAMESPACE,
|
||||
SESSION,
|
||||
openProviderTimelineRig
|
||||
} from '../../../native-chat/agent-session-timeline/provider-timeline-assembler-test-support'
|
||||
@@ -81,15 +80,22 @@ export async function openAcpFixtureRig(
|
||||
dialect: AcpDialect = GROK_ACP_DIALECT,
|
||||
{ journalOwnership = false }: { journalOwnership?: boolean } = {}
|
||||
) {
|
||||
const rig = await openProviderTimelineRig()
|
||||
let providerSessionId = 'session-1'
|
||||
// Production lanes key the journal namespace by the provider session the reader resolves.
|
||||
const rig = await openProviderTimelineRig(
|
||||
journalOwnership ? { namespace: providerSessionId } : {}
|
||||
)
|
||||
const scheme = createLegacyProviderTimelineIdentityScheme({ agent: AGENT, sessionId: SESSION })
|
||||
const translator = () =>
|
||||
new AcpTimelineTranslator({
|
||||
sessionId: providerSessionId,
|
||||
dialect,
|
||||
...(journalOwnership
|
||||
? { ownership: createAcpOwnershipReader(scheme, NAMESPACE, () => rig.sink.journalItems()) }
|
||||
? {
|
||||
ownership: createAcpOwnershipReader(scheme, providerSessionId, () =>
|
||||
rig.sink.journalItems()
|
||||
)
|
||||
}
|
||||
: {})
|
||||
})
|
||||
let lane = translator()
|
||||
|
||||
@@ -6,6 +6,7 @@ import type { AcpStructuredSession } from '../session/acp-structured-session-con
|
||||
import type { AcpStructuredConnection } from '../process/acp-structured-connection'
|
||||
import type { AcpChildStops, AcpDialect } from '../acp-dialects/acp-dialect'
|
||||
import { AcpAgentError } from '../transport/acp-errors'
|
||||
import type { InitializeResponse } from '../generated/acp-protocol.generated'
|
||||
import type {
|
||||
AgentChildWorkStopAcknowledgement,
|
||||
AgentSessionBackgroundTaskStops
|
||||
@@ -72,15 +73,43 @@ async function probeAcpBackgroundTaskStop(
|
||||
|
||||
export async function probeAcpChildStops(
|
||||
connection: AcpStructuredConnection,
|
||||
dialect: AcpDialect
|
||||
dialect: AcpDialect,
|
||||
initialized: InitializeResponse
|
||||
): Promise<AcpChildStops> {
|
||||
const [subagents, backgroundTasks] = await Promise.all([
|
||||
probeAcpSubagentStop(connection, dialect),
|
||||
dialect.childSessionStop?.supported(initialized) === true ||
|
||||
probeAcpSubagentStop(connection, dialect),
|
||||
probeAcpBackgroundTaskStop(connection, dialect)
|
||||
])
|
||||
return { subagents, backgroundTasks }
|
||||
}
|
||||
|
||||
/** The reply only says the request arrived; the child's own report settles it. */
|
||||
async function closeAcpChildSession(
|
||||
session: AcpStructuredSession,
|
||||
id: string
|
||||
): Promise<ChildStopResult> {
|
||||
try {
|
||||
await session.connection.closeSession(id)
|
||||
return { cancelled: true }
|
||||
} catch (error) {
|
||||
if (error instanceof AcpAgentError) {
|
||||
return { cancelled: false, stillRunning: true }
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/** A user's Stop also ends subagents that outlive the cancelled turn. */
|
||||
export function closeAcpChildSessions(session: AcpStructuredSession): void {
|
||||
if (!session.childStops?.subagents || !session.spec.dialect.childSessionStop) {
|
||||
return
|
||||
}
|
||||
for (const id of session.lane.translator.children.live()) {
|
||||
void session.connection.closeSession(id).catch(() => undefined)
|
||||
}
|
||||
}
|
||||
|
||||
async function stopAcpSubagent(
|
||||
session: AcpStructuredSession,
|
||||
control: SubagentStop,
|
||||
@@ -145,13 +174,21 @@ export async function stopAcpChildren(
|
||||
taskIds: readonly string[],
|
||||
acknowledge: (acknowledgement: AgentChildWorkStopAcknowledgement) => void = () => {}
|
||||
): Promise<{ cancelled: boolean; stillRunning?: true }> {
|
||||
const childSessions =
|
||||
session.childStops?.subagents === true && !!session.spec.dialect.childSessionStop
|
||||
const subagentStop = session.childStops?.subagents ? session.spec.dialect.subagentStop : undefined
|
||||
const taskStop = session.childStops?.backgroundTasks
|
||||
? session.spec.dialect.backgroundTaskStop
|
||||
: undefined
|
||||
const routed = (id: string) =>
|
||||
acpBackgroundTaskStopId(id) === undefined ? subagentStop !== undefined : taskStop !== undefined
|
||||
if (session.fence !== fence || (!subagentStop && !taskStop) || !taskIds.every(routed)) {
|
||||
acpBackgroundTaskStopId(id) === undefined
|
||||
? subagentStop !== undefined || childSessions
|
||||
: taskStop !== undefined
|
||||
if (
|
||||
session.fence !== fence ||
|
||||
(!subagentStop && !childSessions && !taskStop) ||
|
||||
!taskIds.every(routed)
|
||||
) {
|
||||
throw new Error('ACP child cancellation is unavailable')
|
||||
}
|
||||
let cancelled = false
|
||||
@@ -161,9 +198,11 @@ export async function stopAcpChildren(
|
||||
const result: ChildStopResult =
|
||||
taskId !== undefined && taskStop
|
||||
? await stopAcpBackgroundTask(session, taskStop, taskId)
|
||||
: subagentStop
|
||||
? await stopAcpSubagent(session, subagentStop, id)
|
||||
: { cancelled: false }
|
||||
: childSessions
|
||||
? await closeAcpChildSession(session, id)
|
||||
: subagentStop
|
||||
? await stopAcpSubagent(session, subagentStop, id)
|
||||
: { cancelled: false }
|
||||
cancelled ||= result.cancelled
|
||||
stillRunning ||= result.stillRunning === true
|
||||
if (result.acknowledged) {
|
||||
|
||||
Reference in New Issue
Block a user