diff --git a/packages/host-service/src/terminal/DaemonClient/DaemonClient.node-test.ts b/packages/host-service/src/terminal/DaemonClient/DaemonClient.node-test.ts index 11688e6c8aa..437547a7bf2 100644 --- a/packages/host-service/src/terminal/DaemonClient/DaemonClient.node-test.ts +++ b/packages/host-service/src/terminal/DaemonClient/DaemonClient.node-test.ts @@ -3,15 +3,19 @@ // daemon spawns real PTYs via node-pty. import { strict as assert } from "node:assert"; +import { once } from "node:events"; +import { mkdtempSync, rmSync } from "node:fs"; import * as net from "node:net"; import * as os from "node:os"; import * as path from "node:path"; import { after, before, test } from "node:test"; import { Server } from "@superset/pty-daemon"; import { + type ClientMessage, CURRENT_PROTOCOL_VERSION, encodeFrame, FrameDecoder, + type ListMessage, } from "@superset/pty-daemon/protocol"; import { TerminalModes } from "@superset/pty-daemon/terminal-modes"; import { DaemonClient, DaemonUnavailableError } from "./DaemonClient.ts"; @@ -405,6 +409,126 @@ test("adoption flow: client A opens, drops, client B finds + subscribes-with-rep await b.dispose(); }); +test( + "a timed-out list reply cannot settle the next list request", + { timeout: 5000 }, + async (t) => { + const socketDir = mkdtempSync(path.join(os.tmpdir(), "paradev-list-")); + const socketPath = path.join(socketDir, "daemon.sock"); + const firstRequest = Promise.withResolvers(); + const secondRequest = Promise.withResolvers<{ + message: ListMessage; + socket: net.Socket; + }>(); + let count = 0; + const fake = net.createServer((socket) => { + const decoder = new FrameDecoder(); + socket.on("data", (chunk) => { + decoder.push(chunk); + for (const frame of decoder.drain()) { + const message = frame.message as ClientMessage; + if (message.type === "hello") { + socket.write( + encodeFrame({ + type: "hello-ack", + protocol: CURRENT_PROTOCOL_VERSION, + daemonVersion: "test", + supportsListRequestIds: true, + }), + ); + } else if (message.type === "list") { + if (++count === 1) firstRequest.resolve(message); + else secondRequest.resolve({ message, socket }); + } + } + }); + }); + const client = new DaemonClient({ socketPath }); + const cancelled = Promise.withResolvers(); + const cancel = () => + cancelled.reject(t.signal.reason ?? new Error("Fixture closed")); + void cancelled.promise.catch(() => {}); + t.signal.addEventListener("abort", cancel, { once: true }); + const wait = (promise: Promise) => + Promise.race([promise, cancelled.promise]); + try { + t.signal.throwIfAborted(); + await once(fake.listen(socketPath), "listening", { signal: t.signal }); + await client.connect(); + t.signal.throwIfAborted(); + t.mock.timers.enable({ apis: ["setTimeout"] }); + const [first] = await wait( + Promise.all([ + firstRequest.promise.then((message) => { + t.mock.timers.runAll(); + return message; + }), + assert.rejects(client.list(), DaemonUnavailableError), + ]), + ); + + const session = { + id: "current", + pid: 1, + cols: 80, + rows: 24, + alive: true, + }; + const [sessions] = await wait( + Promise.all([ + client.list(), + (async () => { + const { message: second, socket } = await wait( + secondRequest.promise, + ); + const repliesRead = Promise.withResolvers(); + client.subscribe( + "list-test-marker", + { replay: false }, + { + onOutput: () => repliesRead.resolve(), + onExit: () => {}, + }, + ); + socket.write( + Buffer.concat([ + encodeFrame({ + type: "list-reply", + requestId: first.requestId, + sessions: [], + }), + encodeFrame({ + type: "list-reply", + requestId: second.requestId, + sessions: [session], + }), + encodeFrame( + { type: "output", id: "list-test-marker" }, + Buffer.from("replies read"), + ), + ]), + ); + // The marker arrives after both replies, even if neither matched. + await wait(repliesRead.promise); + t.mock.timers.runAll(); + })(), + ]), + ); + assert.deepEqual(sessions, [session]); + } finally { + t.signal.removeEventListener("abort", cancel); + cancel(); + t.mock.timers.reset(); + try { + await client.dispose(); + await new Promise((resolve) => fake.close(() => resolve())); + } finally { + rmSync(socketDir, { recursive: true, force: true }); + } + } + }, +); + test("open rejects with DaemonUnavailableError when the daemon dies mid-request", async () => { // Fake daemon: completes the handshake, then never answers `open` — the // socket dying underneath the pending request must classify as diff --git a/packages/host-service/src/terminal/DaemonClient/DaemonClient.ts b/packages/host-service/src/terminal/DaemonClient/DaemonClient.ts index 485c4ad2846..850e2c166de 100644 --- a/packages/host-service/src/terminal/DaemonClient/DaemonClient.ts +++ b/packages/host-service/src/terminal/DaemonClient/DaemonClient.ts @@ -21,6 +21,8 @@ import { CURRENT_PROTOCOL_VERSION, encodeFrame, FrameDecoder, + type ListMessage, + type PrepareUpgradeMessage, type ServerMessage, type SessionInfo, type SessionMeta, @@ -99,6 +101,8 @@ export class DaemonClient { private connected = false; private modeSnapshots = false; private colorQueries = false; + private listRequestIds = false; + private lastListRequestId = 0; constructor(opts: DaemonClientOptions) { this.opts = opts; @@ -179,8 +183,11 @@ export class DaemonClient { } async list(): Promise { + const requestId = this.listRequestIds + ? ++this.lastListRequestId + : undefined; const reply = await this.requestNonSession( - { type: "list" }, + { type: "list", requestId }, "list-reply", LIST_TIMEOUT_MS, ); @@ -331,6 +338,7 @@ export class DaemonClient { } this.modeSnapshots = ack.supportsModeSnapshots === true; this.colorQueries = ack.supportsColorQueries === true; + this.listRequestIds = ack.supportsListRequestIds === true; this.daemonVersion = ack.daemonVersion; this.negotiated = ack.protocol; } @@ -385,10 +393,11 @@ export class DaemonClient { } private requestNonSession( - req: { type: "list" } | { type: "prepare-upgrade" }, + req: ListMessage | PrepareUpgradeMessage, expectType: "list-reply" | "upgrade-prepared", timeoutMs: number, ): Promise { + const requestId = req.type === "list" ? req.requestId : undefined; return new Promise((resolve, reject) => { let resolved = false; const settle = (m: ServerMessage) => { @@ -405,14 +414,17 @@ export class DaemonClient { }; const off = this.on((m) => { if (m.type === expectType) { - settle(m); + if (m.type !== "list-reply" || m.requestId === requestId) settle(m); return; } - // Non-session error frames (no `id`) belong to the - // most-recent non-session request — settle on those. Errors - // keyed to a session id come from concurrent ops on that - // session; ignore them here. - if (m.type === "error" && m.id === undefined) settle(m); + // An untagged error cannot be attributed to a tagged list request. + if ( + requestId === undefined && + m.type === "error" && + m.id === undefined + ) { + settle(m); + } }); const offDisc = this.onDisconnect((err) => fail(new DaemonUnavailableError(err?.message ?? "daemon disconnected")), diff --git a/packages/pty-daemon/src/Server/Server.ts b/packages/pty-daemon/src/Server/Server.ts index 250f579c221..36cbf9d82e7 100644 --- a/packages/pty-daemon/src/Server/Server.ts +++ b/packages/pty-daemon/src/Server/Server.ts @@ -471,6 +471,7 @@ export class Server { trustdHealthy: this.trustdHealthy, supportsModeSnapshots: true, supportsColorQueries: true, + supportsListRequestIds: true, }); return; } @@ -512,7 +513,7 @@ export class Server { return; } case "list": { - conn.send(handleList(ctx)); + conn.send({ ...handleList(ctx), requestId: msg.requestId }); return; } case "subscribe": { diff --git a/packages/pty-daemon/src/protocol/messages.ts b/packages/pty-daemon/src/protocol/messages.ts index 000c7b73106..11eb25c45a1 100644 --- a/packages/pty-daemon/src/protocol/messages.ts +++ b/packages/pty-daemon/src/protocol/messages.ts @@ -52,6 +52,7 @@ export interface HelloAckMessage { trustdHealthy?: boolean; supportsModeSnapshots?: boolean; supportsColorQueries?: boolean; + supportsListRequestIds?: boolean; } // ---------- Client -> Daemon ---------- @@ -90,6 +91,7 @@ export interface CloseMessage { export interface ListMessage { type: "list"; + requestId?: number; } export interface SubscribeMessage { @@ -152,6 +154,7 @@ export interface ClosedMessage { export interface ListReplyMessage { type: "list-reply"; + requestId?: number; sessions: SessionInfo[]; } diff --git a/packages/pty-daemon/test/control-plane.test.ts b/packages/pty-daemon/test/control-plane.test.ts index fed43e37234..fee70dd4183 100644 --- a/packages/pty-daemon/test/control-plane.test.ts +++ b/packages/pty-daemon/test/control-plane.test.ts @@ -112,6 +112,28 @@ describe("handshake", () => { await c.close(); }); + test("echoes a list request ID and still accepts an untagged list", async () => { + const c = await connect(sockPath); + try { + c.send({ type: "hello", protocols: [2] }); + const ack = await c.waitFor((m) => m.type === "hello-ack"); + assert.equal(ack.type, "hello-ack"); + assert.equal(ack.supportsListRequestIds, true); + c.send({ type: "list", requestId: 42 }); + const tagged = await c.waitFor((m) => m.type === "list-reply"); + assert.deepEqual(tagged, { + type: "list-reply", + requestId: 42, + sessions: [], + }); + c.send({ type: "list" }); + const untagged = await c.waitForNext((m) => m.type === "list-reply"); + assert.deepEqual(untagged, { type: "list-reply", sessions: [] }); + } finally { + await c.close(); + } + }); + test("rejects duplicate hello", async () => { const c = await connectAndHello(sockPath); c.send({ type: "hello", protocols: [2] });