Skip to content

Commit 614f15e

Browse files
bfowlerclaude
andcommitted
fix(shared): narrow the editor discovery fix to PATH listings
Keep only the change that fixes #4697: list each PATH directory once per scan, relisting it when its mtime changes, and probe only listed names. That alone takes discovery on a 73-entry Windows PATH from 6-11 s to ~250 ms, so concurrent probes, the partial-result budget, and keeping the last complete list are dropped here; they only matter for a probe that hangs outright and can follow separately. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 2552750 commit 614f15e

4 files changed

Lines changed: 75 additions & 288 deletions

File tree

‎apps/server/src/process/externalLauncher.test.ts‎

Lines changed: 8 additions & 104 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,10 @@ import * as NodePath from "node:path";
66
import * as NodeServices from "@effect/platform-node/NodeServices";
77
import { assert, it } from "@effect/vitest";
88
import * as ConfigProvider from "effect/ConfigProvider";
9-
import * as DateTime from "effect/DateTime";
109
import * as Effect from "effect/Effect";
1110
import * as Fiber from "effect/Fiber";
1211
import * as FileSystem from "effect/FileSystem";
1312
import * as Layer from "effect/Layer";
14-
import * as Option from "effect/Option";
1513
import * as Path from "effect/Path";
1614
import * as Sink from "effect/Sink";
1715
import * as Stream from "effect/Stream";
@@ -844,9 +842,10 @@ it.effect.skipIf(windowsHost)(
844842
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
845843
);
846844

