Skip to content

Commit 75c39fd

Browse files
committed
perf(desktop): cache Windows shell environment
1 parent 36f4314 commit 75c39fd

2 files changed

Lines changed: 194 additions & 13 deletions

File tree

‎apps/desktop/src/shell/DesktopShellEnvironment.test.ts‎

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import * as NodeServices from "@effect/platform-node/NodeServices";
22
import { assert, describe, it } from "@effect/vitest";
33
import * as Effect from "effect/Effect";
4+
import * as FileSystem from "effect/FileSystem";
45
import * as Layer from "effect/Layer";
56
import * as Logger from "effect/Logger";
67
import * as PlatformError from "effect/PlatformError";
@@ -69,11 +70,18 @@ function runShellEnvironment(input: {
6970
readonly platform: NodeJS.Platform;
7071
readonly handler: (command: ChildProcess.Command) => string;
7172
readonly failure?: PlatformError.PlatformError;
73+
readonly stateDir?: string;
7274
}) {
7375
const environmentLayer = Layer.succeed(
7476
DesktopEnvironment.DesktopEnvironment,
7577
DesktopEnvironment.DesktopEnvironment.of({
7678
platform: input.platform,
79+
...(input.stateDir === undefined
80+
? {}
81+
: {
82+
stateDir: input.stateDir,
83+
path: { join: (directory: string, fileName: string) => `${directory}\\${fileName}` },
84+
}),
7785
} as DesktopEnvironment.DesktopEnvironment["Service"]),
7886
);
7987
const spawnerLayer = Layer.succeed(
@@ -347,6 +355,103 @@ describe("DesktopShellEnvironment", () => {
347355
}),
348356
);
349357

358+
it.effect("reuses a fresh Windows shell environment cache on the next launch", () =>
359+
Effect.scoped(
360+
Effect.gen(function* () {
361+
const fileSystem = yield* FileSystem.FileSystem;
362+
const stateDir = yield* fileSystem.makeTempDirectoryScoped({
363+
prefix: "t3-windows-shell-environment-test-",
364+
});
365+
const makeEnv = (): NodeJS.ProcessEnv => ({
366+
PATH: "C:\\Windows\\System32",
367+
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
368+
LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
369+
USERPROFILE: "C:\\Users\\testuser",
370+
});
371+
let commandCount = 0;
372+
const handler = (command: ChildProcess.Command) => {
373+
commandCount += 1;
374+
if (command._tag !== "StandardCommand") return "";
375+
return command.args.includes("-NoProfile")
376+
? envOutput({ PATH: "C:\\Custom\\Bin;C:\\Windows\\System32" })
377+
: envOutput({ PATH: "C:\\Profile\\Node;C:\\Windows\\System32" });
378+
};
379+
380+
const firstEnv = makeEnv();
381+
yield* runShellEnvironment({
382+
env: firstEnv,
383+
platform: "win32",
384+
stateDir,
385+
handler,
386+
});
387+
assert.equal(commandCount, 2);
388+
389+
const secondEnv = makeEnv();
390+
yield* runShellEnvironment({
391+
env: secondEnv,
392+
platform: "win32",
393+
stateDir,
394+
handler,
395+
});
396+
assert.equal(commandCount, 2);
397+
assert.equal(secondEnv.PATH, firstEnv.PATH);
398+
}),
399+
).pipe(Effect.provide(NodeServices.layer)),
400+
);
401+
402+
it.effect("retries incomplete Windows shell environment probes on the next launch", () =>
403+
Effect.scoped(
404+
Effect.gen(function* () {
405+
const fileSystem = yield* FileSystem.FileSystem;
406+
const stateDir = yield* fileSystem.makeTempDirectoryScoped({
407+
prefix: "t3-windows-shell-environment-test-",
408+
});
409+
const makeEnv = (): NodeJS.ProcessEnv => ({
410+
PATH: "C:\\Windows\\System32",
411+
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
412+
LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
413+
USERPROFILE: "C:\\Users\\testuser",
414+
});
415+
let commandCount = 0;
416+
let profileProbeSucceeds = false;
417+
const handler = (command: ChildProcess.Command) => {
418+
commandCount += 1;
419+
if (command._tag !== "StandardCommand") return "";
420+
if (command.args.includes("-NoProfile")) {
421+
return envOutput({ PATH: "C:\\Custom\\Bin;C:\\Windows\\System32" });
422+
}
423+
return profileProbeSucceeds
424+
? envOutput({
425+
PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
426+
FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
427+
})
428+
: envOutput({ FNM_DIR: "C:\\Incomplete\\fnm" });
429+
};
430+
431+
yield* runShellEnvironment({
432+
env: makeEnv(),
433+
platform: "win32",
434+
stateDir,
435+
handler,
436+
});
437+
assert.equal(commandCount, 2);
438+
439+
profileProbeSucceeds = true;
440+
const secondEnv = makeEnv();
441+
yield* runShellEnvironment({
442+
env: secondEnv,
443+
platform: "win32",
444+
stateDir,
445+
handler,
446+
});
447+
448+
assert.equal(commandCount, 4);
449+
assert.match(secondEnv.PATH ?? "", /^C:\\Profile\\Node;/u);
450+
assert.equal(secondEnv.FNM_DIR, "C:\\Users\\testuser\\AppData\\Roaming\\fnm");
451+
}),
452+
).pipe(Effect.provide(NodeServices.layer)),
453+
);
454+
350455
it.effect("prefers login-shell desktop session hints over inherited values on linux", () =>
351456
Effect.gen(function* () {
352457
const env: NodeJS.ProcessEnv = {

‎apps/desktop/src/shell/DesktopShellEnvironment.ts‎

Lines changed: 89 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import * as Context from "effect/Context";
2+
import * as Clock from "effect/Clock";
23
import * as Duration from "effect/Duration";
34
import * as Effect from "effect/Effect";
45
import * as FileSystem from "effect/FileSystem";
@@ -16,6 +17,10 @@ interface ShellEnvironmentConfig {
1617
readonly env: NodeJS.ProcessEnv;
1718
readonly platform: NodeJS.Platform;
1819
readonly userShell: Option.Option<string>;
20+
readonly windowsEnvironmentCache?: {
21+
readonly path: string;
22+
readonly directory: string;
23+
};
1924
}
2025

2126
interface WindowsProbeOptions {
@@ -93,6 +98,20 @@ const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
9398
const LOGIN_SHELL_TIMEOUT = Duration.seconds(5);
9499
const LAUNCHCTL_TIMEOUT = Duration.seconds(2);
95100
const PROCESS_TERMINATE_GRACE = Duration.seconds(1);
101+
const WINDOWS_ENVIRONMENT_CACHE_MAX_AGE_MS = Duration.toMillis(Duration.hours(24));
102+
const WINDOWS_ENVIRONMENT_CACHE_FILE_NAME = "windows-shell-environment.json";
103+
104+
const WindowsEnvironmentCache = Schema.Struct({
105+
version: Schema.Literal(1),
106+
capturedAt: Schema.Number,
107+
inheritedPath: Schema.String,
108+
noProfile: Schema.Record(Schema.String, Schema.String),
109+
profile: Schema.Record(Schema.String, Schema.String),
110+
});
111+
type WindowsEnvironmentCache = typeof WindowsEnvironmentCache.Type;
112+
const WindowsEnvironmentCacheJson = Schema.fromJsonString(WindowsEnvironmentCache);
113+
const decodeWindowsEnvironmentCache = Schema.decodeUnknownOption(WindowsEnvironmentCacheJson);
114+
const encodeWindowsEnvironmentCache = Schema.encodeEffect(WindowsEnvironmentCacheJson);
96115

97116
const trimNonEmpty = (value: string | null | undefined): Option.Option<string> =>
98117
Option.fromNullishOr(value).pipe(
@@ -383,19 +402,65 @@ const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEn
383402
const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWindowsEnvironment")(
384403
function* (
385404
config: ShellEnvironmentConfig,
386-
): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
387-
// Concurrent, not sequential: these two probes are independent (only their
388-
// results are combined below) and each spawns its own PowerShell. Run in
389-
// series they sit at offset 0 of desktop.startup, before anything else, and
390-
// launch traces measured them at 2718ms then 2066ms — the entire 4.8s
391-
// startup span, of which desktop.bootstrap is ~30ms.
392-
const [noProfile, profile] = yield* Effect.all(
393-
[
394-
readWindowsEnvironment(["PATH"], { loadProfile: false }),
395-
readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, { loadProfile: true }),
396-
],
397-
{ concurrency: 2 },
398-
);
405+
): Effect.fn.Return<
406+
void,
407+
never,
408+
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
409+
> {
410+
const fileSystem = yield* FileSystem.FileSystem;
411+
const inheritedPath = Option.getOrElse(readEnvPath(config.env), () => "");
412+
const cache = config.windowsEnvironmentCache ?? null;
413+
const cachePath = cache?.path ?? null;
414+
const now = yield* Clock.currentTimeMillis;
415+
// Loading a PowerShell profile dominates warm Windows launches. Reuse its
416+
// small environment snapshot while the inherited PATH is unchanged, but
417+
// bound its lifetime so profile-only changes are eventually discovered.
418+
// A missing, corrupt, or stale cache simply falls through to the probes.
419+
const cached: Option.Option<WindowsEnvironmentCache> =
420+
cachePath === null
421+
? Option.none<WindowsEnvironmentCache>()
422+
: yield* fileSystem.readFileString(cachePath).pipe(
423+
Effect.map(decodeWindowsEnvironmentCache),
424+
Effect.orElseSucceed(() => Option.none()),
425+
Effect.map((entry) =>
426+
Option.filter(
427+
entry,
428+
(value) =>
429+
value.inheritedPath === inheritedPath &&
430+
now >= value.capturedAt &&
431+
now - value.capturedAt <= WINDOWS_ENVIRONMENT_CACHE_MAX_AGE_MS,
432+
),
433+
),
434+
);
435+
436+
const [noProfile, profile] = Option.isSome(cached)
437+
? [cached.value.noProfile, cached.value.profile]
438+
: yield* Effect.all(
439+
[
440+
readWindowsEnvironment(["PATH"], { loadProfile: false }),
441+
readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, { loadProfile: true }),
442+
],
443+
{ concurrency: 2 },
444+
);
445+
446+
const probesCompleted =
447+
Option.isSome(trimNonEmpty(noProfile.PATH)) && Option.isSome(trimNonEmpty(profile.PATH));
448+
449+
if (Option.isNone(cached) && cache !== null && probesCompleted) {
450+
const encoded = yield* encodeWindowsEnvironmentCache({
451+
version: 1,
452+
capturedAt: now,
453+
inheritedPath,
454+
noProfile,
455+
profile,
456+
}).pipe(Effect.option);
457+
if (Option.isSome(encoded)) {
458+
yield* fileSystem.makeDirectory(cache.directory, { recursive: true }).pipe(
459+
Effect.andThen(fileSystem.writeFileString(cache.path, `${encoded.value}\n`)),
460+
Effect.catchCause(() => Effect.void),
461+
);
462+
}
463+
}
399464
const mergedPath = mergePaths("win32", [
400465
trimNonEmpty(profile.PATH),
401466
trimNonEmpty(knownWindowsCliDirs(config.env).join(";")),
@@ -539,6 +604,17 @@ export const make = Effect.gen(function* () {
539604
env: process.env,
540605
platform: environment.platform,
541606
userShell: Option.none(),
607+
...(typeof environment.stateDir === "string" && environment.stateDir.length > 0
608+
? {
609+
windowsEnvironmentCache: {
610+
path: environment.path.join(
611+
environment.stateDir,
612+
WINDOWS_ENVIRONMENT_CACHE_FILE_NAME,
613+
),
614+
directory: environment.stateDir,
615+
},
616+
}
617+
: {}),
542618
}).pipe(
543619
Effect.provideService(FileSystem.FileSystem, fileSystem),
544620
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),

0 commit comments

Comments
 (0)