Skip to content

Commit 65d8320

Browse files
zknprclaude
andcommitted
fix(codex-rescue): address PR #346 review — sentinel gating, foreground wait, worker pid
Three regressions from e1b8ae3/c4722b5: - renderTaskResult stamped [[codex-task status=complete]] on failure/empty fallback output, so a failed run carried the success sentinel and the completion hook read it as success. The sentinel is now appended only on a successful exit (status 0); failure/empty output renders without it. - runForegroundTaskWorker inherited the 240s status-wait default, so foreground xhigh runs (routinely >4min) timed out instead of returning the result. The inline wait is now unbounded; the detached worker provides survival. - enqueueBackgroundTask left the queued record pid: null and never persisted the spawned worker pid, breaking /codex:cancel. The worker pid is now written after spawn, guarded against clobbering a finished job. Tests: 97/97 (added failure-no-sentinel + worker-pid coverage). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
1 parent c4722b5 commit 65d8320

4 files changed

Lines changed: 67 additions & 4 deletions

File tree

‎plugins/codex/scripts/codex-companion.mjs‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -499,6 +499,7 @@ async function executeTaskRun(request) {
499499
{
500500
rawOutput,
501501
failureMessage,
502+
status: result.status,
502503
reasoningSummary: result.reasoningSummary
503504
},
504505
{
@@ -675,7 +676,19 @@ function enqueueBackgroundTask(cwd, job, request) {
675676
writeJobFile(job.workspaceRoot, job.id, queuedRecord);
676677
upsertJob(job.workspaceRoot, queuedRecord);
677678

678-
spawnDetachedTaskWorker(cwd, job.id);
679+
const child = spawnDetachedTaskWorker(cwd, job.id);
680+
// PR #346 review: keep the pre-spawn record, then persist the worker pid for cancellation.
681+
const spawnedRecord = readStoredJob(job.workspaceRoot, job.id) ?? queuedRecord;
682+
if (isActiveJobStatus(spawnedRecord.status)) {
683+
writeJobFile(job.workspaceRoot, job.id, {
684+
...spawnedRecord,
685+
pid: child.pid ?? null
686+
});
687+
upsertJob(job.workspaceRoot, {
688+
id: job.id,
689+
pid: child.pid ?? null
690+
});
691+
}
679692

680693
return {
681694
payload: {
@@ -731,6 +744,8 @@ async function runForegroundTaskWorker(cwd, job, request, options = {}) {
731744
// Foreground tasks run in the same detached worker as background tasks, then wait inline for
732745
// the stored result so Bash auto-backgrounding and subagent teardown do not kill the Codex turn.
733746
const snapshot = await waitForSingleJobSnapshot(cwd, job.id, {
747+
// PR #346 review: foreground xhigh waits must survive beyond the 240s status default.
748+
timeoutMs: Infinity,
734749
pollIntervalMs: FOREGROUND_TASK_POLL_INTERVAL_MS
735750
});
736751
if (snapshot.waitTimedOut) {

‎plugins/codex/scripts/lib/render.mjs‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -320,12 +320,14 @@ export function renderNativeReviewResult(result, meta) {
320320
export function renderTaskResult(parsedResult, meta) {
321321
const rawOutput = typeof parsedResult?.rawOutput === "string" ? parsedResult.rawOutput : "";
322322
const completeToken = buildTaskCompleteStatusToken();
323+
// PR #346 review: only successful Codex task exits may stamp the success sentinel.
324+
const succeeded = parsedResult?.status === 0 || parsedResult?.exitStatus === 0 || meta?.success === true;
323325
if (rawOutput) {
324-
return appendTaskStatusToken(rawOutput, completeToken);
326+
return succeeded ? appendTaskStatusToken(rawOutput, completeToken) : rawOutput.endsWith("\n") ? rawOutput : `${rawOutput}\n`;
325327
}
326328

327329
const message = String(parsedResult?.failureMessage ?? "").trim() || "Codex did not return a final message.";
328-
return appendTaskStatusToken(message, completeToken);
330+
return succeeded ? appendTaskStatusToken(message, completeToken) : `${message}\n`;
329331
}
330332

331333
export function renderStatusReport(report) {

‎tests/render.test.mjs‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import test from "node:test";
22
import assert from "node:assert/strict";
33

4-
import { renderReviewResult, renderStoredJobResult } from "../plugins/codex/scripts/lib/render.mjs";
4+
import { renderReviewResult, renderStoredJobResult, renderTaskResult } from "../plugins/codex/scripts/lib/render.mjs";
5+
6+
const TASK_COMPLETE_STATUS_TOKEN = "[[codex-task status=complete]]";
57

68
test("renderReviewResult degrades gracefully when JSON is missing required review fields", () => {
79
const output = renderReviewResult(
@@ -57,3 +59,27 @@ test("renderStoredJobResult prefers rendered output for structured review jobs",
5759
assert.match(output, /Codex session ID: thr_123/);
5860
assert.match(output, /Resume in Codex: codex resume thr_123/);
5961
});
62+
63+
test("renderTaskResult only stamps the complete sentinel for successful task runs", () => {
64+
const successful = renderTaskResult(
65+
{
66+
rawOutput: "Handled the requested task.",
67+
status: 0
68+
},
69+
{}
70+
);
71+
72+
assert.equal(successful, `Handled the requested task.\n${TASK_COMPLETE_STATUS_TOKEN}\n`);
73+
74+
const failedEmpty = renderTaskResult(
75+
{
76+
rawOutput: "",
77+
failureMessage: "Codex failed before producing a final message.",
78+
status: 1
79+
},
80+
{}
81+
);
82+
83+
assert.equal(failedEmpty, "Codex failed before producing a final message.\n");
84+
assert.doesNotMatch(failedEmpty, /\[\[codex-task status=complete\]\]/);
85+
});

‎tests/runtime.test.mjs‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -611,6 +611,15 @@ test("foreground task enqueues a detached worker and prints the stored result",
611611
assert.equal(result.stdout, storedJob.rendered);
612612
});
613613

614+
test("foreground task worker wait is not bounded by the default status timeout", () => {
615+
const source = fs.readFileSync(SCRIPT, "utf8");
616+
const match = source.match(/async function runForegroundTaskWorker[\s\S]*?\n}\n\nasync function handleTask/);
617+
618+
assert.ok(match, "expected to locate runForegroundTaskWorker");
619+
assert.match(match[0], /timeoutMs:\s*Infinity/);
620+
assert.match(match[0], /pollIntervalMs:\s*FOREGROUND_TASK_POLL_INTERVAL_MS/);
621+
});
622+
614623
test("task --resume acts like --resume-last without leaking the flag into the prompt", () => {
615624
const repo = makeTempDir();
616625
const binDir = makeTempDir();
@@ -834,6 +843,17 @@ test("task --background enqueues a detached worker and exposes per-job status",
834843
assert.equal(launchPayload.status, "queued");
835844
assert.match(launchPayload.jobId, /^task-/);
836845

846+
const stateDir = resolveStateDir(repo);
847+
const launchedState = JSON.parse(fs.readFileSync(path.join(stateDir, "state.json"), "utf8"));
848+
const launchedJob = launchedState.jobs.find((candidate) => candidate.id === launchPayload.jobId);
849+
assert.ok(Number.isInteger(launchedJob?.pid) && launchedJob.pid > 0, "expected launched job to record worker pid");
850+
851+
const launchedStoredJob = JSON.parse(fs.readFileSync(path.join(stateDir, "jobs", `${launchPayload.jobId}.json`), "utf8"));
852+
assert.ok(
853+
Number.isInteger(launchedStoredJob.pid) && launchedStoredJob.pid > 0,
854+
"expected stored launched job to record worker pid"
855+
);
856+
837857
const waitedStatus = run(
838858
"node",
839859
[SCRIPT, "status", launchPayload.jobId, "--wait", "--timeout-ms", "15000", "--json"],

0 commit comments

Comments
 (0)