Skip to content

Commit 9d2c300

Browse files
committed
fix: forward goal work set before the first prompt
Goal control subscribed to nothing on a session that had not run a prompt yet, so the goal update and the turn app-server starts for it were dropped. Subscribe the session to its notifications before handling goal control; the next prompt replaces that handler.
1 parent 4461c5b commit 9d2c300

2 files changed

Lines changed: 104 additions & 0 deletions

File tree

‎src/CodexAcpServer.ts‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,8 @@ export interface SessionState {
201201
clientCapabilities: ClientCapabilities;
202202
currentGoal?: ThreadGoalSnapshot | null;
203203
goalRevision: number;
204+
/** Settles once app-server notifications for this thread reach an ACP event handler. */
205+
eventSubscription?: Promise<void>;
204206
sessionTitle: string | null;
205207
sessionTitleSource: "unset" | "fallback" | "explicit" | "unknown";
206208
sessionFailure?: SessionFailure;
@@ -531,6 +533,7 @@ export class CodexAcpServer {
531533
if (!sessionState) {
532534
throw RequestError.invalidParams(undefined, `Unknown session: ${methodRequest.params.sessionId}`);
533535
}
536+
await this.ensureSessionEventSubscription(sessionState);
534537
const sessionGeneration = this.getSessionGeneration(sessionState.sessionId);
535538
const goalControlGeneration = this.bumpGoalControlGeneration(sessionState.sessionId);
536539
if (methodRequest.params.action === "set") {
@@ -1886,6 +1889,61 @@ export class CodexAcpServer {
18861889
return {outcome: "startedNewTurn"};
18871890
}
18881891

1892+
/**
1893+
* Subscribes a session that has not run a prompt yet to its app-server notifications.
1894+
*
1895+
* A prompt subscribes the thread and its handler keeps forwarding session-scoped
1896+
* notifications after the prompt ends. Before the first prompt nothing is subscribed, so
1897+
* goal control would drop the goal update and the goal turn app-server starts for it.
1898+
* The next prompt replaces this handler.
1899+
*/
1900+
private ensureSessionEventSubscription(sessionState: SessionState): Promise<void> {
1901+
sessionState.eventSubscription ??= this.subscribeSessionEvents(sessionState).catch((error: unknown) => {
1902+
delete sessionState.eventSubscription;
1903+
throw error;
1904+
});
1905+
return sessionState.eventSubscription;
1906+
}
1907+
1908+
private async subscribeSessionEvents(sessionState: SessionState): Promise<void> {
1909+
const eventHandler = new CodexEventHandler(
1910+
this.connection,
1911+
sessionState,
1912+
clientSupportsTypedSessionFailures(this.clientCapabilities),
1913+
this.sessionFailureEpoch,
1914+
sessionState.subagents,
1915+
(accountUpdated) => this.handleAccountUpdated(accountUpdated),
1916+
false,
1917+
clientSupportsCompaction(this.clientCapabilities),
1918+
clientSupportsNotices(this.clientCapabilities),
1919+
);
1920+
const permissionContext = this.permissionLifecycleContext(sessionState).beginPrompt();
1921+
const toolCallRenderer = new AcpToolCallRenderer(this.capabilities);
1922+
const signal = new AbortController().signal;
1923+
const approvalHandler = new CodexApprovalHandler(this.connection, permissionContext, signal, toolCallRenderer);
1924+
const elicitationHandler = new CodexElicitationHandler(
1925+
this.connection,
1926+
permissionContext,
1927+
this.clientCapabilities,
1928+
signal,
1929+
toolCallRenderer,
1930+
);
1931+
const observeInteraction = async (event: ServerNotification): Promise<void> => {
1932+
permissionContext.handleNotification(event);
1933+
await elicitationHandler.handleNotification(event);
1934+
};
1935+
await this.codexAcpClient.subscribeToSessionEvents(sessionState.sessionId,
1936+
async (event) => {
1937+
await observeInteraction(event);
1938+
await eventHandler.handleSessionScopedNotification(event);
1939+
},
1940+
approvalHandler,
1941+
elicitationHandler,
1942+
clientSupportsSubagents(this.clientCapabilities),
1943+
observeInteraction,
1944+
childThreadId => eventHandler.waitForNativeSubagentSession(childThreadId));
1945+
}
1946+
18891947
private async startGoalContinuationIfCurrent(
18901948
sessionState: SessionState,
18911949
sessionGeneration: number,
@@ -3059,6 +3117,7 @@ export class CodexAcpServer {
30593117
clientSupportsSubagents(this.clientCapabilities),
30603118
observeInteraction,
30613119
childThreadId => promptEventHandler.waitForNativeSubagentSession(childThreadId));
3120+
sessionState.eventSubscription = Promise.resolve();
30623121

30633122
if (activePrompt.signal.aborted) {
30643123
return cancelledPromptResponse();

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

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3272,6 +3272,51 @@ describe('ACP server test', { timeout: 40_000 }, () => {
32723272
expect(turnStartSpy).not.toHaveBeenCalled();
32733273
});
32743274

3275+
it('forwards goal work set before the first prompt', async () => {
3276+
const {mockFixture, sessionState} = setupPromptFixture();
3277+
// @ts-expect-error - registering local session state for the extension request path
3278+
mockFixture.getCodexAcpAgent().sessions.set("session-id", sessionState);
3279+
const goal = createThreadGoal({objective: "Finish the migration", status: "active"});
3280+
vi.spyOn(mockFixture.getCodexAcpClient(), "setGoal")
3281+
.mockImplementation(async (_sessionId, _objective, _onTurnStarted, onGoalSet) => {
3282+
mockFixture.sendServerNotification({
3283+
method: "thread/goal/updated",
3284+
params: {threadId: "session-id", turnId: null, goal},
3285+
});
3286+
onGoalSet?.(goal);
3287+
mockFixture.sendServerNotification({
3288+
method: "item/agentMessage/delta",
3289+
params: {threadId: "session-id", turnId: "routed-goal-turn", itemId: "message", delta: "Working on it"},
3290+
});
3291+
return {
3292+
threadId: "session-id",
3293+
turn: createTurn("routed-goal-turn", "completed"),
3294+
};
3295+
});
3296+
mockFixture.clearAcpConnectionDump();
3297+
3298+
await expect(mockFixture.getCodexAcpAgent().extMethod(GOAL_CONTROL_METHOD, {
3299+
sessionId: "session-id",
3300+
action: "set",
3301+
objective: goal.objective,
3302+
})).resolves.toEqual({});
3303+
await mockFixture.getCodexAcpClient().waitForSessionNotifications("session-id");
3304+
3305+
const updates = mockFixture.getAcpConnectionEvents([])
3306+
.filter(event => event.method === "sessionUpdate" && "args" in event)
3307+
.map(event => event.args[0]?.update);
3308+
expect(updates).toEqual(expect.arrayContaining([
3309+
expect.objectContaining({
3310+
sessionUpdate: "session_info_update",
3311+
_meta: {jetbrains: {air: {version: 1, goal: expect.objectContaining({objective: goal.objective})}}},
3312+
}),
3313+
expect.objectContaining({
3314+
sessionUpdate: "agent_message_chunk",
3315+
content: expect.objectContaining({text: "Working on it"}),
3316+
}),
3317+
]));
3318+
});
3319+
32753320
it('ignores an older goal refresh that completes after a newer refresh', async () => {
32763321
const mockFixture = createCodexMockTestFixture();
32773322
const codexAcpAgent = mockFixture.getCodexAcpAgent();

0 commit comments

Comments
 (0)