Compare commits

..
Author SHA1 Message Date
paseo-bot[bot]andClaude Opus 5.5 b1677e58d8 Start Windows terminals when ConPTY's output worker is slow (#11238)
* fix(terminal): let a Windows terminal start when ConPTY's worker is slow

node-pty starts a worker thread for ConPTY output and waits 5 s for it
to report ready. When the message comes later, it fails the spawn and
the program exits with code -1 before it runs. On a loaded Windows CI
runner this made "delivers MCP key tokens through in-process" find no
terminal at all. Patch the wait to 30 s; a worker that fails still
reports an error at once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(terminal): block the event loop from a check-phase callback

The old 5 s ConPTY timer now always runs before the worker's ready
message, so the test fails without the node-pty patch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 00:55:51 +00:00
5 changed files with 65 additions and 365 deletions
@@ -14,7 +14,6 @@ import type {
ProviderEvent,
ProviderInput,
ProviderRegistration,
ProviderStatus,
} from "@getpaseo/plugin/server/provider";
import { sendPreparedPromptToAgent, startAgentRun } from "./agent-prompt.js";
import { setImmediate as nextTurn } from "node:timers/promises";
@@ -4096,307 +4095,3 @@ describe("plugin ACP hung-cancel retirement through AgentManager (#3256)", () =>
}
});
});
test("lazily connects command-backed plugin providers for session listing", async () => {
const logger = createTestLogger();
const cwd = tmpdir();
let listableStatusCalls = 0;
let listableConnects = 0;
let missingConnects = 0;
let noListConnects = 0;
let gatedAvailable = false;
let gatedConnects = 0;
const listableHarness = createProviderHarness({
capabilities: ["prompt.message", "session.list"],
handleInput: async (input, emit) => {
if (input.type !== "sessions") return false;
emit({
type: "sessions",
requestId: input.requestId,
sessions: [
{
persistence: { version: 1, data: { sessionId: "native-lazy-1" } },
cwd,
title: "Lazy listed session",
updatedAt: "2026-04-01T00:00:00.000Z",
},
],
});
return true;
},
});
const noListHarness = createProviderHarness({
capabilities: ["prompt.message"],
});
const gatedHarness = createProviderHarness({
capabilities: ["prompt.message", "session.list"],
handleInput: async (input, emit) => {
if (input.type !== "sessions") return false;
emit({
type: "sessions",
requestId: input.requestId,
sessions: [
{
persistence: { version: 1, data: { sessionId: "native-gated-1" } },
cwd,
title: "Gated session",
updatedAt: "2026-04-02T00:00:00.000Z",
},
],
});
return true;
},
});
const listableRegistration: ProviderRegistration = {
...listableHarness.registration,
id: "lazy-listable",
label: "Lazy Listable",
command: [process.execPath, "-e", ""],
async status() {
listableStatusCalls += 1;
await nextTurn();
return { available: true };
},
async connect(request) {
listableConnects += 1;
return listableHarness.registration.connect(request);
},
};
const missingRegistration: ProviderRegistration = {
id: "lazy-missing",
label: "Lazy Missing",
command: [join(cwd, `paseo-missing-binary-${process.pid}`)],
async connect() {
missingConnects += 1;
throw new Error("should not connect when executable is missing");
},
};
const noListRegistration: ProviderRegistration = {
...noListHarness.registration,
id: "lazy-no-list",
label: "Lazy No List",
command: [process.execPath, "-e", ""],
async connect(request) {
noListConnects += 1;
return noListHarness.registration.connect(request);
},
};
const gatedRegistration: ProviderRegistration = {
...gatedHarness.registration,
id: "lazy-gated",
label: "Lazy Gated",
command: [process.execPath, "-e", ""],
async status() {
return gatedAvailable
? { available: true }
: { available: false, diagnostic: "Sign in first" };
},
async connect(request) {
gatedConnects += 1;
return gatedHarness.registration.connect(request);
},
};
const plugins = new PluginAgentClientRegistry(logger);
plugins.replace([
listableRegistration,
missingRegistration,
noListRegistration,
gatedRegistration,
]);
const registry = buildProviderRegistry(logger, { pluginProviders: plugins.definitions() });
const clients = {
"lazy-listable": registry["lazy-listable"].createClient(logger),
"lazy-missing": registry["lazy-missing"].createClient(logger),
"lazy-no-list": registry["lazy-no-list"].createClient(logger),
"lazy-gated": registry["lazy-gated"].createClient(logger),
};
const manager = new AgentManager({
logger,
clients,
providerDefinitions: {
"lazy-listable": registry["lazy-listable"],
"lazy-missing": registry["lazy-missing"],
"lazy-no-list": registry["lazy-no-list"],
"lazy-gated": registry["lazy-gated"],
},
});
try {
expect(listableConnects).toBe(0);
expect(noListConnects).toBe(0);
// Concurrent cold listings share one availability probe and connection attempt.
const [listing, concurrentListing] = await Promise.all([
manager.listImportableSessions({ limit: 20 }),
manager.listImportableSessions({ limit: 20 }),
]);
for (const result of [listing, concurrentListing]) {
expect(result.providerErrors).toEqual([]);
expect(result.sessions).toEqual([
expect.objectContaining({
provider: "lazy-listable",
cwd,
title: "Lazy listed session",
}),
]);
}
expect(listableStatusCalls).toBe(1);
expect(listableConnects).toBe(1);
expect(missingConnects).toBe(0);
expect(noListConnects).toBe(1);
expect(gatedConnects).toBe(0);
expect(clients["lazy-listable"].capabilities.supportsSessionListing).toBe(true);
expect(clients["lazy-no-list"].capabilities.supportsSessionListing).toBe(false);
// Once an unavailable provider becomes available, cold listing connects and returns its rows.
gatedAvailable = true;
const afterSignIn = await manager.listImportableSessions({ limit: 20 });
expect(afterSignIn.providerErrors).toEqual([]);
expect(afterSignIn.sessions).toEqual([
expect.objectContaining({
provider: "lazy-gated",
cwd,
title: "Gated session",
}),
expect.objectContaining({
provider: "lazy-listable",
cwd,
title: "Lazy listed session",
}),
]);
expect(listableConnects).toBe(1);
expect(noListConnects).toBe(1);
expect(gatedConnects).toBe(1);
expect(noListHarness.inputs).toEqual([]);
} finally {
await plugins.shutdown();
}
expect(clients["lazy-listable"].capabilities.supportsSessionListing).toBe(false);
await expect(clients["lazy-missing"].listImportableSessions?.()).rejects.toThrow(
"Provider runtime is closed",
);
});
test("coalesces cold listings during a concurrent launch-wrap connection", async () => {
const statusStarted = Promise.withResolvers<void>();
const finishStatus = Promise.withResolvers<ProviderStatus>();
const connectionStarted = Promise.withResolvers<void>();
const finishConnection = Promise.withResolvers<void>();
const unavailable: ProviderStatus = { available: false, diagnostic: "Sign in first" };
const harness = createProviderHarness({
capabilities: ["prompt.message", "session.list", "session.launch_wrap"],
async handleInput(input) {
throw new Error(`Unexpected provider input: ${input.type}`);
},
});
const registry = new PluginAgentClientRegistry(createTestLogger());
registry.replace([
{
...harness.registration,
command: [process.execPath],
launchWrap: true,
status() {
statusStarted.resolve();
return finishStatus.promise;
},
async connect(request) {
connectionStarted.resolve();
await finishConnection.promise;
return harness.registration.connect(request);
},
},
]);
const client = registry.clients()[harness.registration.id]!;
try {
const first = client.listImportableSessions!();
await statusStarted.promise;
const wrap = client.requireLaunchWrap!();
await connectionStarted.promise;
const second = client.listImportableSessions!();
finishStatus.resolve(unavailable);
finishConnection.resolve();
await Promise.all([
expect(Promise.all([first, second])).resolves.toEqual([[], []]),
expect(wrap).resolves.toBeUndefined(),
]);
expect(harness.inputs).toEqual([]);
} finally {
finishStatus.resolve(unavailable);
finishConnection.resolve();
await registry.shutdown();
}
});
test("cold listing surfaces status() failures and does not block shutdown", async () => {
const logger = createTestLogger();
let resolveHangingStatus: ((value: { available: true }) => void) | undefined;
let hangingConnects = 0;
const failingRegistration: ProviderRegistration = {
id: "lazy-status-error",
label: "Lazy Status Error",
command: [process.execPath, "-e", ""],
async status() {
throw new Error("Plugin RPC timed out");
},
async connect() {
throw new Error("should not connect after status() failure");
},
};
const hangingRegistration: ProviderRegistration = {
id: "lazy-status-hang",
label: "Lazy Status Hang",
command: [process.execPath, "-e", ""],
status() {
return new Promise((resolve) => {
resolveHangingStatus = resolve;
});
},
async connect() {
hangingConnects += 1;
throw new Error("should not connect after shutdown");
},
};
const plugins = new PluginAgentClientRegistry(logger);
plugins.replace([failingRegistration, hangingRegistration]);
const registry = buildProviderRegistry(logger, { pluginProviders: plugins.definitions() });
const clients = {
"lazy-status-error": registry["lazy-status-error"].createClient(logger),
"lazy-status-hang": registry["lazy-status-hang"].createClient(logger),
};
const manager = new AgentManager({
logger,
clients,
providerDefinitions: {
"lazy-status-error": registry["lazy-status-error"],
"lazy-status-hang": registry["lazy-status-hang"],
},
});
const errorListing = await manager.listImportableSessions({
limit: 20,
providerFilter: new Set(["lazy-status-error"]),
});
expect(errorListing.sessions).toEqual([]);
expect(errorListing.providerErrors).toEqual([
{
provider: "lazy-status-error",
message: "Plugin RPC timed out",
},
]);
const hangingListing = clients["lazy-status-hang"].listImportableSessions?.();
await expect.poll(() => resolveHangingStatus, { timeout: 2_000 }).toBeDefined();
// Shutdown must complete without waiting on an in-flight cold status() probe.
await plugins.shutdown();
resolveHangingStatus?.({ available: true });
await expect(hangingListing).rejects.toThrow("Provider runtime is closed");
expect(hangingConnects).toBe(0);
});
@@ -183,18 +183,10 @@ function toProviderLaunch(launch: ProviderInstallationLaunch): ProviderLaunch {
return { command: launch.command, args: launch.args, env: launch.env };
}
class ProviderExecutableNotFoundError extends Error {
constructor(public readonly command: string) {
super(`${command} not found on PATH`);
this.name = "ProviderExecutableNotFoundError";
}
}
class ProviderRuntime {
private connection: ProviderConnection | null = null;
connectedLaunch: ProviderLaunch | undefined;
private connecting: Promise<ProviderConnection> | null = null;
private listingConnect: Promise<ProviderConnection | null> | null = null;
private closed = false;
private generation = 0;
private closePromise: Promise<void> | null = null;
@@ -260,7 +252,7 @@ class ProviderRuntime {
this.registration.status ? { probe: false } : undefined,
);
if (!launch) return undefined;
if (!launch.resolved) throw new ProviderExecutableNotFoundError(launch.command);
if (!launch.resolved) throw new Error(`${launch.command} not found on PATH`);
return toProviderLaunch(launch);
}
@@ -388,10 +380,6 @@ class ProviderRuntime {
return callback({ ...options, launch: launch && toProviderLaunch(launch) });
}
get canProbeSessionListing(): boolean {
return !this.closed && this.connection === null;
}
get negotiatedCapabilities(): readonly string[] {
return this.connection?.capabilities ?? [];
}
@@ -425,8 +413,8 @@ class ProviderRuntime {
limit?: number;
} = {},
): Promise<Extract<ProviderEvent, { type: "sessions" }>["sessions"]> {
const connection = await this.ensureConnectionForListing();
if (!connection || !connection.capabilities.includes("session.list")) return [];
const connection = await this.getConnection();
if (!connection.capabilities.includes("session.list")) return [];
const event = await this.complete({ type: "sessions", requestId: randomUUID(), ...input });
if (event.type !== "sessions")
throw new Error("Provider returned an invalid sessions response");
@@ -510,8 +498,6 @@ class ProviderRuntime {
const connection = this.connection;
const connecting = connection ? null : this.connecting;
this.connection = null;
// A plugin's status hook can outlive shutdown.
this.listingConnect = null;
this.unsubscribe?.();
this.unsubscribe = null;
for (const session of this.sessions.values()) session.connectionClosed();
@@ -578,44 +564,12 @@ class ProviderRuntime {
this.providerSessions.delete(providerSessionId);
}
private ensureConnectionForListing(): Promise<ProviderConnection | null> {
if (this.closed) return Promise.reject(new Error("Provider runtime is closed"));
if (this.connection) return Promise.resolve(this.connection);
if (this.listingConnect) return this.listingConnect;
const attempt = this.connecting ?? this.connectForListing();
const pending = attempt
.catch((error: unknown) => {
if (error instanceof ProviderExecutableNotFoundError) return null;
throw error;
})
.finally(() => {
if (this.listingConnect === pending) this.listingConnect = null;
});
this.listingConnect = pending;
return pending;
}
private async connectForListing(): Promise<ProviderConnection | null> {
const launchPromise = this.resolveLaunch();
const launch = await launchPromise;
if (this.closed) throw new Error("Provider runtime is closed");
if (this.registration.status) {
const status = ProviderStatusSchema.parse(await this.registration.status({ launch }));
if (this.closed) throw new Error("Provider runtime is closed");
if (!status.available) return null;
}
return this.getConnection(launchPromise);
}
private getConnection(
launchPromise?: Promise<ProviderLaunch | undefined>,
): Promise<ProviderConnection> {
private getConnection(): Promise<ProviderConnection> {
if (this.closed) return Promise.reject(new Error("Provider runtime is closed"));
if (this.connection) return Promise.resolve(this.connection);
if (this.connecting) return this.connecting;
const generation = this.generation;
const connecting = this.establishConnection(generation, launchPromise ?? this.resolveLaunch());
const connecting = this.establishConnection(generation);
this.connecting = connecting;
connecting.then(
() => {
@@ -630,12 +584,8 @@ class ProviderRuntime {
return connecting;
}
private async establishConnection(
generation: number,
launchPromise: Promise<ProviderLaunch | undefined>,
): Promise<ProviderConnection> {
const launch = await launchPromise;
if (this.closed) throw new Error("Provider runtime is closed");
private async establishConnection(generation: number): Promise<ProviderConnection> {
const launch = await this.resolveLaunch();
const rawConnection = await this.registration.connect({
launch,
clientInfo: resolvePluginClientInfo(),
@@ -1262,9 +1212,7 @@ class PluginAgentClient implements AgentClient {
}
get capabilities(): AgentCapabilityFlags {
const capabilities = agentCapabilities(this.runtime.negotiatedCapabilities);
if (this.runtime.canProbeSessionListing) capabilities.supportsSessionListing = true;
return capabilities;
return agentCapabilities(this.runtime.negotiatedCapabilities);
}
async requireLaunchWrap(): Promise<void> {
@@ -653,6 +653,39 @@ describe("createTerminal", () => {
expect(session.getExitInfo()).toEqual(exitInfo);
});
it.runIf(isPlatform("win32"))(
"starts a ConPTY program when the event loop stalls past five seconds after spawn",
async () => {
// node-pty reports the ConPTY output worker ready by a worker message, and failed the
// spawn with exit code -1 when that message came after 5 s. A loaded runner delays it
// that long; blocking the event loop for 6 s makes the delay certain. Spawning and
// blocking inside a check-phase callback makes the next loop iteration start with the
// timers phase, so the old 5 s timer always runs before the worker message is delivered.
const child = await new Promise<pty.IPty>((resolve) => {
setImmediate(() => {
const spawned = pty.spawn(process.execPath, ["-e", "process.stdout.write('STARTED')"], {
cols: 80,
rows: 24,
cwd: realpathSync(tmpdir()),
});
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 6000);
resolve(spawned);
});
});
let output = "";
child.onData((data) => {
output += data;
});
const exited = new Promise<number>((resolve) => {
child.onExit(({ exitCode }) => resolve(exitCode));
});
expect(await exited).toBe(0);
expect(output).toContain("STARTED");
},
30_000,
);
it("retains the final lines after output far exceeds the recent-output char cap", async () => {
// Emit many small chunks whose total length is well past the 16000-char
// recent-output cap, so the chunk-trimming path runs repeatedly. The final
+16
View File
@@ -0,0 +1,16 @@
diff --git a/node_modules/node-pty/lib/windowsPtyAgent.js b/node_modules/node-pty/lib/windowsPtyAgent.js
index 90ffd8f..d9567b1 100644
--- a/node_modules/node-pty/lib/windowsPtyAgent.js
+++ b/node_modules/node-pty/lib/windowsPtyAgent.js
@@ -21,7 +21,10 @@ var conptyNative;
* has started.
*/
var FLUSH_DATA_INTERVAL = 1000;
-var CONNECTION_TIMEOUT = 5000;
+// Paseo: the output worker is a worker thread that reports ready by message. A busy event loop
+// or a loaded machine can delay that message past 5 s, and the spawn then fails with exit
+// code -1 before the program starts. Wait 30 s instead; a worker that fails still errors at once.
+var CONNECTION_TIMEOUT = 30000;
var defaultWindowsPtyAgentOptions = {
connectionTimeout: CONNECTION_TIMEOUT,
conoutConnectionFactory: function (conoutPipeName, useConptyDll) { return new windowsConoutConnection_1.ConoutConnection(conoutPipeName, useConptyDll); }
+8
View File
@@ -123,6 +123,14 @@ const patchedPackages = [
patchPrefix: "@opencode-ai+sdk+",
cwd: "packages/server",
},
// Windows: wait 30 s instead of 5 s for the ConPTY output worker to report ready. A loaded
// machine delays that message past 5 s, and the program then exits with code -1 before it
// starts. Upstream keeps 5 s through 1.2.0-beta.18; keep while the server uses node-pty.
{
nodeModulesPath: "packages/server/node_modules/node-pty",
patchPrefix: "node-pty+",
cwd: "packages/server",
},
];
const installedPackages = patchedPackages.filter(({ nodeModulesPath }) =>