Skip to content

Commit b75f117

Browse files
fix(server): Rescan finds tools installed after T3 Code started (pingdotgg#23610)
1 parent 9c19aa9 commit b75f117

4 files changed

Lines changed: 203 additions & 43 deletions

File tree

‎apps/server/src/os-jank.ts‎

Lines changed: 104 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,22 @@
11
import * as HostProcess from "@t3tools/shared/HostProcess";
22
import {
3+
buildEnvironmentCaptureCommand,
4+
extractEnvironmentValues,
35
listLoginShellCandidates,
46
mergePathEntries,
57
readEnvironmentFromLoginShell,
68
readPathFromLaunchctl,
79
resolveWindowsEnvironment,
810
setWindowsPath,
911
} from "@t3tools/shared/shell";
12+
import * as Duration from "effect/Duration";
1013
import * as Effect from "effect/Effect";
1114
import * as FileSystem from "effect/FileSystem";
15+
import * as Option from "effect/Option";
1216
import * as Path from "effect/Path";
17+
import * as Stream from "effect/Stream";
18+
import * as ChildProcess from "effect/process/ChildProcess";
19+
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
1320
// @effect-diagnostics-next-line nodeBuiltinImport:off -- the shared login shell probe runs synchronously through execFileSync.
1421
import * as NodeChildProcess from "node:child_process";
1522
import * as NodeOS from "node:os";
@@ -20,30 +27,49 @@ function logPathHydrationWarning(message: string, error?: unknown): void {
2027
);
2128
}
2229

23-
// mise's record of the PATH entries it added. It must travel with the
24-
// shell's PATH, or `mise x` can rebuild PATH behind a same-named wrapper
25-
// (`exec mise x claude -- claude`) that then re-runs itself forever.
26-
const LOGIN_SHELL_ENVIRONMENT_NAMES = ["PATH", "__MISE_DIFF", "JAVA_HOME"];
30+
// __MISE_DIFF is mise's record of the PATH entries it added. It must travel
31+
// with the shell's PATH, or `mise x` can rebuild PATH behind a same-named
32+
// wrapper (`exec mise x claude -- claude`) that then re-runs itself forever.
33+
const LOGIN_SHELL_ENV_NAMES = ["PATH", "__MISE_DIFF", "JAVA_HOME"] as const;
34+
const LOGIN_SHELL_TIMEOUT = Duration.seconds(5);
2735
const SLOW_LOGIN_SHELL_TIMEOUT_MS = 20_000;
2836

