Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as Schema from "effect/Schema";
7import * as ChildProcess from "effect/unstable/process/ChildProcess";
8import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
9
10import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
11
12type EnvironmentPatch = Record<string, string>;
13
14interface ShellEnvironmentConfig {
15 readonly env: NodeJS.ProcessEnv;
16 readonly platform: NodeJS.Platform;
17 readonly userShell: Option.Option<string>;
18}
19
20const DesktopShellEnvironmentProbe = Schema.Literals(["login-shell", "launchctl-path"]);
21type DesktopShellEnvironmentProbe = typeof DesktopShellEnvironmentProbe.Type;
22
23const desktopShellEnvironmentCommandFields = {
24 probe: DesktopShellEnvironmentProbe,
25 executable: Schema.String,
26 argumentCount: Schema.Number,
27};
28
29export class DesktopShellEnvironmentCommandError extends Schema.TaggedErrorClass<DesktopShellEnvironmentCommandError>()(
30 "DesktopShellEnvironmentCommandError",
31 {
32 ...desktopShellEnvironmentCommandFields,
33 cause: Schema.Defect(),
34 },
35) {
36 override get message(): string {
37 return `Desktop shell environment ${this.probe} probe (${this.executable}) failed.`;
38 }
39}
40
41export class DesktopShellEnvironmentCommandTimeoutError extends Schema.TaggedErrorClass<DesktopShellEnvironmentCommandTimeoutError>()(
42 "DesktopShellEnvironmentCommandTimeoutError",
43 {
44 ...desktopShellEnvironmentCommandFields,
45 timeoutMs: Schema.Number,
46 },
47) {
48 override get message(): string {
49 return `Desktop shell environment ${this.probe} probe (${this.executable}) timed out after ${this.timeoutMs}ms.`;
50 }
51}
52
53export class DesktopShellEnvironment extends Context.Service<
54 DesktopShellEnvironment,
55 {
56 readonly installIntoProcess: Effect.Effect<void>;
57 }
58>()("@piku/desktop/shell/DesktopShellEnvironment") {}
59
60const LOGIN_SHELL_ENV_NAMES = [
61 "PATH",
62 "SSH_AUTH_SOCK",
63 "HOMEBREW_PREFIX",
64 "HOMEBREW_CELLAR",
65 "HOMEBREW_REPOSITORY",
66 "XDG_CONFIG_HOME",
67 "XDG_DATA_HOME",
68] as const;
69const LOGIN_SHELL_TIMEOUT = Duration.seconds(5);
70const LAUNCHCTL_TIMEOUT = Duration.seconds(2);
71const PROCESS_TERMINATE_GRACE = Duration.seconds(1);
72
73const trimNonEmpty = (value: string | null | undefined): Option.Option<string> =>
74 Option.fromNullishOr(value).pipe(
75 Option.map((entry) => entry.trim()),
76 Option.filter((entry) => entry.length > 0),
77 );
78
79const readEnvPath = (env: NodeJS.ProcessEnv): Option.Option<string> =>
80 trimNonEmpty(env.PATH ?? env.Path ?? env.path);
81
82const pathComparisonKey = (entry: string) => entry.trim().replace(/^"+|"+$/g, "");
83
84const mergePaths = (values: ReadonlyArray<Option.Option<string>>): Option.Option<string> => {
85 const delimiter = ":";
86 const entries: string[] = [];
87 const seen = new Set<string>();
88
89 for (const value of values) {
90 if (Option.isNone(value)) continue;
91
92 for (const entry of value.value.split(delimiter)) {
93 const trimmed = entry.trim();
94 if (trimmed.length === 0) continue;
95
96 const key = pathComparisonKey(trimmed);
97 if (key.length === 0 || seen.has(key)) continue;
98
99 seen.add(key);
100 entries.push(trimmed);
101 }
102 }
103
104 return entries.length > 0 ? Option.some(entries.join(delimiter)) : Option.none();
105};
106
107const listLoginShellCandidates = (config: ShellEnvironmentConfig): ReadonlyArray<string> => {
108 const fallback =
109 config.platform === "darwin" ? "/bin/zsh" : config.platform === "linux" ? "/bin/bash" : "";
110 const seen = new Set<string>();
111 const candidates: string[] = [];
112
113 for (const candidate of [
114 trimNonEmpty(config.env.SHELL),
115 config.userShell,
116 trimNonEmpty(fallback),
117 ]) {
118 if (Option.isNone(candidate) || seen.has(candidate.value)) continue;
119 seen.add(candidate.value);
120 candidates.push(candidate.value);
121 }
122
123 return candidates;
124};
125
126const startMarker = (name: string) => `__PIKU_ENV_${name}_START__`;
127const endMarker = (name: string) => `__PIKU_ENV_${name}_END__`;
128
129const executableName = (command: string): string => command.split(/[\\/]/u).at(-1) ?? command;
130
131const logShellEnvironmentCommandError = (
132 error: DesktopShellEnvironmentCommandError | DesktopShellEnvironmentCommandTimeoutError,
133) =>
134 Effect.logWarning(error).pipe(
135 Effect.annotateLogs({
136 component: "desktop-shell-environment",
137 error,
138 }),
139 );
140
141const capturePosixEnvironmentCommand = (names: ReadonlyArray<string>) =>
142 names
143 .map((name) => {
144 return [
145 `printf '%s\\n' '${startMarker(name)}'`,
146 `printenv ${name} || true`,
147 `printf '%s\\n' '${endMarker(name)}'`,
148 ].join("; ");
149 })
150 .join("; ");
151
152const extractEnvironment = (output: string, names: ReadonlyArray<string>): EnvironmentPatch => {
153 const environment: EnvironmentPatch = {};
154
155 for (const name of names) {
156 const start = output.indexOf(startMarker(name));
157 if (start === -1) continue;
158
159 const valueStart = start + startMarker(name).length;
160 const end = output.indexOf(endMarker(name), valueStart);
161 if (end === -1) continue;
162
163 const value = output
164 .slice(valueStart, end)
165 .replace(/^\r?\n/, "")
166 .replace(/\r?\n$/, "");
167 if (value.length > 0) {
168 environment[name] = value;
169 }
170 }
171
172 return environment;
173};
174
175const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(function* (input: {
176 readonly probe: DesktopShellEnvironmentProbe;
177 readonly command: string;
178 readonly args: ReadonlyArray<string>;
179 readonly timeout: Duration.Duration;
180 readonly shell?: boolean;
181}): Effect.fn.Return<string, never, ChildProcessSpawner.ChildProcessSpawner> {
182 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
183 const output = yield* spawner
184 .string(
185 ChildProcess.make(input.command, input.args, {
186 shell: input.shell ?? false,
187 stdin: "ignore",
188 stdout: "pipe",
189 stderr: "pipe",
190 killSignal: "SIGTERM",
191 forceKillAfter: PROCESS_TERMINATE_GRACE,
192 }),
193 )
194 .pipe(
195 Effect.mapError(
196 (cause) =>
197 new DesktopShellEnvironmentCommandError({
198 probe: input.probe,
199 executable: executableName(input.command),
200 argumentCount: input.args.length,
201 cause,
202 }),
203 ),
204 Effect.catchTags({
205 DesktopShellEnvironmentCommandError: (error) =>
206 logShellEnvironmentCommandError(error).pipe(Effect.as("")),
207 }),
208 Effect.timeoutOption(input.timeout),
209 );
210 if (Option.isSome(output)) {
211 return output.value;
212 }
213
214 const error = new DesktopShellEnvironmentCommandTimeoutError({
215 probe: input.probe,
216 executable: executableName(input.command),
217 argumentCount: input.args.length,
218 timeoutMs: Duration.toMillis(input.timeout),
219 });
220 yield* logShellEnvironmentCommandError(error);
221 return "";
222});
223
224const readLoginShellEnvironment = (
225 shell: string,
226 names: ReadonlyArray<string>,
227): Effect.Effect<EnvironmentPatch, never, ChildProcessSpawner.ChildProcessSpawner> =>
228 names.length === 0
229 ? Effect.succeed({})
230 : runCommandOutput({
231 probe: "login-shell",
232 command: shell,
233 args: ["-ilc", capturePosixEnvironmentCommand(names)],
234 timeout: LOGIN_SHELL_TIMEOUT,
235 }).pipe(Effect.map((output) => extractEnvironment(output, names)));
236
237const readLaunchctlPath = runCommandOutput({
238 probe: "launchctl-path",
239 command: "/bin/launchctl",
240 args: ["getenv", "PATH"],
241 timeout: LAUNCHCTL_TIMEOUT,
242}).pipe(Effect.map(trimNonEmpty));
243
244const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosixEnvironment")(
245 function* (
246 config: ShellEnvironmentConfig,
247 ): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
248 const shellEnvironment: EnvironmentPatch = {};
249
250 for (const shell of listLoginShellCandidates(config)) {
251 Object.assign(
252 shellEnvironment,
253 yield* readLoginShellEnvironment(shell, LOGIN_SHELL_ENV_NAMES),
254 );
255 if (shellEnvironment.PATH) break;
256 }
257
258 const launchctlPath =
259 config.platform === "darwin" && !shellEnvironment.PATH
260 ? yield* readLaunchctlPath
261 : Option.none<string>();
262 const mergedPath = mergePaths([
263 trimNonEmpty(shellEnvironment.PATH).pipe(Option.orElse(() => launchctlPath)),
264 readEnvPath(config.env),
265 ]);
266
267 if (Option.isSome(mergedPath)) {
268 config.env.PATH = mergedPath.value;
269 }
270 if (!config.env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
271 config.env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
272 }
273
274 for (const name of [
275 "HOMEBREW_PREFIX",
276 "HOMEBREW_CELLAR",
277 "HOMEBREW_REPOSITORY",
278 "XDG_CONFIG_HOME",
279 "XDG_DATA_HOME",
280 ] as const) {
281 if (!config.env[name] && shellEnvironment[name]) {
282 config.env[name] = shellEnvironment[name];
283 }
284 }
285 },
286);
287
288const installShellEnvironment = (
289 config: ShellEnvironmentConfig,
290): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> => {
291 if (config.platform === "darwin" || config.platform === "linux") {
292 return installPosixEnvironment(config);
293 }
294 return Effect.void;
295};
296
297export const make = Effect.gen(function* () {
298 const environment = yield* DesktopEnvironment.DesktopEnvironment;
299 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
300 const installIntoProcess: DesktopShellEnvironment["Service"]["installIntoProcess"] =
301 installShellEnvironment({
302 env: process.env,
303 platform: environment.platform,
304 userShell: Option.none(),
305 }).pipe(
306 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
307 Effect.withSpan("desktop.shellEnvironment.installIntoProcess"),
308 );
309
310 return DesktopShellEnvironment.of({ installIntoProcess });
311});
312
313export const layer = Layer.effect(DesktopShellEnvironment, make);