Skip to content

Commit 850c9fa

Browse files
committed
fix(agents): resume Codex thread before compaction
Signed-off-by: Ho Lim <[email protected]>
1 parent 704042a commit 850c9fa

2 files changed

Lines changed: 190 additions & 8 deletions

File tree

‎extensions/codex/src/app-server/compact.test.ts‎

Lines changed: 120 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -381,7 +381,7 @@ describe("maybeCompactCodexAppServerSession", () => {
381381
});
382382
});
383383

384-
it("starts native app-server compaction for post-context-engine budget requests", async () => {
384+
it("resumes the bound thread before post-context-engine budget compaction", async () => {
385385
const fake = createFakeCodexClient();
386386
setCodexAppServerClientFactoryForTest(async () => fake.client);
387387
const sessionFile = await writeTestBinding({
@@ -417,6 +417,11 @@ describe("maybeCompactCodexAppServerSession", () => {
417417
{ threadId: "thread-1" },
418418
{ timeoutMs: 60_000 },
419419
);
420+
expect(fake.request.mock.calls.map(([method]) => method)).toEqual([
421+
"thread/resume",
422+
"thread/compact/start",
423+
"thread/unsubscribe",
424+
]);
420425
expect(result.ok).toBe(true);
421426
expect(result.compacted).toBe(true);
422427
expect(result.reason).toBeUndefined();
@@ -501,6 +506,61 @@ describe("maybeCompactCodexAppServerSession", () => {
501506
});
502507
});
503508

509+
it("preserves projection when the post-run thread cannot be resumed", async () => {
510+
const fake = createFakeCodexClient();
511+
fake.request.mockRejectedValueOnce(
512+
new CodexAppServerRpcError(
513+
{ code: -32_600, message: "thread not found: thread-1" },
514+
"thread/resume",
515+
),
516+
);
517+
setCodexAppServerClientFactoryForTest(async () => fake.client);
518+
const sessionFile = await writeTestBinding({
519+
contextEngine: {
520+
schemaVersion: 1,
521+
engineId: "lossless-claw",
522+
policyFingerprint: "policy-1",
523+
projection: {
524+
schemaVersion: 1,
525+
mode: "thread_bootstrap",
526+
epoch: "epoch-1",
527+
fingerprint: "fingerprint-1",
528+
},
529+
},
530+
});
531+
532+
const result = requireCompactResult(
533+
await maybeCompactCodexAppServerSession(
534+
{
535+
sessionId: "session-1",
536+
sessionKey: "agent:main:session-1",
537+
sessionFile,
538+
workspaceDir: tempDir,
539+
trigger: "budget",
540+
currentTokenCount: 456,
541+
},
542+
{ allowNonManualNativeRequest: true },
543+
),
544+
);
545+
546+
expect(fake.request.mock.calls.map(([method]) => method)).toEqual(["thread/resume"]);
547+
expect(result).toMatchObject({
548+
ok: false,
549+
compacted: false,
550+
reason: "thread not found: thread-1",
551+
failure: { reason: "stale_thread_binding" },
552+
});
553+
expect(await readCodexAppServerBinding(sessionFile)).toMatchObject({
554+
threadId: "thread-1",
555+
contextEngine: {
556+
projection: {
557+
epoch: "epoch-1",
558+
fingerprint: "fingerprint-1",
559+
},
560+
},
561+
});
562+
});
563+
504564
it("skips post-context-engine native compaction when the binding changes before projection clear", async () => {
505565
const fake = createFakeCodexClient();
506566
setCodexAppServerClientFactoryForTest(async () => fake.client);
@@ -588,7 +648,13 @@ describe("maybeCompactCodexAppServerSession", () => {
588648
let externalWriteStarted = false;
589649
let externalWriteFinished = false;
590650
const fake = createFakeCodexClient();
591-
fake.request.mockImplementation(async () => {
651+
fake.request.mockImplementation(async (method, params) => {
652+
if (method === "thread/resume") {
653+
return codexThreadResumeResult((params as { threadId: string }).threadId);
654+
}
655+
if (method === "thread/unsubscribe") {
656+
return {};
657+
}
592658
const response = await expectExternalMutationBlockedDuringNativeRequest({
593659
releaseExternalMutation: releaseExternalWrite,
594660
isExternalMutationStarted: () => externalWriteStarted,
@@ -672,7 +738,13 @@ describe("maybeCompactCodexAppServerSession", () => {
672738
let externalClearStarted = false;
673739
let externalClearFinished = false;
674740
const fake = createFakeCodexClient();
675-
fake.request.mockImplementation(async () => {
741+
fake.request.mockImplementation(async (method, params) => {
742+
if (method === "thread/resume") {
743+
return codexThreadResumeResult((params as { threadId: string }).threadId);
744+
}
745+
if (method === "thread/unsubscribe") {
746+
return {};
747+
}
676748
const response = await expectExternalMutationBlockedDuringNativeRequest({
677749
releaseExternalMutation: releaseExternalClear,
678750
isExternalMutationStarted: () => externalClearStarted,
@@ -1479,8 +1551,9 @@ describe("maybeCompactCodexAppServerSession", () => {
14791551
});
14801552

14811553
it("detaches a guarded remote start after releasing the binding lock", async () => {
1482-
const fake = createFakeCodexClient();
1483-
fake.request.mockRejectedValueOnce(new Error("thread/compact/start timed out"));
1554+
const fake = createFakeCodexClient({
1555+
compactStartError: new Error("thread/compact/start timed out"),
1556+
});
14841557
fake.closeAndWait.mockResolvedValueOnce(false);
14851558
const sessionFile = await writeTestBinding();
14861559

@@ -1896,9 +1969,45 @@ describe("maybeCompactCodexAppServerSession", () => {
18961969
});
18971970
});
18981971

1972+
function codexThreadResumeResult(threadId: string) {
1973+
return {
1974+
thread: {
1975+
id: threadId,
1976+
sessionId: "session-1",
1977+
forkedFromId: null,
1978+
preview: "",
1979+
ephemeral: false,
1980+
modelProvider: "openai",
1981+
createdAt: 1,
1982+
updatedAt: 1,
1983+
status: { type: "idle" },
1984+
path: null,
1985+
cwd: tempDir,
1986+
cliVersion: "0.139.0",
1987+
source: "unknown",
1988+
agentNickname: null,
1989+
agentRole: null,
1990+
gitInfo: null,
1991+
name: null,
1992+
turns: [],
1993+
},
1994+
model: "gpt-5.5-codex",
1995+
modelProvider: "openai",
1996+
serviceTier: null,
1997+
cwd: tempDir,
1998+
instructionSources: [],
1999+
approvalPolicy: "never",
2000+
approvalsReviewer: "user",
2001+
sandbox: { type: "dangerFullAccess" },
2002+
permissionProfile: null,
2003+
reasoningEffort: null,
2004+
};
2005+
}
2006+
18992007
function createFakeCodexClient(
19002008
options: {
19012009
autoCompleteCompaction?: boolean;
2010+
compactStartError?: Error;
19022011
interruptError?: Error;
19032012
rejectInterrupt?: boolean;
19042013
} = {},
@@ -1951,12 +2060,18 @@ function createFakeCodexClient(
19512060
};
19522061
const request = vi.fn<CodexAppServerClient["request"]>(
19532062
async (method: string, params?: unknown) => {
2063+
if (method === "thread/resume") {
2064+
return codexThreadResumeResult((params as { threadId: string }).threadId);
2065+
}
19542066
if (method === "turn/interrupt" && options.interruptError) {
19552067
throw options.interruptError;
19562068
}
19572069
if (method === "turn/interrupt" && options.rejectInterrupt) {
19582070
throw new Error("interrupt unavailable");
19592071
}
2072+
if (method === "thread/compact/start" && options.compactStartError) {
2073+
throw options.compactStartError;
2074+
}
19602075
if (method === "thread/compact/start" && options.autoCompleteCompaction !== false) {
19612076
const threadId = (params as { threadId?: unknown }).threadId;
19622077
if (typeof threadId !== "string") {

‎extensions/codex/src/app-server/compact.ts‎

Lines changed: 70 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,11 @@ import {
88
type EmbeddedAgentCompactResult,
99
} from "openclaw/plugin-sdk/agent-harness-runtime";
1010
import { resolveAgentDir, resolveDefaultAgentId } from "openclaw/plugin-sdk/agent-runtime";
11+
import {
12+
closeCodexStartupClientBestEffort,
13+
CODEX_APP_SERVER_UNSUBSCRIBE_TIMEOUT_MS,
14+
unsubscribeCodexThreadBestEffort,
15+
} from "./attempt-client-cleanup.js";
1116
import { readCodexNotificationItem } from "./attempt-notifications.js";
1217
import { resolveCodexBindingAppServerConnection } from "./binding-connection.js";
1318
import { CodexAppServerRpcError, type CodexAppServerClient } from "./client.js";
@@ -29,6 +34,7 @@ import {
2934
releaseLeasedSharedCodexAppServerClient,
3035
type CodexAppServerClientFactory,
3136
} from "./shared-client.js";
37+
import { resumeCodexAppServerThread } from "./thread-resume.js";
3238

3339
const warnedIgnoredCompactionOverrides = new Set<string>();
3440
const codexNativeCompactionQueues = new Map<string, Promise<void>>();
@@ -581,6 +587,7 @@ async function compactCodexNativeThread(
581587
agentDir: params.agentDir,
582588
config: params.config,
583589
});
590+
let subscribedForPostRunCompaction = false;
584591
const completionWatch = watchCodexNativeCompactionCompletion({
585592
client,
586593
threadId: binding.threadId,
@@ -682,6 +689,36 @@ async function compactCodexNativeThread(
682689
};
683690
}
684691
binding = currentBinding;
692+
try {
693+
// One-shot runs retire their app-server before post-run budget
694+
// checks, so restore the persisted thread on this leased client.
695+
await resumeCodexAppServerThread({
696+
client,
697+
abandonClient: () => closeCodexStartupClientBestEffort(client),
698+
request: {
699+
threadId: binding.threadId,
700+
excludeTurns: true,
701+
initialTurnsPage: {
702+
limit: 1,
703+
sortDirection: "desc",
704+
itemsView: "notLoaded",
705+
},
706+
},
707+
timeoutMs: Math.min(
708+
appServer.requestTimeoutMs,
709+
CODEX_APP_SERVER_BINDING_GUARDED_REQUEST_TIMEOUT_MS,
710+
),
711+
...(params.abortSignal ? { signal: params.abortSignal } : {}),
712+
});
713+
subscribedForPostRunCompaction = true;
714+
} catch (error) {
715+
return {
716+
started: true as const,
717+
accepted: false as const,
718+
requestStarted: false as const,
719+
error,
720+
};
721+
}
685722
await clearContextEngineProjectionBeforeNativeCompaction({
686723
sessionId: params.sessionId,
687724
bindingStore: options.bindingStore,
@@ -695,23 +732,34 @@ async function compactCodexNativeThread(
695732
CODEX_APP_SERVER_BINDING_GUARDED_REQUEST_TIMEOUT_MS,
696733
),
697734
);
698-
return { started: true as const, accepted: true as const };
735+
return {
736+
started: true as const,
737+
accepted: true as const,
738+
requestStarted: true as const,
739+
};
699740
} catch (error) {
700741
await options.bindingStore.mutate(bindingIdentity, {
701742
kind: "set",
702743
binding,
703744
});
704745
// Retire outside the binding lock: remote detach acquires this
705746
// same lock and would otherwise deadlock the failure path.
706-
return { started: true as const, accepted: false as const, error };
747+
return {
748+
started: true as const,
749+
accepted: false as const,
750+
requestStarted: true as const,
751+
error,
752+
};
707753
}
708754
},
709755
);
710756
if (!guardedResult.started) {
711757
return guardedResult.result;
712758
}
713759
if (!guardedResult.accepted) {
714-
await settleNativeCompactionRequestError(guardedResult.error);
760+
if (guardedResult.requestStarted) {
761+
await settleNativeCompactionRequestError(guardedResult.error);
762+
}
715763
throw guardedResult.error;
716764
}
717765
} else {
@@ -756,6 +804,25 @@ async function compactCodexNativeThread(
756804
};
757805
} finally {
758806
completionWatch.cancel();
807+
if (subscribedForPostRunCompaction) {
808+
const unsubscribed = await unsubscribeCodexThreadBestEffort(client, {
809+
threadId: binding.threadId,
810+
timeoutMs: CODEX_APP_SERVER_UNSUBSCRIBE_TIMEOUT_MS,
811+
});
812+
if (!unsubscribed) {
813+
try {
814+
await closeCodexStartupClientBestEffort(client);
815+
} catch (error) {
816+
embeddedAgentLog.warn(
817+
"failed to retire codex app-server after compaction unsubscribe failure",
818+
{
819+
threadId: binding.threadId,
820+
reason: formatCompactionError(error),
821+
},
822+
);
823+
}
824+
}
825+
}
759826
if (shouldReleaseDefaultLease) {
760827
releaseLeasedSharedCodexAppServerClient(client);
761828
}

0 commit comments

Comments
 (0)