847-
// The handler probe carries its own timeout so a wedged xdg-mime costs only
848-
// the file manager and the scan still completes. Runs on the live clock so
849-
// the probe's real timeout fires.
845+
// The handler probe carries its own timeout because the editor scan's outer
846+
// timeout in server.getConfig degrades to an EMPTY editor list: a wedged
847+
// xdg-mime must cost only the file manager, never the other editors. Runs on
848+
// the live clock so the probe's real timeout fires.
850849
it.live.skipIf(windowsHost)("a stalled handler probe drops only the file manager", () =>
851850
Effect.gen(function* () {
852851
const fileSystem = yield* FileSystem.FileSystem;
@@ -1076,24 +1075,17 @@ it.effect.skipIf(windowsHost)("ignores unusable app bundles and keeps PATH launc
10761075
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
10771076
);
10781077

1079-
// Stubbed stats answer for PATH directories too, and discovery checks a
1080-
// directory's mtime before reusing its listing, so the stub carries one.
1081-
const stubFileInfo = {
1082-
type: "File",
1083-
mtime: Option.some(DateTime.toDateUtc(DateTime.makeUnsafe(0))),
1084-
} as FileSystem.File.Info;
1085-
10861078
it.effect("memoizes editor discovery and refreshes after the cache window", () => {
10871079
let statCalls = 0;
1080+
const fileInfo = { type: "File" } as FileSystem.File.Info;
10881081
const launcherLayer = ExternalLauncher.layer.pipe(
10891082
Layer.provide(
10901083
Layer.mergeAll(
10911084
FileSystem.layerNoop({
1092-
readDirectory: () => Effect.succeed(["code.CMD"]),
10931085
stat: () =>
10941086
Effect.sync(() => {
10951087
statCalls += 1;
1096-
return stubFileInfo;
1088+
return fileInfo;
10971089
}),
10981090
}),
10991091
Path.layer,
@@ -1148,13 +1140,13 @@ it.effect("memoizes editor discovery and refreshes after the cache window", () =
11481140
// replayed it to every later connect for the whole TTL, so `server.getConfig`
11491141
// failed and no client could reconnect until the server restarted.
11501142
it.effect("rescans after an interrupted discovery instead of caching the interrupt", () => {
1143+
const fileInfo = { type: "File" } as FileSystem.File.Info;
11511144
let blockFirstScan = true;
11521145
let scans = 0;
11531146
const launcherLayer = ExternalLauncher.layer.pipe(
11541147
Layer.provide(
11551148
Layer.mergeAll(
11561149
FileSystem.layerNoop({
1157-
readDirectory: () => Effect.succeed(["code.CMD"]),
11581150
// The first scan parks inside `stat` so the interrupt lands while
11591151
// discovery is in flight, which is what a client disconnecting
11601152
// mid-connect does to the shared effect.
@@ -1164,7 +1156,7 @@ it.effect("rescans after an interrupted discovery instead of caching the interru
11641156
if (blockFirstScan) {
11651157
return yield* Effect.never;
11661158
}
1167-
return stubFileInfo;
1159+
return fileInfo;
11681160
}),
11691161
}),
11701162
Path.layer,
@@ -1207,94 +1199,6 @@ it.effect("rescans after an interrupted discovery instead of caching the interru
12071199
);
12081200
});
12091201

1210-
// One Windows PATH directory listing `listed`. Every stat reports a file except
1211-
// the ones `stalls` matches, which never resolve, like a probe wedged on a
1212-
// slow disk or share. Each test passes its own PATH so the process-wide
1213-
// command-resolution cache cannot leak results between tests.
1214-
const stubbedWindowsDiscoveryLayer = (input: {
1215-
readonly pathDirectory: string;
1216-
readonly listed: ReadonlyArray<string>;
1217-
readonly stalls: (filePath: string) => boolean;
1218-
readonly onStat?: () => void;
1219-
}) =>
1220-
Layer.mergeAll(
1221-
ExternalLauncher.layer.pipe(
1222-
Layer.provide(
1223-
Layer.mergeAll(
1224-
FileSystem.layerNoop({
1225-
readDirectory: () => Effect.succeed([...input.listed]),
1226-
stat: (filePath) => {
1227-
input.onStat?.();
1228-
return input.stalls(filePath) ? Effect.never : Effect.succeed(stubFileInfo);
1229-
},
1230-
}),
1231-
Path.layer,
1232-
Layer.succeed(
1233-
ChildProcessSpawner.ChildProcessSpawner,
1234-
ChildProcessSpawner.make(() => Effect.sync(() => makeMockDetachedHandle())),
1235-
),
1236-
),
1237-
),
1238-
),
1239-
Layer.succeed(HostProcessPlatform, "win32"),
1240-
ConfigProvider.layer(
1241-
ConfigProvider.fromEnv({ env: { PATH: input.pathDirectory, PATHEXT: ".EXE;.CMD" } }),
1242-
),
1243-
);
1244-
1245-
it.effect("returns the editors found when one probe outlives the scan budget", () =>
1246-
Effect.gen(function* () {
1247-
const launcher = yield* ExternalLauncher.ExternalLauncher;
1248-
const fiber = yield* Effect.forkChild(launcher.resolveAvailableEditors());
1249-
yield* TestClock.adjust("4 seconds");
1250-
1251-
// Trae stalls, but the editors on either side of it, including the file
1252-
// manager probed last, are still reported.
1253-
assert.deepEqual(yield* Fiber.join(fiber), ["cursor", "file-manager"]);
1254-
}).pipe(
1255-
Effect.provide(
1256-
stubbedWindowsDiscoveryLayer({
1257-
pathDirectory: "C:\\t3-editor-scan-budget-test",
1258-
listed: ["cursor.EXE", "trae.EXE", "explorer.EXE"],
1259-
stalls: (filePath) => filePath.includes("trae"),
1260-
}),
1261-
),
1262-
),
1263-
);
1264-
1265-
it.effect("keeps editors from the last complete scan when a rescan runs out of time", () => {
1266-
let stallVscode = false;
1267-
let stats = 0;
1268-
return Effect.gen(function* () {
1269-
const launcher = yield* ExternalLauncher.ExternalLauncher;
1270-
assert.deepEqual(yield* launcher.resolveAvailableEditors(), ["vscode", "file-manager"]);
1271-
1272-
// Past the discovery cache window, the rescan stalls on VS Code.
1273-
yield* TestClock.adjust("61 seconds");
1274-
stallVscode = true;
1275-
const fiber = yield* Effect.forkChild(launcher.resolveAvailableEditors());
1276-
yield* TestClock.adjust("4 seconds");
1277-
assert.deepEqual(yield* Fiber.join(fiber), ["vscode", "file-manager"]);
1278-
1279-
// The incomplete scan was not cached, so the next call scans again.
1280-
stallVscode = false;
1281-
const statsBeforeRescan = stats;
1282-
assert.deepEqual(yield* launcher.resolveAvailableEditors(), ["vscode", "file-manager"]);
1283-
assert.isAbove(stats, statsBeforeRescan);
1284-
}).pipe(
1285-
Effect.provide(
1286-
stubbedWindowsDiscoveryLayer({
1287-
pathDirectory: "C:\\t3-editor-incomplete-rescan-test",
1288-
listed: ["code.CMD", "explorer.EXE"],
1289-
stalls: (filePath) => stallVscode && filePath.includes("code"),
1290-
onStat: () => {
1291-
stats += 1;
1292-
},
1293-
}),
1294-
),
1295-
);
1296-
});
1297-
12981202
it.effect("rejects unknown editors through the service API", () =>
12991203
Effect.gen(function* () {
13001204
const launcher = yield* ExternalLauncher.ExternalLauncher;

‎apps/server/src/process/externalLauncher.ts‎

Lines changed: 27 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -252,9 +252,10 @@ function fileManagerCommandForPlatform(
252252
// so the client would see a silent no-op. Require the handler before
253253
// advertising the file manager on Linux.
254254
//
255-
// The probe carries its own timeout well inside the editor scan budget, so a
256-
// hung `xdg-mime` (broken D-Bus or desktop session) costs only the file
257-
// manager and the scan still completes and gets cached.
255+
// The probe carries its own timeout well inside the scan timeout
256+
// `server.getConfig` applies to editor discovery: that outer timeout degrades
257+
// to an empty editor list, so a hung `xdg-mime` (broken D-Bus or desktop
258+
// session) must cost only the file manager, not every discovered editor.
258259
const LINUX_DIRECTORY_HANDLER_PROBE_TIMEOUT = "2 seconds";
259260

260261
const hasUsableLinuxDirectoryHandler = Effect.fn("externalLauncher.hasUsableLinuxDirectoryHandler")(
@@ -407,53 +408,31 @@ function buildBrowserLaunch(
407408
};
408409
}
409410

410-
// Stop probing before server.getConfig's five-second discovery bound, which
411-
// would otherwise discard everything the scan had found.
412-
const EDITOR_SCAN_BUDGET = "4 seconds";
413-
414-
interface EditorScan {
415-
readonly editors: ReadonlyArray<EditorId>;
416-
readonly complete: boolean;
417-
}
418-
419-
const isEditorAvailable = Effect.fn("externalLauncher.isEditorAvailable")(function* (
420-
editor: (typeof EDITORS)[number],
421-
platform: NodeJS.Platform,
422-
env: NodeJS.ProcessEnv,
423-
) {
424-
if (editor.commands === null) {
425-
return (yield* resolveUsableFileManagerCommand(platform, env)) !== undefined;
426-
}
427-
return Option.isSome(yield* resolveEditorCommand(editor, env));
428-
});
429-
430-
// Editors are probed concurrently, so one stalled lookup cannot hide the rest,
431-
// and share PATH directory listings, so a long Windows PATH costs one listing
432-
// per directory rather than a stat per PATH x PATHEXT candidate per editor.
433411
const buildAvailableEditors = Effect.fn("externalLauncher.buildAvailableEditors")(function* (
434412
platform: NodeJS.Platform,
435413
env: NodeJS.ProcessEnv,
436414
): Effect.fn.Return<
437-
EditorScan,
415+
ReadonlyArray<EditorId>,
438416
never,
439417
FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
440418
> {
441-
const found = new Set<EditorId>();
442-
const finished = yield* Effect.forEach(
443-
EDITORS,
444-
(editor) =>
445-
isEditorAvailable(editor, platform, env).pipe(
446-
Effect.map((available) => {
447-
if (available) found.add(editor.id);
448-
}),
449-
),
450-
{ concurrency: "unbounded", discard: true },
451-
).pipe(withPathDirectoryListings, Effect.timeoutOption(EDITOR_SCAN_BUDGET));
419+
const available: EditorId[] = [];
452420

453-
return {
454-
editors: EDITORS.flatMap((editor) => (found.has(editor.id) ? [editor.id] : [])),
455-
complete: Option.isSome(finished),
456-
};
421+
for (const editor of EDITORS) {
422+
if (editor.commands === null) {
423+
if ((yield* resolveUsableFileManagerCommand(platform, env)) !== undefined) {
424+
available.push(editor.id);
425+
}
426+
continue;
427+
}
428+
429+
const command = yield* resolveEditorCommand(editor, env);
430+
if (Option.isSome(command)) {
431+
available.push(editor.id);
432+
}
433+
}
434+
435+
return available;
457436
});
458437

459438
const resolveBrowserLaunch = Effect.fn("externalLauncher.resolveBrowserLaunch")(function* (
@@ -467,7 +446,7 @@ const resolveBrowserLaunch = Effect.fn("externalLauncher.resolveBrowserLaunch")(
467446
const resolveAvailableEditors = Effect.fn("externalLauncher.resolveAvailableEditors")(function* () {
468447
const platform = yield* HostProcessPlatform;
469448
const env = { ...(yield* readBrowserLaunchEnv), ...(yield* readCommandLookupEnv) };
470-
return yield* buildAvailableEditors(platform, env);
449+
return yield* buildAvailableEditors(platform, env).pipe(withPathDirectoryListings);
471450
});
472451

473452
const resolveFileManagerRevealKind = Effect.fn("externalLauncher.resolveFileManagerRevealKind")(
@@ -488,10 +467,8 @@ const resolveFileManagerRevealKind = Effect.fn("externalLauncher.resolveFileMana
488467
// on the connection fiber under a timeout (`resolveAvailableEditorsForConfig`),
489468
// so one client disconnecting mid-scan would cache the interrupt and replay it
490469
// to every later connect for the whole TTL, breaking `server.getConfig`
491-
// permanently. Storing only complete scans means an interrupted or
492-
// out-of-budget scan leaves the cache untouched and the next connect simply
493-
// rescans. An incomplete scan still never hides an editor the last complete
494-
// scan found: running out of time is not evidence that it was uninstalled.
470+
// permanently. Storing only on success means an interrupted scan leaves the
471+
// cache untouched and the next connect simply rescans.
495472
// Expiry uses the monotonic clock (Clock.currentTimeNanos), matching the
496473
// command-resolution cache in @t3tools/shared/shell, so a backward wall-clock
497474
// adjustment cannot keep an expired entry alive.
@@ -792,24 +769,17 @@ export const make = Effect.gen(function* () {
792769
if (Option.isSome(entry) && entry.value.expiresAtNanos > nowNanos) {
793770
return entry.value.editors;
794771
}
795-
const scan = yield* provideCommandResolutionServices(resolveAvailableEditors()).pipe(
772+
const editors = yield* provideCommandResolutionServices(resolveAvailableEditors()).pipe(
796773
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
797774
);
798-
if (!scan.complete) {
799-
const kept = new Set([
800-
...scan.editors,
801-
...Option.match(entry, { onNone: () => [], onSome: ({ editors }) => editors }),
802-
]);
803-
return EDITORS.flatMap((editor) => (kept.has(editor.id) ? [editor.id] : []));
804-
}
805775
yield* Ref.set(
806776
editorDiscoveryCache,
807777
Option.some({
808-
editors: scan.editors,
778+
editors,
809779
expiresAtNanos: nowNanos + EDITOR_DISCOVERY_CACHE_TTL_NANOS,
810780
}),
811781
);
812-
return scan.editors;
782+
return editors;
813783
});
814784

815785
return ExternalLauncher.of({

0 commit comments

Comments
 (0)