Skip to content

Commit 927c480

Browse files
authored
fix: resynchronize current session metadata on ACP v2 resume (#717)
## Summary - Add one v2 session-info metadata owner at the common send boundary. Shared v1-shaped and direct v2 publications use the same shallow patch state. Omission leaves values unchanged, top-level nulls remove keys, and nested objects replace whole values. - On every successful resume, after replay/live-event draining and before the response, clear retained client metadata with `_meta: null`, then restore the agent's currently known metadata when nonempty. Serialize both frames with live session-info updates so an older restoration cannot overwrite a newer patch. - Keep metadata for the active session lifetime, including full replay. Resume reinstalls `SessionState`, so the metadata lifetime must not follow that object's identity. Seed known native thread status before releasing new live events. Close/reopen starts a fresh metadata lifetime. - Carry the current failure reference across active reinstallation. Clear published failure metadata when that incident resolves, preserving sibling metadata and checking the ID/revision so a late resolution cannot remove a newer incident. - Preserve notification `params._meta` through the shared v2 conversion path, but do not store or replay it as entity metadata. Keep v1 wire behavior unchanged. Checked against ACP `a965f1f1`: `docs/protocol/v2/extensibility.mdx:103-150` defines metadata replacement/removal and explicit resynchronization clears. `docs/protocol/v2/session-setup.mdx:355-358` recommends current session info after replay and before the response, including omitted/null `replayFrom`. ## Scope This synchronizes currently known `session_info_update` metadata. It does not invent a deep merge for extension namespaces, copy raw session-list snapshot metadata into entity patches, or reconstruct every metadata field from persistent storage. Writers sharing a top-level namespace still need to compose complete values; that cleanup is separate, with the new serialized domain-patch API available for it. Newer upstream auth/proxy/background schema additions are not adopted here. No review/checklist Markdown file is included. ## Validation - `npm run typecheck` - `npm run build` - `npm test`: 2,358 passed, 39 skipped - `npm run test:integration`: all 19 passed - `npm run codex-test -- -p "Reply with exactly OK. Do not use tools or modify any files." -o summary`: completed with `end_turn` - `git diff --check` - Opt-in E2E tests were not run. Coverage includes shallow replacement and removals, nested null values, clearing keys the agent has never seen, JSON copies, notification-only metadata, serialization under backpressure, queued patches, disposal during restoration, write-failure recovery, failure revision matching, active resumes with/without replay, close/reopen, current failure continuity, and post-close publication fencing. The real-Codex foreground-state integration covers all replay settings with the extended info synchronization sequence.
1 parent 580d8b9 commit 927c480

11 files changed

Lines changed: 396 additions & 17 deletions

‎src/ACPSessionConnection.ts‎

Lines changed: 53 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {toV2ReplayUpdates} from "./AcpV2Replay";
1010
import {toV1RequestPermissionResponse, toV2RequestPermissionRequest} from "./AcpV2Permissions";
1111
import {elicitationSessionId, toV1CreateElicitationResponse, toV2CreateElicitationRequest} from "./AcpV2Elicitation";
1212
import {AcpV2ForegroundState} from "./AcpV2ForegroundState";
13+
import {AcpV2SessionInfo, type SessionMetadataPatch} from "./AcpV2SessionInfo";
1314
import {type AcpClientDelivery, clientNotificationSessionId, clientRequestSessionId} from "./AcpClientDelivery";
1415

1516
export type AcpClientConnection = Pick<acp.AgentContext, "notify" | "request">;
@@ -23,6 +24,7 @@ export class AcpV2Connection {
2324
readonly client: AcpV2ClientConnection;
2425
private isTurnRunning: (sessionId: string) => boolean = () => true;
2526
private readonly foreground = new Map<string, AcpV2ForegroundState>();
27+
private readonly sessionInfo = new Map<string, AcpV2SessionInfo>();
2628
private sessionDelivery: AcpClientDelivery | null = null;
2729
private sendElicitationCompletion: (params: unknown) => Promise<void>;
2830

@@ -34,6 +36,10 @@ export class AcpV2Connection {
3436
if (method === acpV2.methods.client.elicitation.complete) return this.sendElicitationCompletion(params);
3537
const sessionId = clientNotificationSessionId(method, params);
3638
if (sessionId !== null && this.sessionDelivery && !this.sessionDelivery.canPublishSession(sessionId)) return Promise.resolve();
39+
if (sessionId !== null) {
40+
const {update, _meta} = params as acpV2.UpdateSessionNotification;
41+
if (acpV2.SessionUpdate.isSessionInfoUpdate(update)) return this.sessionInfoFor(sessionId).update(update, _meta);
42+
}
3743
return client.notify(method as `_${string}`, params);
3844
},
3945
request: (method: string, params?: unknown, options?: acpV2.SendRequestOptions) => {
@@ -80,9 +86,10 @@ export class AcpV2Connection {
8086
* Sends a session update, rendered in the v2 wire shape, through the v2 `session/update`
8187
* binding. One update can render to several v2 updates (or none), sent in order.
8288
*/
83-
async updateSession(sessionId: string, update: AcpSessionUpdate): Promise<void> {
89+
async updateSession(sessionId: string, update: AcpSessionUpdate, metadata?: acpV2.UpdateSessionNotification["_meta"]): Promise<void> {
8490
for (const v2Update of toV2SessionUpdates(update)) {
85-
await this.client.notify(acpV2.methods.client.session.update, {sessionId, update: v2Update});
91+
await this.client.notify(acpV2.methods.client.session.update,
92+
{sessionId, update: v2Update, ...(metadata !== undefined ? {_meta: metadata} : {})});
8693
}
8794
}
8895

@@ -99,6 +106,24 @@ export class AcpV2Connection {
99106
return this.foregroundFor(sessionId).snapshot();
100107
}
101108

109+
resetSessionInfo(sessionId: string, metadata: Record<string, unknown> | null): void {
110+
this.sessionInfo.get(sessionId)?.dispose();
111+
this.sessionInfo.delete(sessionId);
112+
this.sessionInfoFor(sessionId, metadata);
113+
}
114+
115+
refreshSessionInfo(sessionId: string, metadata: Record<string, unknown> | null): Promise<void> {
116+
return metadata ? this.sessionInfoFor(sessionId).seedMetadata(metadata) : Promise.resolve();
117+
}
118+
119+
snapshotSessionInfo(sessionId: string, title: string | null): Promise<void> {
120+
return this.sessionInfoFor(sessionId).snapshot(title);
121+
}
122+
123+
patchSessionMetadata(sessionId: string, change: SessionMetadataPatch): Promise<void> {
124+
return this.sessionInfoFor(sessionId).patchMetadata(change);
125+
}
126+
102127
startForegroundItem(sessionId: string, itemId: string): Promise<void> {
103128
return this.foregroundFor(sessionId).startItem(itemId);
104129
}
@@ -114,6 +139,26 @@ export class AcpV2Connection {
114139
forgetSession(sessionId: string): void {
115140
this.foreground.get(sessionId)?.dispose();
116141
this.foreground.delete(sessionId);
142+
this.sessionInfo.get(sessionId)?.dispose();
143+
this.sessionInfo.delete(sessionId);
144+
}
145+
146+
private sessionInfoFor(sessionId: string, metadata: Record<string, unknown> | null = null): AcpV2SessionInfo {
147+
if (this.sessionDelivery && !this.sessionDelivery.canPublishSession(sessionId)) {
148+
const closed = new AcpV2SessionInfo(async () => {});
149+
closed.dispose();
150+
return closed;
151+
}
152+
let info = this.sessionInfo.get(sessionId);
153+
if (!info) {
154+
info = new AcpV2SessionInfo((update, notificationMetadata) => {
155+
if (this.sessionDelivery && !this.sessionDelivery.canPublishSession(sessionId)) return Promise.resolve();
156+
return this.transportClient.notify(acpV2.methods.client.session.update,
157+
{sessionId, update, ...(notificationMetadata !== undefined ? {_meta: notificationMetadata} : {})});
158+
}, metadata);
159+
this.sessionInfo.set(sessionId, info);
160+
}
161+
return info;
117162
}
118163

119164
private foregroundFor(sessionId: string, running = false): AcpV2ForegroundState {
@@ -216,7 +261,7 @@ export class AcpV2Connection {
216261
}
217262
if (method === acp.methods.client.session.update) {
218263
const notification = params as AcpSessionNotification;
219-
return this.updateSession(notification.sessionId, notification.update);
264+
return this.updateSession(notification.sessionId, notification.update, notification._meta);
220265
}
221266
if (method === acp.methods.client.elicitation.complete) {
222267
return this.completeElicitation(params as acp.CompleteElicitationNotification);
@@ -297,6 +342,11 @@ export class ACPSessionConnection {
297342

298343
forSession(sessionId: string): ACPSessionConnection { return new ACPSessionConnection(this.connection, sessionId); }
299344

345+
/** Domain writers can rebuild an owned metadata value without changing v2's shallow patch semantics. */
346+
patchSessionMetadata(change: SessionMetadataPatch): Promise<void> {
347+
return this.v2Connection?.patchSessionMetadata(this.sessionId, change) ?? Promise.resolve();
348+
}
349+
300350
/** Replay shares live report filtering, with v2 entity initialization after conversion. */
301351
replayUpdate(update: UpdateSessionEvent, initialized: Set<string>): Promise<void> {
302352
return this.v2Connection

‎src/AcpV2SessionInfo.ts‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import type * as acp from "@agentclientprotocol/sdk/experimental/v2/unstable";
2+
import {isRecord} from "./permissions/json";
3+
4+
type Update = acp.SessionInfoUpdate & {sessionUpdate: "session_info_update"};
5+
type NotificationMetadata = acp.UpdateSessionNotification["_meta"];
6+
export type SessionMetadataPatch = (current: Readonly<Record<string, unknown>>) => Record<string, unknown> | null;
7+
8+
/** Owns current session metadata and orders live patches against resume resynchronization. */
9+
export class AcpV2SessionInfo {
10+
private readonly metadata = new Map<string, unknown>();
11+
private tail = Promise.resolve();
12+
private disposed = false;
13+
14+
constructor(
15+
private readonly send: (update: Update, notificationMetadata?: NotificationMetadata) => Promise<void>,
16+
initialMetadata: Record<string, unknown> | null = null,
17+
) {
18+
this.applyMetadata(JSON.parse(JSON.stringify({_meta: initialMetadata}))._meta);
19+
}
20+
21+
update(update: Update, notificationMetadata?: NotificationMetadata): Promise<void> {
22+
let copy: {update: Update; _meta?: NotificationMetadata};
23+
try { copy = JSON.parse(JSON.stringify({update, _meta: notificationMetadata})); }
24+
catch (error) { return Promise.reject(error); }
25+
return this.enqueue(async () => {
26+
this.applyMetadata(copy.update._meta);
27+
await this.publish(copy.update, copy._meta);
28+
});
29+
}
30+
31+
patchMetadata(change: SessionMetadataPatch): Promise<void> {
32+
return this.enqueue(async () => {
33+
const current = JSON.parse(JSON.stringify(Object.fromEntries(this.metadata))) as Record<string, unknown>;
34+
const patch = change(current);
35+
if (patch === null) return;
36+
const update: Update = JSON.parse(JSON.stringify({sessionUpdate: "session_info_update", _meta: patch}));
37+
this.applyMetadata(update._meta);
38+
await this.publish(update);
39+
});
40+
}
41+
42+
seedMetadata(metadata: Record<string, unknown>): Promise<void> {
43+
const copy: unknown = JSON.parse(JSON.stringify({_meta: metadata}))._meta;
44+
return this.enqueue(async () => { this.applyMetadata(copy); });
45+
}
46+
47+
snapshot(title: string | null): Promise<void> {
48+
return this.enqueue(async () => {
49+
// The client may hold keys this connection has never seen.
50+
await this.publish({sessionUpdate: "session_info_update", title, _meta: null});
51+
if (this.metadata.size > 0) {
52+
await this.publish({sessionUpdate: "session_info_update", _meta: Object.fromEntries(this.metadata)});
53+
}
54+
});
55+
}
56+
57+
dispose(): void {
58+
this.disposed = true;
59+
this.metadata.clear();
60+
}
61+
62+
private applyMetadata(patch: unknown): void {
63+
if (patch === null) this.metadata.clear();
64+
else if (isRecord(patch)) for (const [key, value] of Object.entries(patch)) {
65+
if (value === null) this.metadata.delete(key);
66+
else this.metadata.set(key, value);
67+
}
68+
}
69+
70+
private enqueue(operation: () => Promise<void>): Promise<void> {
71+
const next = this.tail.then(async () => {
72+
if (!this.disposed) await operation();
73+
});
74+
this.tail = next.catch(() => {});
75+
return next;
76+
}
77+
78+
private publish(update: Update, notificationMetadata?: NotificationMetadata): Promise<void> {
79+
return this.disposed ? Promise.resolve() : this.send(update, notificationMetadata);
80+
}
81+
}

‎src/CodexAcpServer.ts‎

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1407,7 +1407,7 @@ export class CodexAcpServer {
14071407
this.sessionIndex.titleWriter(sessionId),
14081408
);
14091409
sessionState.promptSuggestions = this.createPromptSuggestions(sessionState);
1410-
this.installSessionState(sessionState);
1410+
this.installSessionState(sessionState, sessionMetadata.threadStatus);
14111411
AcpV2Connection.of(this.connection)?.restoreForegroundState(sessionId, sessionMetadata.threadStatus?.type === "active");
14121412
this.recovery?.markLoaded(sessionState, openGeneration);
14131413
if (settleTrackerReady) {
@@ -1593,13 +1593,24 @@ export class CodexAcpServer {
15931593
);
15941594
}
15951595

1596-
private installSessionState(sessionState: SessionState): void {
1596+
private installSessionState(sessionState: SessionState, threadStatus?: SessionMetadata["threadStatus"]): void {
15971597
const previous = this.sessions.get(sessionState.sessionId);
15981598
previous?.asyncTasks.clear();
15991599
// The new state holds no suggestion, so the old one must drop its result in flight and clear what it published.
16001600
void previous?.promptSuggestions?.clear();
16011601
this.sessions.set(sessionState.sessionId, sessionState);
16021602
this.clientDelivery.openSession(sessionState.sessionId);
1603+
const v2 = AcpV2Connection.of(this.connection);
1604+
if (v2) {
1605+
const metadata = threadStatus ? {codex: {threadStatus}} : null;
1606+
// Seeding is queued before new live events; metadata belongs to the active session lifetime.
1607+
if (previous) {
1608+
if (previous.sessionFailure) sessionState.sessionFailure = previous.sessionFailure;
1609+
void v2.refreshSessionInfo(sessionState.sessionId, metadata);
1610+
} else {
1611+
v2.resetSessionInfo(sessionState.sessionId, metadata);
1612+
}
1613+
}
16031614
}
16041615

16051616
/**
@@ -1962,10 +1973,7 @@ export class CodexAcpServer {
19621973
// Drain live events released by setup/replay before taking the ordered snapshot.
19631974
await this.codexAcpClient.waitForSessionNotifications(sessionId);
19641975
const state = this.getSessionState(sessionId);
1965-
await new ACPSessionConnection(this.connection, sessionId).update({
1966-
sessionUpdate: "session_info_update",
1967-
title: state.sessionTitle,
1968-
});
1976+
await AcpV2Connection.of(this.connection)!.snapshotSessionInfo(sessionId, state.sessionTitle);
19691977
await AcpV2Connection.of(this.connection)!.snapshotForegroundState(sessionId);
19701978
}
19711979

@@ -3567,7 +3575,7 @@ export class CodexAcpServer {
35673575
this.sessionIndex.titleWriter(sessionId),
35683576
);
35693577
sessionState.promptSuggestions = this.createPromptSuggestions(sessionState);
3570-
this.installSessionState(sessionState);
3578+
this.installSessionState(sessionState, thread.status);
35713579
AcpV2Connection.of(this.connection)?.restoreForegroundState(sessionId, thread.status.type === "active");
35723580
this.recovery?.markLoaded(sessionState, openGeneration);
35733581
if (knownAccount === "pending") {

‎src/CodexEventHandler.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ import {
5656
} from "./ContentChunks";
5757
import {goalSessionInfoUpdate, sameThreadGoalSnapshot, toThreadGoalSnapshot} from "./ThreadGoalSnapshot";
5858
import {logger} from "./Logger";
59+
import {recordOrNull} from "./permissions/json";
5960
import {
6061
AIR_EXTENSION_VERSION,
6162
AIR_EXTENSION_VERSION_KEY,
@@ -372,7 +373,17 @@ export class CodexEventHandler {
372373
}
373374

374375
async clearSessionFailure(): Promise<void> {
376+
const failure = this.sessionState.sessionFailure;
375377
delete this.sessionState.sessionFailure;
378+
if (!failure || this.session.protocolVersion !== 2) return;
379+
await this.session.patchSessionMetadata(metadata => {
380+
const jetbrains = recordOrNull(metadata[JETBRAINS_META_KEY]);
381+
const air = recordOrNull(jetbrains?.[AIR_META_KEY]);
382+
const published = recordOrNull(air?.[AIR_SESSION_FAILURE_KEY]);
383+
if (!air || published?.["id"] !== failure.id || published?.["revision"] !== failure.revision) return null;
384+
const {[AIR_SESSION_FAILURE_KEY]: _failure, ...currentAir} = air;
385+
return {[JETBRAINS_META_KEY]: {...jetbrains, [AIR_META_KEY]: currentAir}};
386+
});
376387
}
377388

378389
async completeSuccessfulTurn(turnId: string | null): Promise<void> {
@@ -381,7 +392,7 @@ export class CodexEventHandler {
381392
const active = this.sessionState.sessionFailure;
382393
if (active?.id !== this.activeFailureIdByScope.get(turnId) || active?.severity !== "warning") return;
383394
this.activeFailureIdByScope.delete(turnId);
384-
delete this.sessionState.sessionFailure;
395+
await this.clearSessionFailure();
385396
}
386397

387398
async handleFailedTurn(turn: Turn): Promise<void> {
@@ -1199,7 +1210,7 @@ export class CodexEventHandler {
11991210
if (activeId === undefined || this.failuresById.get(activeId)?.severity !== "warning") return;
12001211
this.activeFailureIdByScope.delete(turnId);
12011212
if (this.sessionState.sessionFailure?.id === activeId) {
1202-
delete this.sessionState.sessionFailure;
1213+
void this.clearSessionFailure().catch(error => logger.error("Failed to clear session failure metadata", error));
12031214
}
12041215
}
12051216

0 commit comments

Comments
 (0)