Skip to content

Commit 564e84d

Browse files
cliffhallclaude
andcommitted
fix(filesystem): keep tool calls waiting for the update that overtook the initial roots
When a roots/list_changed overtakes the initial roots/list, the initial refresh's stale answer is discarded, but it used to release the tool calls waiting on the initial load, which then ran against the command-line directories before the newer roots applied. The overtaking refresh now replaces the initialization gate while the initial load is pending, and waiting calls follow it until it settles (Copilot on #5098). Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 423fe6b commit 564e84d

2 files changed

Lines changed: 110 additions & 13 deletions

File tree

‎src/filesystem/__tests__/server-roots.test.ts‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -417,6 +417,83 @@ describe("roots/list_changed", () => {
417417
expect(await allowedDirectoriesOf(client)).toEqual([cliDir]);
418418
});
419419

420+
// #5097: a call waiting for the initial roots must not be released by the
421+
// stale initial answer; it waits for the update that overtook it.
422+
it("holds waiting tool calls until the update that overtook the initial load applies (#5097)", async () => {
423+
let calls = 0;
424+
let releaseInitial!: () => void;
425+
let releaseUpdate!: () => void;
426+
const initialHeld = new Promise<void>(
427+
(resolve) => (releaseInitial = resolve),
428+
);
429+
const updateHeld = new Promise<void>(
430+
(resolve) => (releaseUpdate = resolve),
431+
);
432+
const { client } = await connectTracked([cliDir], {
433+
capabilities: ROOTS,
434+
listRoots: async () => {
435+
calls += 1;
436+
await (calls === 1 ? initialHeld : updateHeld);
437+
return [rootOf(rootDir)];
438+
},
439+
});
440+
await vi.waitFor(() => expect(calls).toBe(1));
441+
await client.sendRootsListChanged();
442+
await vi.waitFor(() => expect(calls).toBe(2));
443+
444+
releaseInitial();
445+
await vi.waitFor(() =>
446+
expect(stderr).toHaveBeenCalledWith(
447+
"Discarded a stale roots/list answer: a newer roots update has started",
448+
),
449+
);
450+
// Asked before the update has answered: it must not run against the
451+
// command-line directory in the meantime.
452+
let settled = false;
453+
const pending = call(client, "list_directory", { path: cliDir }).then(
454+
(result) => {
455+
settled = true;
456+
return result;
457+
},
458+
);
459+
await new Promise((resolve) => setTimeout(resolve, 50));
460+
expect(settled).toBe(false);
461+
462+
releaseUpdate();
463+
expect(textOf(await pending)).toMatch(/^Access denied/);
464+
expect(await allowedDirectoriesOf(client)).toEqual([rootDir]);
465+
});
466+
467+
it("releases waiting tool calls when the update that overtook the initial load fails (#5097)", async () => {
468+
let calls = 0;
469+
let releaseInitial!: () => void;
470+
const initialHeld = new Promise<void>(
471+
(resolve) => (releaseInitial = resolve),
472+
);
473+
const { client } = await connectTracked([cliDir], {
474+
capabilities: ROOTS,
475+
listRoots: async () => {
476+
calls += 1;
477+
if (calls === 1) {
478+
await initialHeld;
479+
return [rootOf(rootDir)];
480+
}
481+
throw new Error("gone");
482+
},
483+
});
484+
await vi.waitFor(() => expect(calls).toBe(1));
485+
await client.sendRootsListChanged();
486+
await vi.waitFor(() =>
487+
expect(stderr).toHaveBeenCalledWith(
488+
"Failed to request roots from client:",
489+
"gone",
490+
),
491+
);
492+
493+
releaseInitial();
494+
expect(await allowedDirectoriesOf(client)).toEqual([cliDir]);
495+
});
496+
420497
it("logs and keeps the current directories when the re-fetch fails", async () => {
421498
let fail = false;
422499
const { client } = await connectTracked([], {

‎src/filesystem/server.ts‎

Lines changed: 33 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -193,14 +193,24 @@ export function createServer(
193193
// command-line directories (#3204). It is replaced in oninitialized, which
194194
// the SDK runs before any request sent after notifications/initialized.
195195
let initialization: Promise<void> = Promise.resolve();
196+
// True from the initial roots/list until a refresh's answer has been
197+
// applied or the newest refresh has failed. A roots/list_changed that
198+
// overtakes the initial load while this holds replaces `initialization`, so
199+
// waiting tool calls keep waiting for the refresh that will actually apply
200+
// rather than running against the command-line directories (#5097).
201+
let initialRootsPending = false;
196202
const registerTool = server.registerTool.bind(server);
197203
server.registerTool = ((
198204
name: string,
199205
config: Parameters<typeof registerTool>[1],
200206
handler: (...args: unknown[]) => unknown,
201207
) =>
202208
registerTool(name, config, (async (...args: unknown[]) => {
203-
await initialization;
209+
let awaited: Promise<void>;
210+
do {
211+
awaited = initialization;
212+
await awaited;
213+
} while (awaited !== initialization);
204214
return handler(...args);
205215
}) as never)) as typeof server.registerTool;
206216

@@ -800,19 +810,26 @@ export function createServer(
800810
"notifications/roots/list_changed",
801811
async () => {
802812
const generation = ++rootsGeneration;
803-
try {
804-
// Request the updated roots list from the client
805-
const response = await server.server.listRoots();
806-
/* v8 ignore else -- the SDK validates the roots/list result against ListRootsResultSchema, which requires roots, so the implicit else cannot run */
807-
if (response && "roots" in response) {
808-
await updateAllowedDirectoriesFromRoots(response.roots, generation);
813+
const refresh = (async () => {
814+
try {
815+
// Request the updated roots list from the client
816+
const response = await server.server.listRoots();
817+
/* v8 ignore else -- the SDK validates the roots/list result against ListRootsResultSchema, which requires roots, so the implicit else cannot run */
818+
if (response && "roots" in response) {
819+
await updateAllowedDirectoriesFromRoots(response.roots, generation);
820+
}
821+
} catch (error) {
822+
console.error(
823+
"Failed to request roots from client:",
824+
error instanceof Error ? error.message : String(error),
825+
);
826+
} finally {
827+
if (generation === rootsGeneration) initialRootsPending = false;
809828
}
810-
} catch (error) {
811-
console.error(
812-
"Failed to request roots from client:",
813-
error instanceof Error ? error.message : String(error),
814-
);
815-
}
829+
})();
830+
// Overtaking the initial load: tool calls wait for this refresh instead.
831+
if (initialRootsPending) initialization = refresh;
832+
await refresh;
816833
},
817834
);
818835

@@ -827,6 +844,7 @@ export function createServer(
827844

828845
if (clientCapabilities?.roots) {
829846
const generation = ++rootsGeneration;
847+
initialRootsPending = true;
830848
try {
831849
const response = await server.server.listRoots();
832850
/* v8 ignore else -- the SDK validates the roots/list result against ListRootsResultSchema, which requires roots, so the else cannot run */
@@ -842,6 +860,8 @@ export function createServer(
842860
"Failed to request initial roots from client:",
843861
error instanceof Error ? error.message : String(error),
844862
);
863+
} finally {
864+
if (generation === rootsGeneration) initialRootsPending = false;
845865
}
846866
} else {
847867
if (allowedDirectories.length > 0) {

0 commit comments

Comments
 (0)