Compare commits

...
Author SHA1 Message Date
paseo-bot[bot] 59a21245bd Let Muse sessions finish closing when a child read ends
Releasing an outstanding child read during host shutdown must not report a runtime failure to the adapter that is already closing the session.
2026-11-20 11:11:43 +00:00
paseo-bot[bot] 6b1311d3b2 Keep Muse child projection within the parent session lifetime
Check the parent again after reading a child. Closing a parent while that read is in flight no longer publishes an event for a parent the runtime has removed.
2026-11-20 11:05:19 +00:00
paseo-bot[bot]andGeorge b9196fa259 test(muse): exercise child history replay without a live setup turn
Seed a historical child after closing an empty session so the replay
regression reaches resume even when live subagent projection is broken.
Both paths now fail independently with the reported negotiation error.

Co-authored-by: George <90179633+georgepullen@users.noreply.github.com>
2026-11-20 10:41:32 +00:00
George c086c8a5ad test(plugins): launch fake muse through the provider command override 2026-11-20 10:41:32 +00:00
George af2498ae99 test(plugins): cover muse subsession negotiation through PluginRuntime 2026-11-20 10:41:31 +00:00
George 5a16dd0c13 docs(plugins): require session.subsession negotiation before opening a child 2026-11-20 10:41:31 +00:00
George a85695679a test(muse-provider): reach the subsession gate with a child-bearing fixture 2026-11-20 10:41:31 +00:00
George e7245e0883 fix(muse-provider): negotiate session.subsession and gate child projection 2026-11-20 10:41:31 +00:00
7 changed files with 287 additions and 14 deletions
@@ -6,7 +6,12 @@ import { PassThrough } from "node:stream";
import path from "node:path";
import { fileURLToPath } from "node:url";
import pino from "pino";
import type { ProviderEvent, ProviderRegistration } from "@getpaseo/plugin/server/provider";
import {
PROVIDER_CAPABILITIES,
type ProviderEvent,
type ProviderPrompt,
type ProviderRegistration,
} from "@getpaseo/plugin/server/provider";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { AgentStreamEvent } from "../agent/agent-sdk-types.js";
import { PluginAgentClientRegistry } from "../agent/plugin-provider.js";
@@ -358,6 +363,232 @@ register(${JSON.stringify(guardUrl)});`;
await adapters.shutdown();
await runtime.stopAll();
});
// The muse provider runs against a fake MSP host (injected through the
// provider's command override), but everything above it is real: the plugin
// subprocess, PluginRuntime's capability enforcement, and the
// PluginAgentClientRegistry path an agent actually uses. On a muse build
// that does not negotiate `session.subsession`, the daemon fails the whole
// provider connection when the child is projected, so both tests fail
// before the fix.
async function startMuseRuntime() {
const fakeMuse = fileURLToPath(
new URL("../../../../../plugins/muse-provider/test/fake-muse.mjs", import.meta.url),
);
const directory = fileURLToPath(
new URL("../../../../../plugins/muse-provider/", import.meta.url),
);
const runtime = createTestRuntime({}, undefined, "0.11.0");
await runtime.startPlugin("muse-provider", directory);
const [metadata] = runtime.getProviderRegistrations("muse-provider");
expect(metadata).toBeDefined();
return { runtime, metadata: metadata!, fakeMuse };
}
async function startMuseClient(extraEnv: Record<string, string>) {
const { runtime, metadata, fakeMuse } = await startMuseRuntime();
const adapters = new PluginAgentClientRegistry(pino({ level: "silent" }));
adapters.replace([
{
...adaptRuntimeProvider(runtime, "muse-provider", metadata),
command: metadata.command,
},
]);
const client = adapters.definitions()[metadata.id]!.createClient(pino({ level: "silent" }), {
command: { mode: "replace", argv: [process.execPath, fakeMuse] },
env: { MUSE_TEST_SCENARIO: "subagent", MUSE_TEST_CHILD: "tool", ...extraEnv },
});
return { runtime, adapters, client };
}
function hasSettledTurn(events: readonly AgentStreamEvent[]): boolean {
return events.some((event) => event.type === "turn_completed" || event.type === "turn_failed");
}
// Asserting on the settled turn (rather than polling only for completion)
// puts the provider's failure — e.g. "Provider parent session did not
// negotiate session.subsession" — in the test output.
async function expectTurnCompleted(events: readonly AgentStreamEvent[]): Promise<void> {
await expect.poll(() => hasSettledTurn(events)).toBe(true);
expect(events.filter((event) => event.type === "turn_failed")).toEqual([]);
expect(hasCompletedAgentTurn(events)).toBe(true);
}
function hasSubagentTimeline(events: readonly AgentStreamEvent[]): boolean {
return events.some(
(event) =>
event.type === "provider_subagent" &&
event.event.type === "timeline" &&
event.event.item.type === "assistant_message" &&
event.event.item.text.includes("SUBAGENT_PHASE0_OK"),
);
}
it("projects a muse subagent through PluginRuntime without failing the connection", async () => {
const { runtime, adapters, client } = await startMuseClient({});
try {
const events: AgentStreamEvent[] = [];
const session = await client.createSession({ provider: "muse", cwd: process.cwd() });
session.subscribe((event) => events.push(event));
await session.startTurn("dispatch a subagent", { clientMessageId: "muse-live" });
await expectTurnCompleted(events);
expect(hasSubagentTimeline(events)).toBe(true);
// The connection survives: a fresh session on the same provider opens
// and completes a turn instead of hitting a dead cached connection.
const second = await client.createSession({ provider: "muse", cwd: process.cwd() });
const secondEvents: AgentStreamEvent[] = [];
second.subscribe((event) => secondEvents.push(event));
await second.startTurn("again", { clientMessageId: "muse-live-2" });
await expectTurnCompleted(secondEvents);
await second.close();
await session.close();
} finally {
await adapters.shutdown();
await runtime.stopAll();
}
});
it("replays a muse subagent from history on resume without failing the connection", async () => {
const historyDirectory = await mkdtemp(path.join(tmpdir(), "paseo-muse-history-"));
temporaryDirectories.push(historyDirectory);
const { runtime, adapters, client } = await startMuseClient({
MUSE_TEST_HISTORY: path.join(historyDirectory, "native-history.ndjson"),
});
try {
const first = await client.createSession({ provider: "muse", cwd: process.cwd() });
const persistence = first.describePersistence();
expect(persistence).not.toBeNull();
await first.close();
// Seed old history without running a live subagent first, so this test
// reaches resume even when live child projection is broken.
await writeFile(
path.join(historyDirectory, "native-history.ndjson"),
JSON.stringify({
itemId: "historical-subagent",
revision: 1,
kind: "toolCall",
status: "completed",
tool: "subagent_spawn",
childSessionId: "fixture-child",
}) + "\n",
);
const resumed = await client.resumeSession(persistence!, { cwd: process.cwd() });
const resumedEvents: AgentStreamEvent[] = [];
resumed.subscribe((event) => resumedEvents.push(event));
// History replayed during resume is exposed through streamHistory.
const replayed: AgentStreamEvent[] = [];
for await (const event of resumed.streamHistory()) replayed.push(event);
expect(hasSubagentTimeline(replayed)).toBe(true);
await resumed.startTurn("continue", { clientMessageId: "muse-resumed" });
await expectTurnCompleted(resumedEvents);
await resumed.close();
} finally {
await adapters.shutdown();
await runtime.stopAll();
}
});
it("keeps other Muse sessions live when a parent closes during a child read", async () => {
const directory = await mkdtemp(path.join(tmpdir(), "paseo-muse-child-read-"));
temporaryDirectories.push(directory);
const requests = path.join(directory, "requests.ndjson");
const release = path.join(directory, "release");
const { runtime, metadata, fakeMuse } = await startMuseRuntime();
try {
const connection = await runtime.connectProvider("muse-provider", metadata.id, {
versions: [1],
capabilities: PROVIDER_CAPABILITIES,
launch: {
command: process.execPath,
args: [fakeMuse],
env: {
MUSE_TEST_SCENARIO: "subagent",
MUSE_TEST_CHILD: "tool",
MUSE_TEST_REQUESTS: requests,
MUSE_TEST_CHILD_READ_RELEASE: release,
},
},
});
const events: ProviderEvent[] = [];
connection.onEvent((event) => events.push(event));
for (const sessionId of ["closing", "sibling"]) {
await connection.send({
type: "session.open",
requestId: `open-${sessionId}`,
sessionId,
history: "skip",
config: { cwd: process.cwd(), env: {}, mcpServers: {}, settings: {}, persist: true },
});
await expect
.poll(() => events, { timeout: 5000 })
.toContainEqual(expect.objectContaining({ type: "session.ready", sessionId }));
}
const prompt: ProviderPrompt = {
clientMessageId: "spawn-child",
delivery: "auto",
input: { type: "message", content: [{ type: "text", text: "spawn a child" }] },
};
await connection.send({ type: "session.prompt", sessionId: "closing", prompt });
await expect
.poll(() => readFile(requests, "utf8"), { timeout: 5000 })
.toContain('"method":"session/read"');
// send() resolves after the runtime has accepted the close and removed
// the parent from its session table, while the child read is still pending.
await connection.send({
type: "session.close",
requestId: "close-parent",
sessionId: "closing",
});
await writeFile(release, "");
const closeSettled = (event: ProviderEvent) =>
(event.type === "request.completed" && event.requestId === "close-parent") ||
(event.type === "session.runtime_failed" && event.sessionId === "sibling");
await expect.poll(() => events.some(closeSettled), { timeout: 5000 }).toBe(true);
expect(
events.filter(
(event) => event.type === "session.runtime_failed" && event.sessionId === "sibling",
),
).toEqual([]);
expect(events).toContainEqual({ type: "request.completed", requestId: "close-parent" });
await connection.send({ type: "session.prompt", sessionId: "sibling", prompt });
await expect
.poll(() => events, { timeout: 5000 })
.toContainEqual(
expect.objectContaining({
type: "session.turn",
sessionId: "sibling",
state: "completed",
}),
);
} finally {
await writeFile(release, "");
await runtime.stopAll();
}
});
it("closes a Muse agent when the host exits without answering a child read", async () => {
const directory = await mkdtemp(path.join(tmpdir(), "paseo-muse-close-"));
temporaryDirectories.push(directory);
const requests = path.join(directory, "requests.ndjson");
const { runtime, adapters, client } = await startMuseClient({
MUSE_TEST_HANG: "session/read",
MUSE_TEST_REQUESTS: requests,
});
try {
const session = await client.createSession({ provider: "muse", cwd: process.cwd() });
await session.startTurn("spawn a child", { clientMessageId: "close-with-pending-read" });
await expect
.poll(() => readFile(requests, "utf8"), { timeout: 5000 })
.toContain('"method":"session/read"');
await expect(session.close()).resolves.toBeUndefined();
} finally {
await adapters.shutdown();
await runtime.stopAll();
}
});
it("runs a provider connection through the real plugin subprocess boundary", async () => {
const directory = await createPlugin(
+4
View File
@@ -21,6 +21,7 @@ export class Children {
private readonly parentId: string,
private readonly cwd: string,
private readonly emit: (event: ProviderEvent) => void,
private readonly canProjectChild: () => boolean,
) {}
async update(item: WireItem): Promise<void> {
@@ -34,6 +35,7 @@ export class Children {
)
)
return;
if (!this.canProjectChild()) return;
const id = item.childSessionId;
if (!this.children.has(id)) {
const { session } = await this.host.request(
@@ -41,6 +43,8 @@ export class Children {
{ sessionId: id },
childSessionSchema,
);
// The parent can close while Muse reads the child.
if (!this.canProjectChild()) return;
this.emit({
type: "session.opened",
sessionId: id,
+1
View File
@@ -32,6 +32,7 @@ const capabilities = [
"session.persistence",
"permission",
"session.list",
"session.subsession",
] as const;
export interface MuseProviderOptions {
+16 -7
View File
@@ -142,7 +142,13 @@ export class Session {
const nativeId = response.session.sessionId;
this.liveState = {
nativeId,
children: new Children(this.host, this.options.id, this.config.cwd, this.options.emit),
children: new Children(
this.host,
this.options.id,
this.config.cwd,
this.options.emit,
() => !this.closing && this.options.capabilities.includes("session.subsession"),
),
timeline: new Timeline(
this.host,
nativeId,
@@ -394,12 +400,15 @@ export class Session {
.catch((error: unknown) => this.runtimeFailed(error));
}
private runtimeFailed(error: unknown): void {
this.live().recovery.close();
this.options.emit({
type: "session.runtime_failed",
sessionId: this.options.id,
error: actionableError(error, this.options.launch),
});
// Closing the host can reject a notification's request. Let the close finish.
if (!this.closing) {
this.live().recovery.close();
this.options.emit({
type: "session.runtime_failed",
sessionId: this.options.id,
error: actionableError(error, this.options.launch),
});
}
const interrupt = this.interruptCompletion;
if (interrupt) interrupt.reject(error instanceof Error ? error : new Error(String(error)));
}
+16 -4
View File
@@ -1,4 +1,4 @@
import { appendFileSync, readFileSync } from "node:fs";
import { appendFileSync, existsSync, readFileSync } from "node:fs";
import { createInterface } from "node:readline";
import path from "node:path";
import { fileURLToPath } from "node:url";
@@ -166,9 +166,7 @@ function parityResponse(frame) {
return true;
}
if (frame.method === "session/read") {
const result = responseFor(readFixture("phase3-child-read"), "session/read");
result.session.sessionId = frame.params.sessionId;
respond(frame, result);
respondToChildRead(frame);
return true;
}
if (frame.method === "usage/read") {
@@ -223,6 +221,20 @@ function parityResponse(frame) {
if (skillResponse(frame)) return true;
return false;
}
function respondToChildRead(frame) {
const result = responseFor(readFixture("phase3-child-read"), "session/read");
result.session.sessionId = frame.params.sessionId;
const releaseFile = process.env.MUSE_TEST_CHILD_READ_RELEASE;
if (releaseFile && !existsSync(releaseFile)) {
const waiting = setInterval(() => {
if (!existsSync(releaseFile)) return;
clearInterval(waiting);
respond(frame, result);
}, 10);
} else {
respond(frame, result);
}
}
function skillResponse(frame) {
if (frame.method === "skill/list") {
const skillRows =
+16 -1
View File
@@ -46,6 +46,7 @@ async function harness(
scenario = "text-reasoning",
env: Record<string, string> = {},
providerOptions?: Record<string, unknown>,
connectCapabilities: readonly string[] = PROVIDER_CAPABILITIES,
) {
const root = await mkdtemp(path.join(os.tmpdir(), "muse-provider-test-"));
roots.push(root);
@@ -63,7 +64,7 @@ async function harness(
const connection = await provider.connect({
launch,
versions: [1],
capabilities: PROVIDER_CAPABILITIES,
capabilities: connectCapabilities,
});
connections.push(connection);
const events: ProviderEvent[] = [];
@@ -1254,6 +1255,20 @@ for (const variant of ["tool", "dedicated", "workflow"]) {
).toHaveLength(1);
});
}
test("subagent children are not projected when session.subsession is not negotiated", async () => {
const h = await harness(
"subagent",
{ MUSE_TEST_CHILD: "tool" },
undefined,
PROVIDER_CAPABILITIES.filter((capability) => capability !== "session.subsession"),
);
await h.open();
await h.prompt();
await h.wait((e) => e.type === "session.turn" && e.state === "completed");
expect(h.events.filter((e) => e.type === "session.opened" && e.parentSessionId)).toHaveLength(0);
expect((await h.recorded()).filter((f) => f.method === "session/read")).toEqual([]);
});
test("gap backfill repairs a missing completion without duplicating item revisions", async () => {
const h = await harness("text-reasoning", { MUSE_TEST_GAP: "1" });
await h.open();
+2 -1
View File
@@ -314,7 +314,8 @@ children. File-only rewind keeps the current session and conversation history.
Use `restoration: "core"` when Paseo can reopen a session from persistence. A provider-owned child
uses `restoration: "parent"`; emit it as another `session.opened` event with `parentSessionId` and
recreate it while restoring the parent.
recreate it while restoring the parent. The parent's `session.opened` capabilities must include
`session.subsession`. Paseo fails the whole connection when a parent without it opens a child.
## Add commands and steering