2937
function readSlowLoginShellEnvironment(shell: string): Partial<Record<string, string>> {
30-
return readEnvironmentFromLoginShell(
31-
shell,
32-
LOGIN_SHELL_ENVIRONMENT_NAMES,
33-
(file, args, options) =>
34-
NodeChildProcess.execFileSync(file, args, {
35-
...options,
36-
timeout: SLOW_LOGIN_SHELL_TIMEOUT_MS,
37-
}),
38+
return readEnvironmentFromLoginShell(shell, LOGIN_SHELL_ENV_NAMES, (file, args, options) =>
39+
NodeChildProcess.execFileSync(file, args, {
40+
...options,
41+
timeout: SLOW_LOGIN_SHELL_TIMEOUT_MS,
42+
}),
3843
);
3944
}
4045

46+
function applyLoginShellEnvironment(
47+
env: NodeJS.ProcessEnv,
48+
platform: NodeJS.Platform,
49+
shellEnvironment: Partial<Record<string, string>>,
50+
fallbackPath?: string,
51+
): void {
52+
const shellPath = shellEnvironment.PATH;
53+
const mergedPath = mergePathEntries(shellPath ?? fallbackPath, env.PATH, platform);
54+
if (mergedPath) {
55+
env.PATH = mergedPath;
56+
}
57+
if (shellPath && shellEnvironment.__MISE_DIFF) {
58+
env.__MISE_DIFF = shellEnvironment.__MISE_DIFF;
59+
}
60+
// Android SDK tools are Java programs. A keg-only JDK (Homebrew's openjdk)
61+
// is only reachable through the JAVA_HOME the shell profile sets.
62+
if (!env.JAVA_HOME && shellEnvironment.JAVA_HOME) {
63+
env.JAVA_HOME = shellEnvironment.JAVA_HOME;
64+
}
65+
}
66+
4167
function hydratePosixPath(env: NodeJS.ProcessEnv, platform: NodeJS.Platform): void {
4268
let shellEnvironment: Partial<Record<string, string>> = {};
4369
let waitedForSlowShell = false;
4470
for (const shell of listLoginShellCandidates(platform, env.SHELL)) {
4571
try {
46-
shellEnvironment = readEnvironmentFromLoginShell(shell, LOGIN_SHELL_ENVIRONMENT_NAMES);
72+
shellEnvironment = readEnvironmentFromLoginShell(shell, LOGIN_SHELL_ENV_NAMES);
4773
} catch (error) {
4874
logPathHydrationWarning(`Failed to read PATH from login shell ${shell}.`, error);
4975
// A profile can be slow only while the machine boots. Wait for it once,
@@ -65,20 +91,9 @@ function hydratePosixPath(env: NodeJS.ProcessEnv, platform: NodeJS.Platform): vo
6591
if (shellEnvironment.PATH) break;
6692
}
6793

68-
const shellPath = shellEnvironment.PATH;
69-
const launchctlPath = platform === "darwin" && !shellPath ? readPathFromLaunchctl() : undefined;
70-
const mergedPath = mergePathEntries(shellPath ?? launchctlPath, env.PATH, platform);
71-
if (mergedPath) {
72-
env.PATH = mergedPath;
73-
}
74-
if (shellPath && shellEnvironment.__MISE_DIFF) {
75-
env.__MISE_DIFF = shellEnvironment.__MISE_DIFF;
76-
}
77-
// Android SDK tools are Java programs. A keg-only JDK (Homebrew's openjdk)
78-
// is only reachable through the JAVA_HOME the shell profile sets.
79-
if (!env.JAVA_HOME && shellEnvironment.JAVA_HOME) {
80-
env.JAVA_HOME = shellEnvironment.JAVA_HOME;
81-
}
94+
const launchctlPath =
95+
platform === "darwin" && !shellEnvironment.PATH ? readPathFromLaunchctl() : undefined;
96+
applyLoginShellEnvironment(env, platform, shellEnvironment, launchctlPath);
8297
}
8398

8499
export function hydratePosixHome(
@@ -140,6 +155,68 @@ export const fixPath = Effect.fn("fixPath")(function* (options?: {
140155
);
141156
});
142157

158+
const readLoginShellOutput = Effect.fn("readLoginShellOutput")(
159+
function* (shell: string) {
160+
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
161+
const child = yield* spawner.spawn(
162+
ChildProcess.make(
163+
shell,
164+
["-ilc", buildEnvironmentCaptureCommand(shell, LOGIN_SHELL_ENV_NAMES)],
165+
{
166+
stdin: "ignore",
167+
stdout: "pipe",
168+
stderr: "ignore",
169+
// A profile that traps SIGTERM would otherwise hold the scope open
170+
// past the timeout while cleanup waits for the exit.
171+
forceKillAfter: "1 second",
172+
},
173+
),
174+
);
175+
const [stdout, exitCode] = yield* Effect.all(
176+
[Stream.mkString(Stream.decodeText(child.stdout)), child.exitCode],
177+
{ concurrency: 2 },
178+
);
179+
if (exitCode === 0) return stdout;
180+
yield* Effect.logWarning(
181+
`Login shell ${shell} exited with code ${exitCode} while reading PATH.`,
182+
);
183+
return "";
184+
},
185+
Effect.scoped,
186+
Effect.timeoutOption(LOGIN_SHELL_TIMEOUT),
187+
);
188+
189+
// Runs even when the desktop prepared the environment: that capture was taken
190+
// once at launch. Only the user's own shell counts; a fallback shell's PATH is
191+
// not their environment. Failure leaves PATH alone.
192+
export const refreshPathFromLoginShell = Effect.fn("refreshPathFromLoginShell")(function* () {
193+
const platform = yield* HostProcess.Platform;
194+
if (platform !== "darwin" && platform !== "linux") return;
195+
const env = yield* HostProcess.Environment;
196+
const [shell] = listLoginShellCandidates(platform, env.SHELL);
197+
if (!shell) return;
198+
199+
const output = yield* readLoginShellOutput(shell).pipe(
200+
Effect.catchCause((cause) =>
201+
Effect.logWarning(`Failed to read PATH from login shell ${shell}.`, cause).pipe(
202+
Effect.as(Option.some("")),
203+
),
204+
),
205+
);
206+
if (Option.isNone(output)) {
207+
yield* Effect.logWarning(
208+
`Timed out reading PATH from login shell ${shell} after ${Duration.format(LOGIN_SHELL_TIMEOUT)}; PATH is unchanged.`,
209+
);
210+
return;
211+
}
212+
const shellEnvironment = extractEnvironmentValues(output.value, LOGIN_SHELL_ENV_NAMES);
213+
if (shellEnvironment.PATH) {
214+
applyLoginShellEnvironment(env, platform, shellEnvironment);
215+
} else {
216+
yield* Effect.logWarning(`Login shell ${shell} printed no PATH; PATH is unchanged.`);
217+
}
218+
});
219+
143220
export const expandHomePath = Effect.fn(function* (input: string) {
144221
const { join } = yield* Path.Path;
145222
const home = yield* HostProcess.HomeDirectory;

‎apps/server/src/sourceControl/SourceControlDiscovery.test.ts‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,10 @@ import {
88
import { assert, it } from "@effect/vitest";
99
import * as NodeServices from "@effect/platform-node/NodeServices";
1010
import * as Effect from "effect/Effect";
11+
import * as FileSystem from "effect/FileSystem";
1112
import * as Layer from "effect/Layer";
1213
import * as Option from "effect/Option";
14+
import * as Path from "effect/Path";
1315
import * as PlatformError from "effect/PlatformError";
1416
import {
1517
providerAuth,
@@ -246,3 +248,63 @@ it.effect.each(["darwin", "linux"] as const)(
246248
);
247249
},
248250
);
251+
252+
// Spawns a real login shell and `jj`, so it runs on wall-clock time; the fixture shell is POSIX sh.
253+
it.live.skipIf(HostProcess.Platform.defaultValue() === "win32")(
254+
"rescans with tools the login shell gained after the server started",
255+
() =>
256+
Effect.gen(function* () {
257+
const fs = yield* FileSystem.FileSystem;
258+
const path = yield* Path.Path;
259+
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-discovery-login-shell-" });
260+
const home = path.join(root, "home");
261+
const fakebin = path.join(home, "fakebin");
262+
const loginShell = path.join(root, "loginsh");
263+
yield* fs.makeDirectory(fakebin, { recursive: true });
264+
// Stands in for `$SHELL -ilc <capture>` and sources only the fixture
265+
// profile, so the host's own shell init cannot change the result.
266+
yield* fs.writeFileString(
267+
loginShell,
268+
`#!/bin/sh\nexport HOME=${home}\n. "$HOME/.profile"\nshift\nexec /bin/sh -c "$1"\n`,
269+
{ mode: 0o755 },
270+
);
271+
const env = yield* HostProcess.Environment;
272+
yield* Effect.acquireRelease(
273+
Effect.sync(() => {
274+
const saved = { PATH: env.PATH, SHELL: env.SHELL };
275+
env.SHELL = loginShell;
276+
return saved;
277+
}),
278+
(saved) =>
279+
Effect.sync(() => {
280+
env.PATH = saved.PATH;
281+
if (saved.SHELL === undefined) delete env.SHELL;
282+
else env.SHELL = saved.SHELL;
283+
}),
284+
);
285+
286+
// The user installs a tool after launch; their login shell now finds it.
287+
yield* fs.writeFileString(path.join(fakebin, "jj"), "#!/bin/sh\necho 'jj 0.99.0-test'\n", {
288+
mode: 0o755,
289+
});
290+
yield* fs.writeFileString(path.join(home, ".profile"), 'export PATH="$HOME/fakebin:$PATH"\n');
291+
292+
const discovery = yield* SourceControlDiscovery.SourceControlDiscovery;
293+
const jj = (yield* discovery.discover).versionControlSystems.find(
294+
(item) => item.kind === "jj",
295+
);
296+
297+
assert.deepStrictEqual(
298+
{ status: jj?.status, version: jj?.version },
299+
{ status: "available", version: Option.some("jj 0.99.0-test") },
300+
);
301+
}).pipe(
302+
Effect.scoped,
303+
Effect.provide(
304+
SourceControlDiscovery.layer.pipe(
305+
Layer.provide(VcsProcess.layer),
306+
Layer.provideMerge(layerDiscovery()),
307+
),
308+
),
309+
),
310+
);

‎apps/server/src/sourceControl/SourceControlDiscovery.ts‎

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,14 @@ import {
44
type VcsDriverKind,
55
} from "@t3tools/contracts";
66
import * as Context from "effect/Context";
7+
import * as Duration from "effect/Duration";
78
import * as Effect from "effect/Effect";
89
import * as Layer from "effect/Layer";
910
import * as Option from "effect/Option";
11+
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
1012

1113
import * as ServerConfig from "../config.ts";
14+
import { refreshPathFromLoginShell } from "../os-jank.ts";
1215
import * as VcsProcess from "../vcs/VcsProcess.ts";
1316
import {
1417
detailFromCause,
@@ -73,6 +76,14 @@ export const make = Effect.gen(function* () {
7376
const config = yield* ServerConfig.ServerConfig;
7477
const process = yield* VcsProcess.VcsProcess;
7578
const sourceControlProviders = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
79+
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
80+
// Discovery re-reads the login shell so a tool installed since launch
81+
// resolves here and in every later spawn. Thread views, the palette and
82+
// mobile also run discovery, so one interactive shell serves a short window.
83+
const refreshPath = yield* refreshPathFromLoginShell().pipe(
84+
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
85+
Effect.cachedWithTTL(Duration.seconds(10)),
86+
);
7687

7788
const probe = <Kind extends VcsDriverKind>(
7889
input: VcsProbe & { readonly kind: Kind },
@@ -125,13 +136,16 @@ export const make = Effect.gen(function* () {
125136
};
126137

127138
return SourceControlDiscovery.of({
128-
discover: Effect.all({
129-
versionControlSystems: Effect.all(
130-
VCS_PROBES.map((entry) => probe(entry)) as ReadonlyArray<Effect.Effect<VcsDiscoveryItem>>,
131-
{ concurrency: "unbounded" },
132-
),
133-
sourceControlProviders: sourceControlProviders.discover,
134-
}),
139+
discover: Effect.andThen(
140+
refreshPath,
141+
Effect.all({
142+
versionControlSystems: Effect.all(
143+
VCS_PROBES.map((entry) => probe(entry)) as ReadonlyArray<Effect.Effect<VcsDiscoveryItem>>,
144+
{ concurrency: "unbounded" },
145+
),
146+
sourceControlProviders: sourceControlProviders.discover,
147+
}),
148+
),
135149
});
136150
});
137151

‎packages/shared/src/shell.ts‎

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -295,6 +295,21 @@ function extractEnvironmentValue(output: string, name: string): string | undefin
295295
return value.length > 0 ? value : undefined;
296296
}
297297

298+
/** Reads the values `buildEnvironmentCaptureCommand` printed; unset or empty names are omitted. */
299+
export function extractEnvironmentValues(
300+
output: string,
301+
names: ReadonlyArray<string>,
302+
): Partial<Record<string, string>> {
303+
const environment: Partial<Record<string, string>> = {};
304+
for (const name of names) {
305+
const value = extractEnvironmentValue(output, name);
306+
if (value !== undefined) {
307+
environment[name] = value;
308+
}
309+
}
310+
return environment;
311+
}
312+
298313
export type ShellEnvironmentReader = (
299314
shell: string,
300315
names: ReadonlyArray<string>,
@@ -320,15 +335,7 @@ export const readEnvironmentFromLoginShell: ShellEnvironmentReader = (
320335
stdio: ["ignore", "pipe", "ignore"],
321336
});
322337

323-
const environment: Partial<Record<string, string>> = {};
324-
for (const name of names) {
325-
const value = extractEnvironmentValue(output, name);
326-
if (value !== undefined) {
327-
environment[name] = value;
328-
}
329-
}
330-
331-
return environment;
338+
return extractEnvironmentValues(output, names);
332339
};
333340

334341
export type WindowsShellEnvironmentReader = (

0 commit comments

Comments
 (0)