Skip to content

Commit a52405d

Browse files
committed
fix: adapt goal work before the first prompt to app-server recovery
Re-applies 9d2c300 on the v2.2.2 candidate. Goal control subscribes a session that has not run a prompt yet to its app-server notifications, so the goal update and the goal turn that the app-server starts are not dropped. v2.2.2 restarts a crashed app-server and replaces the client for a provider restart, then resumes sessions in the new app-server. 9d2c300 remembered the subscription per session only, so after a restart goal control kept trusting a subscription on the dead client and dropped the new app-server's goal work. Bind the subscription to the client it was made on and subscribe again on the installed client after ensureSessionReady. Like a prompt, the permission requests and elicitations of that subscription use a loss-aware connection, so they are cancelled when its app-server dies instead of waiting forever. This adaptation is stacked on the exact v2.2.2 candidate commit at the point where the sync replays goal-before-first-prompt.
1 parent b178bf3 commit a52405d

2 files changed

Lines changed: 194 additions & 0 deletions

File tree

‎src/CodexAcpServer.ts‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,11 @@ export interface SessionState extends SessionIndexTitleState {
221221
clientCapabilities: ClientCapabilities;
222222
currentGoal?: ThreadGoalSnapshot | null;
223223
goalRevision: number;
224+
/**
225+
* The app-server client whose notifications for this thread reach an ACP event handler, and when that
226+
* subscription settles. A restarted app-server has a new client without the subscription.
227+
*/
228+
eventSubscription?: {client: CodexAcpClient, ready: Promise<void>};
224229
sessionTitle: string | null;
225230
sessionTitleSource: "unset" | "fallback" | "explicit" | "unknown";
226231
sessionFailure?: SessionFailure;
@@ -601,6 +606,7 @@ export class CodexAcpServer {
601606
}
602607
const sessionReady = this.ensureSessionReady(sessionState);
603608
if (sessionReady) await sessionReady;
609+
await this.ensureSessionEventSubscription(sessionState);
604610
const sessionGeneration = this.getSessionGeneration(sessionState.sessionId);
605611
const goalControlGeneration = this.bumpGoalControlGeneration(sessionState.sessionId);
606612
if (methodRequest.params.action === "set") {
@@ -2154,6 +2160,84 @@ export class CodexAcpServer {
21542160
return {outcome: "startedNewTurn"};
21552161
}
21562162

2163+
/**
2164+
* Subscribes a session that has not run a prompt yet to its app-server notifications.
2165+
*
2166+
* A prompt subscribes the thread and its handler keeps forwarding session-scoped
2167+
* notifications after the prompt ends. Before the first prompt nothing is subscribed, so
2168+
* goal control would drop the goal update and the goal turn app-server starts for it.
2169+
* The next prompt replaces this handler.
2170+
*
2171+
* The subscription belongs to the client of one app-server. After a crash restart or a
2172+
* provider restart, the session is resumed in a new app-server whose client has no
2173+
* subscription, so it is made again on the installed client. Like a prompt, its
2174+
* permission requests and elicitations end when that app-server is gone.
2175+
*/
2176+
private ensureSessionEventSubscription(sessionState: SessionState): Promise<void> {
2177+
const client = this.codexAcpClient;
2178+
if (sessionState.eventSubscription?.client !== client) {
2179+
const generation = this.recovery?.generation ?? 0;
2180+
const ready = this.subscribeSessionEvents(sessionState, client, generation);
2181+
const subscription = {client, ready};
2182+
sessionState.eventSubscription = subscription;
2183+
// A failed subscription is made again by the next goal control request.
2184+
ready.catch(() => {
2185+
if (sessionState.eventSubscription === subscription) {
2186+
delete sessionState.eventSubscription;
2187+
}
2188+
});
2189+
}
2190+
return sessionState.eventSubscription.ready;
2191+
}
2192+
2193+
private async subscribeSessionEvents(
2194+
sessionState: SessionState,
2195+
client: CodexAcpClient,
2196+
generation: number,
2197+
): Promise<void> {
2198+
const eventHandler = new CodexEventHandler(
2199+
this.connection,
2200+
sessionState,
2201+
clientSupportsTypedSessionFailures(this.clientCapabilities),
2202+
this.sessionFailureEpoch,
2203+
sessionState.subagents,
2204+
(accountUpdated) => this.handleAccountUpdated(accountUpdated),
2205+
false,
2206+
clientSupportsCompaction(this.clientCapabilities),
2207+
clientSupportsNotices(this.clientCapabilities),
2208+
);
2209+
const permissionContext = this.permissionLifecycleContext(sessionState).beginPrompt();
2210+
const toolCallRenderer = new AcpToolCallRenderer(this.capabilities);
2211+
const appServerLost = new AbortController();
2212+
const interactionConnection = this.recovery === null
2213+
? this.connection
2214+
: lossAwareConnection(this.connection, appServerLost.signal);
2215+
this.recovery?.onGenerationLost(generation, () => appServerLost.abort());
2216+
const signal = appServerLost.signal;
2217+
const approvalHandler = new CodexApprovalHandler(interactionConnection, permissionContext, signal, toolCallRenderer);
2218+
const elicitationHandler = new CodexElicitationHandler(
2219+
interactionConnection,
2220+
permissionContext,
2221+
this.clientCapabilities,
2222+
signal,
2223+
toolCallRenderer,
2224+
);
2225+
const observeInteraction = async (event: ServerNotification): Promise<void> => {
2226+
permissionContext.handleNotification(event);
2227+
await elicitationHandler.handleNotification(event);
2228+
};
2229+
await client.subscribeToSessionEvents(sessionState.sessionId,
2230+
async (event) => {
2231+
await observeInteraction(event);
2232+
await eventHandler.handleSessionScopedNotification(event);
2233+
},
2234+
approvalHandler,
2235+
elicitationHandler,
2236+
clientSupportsSubagents(this.clientCapabilities),
2237+
observeInteraction,
2238+
childThreadId => eventHandler.waitForNativeSubagentSession(childThreadId));
2239+
}
2240+
21572241
private async startGoalContinuationIfCurrent(
21582242
sessionState: SessionState,
21592243
sessionGeneration: number,
@@ -3403,6 +3487,7 @@ export class CodexAcpServer {
34033487
clientSupportsSubagents(this.clientCapabilities),
34043488
observeInteraction,
34053489
childThreadId => promptEventHandler.waitForNativeSubagentSession(childThreadId));
3490+
sessionState.eventSubscription = {client: promptClient, ready: Promise.resolve()};
34063491

34073492
if (activePrompt.signal.aborted) {
34083493
return cancelledPromptResponse();

‎src/__tests__/CodexACPAgent/CodexAcpClient.test.ts‎

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,11 @@ import {ModelId} from "../../ModelId";
2121
import {GOAL_CONTROL_METHOD} from "../../AcpExtensions";
2222
import {ClientCapabilities} from "../../tool-calls/ClientCapabilities";
2323
import type {McpStartupResult} from "../../mcp/McpStartupTracker";
24+
import {
25+
createRecoveryFixture,
26+
initialize as initializeRecoveryFixture,
27+
requestsOf as requestsOfRecoveryServer,
28+
} from "../app-server-recovery/recovery-fixture";
2429

2530
describe('ACP server test', { timeout: 40_000 }, () => {
2631

@@ -3441,6 +3446,110 @@ describe('ACP server test', { timeout: 40_000 }, () => {
34413446
expect(turnStartSpy).not.toHaveBeenCalled();
34423447
});
34433448

3449+
it('forwards goal work set before the first prompt', async () => {
3450+
const {mockFixture, sessionState} = setupPromptFixture();
3451+
// @ts-expect-error - registering local session state for the extension request path
3452+
mockFixture.getCodexAcpAgent().sessions.set("session-id", sessionState);
3453+
const goal = createThreadGoal({objective: "Finish the migration", status: "active"});
3454+
vi.spyOn(mockFixture.getCodexAcpClient(), "setGoal")
3455+
.mockImplementation(async (_sessionId, _objective, _onTurnStarted, onGoalSet) => {
3456+
mockFixture.sendServerNotification({
3457+
method: "thread/goal/updated",
3458+
params: {threadId: "session-id", turnId: null, goal},
3459+
});
3460+
onGoalSet?.(goal);
3461+
mockFixture.sendServerNotification({
3462+
method: "item/agentMessage/delta",
3463+
params: {threadId: "session-id", turnId: "routed-goal-turn", itemId: "message", delta: "Working on it"},
3464+
});
3465+
return {
3466+
threadId: "session-id",
3467+
turn: createTurn("routed-goal-turn", "completed"),
3468+
};
3469+
});
3470+
mockFixture.clearAcpConnectionDump();
3471+
3472+
await expect(mockFixture.getCodexAcpAgent().extMethod(GOAL_CONTROL_METHOD, {
3473+
sessionId: "session-id",
3474+
action: "set",
3475+
objective: goal.objective,
3476+
})).resolves.toEqual({});
3477+
await mockFixture.getCodexAcpClient().waitForSessionNotifications("session-id");
3478+
3479+
const updates = mockFixture.getAcpConnectionEvents([])
3480+
.filter(event => event.method === "sessionUpdate" && "args" in event)
3481+
.map(event => event.args[0]?.update);
3482+
expect(updates).toEqual(expect.arrayContaining([
3483+
expect.objectContaining({
3484+
sessionUpdate: "session_info_update",
3485+
_meta: {jetbrains: {air: {version: 1, goal: expect.objectContaining({objective: goal.objective})}}},
3486+
}),
3487+
expect.objectContaining({
3488+
sessionUpdate: "agent_message_chunk",
3489+
content: expect.objectContaining({text: "Working on it"}),
3490+
}),
3491+
]));
3492+
});
3493+
3494+
it('forwards goal work set before the first prompt again after the app-server restarted', async () => {
3495+
const fixture = createRecoveryFixture();
3496+
await initializeRecoveryFixture(fixture, true);
3497+
const {sessionId} = await fixture.agent.newSession({cwd: "/work", mcpServers: []});
3498+
const goal = {threadId: sessionId, objective: "ship it", status: "paused", tokenBudget: null, tokensUsed: 0, timeUsedSeconds: 0, createdAt: 1, updatedAt: 2};
3499+
fixture.answers.set("thread/goal/set", (_params, server) => {
3500+
setImmediate(() => server.rpc.notify({method: "thread/goal/updated", params: {threadId: sessionId, turnId: null, goal}}));
3501+
return {goal};
3502+
});
3503+
const agentMessages = () => fixture.updates()
3504+
.filter(({sessionId: id, update}) => id === sessionId && update["sessionUpdate"] === "agent_message_chunk")
3505+
.map(({update}) => (update["content"] as {text?: string}).text);
3506+
const goalWork = async (delta: string) => {
3507+
await fixture.agent.extMethod(GOAL_CONTROL_METHOD, {sessionId, action: "pause"});
3508+
fixture.current().rpc.notify({
3509+
method: "item/agentMessage/delta",
3510+
params: {threadId: sessionId, turnId: "goal-turn", itemId: `message-${delta}`, delta},
3511+
});
3512+
await vi.waitFor(() => expect(agentMessages()).toContain(delta));
3513+
};
3514+
3515+
await goalWork("before the restart");
3516+
await fixture.kill();
3517+
await goalWork("after the restart");
3518+
3519+
expect(fixture.servers).toHaveLength(2);
3520+
expect(requestsOfRecoveryServer(fixture.current(), "thread/resume")).toHaveLength(1);
3521+
});
3522+
3523+
it('cancels a permission request of goal work set before the first prompt when its app-server dies', async () => {
3524+
const fixture = createRecoveryFixture();
3525+
await initializeRecoveryFixture(fixture, true);
3526+
const {sessionId} = await fixture.agent.newSession({cwd: "/work", mcpServers: []});
3527+
const goal = {threadId: sessionId, objective: "ship it", status: "paused", tokenBudget: null, tokensUsed: 0, timeUsedSeconds: 0, createdAt: 1, updatedAt: 2};
3528+
fixture.answers.set("thread/goal/set", (_params, server) => {
3529+
setImmediate(() => server.rpc.notify({method: "thread/goal/updated", params: {threadId: sessionId, turnId: null, goal}}));
3530+
return {goal};
3531+
});
3532+
let permissionSignal: AbortSignal | undefined;
3533+
fixture.acp.request.mockImplementation(async (method: string, _params: unknown, options?: {cancellationSignal?: AbortSignal}) => {
3534+
if (method === "session/request_permission") {
3535+
permissionSignal = options?.cancellationSignal;
3536+
return await new Promise(() => {});
3537+
}
3538+
return {};
3539+
});
3540+
await fixture.agent.extMethod(GOAL_CONTROL_METHOD, {sessionId, action: "pause"});
3541+
const approval = fixture.current().rpc.requestHandlers.get("item/commandExecution/requestApproval")!({
3542+
threadId: sessionId, turnId: "goal-turn", itemId: "cmd-1", command: "rm -rf build", cwd: "/work", reason: null,
3543+
availableDecisions: ["accept", "decline", "cancel"],
3544+
});
3545+
await vi.waitFor(() => expect(permissionSignal).toBeDefined());
3546+
3547+
await fixture.kill();
3548+
3549+
expect(permissionSignal!.aborted).toBe(true);
3550+
await expect(approval).resolves.toEqual({decision: "cancel"});
3551+
});
3552+
34443553
it('ignores an older goal refresh that completes after a newer refresh', async () => {
34453554
const mockFixture = createCodexMockTestFixture();
34463555
const codexAcpAgent = mockFixture.getCodexAcpAgent();

0 commit comments

Comments
 (0)