Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: honour a Stop raised while a Codex thread/start or turn/start RPC is in flight (#5778)

Adam Eivyfa408944e936
diff --git a/server/services/codexAppServer.js b/server/services/codexAppServer.js
index cf2df905e4..df256e94e6 100644
--- a/server/services/codexAppServer.js
+++ b/server/services/codexAppServer.js
@@ -755,6 +755,64 @@ const cachedModelEntry = (modelId) => {
const turnCancelledError = () =>
codexError(CODEX_TURN_ERROR_CODES.turnInterrupted, 'The Codex turn was cancelled.', { status: 499 });
+/**
+ * Best-effort: tell the app-server to stop working a turn PortOS has abandoned,
+ * so a cancelled request does not keep burning subscription quota.
+ *
+ * Sent on the connection that OWNS the thread, and only while it is still alive
+ * — routing it through `call` would reconnect, spawning a whole new app-server
+ * to interrupt a thread that only existed in the dead one. Fire and forget: the
+ * caller is already gone, and nothing downstream waits on the acknowledgement.
+ */
+const interruptCodexTurn = (owner, threadId, turnId) => {
+ if (!turnId || !owner || owner.closed) return;
+ sendRequest(owner, CODEX_TURN_RPC.turnInterrupt, { threadId, turnId })
+ .catch((err) => console.error(`❌ Codex turn interrupt failed: ${err.message}`));
+};
+
+/**
+ * Await `request`, but give up the moment the caller's Stop lands.
+ *
+ * Without this a Stop raised WHILE an RPC is in flight is invisible until that
+ * RPC answers or hits its own deadline — up to 15s on `thread/start` and the
+ * whole 5-minute turn deadline on `turn/start` against a stalled app-server.
+ *
+ * `Promise.race` settles on the first, but the LOSER keeps running: a raced-away
+ * `sendRequest` still answers (or times out) later. That matters for
+ * `turn/start` — a turn the app-server accepted after the caller walked away
+ * would otherwise generate with nothing telling it to stop, which is worse for
+ * quota than the wait this removes. `onAbandoned` is that compensating path; it
+ * runs outside any request lifecycle, so it is guarded here rather than trusted
+ * to bubble.
+ */
+const raceCodexAbort = (request, signal, onAbandoned = null) => {
+ if (!signal) return request;
+ let abandoned = false;
+ let onAbort = null;
+ const cancelled = new Promise((_, reject) => {
+ onAbort = () => { abandoned = true; reject(turnCancelledError()); };
+ if (signal.aborted) onAbort();
+ else signal.addEventListener('abort', onAbort, { once: true });
+ });
+ // The race hands the caller whichever settles first, so the loser's rejection
+ // would otherwise be an UNHANDLED one — a process-level crash under Node's
+ // default policy. Both sides are parked before they can reject.
+ cancelled.catch(() => {});
+ const watched = request.then((result) => {
+ if (!abandoned) return result;
+ // The Stop already won: this response arrived for a caller that is gone.
+ if (onAbandoned) {
+ try { onAbandoned(result); } catch (err) {
+ console.error(`❌ Codex abandoned-response cleanup failed: ${err.message}`);
+ }
+ }
+ return result;
+ });
+ watched.catch(() => {});
+ return Promise.race([watched, cancelled])
+ .finally(() => signal.removeEventListener('abort', onAbort));
+};
+
/**
* Run ONE bounded text turn against the ChatGPT subscription.
*
@@ -816,11 +874,14 @@ export async function runCodexTextTurn({
if (signal?.aborted) {
throw turnCancelledError();
}
- const started = await sendRequest(owner, CODEX_TURN_RPC.threadStart, {
+ // Raced against the signal: a Stop pressed during the handshake must not wait
+ // out `REQUEST_TIMEOUT_MS`. No compensation is needed here — the thread is
+ // ephemeral and no turn exists yet, so nothing is left running to interrupt.
+ const started = await raceCodexAbort(sendRequest(owner, CODEX_TURN_RPC.threadStart, {
...CODEX_TEXT_THREAD_CONFIG,
cwd,
...(model ? { model } : {}),
- }, REQUEST_TIMEOUT_MS);
+ }, REQUEST_TIMEOUT_MS), signal);
const threadId = typeof started?.thread?.id === 'string' ? started.thread.id : null;
if (!threadId) {
throw codexError(CODEX_ERROR_CODES.protocol, 'Codex started a thread with no id.');
@@ -864,7 +925,14 @@ export async function runCodexTextTurn({
// and Stop does not have to wait out a `turn/start` response that would
// only be thrown away. The `finally` below still runs the shared cleanup.
if (signal?.aborted) await finished;
- const response = await sendRequest(owner, CODEX_TURN_RPC.turnStart, {
+ // Raced the same way, but this one CAN leave a live turn behind: the
+ // app-server may accept the turn just after the Stop won. `onAbandoned`
+ // interrupts it with the id that late response carries, which the `finally`
+ // below cannot do because `acc.turnId` was never set. The `activeTurns`
+ // guard is what tells the two apart — the `finally` has already deleted the
+ // entry by the time an abandoned response lands, whereas a response the
+ // normal path is still reading finds the thread registered.
+ const response = await raceCodexAbort(sendRequest(owner, CODEX_TURN_RPC.turnStart, {
threadId,
input: [{ type: 'text', text: prompt }],
sandboxPolicy: { ...CODEX_TEXT_TURN_SANDBOX },
@@ -872,7 +940,10 @@ export async function runCodexTextTurn({
...(model ? { model } : {}),
...(resolvedEffort ? { effort: resolvedEffort } : {}),
...(responseSchema ? { outputSchema: responseSchema } : {}),
- }, timeoutMs);
+ }, timeoutMs), signal, (late) => {
+ if (activeTurns.has(threadId)) return;
+ interruptCodexTurn(owner, threadId, typeof late?.turn?.id === 'string' ? late.turn.id : null);
+ });
const turnId = typeof response?.turn?.id === 'string' ? response.turn.id : null;
if (turnId) acc.turnId = turnId;
// A turn that completed before its own response was read leaves the
@@ -895,16 +966,10 @@ export async function runCodexTextTurn({
} finally {
clearTimeout(timer);
signal?.removeEventListener('abort', onAbort);
+ // Delete BEFORE the interrupt: this is the flag a late `turn/start`
+ // response reads to decide whether the turn it carries still has an owner.
activeTurns.delete(threadId);
- // Best-effort: tell the app-server to stop working a turn PortOS has
- // abandoned, so a cancelled request does not keep burning subscription
- // quota. Sent to the connection that OWNS the thread, and only while it is
- // still alive — routing it through `call` would reconnect, spawning a whole
- // new app-server to interrupt a thread that only existed in the dead one.
- if (acc.status === 'inProgress' && acc.turnId && !owner.closed) {
- sendRequest(owner, CODEX_TURN_RPC.turnInterrupt, { threadId, turnId: acc.turnId })
- .catch((err) => console.error(`❌ Codex turn interrupt failed: ${err.message}`));
- }
+ if (acc.status === 'inProgress') interruptCodexTurn(owner, threadId, acc.turnId);
}
}
@@ -949,6 +1014,17 @@ export async function stopCodexAppServer() {
}
}
+/**
+ * Test-only: how many turns are still registered.
+ *
+ * A leaked entry is invisible from the outside — it neither fails a turn nor
+ * throws — but it strands the accumulator and misroutes every later event for
+ * that thread id, so the cancellation paths assert against it directly.
+ */
+export function __codexActiveTurnCount() {
+ return activeTurns.size;
+}
+
/** Test-only: drop every module-level handle so a suite starts clean. */
export function __resetCodexAppServer() {
if (pendingLogin) clearTimeout(pendingLogin.timer);
diff --git a/server/services/codexAppServer.turn.test.js b/server/services/codexAppServer.turn.test.js
index b61d1e7652..2744f74ad9 100644
--- a/server/services/codexAppServer.turn.test.js
+++ b/server/services/codexAppServer.turn.test.js
@@ -21,6 +21,7 @@ const { ERROR_CATEGORIES } = await import('../lib/aiToolkit/errorDetection.js');
const { CODEX_ERROR_CODES } = await import('../lib/codexAccount.js');
const { CODEX_TURN_ERROR_CODES } = await import('../lib/codexTurn.js');
const {
+ __codexActiveTurnCount,
__resetCodexAppServer,
benchCodexTextTransport,
getCodexAccountReadiness,
@@ -204,6 +205,52 @@ describe('running a text turn', () => {
expect(child.lastRequest('turn/start')).toBeUndefined();
});
+ it('gives up on a thread/start the app-server never answers, instead of waiting out its deadline', async () => {
+ // Before #5778 the abort listener was registered only AFTER `thread/start`
+ // answered, so a Stop raised here was invisible for the full
+ // REQUEST_TIMEOUT_MS against a stalled app-server. The reply is withheld for
+ // the whole test and no clock is advanced, so the only way to pass is to
+ // reject on the abort itself rather than on the RPC deadline.
+ const controller = new AbortController();
+ const promise = runCodexTextTurn({ prompt: 'long one', signal: controller.signal });
+ await handshake();
+ await awaitRequest(child, 'thread/start', () => {});
+
+ controller.abort();
+
+ await expect(promise).rejects.toMatchObject({ code: CODEX_TURN_ERROR_CODES.turnInterrupted });
+ // No thread id was ever read, so no turn may be dispatched — and nothing is
+ // left registered to strand an accumulator or misroute later events.
+ expect(child.lastRequest('turn/start')).toBeUndefined();
+ expect(__codexActiveTurnCount()).toBe(0);
+ });
+
+ it('interrupts a turn the app-server accepts after the caller has already stopped', async () => {
+ // The compensating path, and the reason a plain race is not enough: bailing
+ // out before the `turn/start` response is read means `acc.turnId` is never
+ // set, so the `finally` cannot interrupt. Without this, a turn Codex DID
+ // accept would keep generating — and burning subscription quota — with
+ // nothing telling it to stop.
+ const controller = new AbortController();
+ const promise = runCodexTextTurn({ prompt: 'long one', signal: controller.signal });
+ await handshake();
+ await awaitRequest(child, 'thread/start', { thread: { id: 'thread-1' } });
+ const pendingStart = await awaitRequest(child, 'turn/start', () => {});
+
+ controller.abort();
+
+ await expect(promise).rejects.toMatchObject({ code: CODEX_TURN_ERROR_CODES.turnInterrupted });
+ expect(__codexActiveTurnCount()).toBe(0);
+ // Nothing to interrupt yet: the turn has no id until its response lands.
+ expect(child.lastRequest('turn/interrupt')).toBeUndefined();
+
+ // The app-server answers only now — it did accept the turn.
+ child.reply(pendingStart, { turn: { id: 'turn-late', items: [], status: 'inProgress' } });
+
+ await vi.waitFor(() => expect(child.lastRequest('turn/interrupt')).toBeTruthy());
+ expect(child.lastRequest('turn/interrupt').params).toEqual({ threadId: 'thread-1', turnId: 'turn-late' });
+ });
+
it('carries a quota failure out as a usage-limit category', async () => {
const promise = runCodexTextTurn({ prompt: 'hi' });
await handshake();