Compare commits

...
Author SHA1 Message Date
paseo-bot[bot] 021b4c8e0b fix(opencode): deliver the delegated child’s final result
Keep the finish subscription active while tracked background work is pending. Recheck it when a native subagent settles during an idle turn.
2026-12-01 05:27:54 +00:00
6 changed files with 204 additions and 18 deletions
@@ -1,6 +1,5 @@
import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages";
import type { AgentStreamEvent } from "../../agent-sdk-types.js";
import type { HostObservation } from "../../host-operations/index.js";
import type { HostObservation, HostObservationEvent } from "../../host-operations/index.js";
import type { FinishSubscription, FinishObservationSession } from "../index.js";
import { createObservationBuffer } from "./observation-buffer.js";
@@ -11,7 +10,7 @@ interface ObservationScope {
signal?: AbortSignal,
): Promise<T>;
}
function isTerminal(snapshot: AgentSnapshotPayload, event?: AgentStreamEvent): boolean {
function isTerminal(snapshot: AgentSnapshotPayload, event?: HostObservationEvent): boolean {
if (snapshot.status === "closed" || snapshot.status === "error") return true;
return (
snapshot.status === "idle" &&
@@ -21,7 +20,7 @@ function isTerminal(snapshot: AgentSnapshotPayload, event?: AgentStreamEvent): b
function observeState(
buffer: ReturnType<typeof createObservationBuffer>,
snapshot: AgentSnapshotPayload | null,
event?: AgentStreamEvent,
event?: HostObservationEvent,
lastMessage: string | null = null,
): void {
if (!snapshot) {
@@ -33,7 +32,7 @@ function observeState(
return;
}
if (event?.type === "turn_started") return;
if (event?.type === "background_work") {
if (event?.type === "work_changed") {
// An idle child's work can settle without another turn.
if (snapshot.status === "idle")
buffer.push({ status: "idle", final: snapshot, lastMessage, error: null, workChanged: true });
@@ -4,9 +4,12 @@ import type { AgentStorage } from "../../agent-storage.js";
import type { AgentMessageDelivery } from "../../agent-messages/index.js";
import { buildStoredAgentPayload, toAgentPayload } from "../../agent-projections.js";
import { serializeSnapshotWithMetadata } from "../../mcp-shared.js";
import { createHostObservationResolver, type ToolHosts } from "../../host-operations/index.js";
import {
createHostObservationResolver,
type HostObservationEvent,
type ToolHosts,
} from "../../host-operations/index.js";
import { openFinishObservation } from "./observation-stream.js";
import type { AgentStreamEvent } from "../../agent-sdk-types.js";
import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages";
import type { FinishObservation, PendingWork } from "../index.js";
@@ -62,7 +65,7 @@ export function createFinishObservation(input: {
await input.waitForResume(agentId, signal);
const stored = await agentStorage.get(agentId);
let updates = Promise.resolve();
const publish = (snapshot: AgentSnapshotPayload | null, event?: AgentStreamEvent) => {
const publish = (snapshot: AgentSnapshotPayload | null, event?: HostObservationEvent) => {
updates = updates
.then(async () =>
handler(snapshot, event, await agentManager.getLastAssistantMessage(agentId)),
@@ -74,13 +77,14 @@ export function createFinishObservation(input: {
(event) => {
if (event.type === "agent_state" && event.agent.lifecycle !== "idle")
publish(toAgentPayload(event.agent, { title: stored?.title }));
else if (event.type === "background_work") {
else if (
event.type === "background_work" ||
(event.type === "provider_subagent" && event.event.type !== "timeline")
) {
const current = agentManager.getAgent(agentId);
if (current)
if (current?.lifecycle === "idle")
publish(toAgentPayload(current, { title: stored?.title }), {
type: "background_work",
provider: current.provider,
items: event.items,
type: "work_changed",
});
} else if (
event.type === "agent_stream" &&
@@ -66,13 +66,15 @@ export class HostObservationError extends Error {
this.name = "HostObservationError";
}
}
export type HostObservationEvent = AgentStreamEvent | { type: "work_changed" };
export interface HostObservation {
wait(agentId: string, signal: AbortSignal): Promise<WaitForFinishResult>;
observe(
agentId: string,
handler: (
snapshot: AgentSnapshotPayload | null,
event?: AgentStreamEvent,
event?: HostObservationEvent,
lastMessage?: string | null,
) => void,
signal: AbortSignal,
@@ -32,7 +32,7 @@ interface Child {
parentID: string;
timeline: V2Timeline;
history: SessionMessageInfo[];
signature?: string;
presentation?: Extract<ProviderSubagentInputEvent, { type: "upsert" }>;
}
export class SessionChildren {
private readonly children = new Map<string, Child>();
@@ -44,6 +44,9 @@ export class SessionChildren {
private draining: Promise<void> | null = null;
private closed = false;
constructor(private readonly options: ChildrenOptions) {}
hasRunning(): boolean {
return [...this.children.values()].some((child) => child.presentation?.status === "running");
}
close() {
this.closed = true;
this.clearFlushTimer();
@@ -234,9 +237,8 @@ export class SessionChildren {
cwd: info.location.directory,
timestamp: new Date(info.time.updated).toISOString(),
};
const signature = JSON.stringify(presentation);
if (child.signature !== signature) {
child.signature = signature;
if (JSON.stringify(child.presentation) !== JSON.stringify(presentation)) {
child.presentation = presentation;
this.options.emit({ type: "provider_subagent", provider: "opencode", event: presentation });
}
const synced = await syncTailMessages(this.options.client(), info.id, child.history);
@@ -553,6 +553,9 @@ export class OpenCodeV2Session implements AgentSession {
steerActiveTurn(prompt: AgentPromptInput, options: SteerActiveTurnOptions): Promise<SteerResult> {
return this.turns.steerActiveTurn(prompt, options);
}
hasPendingWakeup(): boolean {
return this.children.hasRunning() || Boolean(this.background.snapshot()?.items?.length);
}
stopBackgroundWork(id: string) {
return this.background.stopItem(id);
}
@@ -0,0 +1,176 @@
import { mkdir, mkdtemp, rm } from "node:fs/promises";
import path from "node:path";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { expect, test } from "vitest";
import { z } from "zod";
import { createTestLogger } from "../../test-utils/test-logger.js";
import { parseAgentMessage } from "../agent/agent-messages/index.js";
import { OpenCodeBridge } from "../agent/providers/opencode/bridge.js";
import { V2Harness } from "../agent/providers/opencode/test-utils/v2-harness.js";
import { OpenCodeV2AgentClient } from "../agent/providers/opencode/v2/agent.js";
import { DaemonClient } from "../test-utils/daemon-client.js";
import { createTestAgentClient } from "../test-utils/fake-agent-client.js";
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
test.each(["autonomous reply", "subagent completed", "subagent removed"] as const)(
"OpenCode finish notifications follow an idle child through %s",
async (ending) => {
const artifacts = path.resolve(".artifacts");
await mkdir(artifacts, { recursive: true });
const cwd = await mkdtemp(path.join(artifacts, "opencode-finish-"));
const logger = createTestLogger();
const bridge = new OpenCodeBridge({ paseoHome: path.join(cwd, "bridge"), logger });
const runtime = new V2Harness();
runtime.autoComplete = false;
const subagent = { ...runtime.info, id: "background-subagent", parentID: runtime.info.id };
let subagentRunning = false;
const active = runtime.api.session.active;
runtime.api.session.active = async () => ({
...(await active()),
...(subagentRunning ? { [subagent.id]: { type: "running" as const } } : {}),
});
runtime.api.session.list = async (input) => ({
data: input?.parentID === runtime.info.id && subagentRunning ? [subagent] : [],
cursor: {},
});
runtime.api.session.get = async ({ sessionID }) =>
sessionID === subagent.id ? subagent : runtime.info;
runtime.api.model.list = async () => ({ location: runtime.info.location, data: [] });
runtime.api.provider.list = async () => ({
location: runtime.info.location,
data: [{ id: "test", name: "Test", activation: "enabled", package: "test" }],
});
const received: string[] = [];
const parentProvider = createTestAgentClient("claude", {
onStartTurn(prompt) {
if (typeof prompt !== "string") return;
const message = parseAgentMessage(prompt);
if (message.source?.kind === "agent-notification" && message.source.event === "finished")
received.push(message.text);
},
});
function finishTurn(text: string) {
runtime.history.push({
id: text,
type: "assistant",
agent: "build",
model: { providerID: "test", id: "test" },
time: { created: runtime.info.time.busy!, completed: runtime.info.time.busy! },
content: [{ type: "text", text }],
tokens: runtime.info.tokens,
cost: 0,
});
runtime.finishExecution();
}
let daemon: Awaited<ReturnType<typeof createTestPaseoDaemon>> | undefined;
let client: DaemonClient | undefined;
const mcp = new Client({ name: "finish-test", version: "1" });
try {
await bridge.start();
daemon = await createTestPaseoDaemon({
logger,
paseoHomeRoot: path.join(cwd, "daemon"),
agentClients: {
claude: parentProvider,
opencode: new OpenCodeV2AgentClient({ logger, runtime: runtime.runtime, bridge }),
},
});
client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
await client.connect();
const parent = await client.createAgent({
provider: "claude",
cwd,
modeId: "bypassPermissions",
title: "Caller",
});
await mcp.connect(
new StreamableHTTPClientTransport(
new URL(`http://127.0.0.1:${daemon.port}/mcp/agents?callerAgentId=${parent.id}`),
),
);
const created = await mcp.callTool({
name: "create_agent",
arguments: {
relationship: { kind: "subagent" },
workspace: { kind: "current" },
provider: "opencode/test/test",
title: "OpenCode child",
initialPrompt: "Start a background subagent",
notifyOnFinish: true,
},
});
expect(created.isError, JSON.stringify(created.content)).not.toBe(true);
const { agentId } = z.object({ agentId: z.string() }).parse(created.structuredContent);
await expect.poll(() => runtime.prompts).toHaveLength(1);
subagentRunning = true;
runtime.push({
id: "subagent-start",
created: 2,
type: "session.created",
durable: { aggregateID: subagent.id, seq: 1, version: 1 },
data: {
sessionID: subagent.id,
parentID: subagent.parentID,
projectID: subagent.projectID,
location: subagent.location,
slug: subagent.id,
version: "2.3.0",
},
});
await expect
.poll(async () => (await client!.listProviderSubagents(agentId)).subagents)
.toEqual([expect.objectContaining({ status: "running" })]);
finishTurn("Waiting for the subagent");
await expect
.poll(() => daemon!.daemon.agentManager.getAgent(agentId)?.lifecycle, { timeout: 8_000 })
.toBe("idle");
await expect.poll(() => received, { timeout: 8_000 }).toHaveLength(1);
expect(received[0]).toContain("Waiting for the subagent");
expect(received[0]).toContain("It still has background work that will wake it.");
if (ending === "autonomous reply") {
runtime.startExecution();
await expect
.poll(() => daemon!.daemon.agentManager.getAgent(agentId)?.lifecycle)
.toBe("running");
}
subagentRunning = false;
const settled = {
id: "subagent-settled",
created: 3,
durable: { aggregateID: subagent.id, seq: 2, version: 1 as const },
data: { sessionID: subagent.id },
};
runtime.push(
ending === "subagent removed"
? { ...settled, type: "session.deleted" }
: { ...settled, type: "session.execution.succeeded" },
);
if (ending === "autonomous reply") {
await expect
.poll(async () => (await client!.listProviderSubagents(agentId)).subagents)
.toEqual([expect.objectContaining({ status: "completed" })]);
finishTurn("Final subagent result");
}
await expect.poll(() => received, { timeout: 8_000 }).toHaveLength(2);
expect(received[1]).toContain(
ending === "autonomous reply" ? "Final subagent result" : "Waiting for the subagent",
);
expect(received[1]).not.toContain("It still has background work");
expect(runtime.prompts).toHaveLength(1);
} finally {
await mcp.close();
await client?.close();
await daemon?.close();
await bridge.close();
await rm(cwd, { force: true, recursive: true });
}
},
30_000,
);