From a5d51c782af45af395e00997fa795bfcf7f9e3fd Mon Sep 17 00:00:00 2001 From: pabtztd <267608262+pabtztd@users.noreply.github.com> Date: Fri, 6 Nov 2026 07:58:28 +0800 Subject: [PATCH 1/4] =?UTF-8?q?fix:=20=E4=BF=9D=E7=95=99=E5=B7=B2=E5=8F=96?= =?UTF-8?q?=E6=B6=88=E6=9F=A5=E8=AF=A2=E7=9A=84=E8=BF=9B=E7=A8=8B=E8=BE=93?= =?UTF-8?q?=E5=87=BA=E4=BB=A5=E6=94=AF=E6=8C=81=E6=96=AD=E7=BA=BF=E9=87=8D?= =?UTF-8?q?=E8=BF=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/process-sessions.test.ts | 56 +++++++++++++++++++++++++++++++++ src/process-sessions.ts | 4 +++ src/server.test.ts | 60 +++++++++++++++++++++++++++++++++++- src/tool-surfaces/codex.ts | 3 +- 4 files changed, 121 insertions(+), 2 deletions(-) diff --git a/src/process-sessions.test.ts b/src/process-sessions.test.ts index 39849168a..fdf3a18fa 100644 --- a/src/process-sessions.test.ts +++ b/src/process-sessions.test.ts @@ -110,6 +110,62 @@ test("a background session is only readable from its own workspace and reports c assert.match(completed.output, /finished/); }); +test("an aborted poll leaves completed output available to the next poll", async (t) => { + const manager = createManager(t); + + const started = await manager.start({ + workspaceId: "workspace-a", cwd: process.cwd(), + command: `${node} -e "setTimeout(() => console.log('retained-result'), 100)"`, + yieldTimeMs: 0, + }); + + assert.ok(started.sessionId); + const controller = new AbortController(); + + const poll = manager.write({ + workspaceId: "workspace-a", sessionId: started.sessionId, + yieldTimeMs: 2_000, signal: controller.signal, + }); + + controller.abort(); + await assert.rejects(poll, { name: "AbortError" }); + + const recovered = await manager.write({ + workspaceId: "workspace-a", sessionId: started.sessionId, yieldTimeMs: 2_000, + }); + + assert.equal(recovered.running, false); + assert.equal(recovered.exitCode, 0); + assert.match(recovered.output, /retained-result/); + await assert.rejects(manager.write({ + workspaceId: "workspace-a", sessionId: started.sessionId, + }), /Unknown process session/); +}); + +test("an already aborted write does not send input to the process", async (t) => { + const manager = createManager(t); + + const started = await manager.start({ + workspaceId: "workspace-a", cwd: process.cwd(), + command: `${node} -e "process.stdin.once('data', data => { console.log(data.toString()); process.exit(0); })"`, + yieldTimeMs: 0, + }); + + assert.ok(started.sessionId); + await assert.rejects(manager.write({ + workspaceId: "workspace-a", sessionId: started.sessionId, + chars: "cancelled-input\n", signal: AbortSignal.abort(), + }), { name: "AbortError" }); + + const completed = await manager.write({ + workspaceId: "workspace-a", sessionId: started.sessionId, + chars: "accepted-input\n", yieldTimeMs: 2_000, + }); + + assert.match(completed.output, /accepted-input/); + assert.doesNotMatch(completed.output, /cancelled-input/); +}); + test("input written to an interactive session reaches stdin", async (t) => { const manager = createManager(t); diff --git a/src/process-sessions.ts b/src/process-sessions.ts index 4502c7e54..0d50cb4eb 100644 --- a/src/process-sessions.ts +++ b/src/process-sessions.ts @@ -48,6 +48,7 @@ export interface WriteStdinInput { rows?: number; yieldTimeMs?: number; maxOutputTokens?: number; + signal?: AbortSignal; } export interface ProcessSnapshot { @@ -336,6 +337,7 @@ export class ProcessSessionManager { } async write(input: WriteStdinInput): Promise { + input.signal?.throwIfAborted(); const session = this.getOwnedSession(input.workspaceId, input.sessionId); const chars = input.chars ?? ""; @@ -369,6 +371,8 @@ export class ProcessSessionManager { await this.waitForExit(session, yieldTimeMs); } + // A cancelled request must not drain output or discard the completed session. + input.signal?.throwIfAborted(); const snapshot = this.consume(session, input.maxOutputTokens); if (!session.running) this.removeSession(session.id); diff --git a/src/server.test.ts b/src/server.test.ts index 7dfb196b1..04888621e 100644 --- a/src/server.test.ts +++ b/src/server.test.ts @@ -1,4 +1,4 @@ -import { isObjectValue, isFunctionValue, isJsonString, isJsonObject, optionalFields } from "./json-value.js"; +import { isObjectValue, isFunctionValue, isJsonString, isJsonNumber, isJsonObject, optionalFields } from "./json-value.js"; import { unsafeNarrow } from "./unsafe-narrow.js"; import type { JsonObject, WireInput } from "./json-value.js"; import assert from "node:assert/strict"; @@ -1166,6 +1166,64 @@ test("aborting one MCP request does not poison the next stateless request", asyn await waitForFile(join(root, "finished")); }); +test("an aborted HTTP write_stdin preserves its final output for reconnection", async (t) => { + const { root, localBaseUrl, accessToken } = await httpServerFixture(t, "devspace-aborted-poll-test-"); + + const opened = await postModernMcp(localBaseUrl, accessToken, "tools/call", { + name: "open_workspace", arguments: { path: root }, + }); + + const workspaceId = (await opened.json()).result.structuredContent.workspace_id; + + const started = await postModernMcp(localBaseUrl, accessToken, "tools/call", { + name: "exec_command", + arguments: { + workspace_id: workspaceId, yield_time_ms: 0, + cmd: "node -e \"const fs=require('node:fs');process.stdin.once('data',()=>{fs.writeFileSync('polled','');const t=setInterval(()=>{if(fs.existsSync('release')){clearInterval(t);console.log('retained-http-result');process.exit(0)}},20)})\"", + }, + }); + + const sessionId = (await started.json()).result.structuredContent.session_id; + assert.equal(isJsonNumber(sessionId), true); + + // Observe completion of the real manager call before reconnecting, including its error path. + const write = ProcessSessionManager.prototype.write; + let finishPoll: () => void = () => {}; + const pollFinished = new Promise((resolve) => { finishPoll = resolve; }); + t.mock.method(ProcessSessionManager.prototype, "write", async function ( + this: ProcessSessionManager, input: Parameters[0], + ) { + try { + return await write.call(this, input); + } finally { + finishPoll(); + } + }); + + const controller = new AbortController(); + + const poll = postModernMcp(localBaseUrl, accessToken, "tools/call", { + name: "write_stdin", + arguments: { workspace_id: workspaceId, session_id: sessionId, chars: "go\n", yield_time_ms: 10_000 }, + }, { signal: controller.signal }); + + await waitForFile(join(root, "polled")); + controller.abort(); + await assert.rejects(poll, /abort/i); + await writeFile(join(root, "release"), ""); + await pollFinished; + + const reconnected = await postModernMcp(localBaseUrl, accessToken, "tools/call", { + name: "write_stdin", + arguments: { workspace_id: workspaceId, session_id: sessionId, yield_time_ms: 2_000 }, + }); + + const body = await reconnected.json(); + assert.notEqual(body.result?.isError, true, JSON.stringify(body)); + assert.equal(body.result.structuredContent.exit_code, 0); + assert.match(body.result.structuredContent.result, /retained-http-result/); +}); + test("experimental Code Mode executes over stateless HTTP MCP requests", async (t) => { const { root, localBaseUrl, accessToken } = await httpServerFixture( t, diff --git a/src/tool-surfaces/codex.ts b/src/tool-surfaces/codex.ts index f7a39ef6d..7df06530a 100644 --- a/src/tool-surfaces/codex.ts +++ b/src/tool-surfaces/codex.ts @@ -316,7 +316,7 @@ function registerCodexProcessTools(context: ToolRegistrationContext): void { rows, yield_time_ms, max_output_tokens, - }) => { + }, { signal }) => { const startedAt = performance.now(); const workspaceId = workspace_id; const sessionId = session_id; @@ -331,6 +331,7 @@ function registerCodexProcessTools(context: ToolRegistrationContext): void { await workspaces.getWorkspace(workspaceId); return processSessions.write({ + signal, workspaceId, sessionId, chars, From 15c42d403ef2d9d61ebcf744a746ca3761157c1c Mon Sep 17 00:00:00 2001 From: pabtztd <267608262+pabtztd@users.noreply.github.com> Date: Mon, 9 Nov 2026 09:46:32 +0800 Subject: [PATCH 2/4] =?UTF-8?q?fix:=20=E5=8F=96=E6=B6=88=E6=9F=A5=E8=AF=A2?= =?UTF-8?q?=E6=97=B6=E5=8F=8A=E6=97=B6=E9=87=8A=E6=94=BE=E7=AD=89=E5=BE=85?= =?UTF-8?q?=E5=B9=B6=E6=94=BE=E5=AE=BD=E6=96=AD=E7=BA=BF=E5=9B=9E=E5=BD=92?= =?UTF-8?q?=E5=AE=B9=E5=B7=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/process-sessions.test.ts | 35 +++++++++++++++++++++++++++++++++++ src/process-sessions.ts | 16 +++++++++++++--- src/server.test.ts | 11 ++++++++--- 3 files changed, 56 insertions(+), 6 deletions(-) diff --git a/src/process-sessions.test.ts b/src/process-sessions.test.ts index fdf3a18fa..66d23d687 100644 --- a/src/process-sessions.test.ts +++ b/src/process-sessions.test.ts @@ -142,6 +142,41 @@ test("an aborted poll leaves completed output available to the next poll", async }), /Unknown process session/); }); +test("cancelling a pending poll releases its wait without stopping the process", async (t) => { + const manager = createManager(t); + + const started = await manager.start({ + workspaceId: "workspace-a", cwd: process.cwd(), + command: `${node} -e "process.stdin.once('data', () => { console.log('still-running'); process.exit(0); })"`, + yieldTimeMs: 0, + }); + + assert.ok(started.sessionId); + t.mock.timers.enable({ apis: ["setTimeout"] }); + const controller = new AbortController(); + let settled = false; + + const poll = assert.rejects(manager.write({ + workspaceId: "workspace-a", sessionId: started.sessionId, + yieldTimeMs: 10_000, signal: controller.signal, + }), { name: "AbortError" }).then(() => { settled = true; }); + + controller.abort(); + // Let cancellation settle without advancing the mocked yield timer. + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(settled, true); + await poll; + t.mock.timers.reset(); + + const completed = await manager.write({ + workspaceId: "workspace-a", sessionId: started.sessionId, + chars: "continue\n", yieldTimeMs: 2_000, + }); + + assert.equal(completed.exitCode, 0); + assert.match(completed.output, /still-running/); +}); + test("an already aborted write does not send input to the process", async (t) => { const manager = createManager(t); diff --git a/src/process-sessions.ts b/src/process-sessions.ts index 0d50cb4eb..ce4ccdc12 100644 --- a/src/process-sessions.ts +++ b/src/process-sessions.ts @@ -368,7 +368,7 @@ export class ProcessSessionManager { if ((interactionRequested || !session.buffer.hasOutput()) && session.running) { const fallback = interactionRequested ? DEFAULT_INTERACTIVE_YIELD_MS : DEFAULT_POLL_YIELD_MS; const yieldTimeMs = boundedInteger(input.yieldTimeMs, fallback, MAX_PROCESS_YIELD_MS); - await this.waitForExit(session, yieldTimeMs); + await this.waitForExit(session, yieldTimeMs, input.signal); } // A cancelled request must not drain output or discard the completed session. @@ -396,18 +396,28 @@ export class ProcessSessionManager { this.sessions.clear(); } - private async waitForExit(session: ProcessSession, yieldTimeMs: number): Promise { + private async waitForExit(session: ProcessSession, yieldTimeMs: number, signal?: AbortSignal): Promise { let timer: NodeJS.Timeout | undefined; + let onAbort: (() => void) | undefined; try { await Promise.race([ session.exitPromise, - new Promise((resolve) => { + new Promise((resolve, reject) => { timer = setTimeout(resolve, yieldTimeMs); + + if (signal) { + onAbort = () => reject(signal.reason); + signal.addEventListener("abort", onAbort, { once: true }); + + if (signal.aborted) onAbort(); + } }), ]); } finally { if (timer) clearTimeout(timer); + + if (onAbort) signal?.removeEventListener("abort", onAbort); } } diff --git a/src/server.test.ts b/src/server.test.ts index 04888621e..9f08211d6 100644 --- a/src/server.test.ts +++ b/src/server.test.ts @@ -1189,6 +1189,7 @@ test("an aborted HTTP write_stdin preserves its final output for reconnection", // Observe completion of the real manager call before reconnecting, including its error path. const write = ProcessSessionManager.prototype.write; let finishPoll: () => void = () => {}; + let pollSettled = false; const pollFinished = new Promise((resolve) => { finishPoll = resolve; }); t.mock.method(ProcessSessionManager.prototype, "write", async function ( this: ProcessSessionManager, input: Parameters[0], @@ -1196,6 +1197,7 @@ test("an aborted HTTP write_stdin preserves its final output for reconnection", try { return await write.call(this, input); } finally { + pollSettled = true; finishPoll(); } }); @@ -1207,7 +1209,8 @@ test("an aborted HTTP write_stdin preserves its final output for reconnection", arguments: { workspace_id: workspaceId, session_id: sessionId, chars: "go\n", yield_time_ms: 10_000 }, }, { signal: controller.signal }); - await waitForFile(join(root, "polled")); + await waitForFile(join(root, "polled"), 5_000); + assert.equal(pollSettled, false, "the poll must still be pending when cancelled"); controller.abort(); await assert.rejects(poll, /abort/i); await writeFile(join(root, "release"), ""); @@ -1569,8 +1572,10 @@ async function git(cwd: string, args: string[]): Promise { await execFileAsync("git", args, { cwd }); } -async function waitForFile(path: string): Promise { - for (let attempt = 0; attempt < 100; attempt += 1) { +async function waitForFile(path: string, timeoutMs = 1_000): Promise { + const deadline = Date.now() + timeoutMs; + + while (Date.now() < deadline) { try { await access(path); From bccfc01de42c7db38372cefef91b73f5b56bf959 Mon Sep 17 00:00:00 2001 From: pabtztd <267608262+pabtztd@users.noreply.github.com> Date: Mon, 9 Nov 2026 09:59:57 +0800 Subject: [PATCH 3/4] =?UTF-8?q?test:=20=E8=B6=85=E6=97=B6=E5=89=8D?= =?UTF-8?q?=E6=A3=80=E6=9F=A5=E6=9C=80=E5=90=8E=E4=B8=80=E6=AC=A1=E7=AD=89?= =?UTF-8?q?=E5=BE=85=E5=90=8E=E5=87=BA=E7=8E=B0=E7=9A=84=E8=BF=9B=E7=A8=8B?= =?UTF-8?q?=E6=A0=87=E8=AE=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/server.test.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/server.test.ts b/src/server.test.ts index 9f08211d6..853358f11 100644 --- a/src/server.test.ts +++ b/src/server.test.ts @@ -1572,20 +1572,21 @@ async function git(cwd: string, args: string[]): Promise { await execFileAsync("git", args, { cwd }); } +/** Checks the child-process marker before timing out, including after the final delay. */ async function waitForFile(path: string, timeoutMs = 1_000): Promise { const deadline = Date.now() + timeoutMs; - while (Date.now() < deadline) { + while (true) { try { await access(path); return; } catch { + if (Date.now() >= deadline) assert.fail(`Timed out waiting for ${path}`); + await new Promise((resolve) => setTimeout(resolve, 10)); } } - - assert.fail(`Timed out waiting for ${path}`); } async function issueTestAccessToken( From 5ad9a4f680e15e694d1ab52ae72c4c87dc5f128d Mon Sep 17 00:00:00 2001 From: pabtztd <267608262+pabtztd@users.noreply.github.com> Date: Mon, 9 Nov 2026 10:11:37 +0800 Subject: [PATCH 4/4] =?UTF-8?q?test:=20=E4=BF=9D=E7=95=99=E6=A0=87?= =?UTF-8?q?=E8=AE=B0=E9=87=8D=E8=AF=95=E5=AE=B9=E5=B7=AE=E5=B9=B6=E7=94=A8?= =?UTF-8?q?=E5=8D=95=E8=B0=83=E6=97=B6=E9=97=B4=E8=AE=A1=E7=AE=97=E6=98=BE?= =?UTF-8?q?=E5=BC=8F=E8=B6=85=E6=97=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/server.test.ts | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/server.test.ts b/src/server.test.ts index 853358f11..7551b8b46 100644 --- a/src/server.test.ts +++ b/src/server.test.ts @@ -1572,17 +1572,19 @@ async function git(cwd: string, args: string[]): Promise { await execFileAsync("git", args, { cwd }); } -/** Checks the child-process marker before timing out, including after the final delay. */ -async function waitForFile(path: string, timeoutMs = 1_000): Promise { - const deadline = Date.now() + timeoutMs; +/** Keeps legacy retry tolerance; explicit deadlines use elapsed time and include a final check. */ +async function waitForFile(path: string, timeoutMs?: number): Promise { + const deadline = timeoutMs === undefined ? undefined : performance.now() + timeoutMs; - while (true) { + for (let attempt = 0; ; attempt += 1) { try { await access(path); return; } catch { - if (Date.now() >= deadline) assert.fail(`Timed out waiting for ${path}`); + const expired = deadline === undefined ? attempt >= 100 : performance.now() >= deadline; + + if (expired) assert.fail(`Timed out waiting for ${path}`); await new Promise((resolve) => setTimeout(resolve, 10)); }