Skip to content

Commit bc3563d

Browse files
committed
fix: look up codex jobs across workspaces for observe/status/result/cancel
Jobs are keyed by workspace state dir (hash of git root), so running a slash command from outside the workspace where the job was created returned "Job not found" even though /codex:status listed it. Add a cross-workspace fallback that scans CLAUDE_PLUGIN_DATA state subdirs by job id, then routes subsequent reads/writes to the job's stored workspaceRoot. Cancel also targets the matching broker.
1 parent 7188e2c commit bc3563d

6 files changed

Lines changed: 357 additions & 28 deletions

File tree

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1015,7 +1015,7 @@ async function handleCancel(argv) {
10151015
const threadId = existing.threadId ?? job.threadId ?? null;
10161016
const turnId = existing.turnId ?? job.turnId ?? null;
10171017

1018-
const interrupt = await interruptAppServerTurn(cwd, { threadId, turnId });
1018+
const interrupt = await interruptAppServerTurn(workspaceRoot, { threadId, turnId });
10191019
if (interrupt.attempted) {
10201020
appendLogLine(
10211021
job.logFile,

‎plugins/codex/scripts/lib/job-control.mjs‎

Lines changed: 78 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,13 @@
11
import fs from "node:fs";
22

33
import { getSessionRuntimeStatus } from "./codex.mjs";
4-
import { getConfig, listJobs, readJobFile, resolveJobFile } from "./state.mjs";
4+
import {
5+
findJobByIdAcrossWorkspaces,
6+
getConfig,
7+
listJobs,
8+
readJobFile,
9+
resolveJobFile
10+
} from "./state.mjs";
511
import { SESSION_ID_ENV } from "./tracked-jobs.mjs";
612
import { resolveWorkspaceRoot } from "./workspace.mjs";
713

@@ -207,7 +213,21 @@ function matchJobReference(jobs, reference, predicate = () => true) {
207213
throw new Error(`Job reference "${reference}" is ambiguous. Use a longer job id.`);
208214
}
209215

210-
throw new Error(`No job found for "${reference}". Run /codex:status to list known jobs.`);
216+
return null;
217+
}
218+
219+
function findCrossWorkspaceMatch(reference, predicate) {
220+
if (!reference) {
221+
return null;
222+
}
223+
const cross = findJobByIdAcrossWorkspaces(reference);
224+
if (!cross) {
225+
return null;
226+
}
227+
if (predicate && !predicate(cross.job)) {
228+
return { ...cross, predicateRejected: true };
229+
}
230+
return cross;
211231
}
212232

213233
export function buildStatusSnapshot(cwd, options = {}) {
@@ -243,34 +263,59 @@ export function buildSingleJobSnapshot(cwd, reference, options = {}) {
243263
const workspaceRoot = resolveWorkspaceRoot(cwd);
244264
const jobs = sortJobsNewestFirst(listJobs(workspaceRoot));
245265
const selected = matchJobReference(jobs, reference);
246-
if (!selected) {
247-
throw new Error(`No job found for "${reference}". Run /codex:status to inspect known jobs.`);
266+
267+
if (selected) {
268+
return {
269+
workspaceRoot,
270+
job: enrichJob(selected, { maxProgressLines: options.maxProgressLines })
271+
};
248272
}
249273

250-
return {
251-
workspaceRoot,
252-
job: enrichJob(selected, { maxProgressLines: options.maxProgressLines })
253-
};
274+
const cross = findCrossWorkspaceMatch(reference);
275+
if (cross) {
276+
return {
277+
workspaceRoot: cross.job.workspaceRoot ?? workspaceRoot,
278+
job: enrichJob(cross.job, { maxProgressLines: options.maxProgressLines }),
279+
crossWorkspace: true,
280+
crossWorkspaceStateDir: cross.stateDir
281+
};
282+
}
283+
284+
throw new Error(`No job found for "${reference}". Run /codex:status to inspect known jobs.`);
254285
}
255286

256287
export function resolveResultJob(cwd, reference) {
257288
const workspaceRoot = resolveWorkspaceRoot(cwd);
258289
const jobs = sortJobsNewestFirst(reference ? listJobs(workspaceRoot) : filterJobsForCurrentSession(listJobs(workspaceRoot)));
259-
const selected = matchJobReference(
260-
jobs,
261-
reference,
262-
(job) => job.status === "completed" || job.status === "failed" || job.status === "cancelled"
263-
);
290+
const isFinished = (job) =>
291+
job.status === "completed" || job.status === "failed" || job.status === "cancelled";
292+
const isActive = (job) => job.status === "queued" || job.status === "running";
264293

294+
const selected = matchJobReference(jobs, reference, isFinished);
265295
if (selected) {
266296
return { workspaceRoot, job: selected };
267297
}
268298

269-
const active = matchJobReference(jobs, reference, (job) => job.status === "queued" || job.status === "running");
299+
const active = matchJobReference(jobs, reference, isActive);
270300
if (active) {
271301
throw new Error(`Job ${active.id} is still ${active.status}. Check /codex:status and try again once it finishes.`);
272302
}
273303

304+
const cross = findCrossWorkspaceMatch(reference, isFinished);
305+
if (cross && !cross.predicateRejected) {
306+
return {
307+
workspaceRoot: cross.job.workspaceRoot ?? workspaceRoot,
308+
job: cross.job,
309+
crossWorkspace: true,
310+
crossWorkspaceStateDir: cross.stateDir
311+
};
312+
}
313+
if (cross && cross.predicateRejected) {
314+
throw new Error(
315+
`Job ${cross.job.id} is still ${cross.job.status} in another workspace. Check /codex:status and try again once it finishes.`
316+
);
317+
}
318+
274319
if (reference) {
275320
throw new Error(`No finished job found for "${reference}". Run /codex:status to inspect active jobs.`);
276321
}
@@ -281,14 +326,29 @@ export function resolveResultJob(cwd, reference) {
281326
export function resolveCancelableJob(cwd, reference, options = {}) {
282327
const workspaceRoot = resolveWorkspaceRoot(cwd);
283328
const jobs = sortJobsNewestFirst(listJobs(workspaceRoot));
284-
const activeJobs = jobs.filter((job) => job.status === "queued" || job.status === "running");
329+
const isActive = (job) => job.status === "queued" || job.status === "running";
330+
const activeJobs = jobs.filter(isActive);
285331

286332
if (reference) {
287333
const selected = matchJobReference(activeJobs, reference);
288-
if (!selected) {
289-
throw new Error(`No active job found for "${reference}".`);
334+
if (selected) {
335+
return { workspaceRoot, job: selected };
290336
}
291-
return { workspaceRoot, job: selected };
337+
const cross = findCrossWorkspaceMatch(reference, isActive);
338+
if (cross && !cross.predicateRejected) {
339+
return {
340+
workspaceRoot: cross.job.workspaceRoot ?? workspaceRoot,
341+
job: cross.job,
342+
crossWorkspace: true,
343+
crossWorkspaceStateDir: cross.stateDir
344+
};
345+
}
346+
if (cross && cross.predicateRejected) {
347+
throw new Error(
348+
`Job ${cross.job.id} is not active (status: ${cross.job.status}). Nothing to cancel.`
349+
);
350+
}
351+
throw new Error(`No active job found for "${reference}".`);
292352
}
293353

294354
const sessionScopedActiveJobs = filterJobsForCurrentSession(activeJobs, options);

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

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import fs from "node:fs";
22

33
import { parseArgs } from "./args.mjs";
44
import { EVENT_TYPES } from "./event-stream.mjs";
5-
import { loadState, resolveJobsDir } from "./state.mjs";
5+
import { findJobByIdAcrossWorkspaces, loadState, resolveJobsDir } from "./state.mjs";
66
import { resolveWorkspaceRoot } from "./workspace.mjs";
77

88
const POLL_INTERVAL_MS = 500;
@@ -289,12 +289,18 @@ export async function handleObserveCommand(argv) {
289289
const state = loadState(workspaceRoot);
290290

291291
let job;
292+
let crossWorkspaceMatch = null;
292293
if (jobId) {
293294
job = findJobById(state, jobId);
294295
if (!job) {
295-
process.stderr.write(`Error: Job not found: ${jobId}\n`);
296-
process.exitCode = 1;
297-
return;
296+
crossWorkspaceMatch = findJobByIdAcrossWorkspaces(jobId);
297+
if (crossWorkspaceMatch) {
298+
job = crossWorkspaceMatch.job;
299+
} else {
300+
process.stderr.write(`Error: Job not found: ${jobId}\n`);
301+
process.exitCode = 1;
302+
return;
303+
}
298304
}
299305
} else {
300306
job = findLatestRunningJob(state);
@@ -310,7 +316,11 @@ export async function handleObserveCommand(argv) {
310316

311317
// Print header
312318
const statusColor = isCompleted ? (job.status === "completed" ? ANSI.green : ANSI.red) : ANSI.yellow;
313-
process.stdout.write(`${ANSI.dim}Codex Observer — ${job.id} — ${statusColor}${job.status}${ANSI.reset}\n\n`);
319+
process.stdout.write(`${ANSI.dim}Codex Observer — ${job.id} — ${statusColor}${job.status}${ANSI.reset}\n`);
320+
if (crossWorkspaceMatch) {
321+
process.stdout.write(`${ANSI.dim}(job belongs to another workspace; reading from ${crossWorkspaceMatch.stateDir})${ANSI.reset}\n`);
322+
}
323+
process.stdout.write("\n");
314324

315325
if (isCompleted) {
316326
// Render full history and exit

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

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,11 @@ function defaultState() {
2626
};
2727
}
2828

29+
function resolveStateRoot() {
30+
const pluginDataDir = process.env[PLUGIN_DATA_ENV];
31+
return pluginDataDir ? path.join(pluginDataDir, "state") : FALLBACK_STATE_ROOT_DIR;
32+
}
33+
2934
export function resolveStateDir(cwd) {
3035
const workspaceRoot = resolveWorkspaceRoot(cwd);
3136
let canonicalWorkspaceRoot = workspaceRoot;
@@ -38,9 +43,47 @@ export function resolveStateDir(cwd) {
3843
const slugSource = path.basename(workspaceRoot) || "workspace";
3944
const slug = slugSource.replace(/[^a-zA-Z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") || "workspace";
4045
const hash = createHash("sha256").update(canonicalWorkspaceRoot).digest("hex").slice(0, 16);
41-
const pluginDataDir = process.env[PLUGIN_DATA_ENV];
42-
const stateRoot = pluginDataDir ? path.join(pluginDataDir, "state") : FALLBACK_STATE_ROOT_DIR;
43-
return path.join(stateRoot, `${slug}-${hash}`);
46+
return path.join(resolveStateRoot(), `${slug}-${hash}`);
47+
}
48+
49+
export function findJobByIdAcrossWorkspaces(jobId) {
50+
if (!jobId) {
51+
return null;
52+
}
53+
const stateRoot = resolveStateRoot();
54+
if (!fs.existsSync(stateRoot)) {
55+
return null;
56+
}
57+
58+
let entries;
59+
try {
60+
entries = fs.readdirSync(stateRoot, { withFileTypes: true });
61+
} catch {
62+
return null;
63+
}
64+
65+
for (const entry of entries) {
66+
if (!entry.isDirectory()) {
67+
continue;
68+
}
69+
const stateDir = path.join(stateRoot, entry.name);
70+
const stateFile = path.join(stateDir, STATE_FILE_NAME);
71+
if (!fs.existsSync(stateFile)) {
72+
continue;
73+
}
74+
try {
75+
const parsed = JSON.parse(fs.readFileSync(stateFile, "utf8"));
76+
const jobs = Array.isArray(parsed.jobs) ? parsed.jobs : [];
77+
const job = jobs.find((entry) => entry.id === jobId);
78+
if (job) {
79+
return { stateDir, job };
80+
}
81+
} catch {
82+
// Skip corrupted state files
83+
}
84+
}
85+
86+
return null;
4487
}
4588

4689
export function resolveStateFile(cwd) {

‎tests/job-control.test.mjs‎

Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
import fs from "node:fs";
2+
import path from "node:path";
3+
import { mkdtempSync, rmSync } from "node:fs";
4+
import { tmpdir } from "node:os";
5+
import { describe, it, beforeEach, afterEach } from "node:test";
6+
import assert from "node:assert/strict";
7+
8+
import {
9+
buildSingleJobSnapshot,
10+
resolveCancelableJob,
11+
resolveResultJob
12+
} from "../plugins/codex/scripts/lib/job-control.mjs";
13+
14+
describe("job-control cross-workspace fallback", () => {
15+
let pluginDataDir;
16+
let currentWorkspace;
17+
let previousPluginData;
18+
19+
beforeEach(() => {
20+
pluginDataDir = mkdtempSync(path.join(tmpdir(), "job-control-cross-"));
21+
currentWorkspace = mkdtempSync(path.join(tmpdir(), "job-control-cwd-"));
22+
previousPluginData = process.env.CLAUDE_PLUGIN_DATA;
23+
process.env.CLAUDE_PLUGIN_DATA = pluginDataDir;
24+
});
25+
26+
afterEach(() => {
27+
if (previousPluginData === undefined) {
28+
delete process.env.CLAUDE_PLUGIN_DATA;
29+
} else {
30+
process.env.CLAUDE_PLUGIN_DATA = previousPluginData;
31+
}
32+
rmSync(pluginDataDir, { recursive: true, force: true });
33+
rmSync(currentWorkspace, { recursive: true, force: true });
34+
});
35+
36+
function writeRemoteWorkspaceJob(slug, job) {
37+
const stateDir = path.join(pluginDataDir, "state", slug);
38+
fs.mkdirSync(stateDir, { recursive: true });
39+
fs.writeFileSync(
40+
path.join(stateDir, "state.json"),
41+
`${JSON.stringify({ version: 1, jobs: [job] }, null, 2)}\n`,
42+
"utf8"
43+
);
44+
return stateDir;
45+
}
46+
47+
it("buildSingleJobSnapshot falls back to cross-workspace by job id", () => {
48+
const job = {
49+
id: "task-abc-running",
50+
status: "running",
51+
workspaceRoot: "/some/other/repo",
52+
logFile: path.join(pluginDataDir, "log.txt"),
53+
createdAt: new Date().toISOString(),
54+
updatedAt: new Date().toISOString()
55+
};
56+
const stateDir = writeRemoteWorkspaceJob("remote-aaaaaaaaaaaaaaaa", job);
57+
58+
const snapshot = buildSingleJobSnapshot(currentWorkspace, "task-abc-running");
59+
assert.equal(snapshot.crossWorkspace, true);
60+
assert.equal(snapshot.crossWorkspaceStateDir, stateDir);
61+
assert.equal(snapshot.workspaceRoot, "/some/other/repo");
62+
assert.equal(snapshot.job.id, "task-abc-running");
63+
assert.equal(snapshot.job.status, "running");
64+
});
65+
66+
it("buildSingleJobSnapshot still throws when job id is unknown anywhere", () => {
67+
assert.throws(
68+
() => buildSingleJobSnapshot(currentWorkspace, "task-nope"),
69+
/No job found for "task-nope"/
70+
);
71+
});
72+
73+
it("resolveResultJob falls back to cross-workspace finished job", () => {
74+
const job = {
75+
id: "task-done-1",
76+
status: "completed",
77+
workspaceRoot: "/some/other/repo",
78+
createdAt: new Date().toISOString(),
79+
updatedAt: new Date().toISOString()
80+
};
81+
writeRemoteWorkspaceJob("remote-bbbbbbbbbbbbbbbb", job);
82+
83+
const result = resolveResultJob(currentWorkspace, "task-done-1");
84+
assert.equal(result.crossWorkspace, true);
85+
assert.equal(result.workspaceRoot, "/some/other/repo");
86+
assert.equal(result.job.id, "task-done-1");
87+
});
88+
89+
it("resolveResultJob rejects cross-workspace job that is still running", () => {
90+
const job = {
91+
id: "task-still-running",
92+
status: "running",
93+
workspaceRoot: "/some/other/repo"
94+
};
95+
writeRemoteWorkspaceJob("remote-cccccccccccccccc", job);
96+
97+
assert.throws(
98+
() => resolveResultJob(currentWorkspace, "task-still-running"),
99+
/is still running in another workspace/
100+
);
101+
});
102+
103+
it("resolveCancelableJob falls back to cross-workspace running job by id", () => {
104+
const job = {
105+
id: "task-cancelable",
106+
status: "running",
107+
workspaceRoot: "/some/other/repo",
108+
pid: 0
109+
};
110+
writeRemoteWorkspaceJob("remote-dddddddddddddddd", job);
111+
112+
const result = resolveCancelableJob(currentWorkspace, "task-cancelable", { env: {} });
113+
assert.equal(result.crossWorkspace, true);
114+
assert.equal(result.workspaceRoot, "/some/other/repo");
115+
assert.equal(result.job.id, "task-cancelable");
116+
});
117+
118+
it("resolveCancelableJob rejects a non-active cross-workspace match with a clear message", () => {
119+
const job = {
120+
id: "task-not-active",
121+
status: "completed",
122+
workspaceRoot: "/some/other/repo"
123+
};
124+
writeRemoteWorkspaceJob("remote-eeeeeeeeeeeeeeee", job);
125+
126+
assert.throws(
127+
() => resolveCancelableJob(currentWorkspace, "task-not-active", { env: {} }),
128+
/Nothing to cancel/
129+
);
130+
});
131+
132+
it("resolveCancelableJob without reference still requires a local active job", () => {
133+
assert.throws(
134+
() => resolveCancelableJob(currentWorkspace, "", { env: {} }),
135+
/No active Codex jobs to cancel/
136+
);
137+
});
138+
});

0 commit comments

Comments
 (0)