Skip to content

Commit 59974c7

Browse files
fix: hold a fork back from the session list until its session/fork response is out (#642)
## Problem `session/fork` calls `thread/fork` and then sets the session up. Meanwhile `SessionListSubscriptions` gets `thread/started` of the fork and sends `_session/list/changes` with it before the fork response. The client meets an unknown session and lists it as a session of its own. JetBrains Air then refuses the fork (IJAI-4105). ## Fix - `SessionIndexService.forking(...)` wraps `forkSession` (v1, and v2 through it). A `setTimeout(0)` releases the rows after the SDK has written the response. - `SessionListSubscriptions` keeps the rows of a fork in `held` while its fork is in flight: - by `forkedFrom`; - by the fork thread id once `thread/fork` answers (`forkCreated`). A row of a `thread/list` scan has `forkedFromId: null`, so the id is needed. - `SessionForkOrigins.remember` records the parent of a fork that this adapter made, so its rows carry `forkedFrom` without a rollout read. ## Tests `holds the row of a fork back until the response of its session/fork is out` (SessionListSubscriptions.test.ts). It fails without the fix. It uses `path.resolve("/repo")` so that it also passes on Windows.
1 parent 629cea5 commit 59974c7

9 files changed

Lines changed: 137 additions & 5 deletions

‎src/CodexAcpClient.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -711,6 +711,7 @@ export class CodexAcpClient {
711711
async forkSession(
712712
request: WithAcpMcpServers<acp.ForkSessionRequest>,
713713
releaseFailedFork: (threadId: string) => Promise<void> = threadId => this.closeSession(threadId),
714+
forkCreated: (threadId: string) => void = () => {},
714715
): Promise<SessionMetadata> {
715716
const additionalDirectories = readAdditionalDirectories(request.cwd, request.additionalDirectories, request._meta);
716717
return await runForkSession(request, additionalDirectories, {
@@ -724,6 +725,7 @@ export class CodexAcpClient {
724725
this.createModelId(models, model, reasoningEffort).toString(),
725726
getCollaborationMode: sessionId => this.getCollaborationMode(sessionId),
726727
releaseFailedFork,
728+
forkCreated,
727729
});
728730
}
729731

‎src/CodexAcpServer.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1099,7 +1099,11 @@ export class CodexAcpServer {
10991099
sessionMetadata = await this.runWithProcessCheck(() => {
11001100
openGeneration = this.recovery?.generation ?? 0;
11011101
mcpServerStartupVersion = readMcpServerStartupVersion();
1102-
return this.codexAcpClient.forkSession(forkRequest, threadId => this.releaseFailedFork(threadId));
1102+
return this.codexAcpClient.forkSession(
1103+
forkRequest,
1104+
threadId => this.releaseFailedFork(threadId),
1105+
threadId => this.sessionIndex.forkCreated(forkRequest.sessionId, threadId),
1106+
);
11031107
});
11041108
} else {
11051109
logger.log(`Create new session...`);
@@ -1682,6 +1686,10 @@ export class CodexAcpServer {
16821686
}
16831687

16841688
async forkSession(params: WithAcpMcpServers<acp.ForkSessionRequest>): Promise<acp.ForkSessionResponse> {
1689+
return this.sessionIndex.forking(params.sessionId, () => this.createFork(params));
1690+
}
1691+
1692+
private async createFork(params: WithAcpMcpServers<acp.ForkSessionRequest>): Promise<acp.ForkSessionResponse> {
16851693
if (this.providerUpdate !== null) {
16861694
await this.waitForProviderUpdate();
16871695
}

‎src/SessionFork.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ export type SessionForkDependencies = {
2323
getCollaborationMode(sessionId: string): ModeKind;
2424
/** Gives back the subscription of a fork that failed after `thread/fork`, unless another open of it began. */
2525
releaseFailedFork(threadId: string): Promise<void>;
26+
/** `thread/fork` answered with the thread of the fork. */
27+
forkCreated(threadId: string): void;
2628
};
2729

2830
export async function forkSession(
@@ -45,6 +47,7 @@ export async function forkSession(
4547
modelProvider: await dependencies.getResumeModelProvider(),
4648
threadId: request.sessionId,
4749
});
50+
dependencies.forkCreated(response.thread.id);
4851
// `thread/fork` subscribes this connection to the new thread, and only to it: the source thread keeps the
4952
// subscription it had. The fork stays subscribed, as ACP lets the client prompt it at once. Codex keeps an
5053
// unsubscribed thread loaded and runs its turns, but sends their notifications to subscribers only.

‎src/SessionForkOrigins.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,12 @@ export class SessionForkOrigins {
5454
return null;
5555
}
5656

57+
/** This adapter forked `parentId` into `threadId`: the fork parent is known without a read of the rollout. */
58+
remember(threadId: string, parentId: string): void {
59+
this.pending.delete(threadId);
60+
remember(this.origins, threadId, parentId);
61+
}
62+
5763
/** Drops the pending reads. */
5864
dispose(): void {
5965
this.disposed = true;

‎src/SessionIndex.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -577,6 +577,12 @@ export function sessionIndexRowSignature(row: acp.SessionInfo): string {
577577
]);
578578
}
579579

580+
/** The AIR field `forkedFrom` of a row: the thread that its thread was forked from, else `null`. */
581+
export function sessionIndexRowForkedFrom(row: acp.SessionInfo): string | null {
582+
const forkedFrom = asRecord(asRecord(asRecord(row._meta)[JETBRAINS_META_KEY])[AIR_META_KEY])[AIR_FORKED_FROM_KEY];
583+
return typeof forkedFrom === "string" ? forkedFrom : null;
584+
}
585+
580586
function asRecord(value: unknown): Record<string, unknown> {
581587
return value !== null && typeof value === "object" && !Array.isArray(value)
582588
? value as Record<string, unknown>

‎src/SessionIndexService.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,30 @@ export class SessionIndexService {
185185
return {};
186186
}
187187

188+
/**
189+
* Runs `fork`, a `session/fork` request of a thread. The list subscriptions hold back the rows of its forks until
190+
* its response is out, see {@link SessionListSubscriptions.forkStarted}.
191+
*/
192+
async forking<T>(sourceId: string, fork: () => Promise<T>): Promise<T> {
193+
this.subscriptions.forkStarted(sourceId);
194+
try {
195+
return await fork();
196+
} finally {
197+
// The response goes out when the handler returns, before any timer.
198+
setTimeout(() => this.subscriptions.forkAnswered(sourceId), 0);
199+
}
200+
}
201+
202+
/**
203+
* `thread/fork` of a source answered with the thread of the fork. Every row of the fork carries `forkedFrom` from
204+
* now on, also a row of `thread/list`, which answers no `forkedFromId`. The list subscriptions hold the fork back
205+
* by its id until the fork response is out.
206+
*/
207+
forkCreated(sourceId: string, forkId: string): void {
208+
this.forkOrigins.remember(forkId, sourceId);
209+
this.subscriptions.forkCreated(sourceId, forkId);
210+
}
211+
188212
/** The subscriptions of the connection, for tests. */
189213
subscriptionResources(): ReturnType<SessionListSubscriptions["resources"]> {
190214
return this.subscriptions.resources();

‎src/SessionListSubscriptions.ts‎

Lines changed: 54 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ import type {ServerNotification} from "./app-server";
2626
import type {Thread, ThreadListParams, ThreadListResponse, ThreadReadParams, ThreadReadResponse} from "./app-server/v2";
2727
import {CodexHomeWatcher, type CodexHomeWatcherListener} from "./CodexHomeWatcher";
2828
import {logger} from "./Logger";
29-
import {sessionIndexRowSignature} from "./SessionIndex";
29+
import {sessionIndexRowForkedFrom, sessionIndexRowSignature} from "./SessionIndex";
3030
import {isArchivedRolloutPath, isMissingThreadError} from "./SessionIndexMutations";
3131
import {SessionNameLog} from "./SessionNameLog";
3232

@@ -182,6 +182,11 @@ export class SessionListSubscriptions {
182182
private readonly lastChangeAt = new Map<string, number>();
183183
/** Threads of the own app-server that the list never shows: ephemeral, subagent and other helper threads. */
184184
private readonly ignoredThreads = new Set<string>();
185+
/**
186+
* The threads with a `session/fork` in flight: the number of their forks in flight, and the threads that
187+
* `thread/fork` created for them. See {@link forkStarted}.
188+
*/
189+
private readonly forking = new Map<string, {count: number, forks: Set<string>}>();
185190
private disposed = false;
186191

187192
constructor(private readonly deps: SessionListSubscriptionDeps) {
@@ -345,6 +350,51 @@ export class SessionListSubscriptions {
345350
}
346351
}
347352

353+
/**
354+
* A `session/fork` of a thread started. The rows of its forks wait in {@link Subscription.held} until
355+
* {@link forkAnswered}: the client gets the id of a fork from the fork response before a list change shows the
356+
* fork. Otherwise the client sees an unknown session and lists it as a session of its own.
357+
*/
358+
forkStarted(sourceId: string): void {
359+
const source = this.forking.get(sourceId);
360+
if (source !== undefined) source.count++;
361+
else this.forking.set(sourceId, {count: 1, forks: new Set()});
362+
}
363+
364+
/**
365+
* `thread/fork` of a thread answered with the thread of the fork. Its rows wait by its id too: a row of a scan
366+
* can come before the fork parent is known.
367+
*/
368+
forkCreated(sourceId: string, forkId: string): void {
369+
this.forking.get(sourceId)?.forks.add(forkId);
370+
}
371+
372+
/** The response of a `session/fork` of a thread is out: the next flush sends the held rows of its forks. */
373+
forkAnswered(sourceId: string): void {
374+
const source = this.forking.get(sourceId);
375+
if (source === undefined) return;
376+
if (--source.count > 0) return;
377+
this.forking.delete(sourceId);
378+
if ([...this.subscriptions.values()].some(subscription => subscription.held !== null)) this.requestThreads(0);
379+
}
380+
381+
/** Splits held changes into the ones to send now and the rows of forks whose fork response is not out yet. */
382+
private withoutForksInFlight(changes: SessionListChanges): {now: SessionListChanges | null, later: SessionListChanges | null} {
383+
if (this.forking.size === 0) return {now: changes, later: null};
384+
const inFlight = (row: acp.SessionInfo) => {
385+
const forkedFrom = sessionIndexRowForkedFrom(row);
386+
return (forkedFrom !== null && this.forking.has(forkedFrom))
387+
|| [...this.forking.values()].some(source => source.forks.has(row.sessionId));
388+
};
389+
const later = changes.sessions.filter(inFlight);
390+
if (later.length === 0) return {now: changes, later: null};
391+
const sessions = changes.sessions.filter(row => !inFlight(row));
392+
return {
393+
now: sessions.length === 0 && changes.removed.length === 0 ? null : {...changes, sessions},
394+
later: {subscriptionId: changes.subscriptionId, sessions: later, removed: []},
395+
};
396+
}
397+
348398
private threadChanged(threadId: string): void {
349399
// Named by a change of its own: no longer only a thread that a scan found.
350400
this.scanRetries.delete(threadId);
@@ -607,8 +657,9 @@ export class SessionListSubscriptions {
607657
const sent: SessionListChanges[] = [];
608658
for (const subscription of this.subscriptions.values()) {
609659
if (this.disposed || !subscription.ready || subscription.held === null) continue;
610-
const changes = subscription.held;
611-
subscription.held = null;
660+
const {now: changes, later} = this.withoutForksInFlight(subscription.held);
661+
subscription.held = later;
662+
if (changes === null) continue;
612663
await this.send(changes);
613664
sent.push(changes);
614665
}

‎src/__tests__/CodexACPAgent/session-fork.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ describe("ACP session fork", () => {
4242
sessionId: "source-id",
4343
cwd: "/workspace",
4444
mcpServers: [],
45-
}, expect.any(Function));
45+
}, expect.any(Function), expect.any(Function));
4646
// Regression pin: v1 must keep sending `modes` (v2 drops it via `forkSessionV2`).
4747
expect(response.modes).toBeDefined();
4848
});

‎src/__tests__/SessionListSubscriptions.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,38 @@ describe("SessionListSubscriptions", () => {
196196
subscriptions.dispose();
197197
});
198198

199+
it("holds the row of a fork back until the response of its session/fork is out", async () => {
200+
const {codex, subscriptions, sent} = setup();
201+
// The resolved form, so that the subscription covers the threads on every OS.
202+
const cwd = path.resolve("/repo");
203+
codex.put(thread("source", {cwd}));
204+
const subscriptionId = await subscriptions.subscribe(cwd);
205+
await vi.advanceTimersByTimeAsync(0);
206+
207+
subscriptions.forkStarted("source");
208+
codex.put(thread("fork", {cwd, forkedFromId: "source"}));
209+
// A fork whose row does not name its parent, as a row of `thread/list`: it waits by its id.
210+
codex.put(thread("unmarked", {cwd}));
211+
subscriptions.forkCreated("source", "unmarked");
212+
codex.put(thread("other", {cwd}));
213+
for (const id of ["fork", "unmarked", "other"]) {
214+
subscriptions.observe(own("thread/started", {thread: codex.threads.get(id)!.thread}));
215+
}
216+
await vi.advanceTimersByTimeAsync(2_000);
217+
// A thread that is no fork of the source goes out meanwhile.
218+
expect(sent).toEqual([{subscriptionId, sessions: [expect.objectContaining({sessionId: "other"})], removed: []}]);
219+
220+
subscriptions.forkAnswered("source");
221+
await vi.advanceTimersByTimeAsync(0);
222+
expect(sent).toHaveLength(2);
223+
expect(sent[1]).toEqual({subscriptionId, sessions: expect.arrayContaining([
224+
expect.objectContaining({sessionId: "fork"}),
225+
expect.objectContaining({sessionId: "unmarked"}),
226+
]), removed: []});
227+
expect((sent[1]!.sessions.find(row => row.sessionId === "fork")!._meta as any).jetbrains.air.forkedFrom).toBe("source");
228+
subscriptions.dispose();
229+
});
230+
199231
it("sends a thread that another process changed after a WAL write, read by one thread/list without cwd", async () => {
200232
const {codex, subscriptions, sent, listener} = setup();
201233
codex.put(thread("a", {updatedAt: 1_000}));

0 commit comments

Comments
 (0)