Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopCliCommand.ts

497 lines22.0 KB

1// @effect-diagnostics-next-line nodeBuiltinImport:off -- FileSystem.access has no execute check.
2import * as NodeFSP from "node:fs/promises";
3​
4import type { DesktopCliCommandState } from "@t3tools/contracts";
5import * as HostProcess from "@t3tools/shared/HostProcess";
6import * as Context from "effect/Context";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as Random from "effect/Random";
12import * as Schema from "effect/Schema";
13import * as Semaphore from "effect/Semaphore";
14import * as Stream from "effect/Stream";
15import * as ChildProcess from "effect/process/ChildProcess";
16import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
17​
18import { pathSetup, readUserLoginShell } from "@t3tools/shared/shell";
19​
20import * as DesktopCliShim from "./DesktopCliShim.ts";
21import * as DesktopEnvironment from "./DesktopEnvironment.ts";
22import { makeComponentLogger } from "./DesktopObservability.ts";
23​
24const { logInfo, logWarning } = makeComponentLogger("desktop-cli-command");
25​
26export class DesktopCliCommandError extends Schema.TaggedError<DesktopCliCommandError>()(
27 "DesktopCliCommandError",
28 { message: Schema.String },
29) {}
30​
31const userCandidates = (home: string) => [`${home}/.local/bin`, `${home}/bin`];
32​
33// Older builds also linked into these macOS folders. Such a link is found, updated in place, and
34// removed, but no new link goes there.
35const knownLocations = (home: string, platform: NodeJS.Platform) =>
36 platform === "darwin"
37 ? [...userCandidates(home), "/opt/homebrew/bin", "/usr/local/bin"]
38 : userCandidates(home);
39​
40const pathEntries = (value: string | undefined, separator: string) =>
41 (value ?? "").split(separator).filter((entry) => entry.length > 0);
42​
43const sameWindowsPath = (left: string, right: string) =>
44 left.replace(/[\\/]+$/, "").toLowerCase() === right.replace(/[\\/]+$/, "").toLowerCase();
45​
46// Preserve REG_EXPAND_SZ and %VAR% expansion; notify Explorer with WM_SETTINGCHANGE.
47// Failed reads must exit nonzero to prevent replacing PATH wholesale.
48const WINDOWS_USER_PATH_SCRIPT = `
49$ErrorActionPreference = 'Stop'
50if ($env:T3_SET -eq '1') {
51 $key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment')
52 $kind = [Microsoft.Win32.RegistryValueKind]::ExpandString
53 if ($key.GetValueNames() -contains 'Path' -and $key.GetValueKind('Path') -eq 'String') {
54 $kind = [Microsoft.Win32.RegistryValueKind]::String
55 }
56 $key.SetValue('Path', $env:T3_PATH, $kind)
57 Add-Type -Namespace T3 -Name Env -MemberDefinition '[DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern System.IntPtr SendMessageTimeout(System.IntPtr hWnd, uint Msg, System.UIntPtr wParam, string lParam, uint fuFlags, uint uTimeout, out System.UIntPtr lpdwResult);'
58 $result = [System.UIntPtr]::Zero
59 [void][T3.Env]::SendMessageTimeout([System.IntPtr]0xffff, 0x1A, [System.UIntPtr]::Zero, 'Environment', 2, 5000, [ref]$result)
60} else {
61 $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment')
62 $value = if ($key) { $key.GetValue('Path', '', 'DoNotExpandEnvironmentNames') } else { '' }
63 [Console]::Out.Write([Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes([string]$value)))
65`;
66​
67export class DesktopCliCommand extends Context.Service<
68 DesktopCliCommand,
69 {
70 readonly state: Effect.Effect<DesktopCliCommandState>;
71 readonly install: Effect.Effect<DesktopCliCommandState, DesktopCliCommandError>;
72 readonly uninstall: Effect.Effect<DesktopCliCommandState, DesktopCliCommandError>;
73 /** Adds the installed command's folder to PATH in the user's shell startup file. */
74 readonly addToPath: Effect.Effect<DesktopCliCommandState, DesktopCliCommandError>;
75 /** Installs the command on a fresh install's first launch; removing it in Settings sticks. */
76 readonly installOnFirstLaunch: Effect.Effect<void>;
77 }
78>()("@t3tools/desktop/app/DesktopCliCommand") {}
79​
80export const make = Effect.gen(function* () {
81 const environment = yield* DesktopEnvironment.DesktopEnvironment;
82 const fs = yield* FileSystem.FileSystem;
83 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
84 // Read the live env: shell discovery patches PATH after startup, and Windows variable
85 // names are case-insensitive only on process.env, not on Config's copy of it.
86 const env = yield* HostProcess.Environment;
87 const path = environment.path;
88 const windows = environment.platform === "win32";
89 const launcher = DesktopCliShim.launcherPath(environment);
90 const binDirectory = path.dirname(launcher);
91 const ownedPathMarker = path.join(environment.stateDir, "cli-command-path-entry");
92 // Written before PATH changes, so a retry can claim an entry whose record failed.
93 const pendingPathMarker = path.join(environment.stateDir, "cli-command-path-entry-pending");
94 const firstLaunchMarker = path.join(environment.stateDir, "cli-command-first-launch");
95​
96 const fail = (message: string) => new DesktopCliCommandError({ message });
97 const exists = (target: string) => fs.exists(target).pipe(Effect.orElseSucceed(() => false));
98 // Read before this launch writes either one: an app that ran before left its launcher or
99 // settings. Its user may have removed t3 or chosen another, so only Settings installs there.
100 const freshInstall =
101 !(yield* exists(launcher)) && !(yield* exists(environment.desktopSettingsPath));
102 const writableDirectory = (directory: string) =>
103 fs.access(directory, { writable: true }).pipe(
104 Effect.as(true),
105 Effect.orElseSucceed(() => false),
106 );
107​
108 const isOurLink = Effect.fn("DesktopCliCommand.isOurLink")(
109 function* (link: string) {
110 yield* fs.readLink(link);
111 // The launcher is a few KB; never read a large binary another `t3` links to.
112 const info = yield* fs.stat(link);
113 if (info.type !== "File" || Number(info.size) > 16_384) return false;
114 const content = yield* fs.readFileString(link);
115 return content.includes(DesktopCliShim.MARKER);
116 },
117 Effect.orElseSucceed(() => false),
118 );
119​
120 // PATH can reach the regular launcher directly; removal still requires isOurLink.
121 const runsOurLauncher = Effect.fn("DesktopCliCommand.runsOurLauncher")(
122 // Another T3 home's link is marked too, so compare where it leads, not the marker alone.
123 function* (candidate: string) {
124 const [resolved, ours] = yield* Effect.all([fs.realPath(candidate), fs.realPath(launcher)]);
125 if (resolved !== ours) return false;
126 const info = yield* fs.stat(candidate);
127 if (info.type !== "File" || Number(info.size) > 16_384) return false;
128 return (yield* fs.readFileString(candidate)).includes(DesktopCliShim.MARKER);
129 },
130 Effect.orElseSucceed(() => false),
131 );
132​
133 const powershell = (overrides: Record<string, string>) =>
134 Effect.scoped(
135 Effect.gen(function* () {
136 const root = env.SystemRoot ?? env.WINDIR;
137 const handle = yield* spawner.spawn(
138 ChildProcess.make(
139 root ? `${root}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe` : "powershell.exe",
140 ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", WINDOWS_USER_PATH_SCRIPT],
141 { stdin: "ignore", stderr: "ignore", env: overrides, extendEnv: true },
142 ),
143 );
144 const [stdout, exitCode] = yield* Effect.all(
145 [handle.stdout.pipe(Stream.decodeText(), Stream.mkString), handle.exitCode],
146 { concurrency: "unbounded" },
147 );
148 if (exitCode !== 0) return yield* Effect.fail(`powershell exited with ${exitCode}`);
149 return stdout;
150 }),
151 );
152 // Explicit, so an inherited T3_SET=1 can never turn a read into a PATH write.
153 const readUserPath = powershell({ T3_SET: "0" }).pipe(
154 Effect.map((encoded) => Buffer.from(encoded.trim(), "base64").toString("utf8")),
155 Effect.mapError(() => fail("Could not read your PATH, so it was left unchanged.")),
156 );
157 const writeUserPath = (value: string) =>
158 powershell({ T3_SET: "1", T3_PATH: value }).pipe(
159 Effect.asVoid,
160 Effect.mapError(() => fail("Could not update your PATH.")),
161 );
162​
163 const isExecutableFile = Effect.fn("DesktopCliCommand.isExecutableFile")(
164 function* (target: string) {
165 if ((yield* fs.stat(target)).type !== "File") return false;
166 yield* Effect.tryPromise({
167 try: () => NodeFSP.access(target, NodeFSP.constants.X_OK),
168 catch: () => fail(`${target} is not executable.`),
169 });
170 return true;
171 },
172 Effect.orElseSucceed(() => false),
173 );
174​
175 const firstOnPath = Effect.gen(function* () {
176 for (const directory of pathEntries(env.PATH, ":")) {
177 const candidate = path.join(directory, "t3");
178 if (yield* isExecutableFile(candidate)) return Option.some(candidate);
179 }
180 return Option.none<string>();
181 });
182​
183 const foreignFirstOnPath = Effect.gen(function* () {
184 if (windows) return Option.none<string>();
185 const first = yield* firstOnPath;
186 if (Option.isNone(first) || (yield* runsOurLauncher(first.value))) return Option.none<string>();
187 return first;
188 });
189​
190 /** A link to this home's launcher; another home's link is marked too. */
191 const leadsHere = (link: string) =>
192 fs.readLink(link).pipe(
193 Effect.map((target) => target === launcher),
194 Effect.orElseSucceed(() => false),
195 );
196​
197 const installedAt = Effect.gen(function* () {
198 if (windows) {
199 if (!(yield* exists(ownedPathMarker))) return Option.none<string>();
200 const entries = pathEntries(yield* readUserPath, ";");
201 return entries.some((entry) => sameWindowsPath(entry, binDirectory))
202 ? Option.some(launcher)
203 : Option.none<string>();
204 }
205 for (const directory of knownLocations(environment.homeDirectory, environment.platform)) {
206 const link = path.join(directory, "t3");
207 if (yield* isOurLink(link)) return Option.some(link);
208 }
209 return Option.none<string>();
210 });
211​
212 const startupLine = (installedPath: string) => {
213 const setup = pathSetup({
214 directory: path.dirname(installedPath),
215 home: environment.homeDirectory,
216 // A Finder or desktop launch may not set SHELL.
217 shell: env.SHELL || readUserLoginShell(),
218 platform: environment.platform,
219 configHome: env.XDG_CONFIG_HOME,
220 zdotdir: env.ZDOTDIR,
221 });
222 if (setup === undefined) return undefined;
223 const file = setup.file.startsWith("~/")
224 ? path.join(environment.homeDirectory, setup.file.slice(2))
225 : setup.file;
226 return { ...setup, path: file };
227 };
228 const hasLine = (setup: { readonly path: string; readonly line: string }) =>
229 fs.readFileString(setup.path).pipe(
230 Effect.map((content) => content.split("\n").some((line) => line.trim() === setup.line)),
231 Effect.orElseSucceed(() => false),
232 );
233​
234 const folderOnPath = (link: string) =>
235 Effect.sync(() =>
236 pathEntries(env.PATH, ":").some((entry) => entry.replace(/\/+$/, "") === path.dirname(link)),
237 );
238​
239 const state: DesktopCliCommand["Service"]["state"] = Effect.gen(function* () {
240 if (!environment.isPackaged) {
241 return { supported: false, installedPath: null, onPath: false, launcherPath: null } as const;
242 }
243 const launcherPath = (yield* exists(launcher)) ? launcher : null;
244 const found = yield* installedAt;
245 // Our link into another T3 home is not this app's command; Install updates it in place.
246 const installed =
247 windows || (Option.isSome(found) && (yield* leadsHere(found.value)))
248 ? found
249 : Option.none<string>();
250 const shadowedBy = (yield* foreignFirstOnPath).pipe(
251 Option.filter((first) => first !== Option.getOrUndefined(found)),
252 );
253 const shadow = Option.isSome(shadowedBy) ? { shadowedBy: shadowedBy.value } : {};
254 const first = yield* firstOnPath;
255 const onPath = windows
256 ? Option.isSome(installed)
257 : Option.isSome(first) && (yield* runsOurLauncher(first.value));
258 // Only a folder missing from PATH, with no other t3 first: with one, the added folder (last
259 // on PATH) would still not run this t3.
260 const setup =
261 onPath ||
262 Option.isSome(shadowedBy) ||
263 Option.isNone(installed) ||
264 (yield* folderOnPath(installed.value))
265 ? undefined
266 : startupLine(installed.value);
267 return {
268 supported: true,
269 installedPath: Option.getOrNull(installed),
270 onPath,
271 launcherPath,
272 ...shadow,
273 ...(setup === undefined
274 ? {}
275 : { pathSetup: { file: setup.file, added: yield* hasLine(setup) } }),
276 };
277 }).pipe(
278 Effect.orElseSucceed(() => ({
279 supported: false,
280 installedPath: null,
281 onPath: false,
282 launcherPath: null,
283 })),
284 );
285​
286 const ensureLauncher = DesktopCliShim.install.pipe(
287 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
288 Effect.provideService(FileSystem.FileSystem, fs),
289 Effect.flatMap(
290 Option.match({
291 onNone: () => Effect.fail(fail(`Could not set up the t3 launcher at ${launcher}.`)),
292 onSome: () => Effect.void,
293 }),
294 ),
295 );
296​
297 const install: DesktopCliCommand["Service"]["install"] = Effect.gen(function* () {
298 if (!environment.isPackaged) return yield* fail("The t3 command needs an installed app.");
299 yield* ensureLauncher;
300 if (windows) {
301 // PATH would split the folder at the `;`, leaving two wrong entries behind.
302 if (binDirectory.includes(";")) {
303 return yield* fail(
304 `T3 Code cannot put ${binDirectory} on PATH because it has a ";". Run ${launcher} directly.`,
305 );
306 }
307 const entries = pathEntries(yield* readUserPath, ";");
308 const present = entries.some((entry) => sameWindowsPath(entry, binDirectory));
309 if (!present) {
310 yield* fs
311 .writeFileString(pendingPathMarker, `${binDirectory}\n`)
312 .pipe(
313 Effect.mapError(() =>
314 fail("Could not record t3 on your PATH, so it was left unchanged."),
315 ),
316 );
317 // PowerShell can fail after setting PATH (e.g. on the change notification), so the pending
318 // record is dropped only when the entry did not land.
319 yield* writeUserPath([...entries, binDirectory].join(";")).pipe(
320 Effect.tapError(() =>
321 readUserPath.pipe(
322 Effect.map((value) =>
323 pathEntries(value, ";").some((entry) => sameWindowsPath(entry, binDirectory)),
324 ),
325 Effect.orElseSucceed(() => false),
326 Effect.flatMap((landed) =>
327 landed ? Effect.void : fs.remove(pendingPathMarker).pipe(Effect.ignore),
328 ),
329 ),
330 ),
331 );
332 }
333 // An entry already present is ours only if an earlier install began adding it.
334 if (!present || (!(yield* exists(ownedPathMarker)) && (yield* exists(pendingPathMarker)))) {
335 yield* fs
336 .writeFileString(ownedPathMarker, `${binDirectory}\n`)
337 .pipe(Effect.mapError(() => fail("Added t3 to your PATH but could not record it.")));
338 yield* fs.remove(pendingPathMarker).pipe(Effect.ignore);
339 }
340 return yield* state;
341 }
342 const candidates = userCandidates(environment.homeDirectory);
343 const replaced = Option.getOrUndefined(yield* installedAt);
344 if (replaced !== undefined) {
345 const target = yield* fs.readLink(replaced).pipe(Effect.option);
346 if (Option.getOrUndefined(target) === launcher) return yield* state;
347 }
348 const shadowedBy = yield* foreignFirstOnPath;
349 // Our own link into another T3 home runs first too; it is the one this install updates.
350 if (Option.isSome(shadowedBy) && shadowedBy.value !== replaced) {
351 return yield* fail(
352 `Another t3 at ${shadowedBy.value} runs first in a new terminal. Remove it, or run the launcher directly at ${launcher}.`,
353 );
354 }
355 // An old link of ours is updated where it is, so a t3 that works now keeps working. It is
356 // removed only once a new link exists elsewhere.
357 const onPath = pathEntries(env.PATH, ":").map((entry) => entry.replace(/\/+$/, ""));
358 for (const directory of new Set([
359 ...(replaced === undefined ? [] : [path.dirname(replaced)]),
360 ...candidates.filter((candidate) => onPath.includes(candidate)),
361 ...candidates.filter((candidate) => !onPath.includes(candidate)),
362 ])) {
363 const link = path.join(directory, "t3");
364 const created = (yield* exists(directory))
365 ? yield* writableDirectory(directory)
366 : yield* fs.makeDirectory(directory, { recursive: true }).pipe(
367 Effect.as(true),
368 Effect.orElseSucceed(() => false),
369 );
370 if (!created) continue;
371 // Our own link is swapped in place; anything else there makes symlink fail and stays.
372 const staging = `${link}.${yield* Random.nextIntBetween(0, 0xffffff)}.tmp`;
373 const linked = yield* (
374 link === replaced
375 ? fs
376 .symlink(launcher, staging)
377 .pipe(
378 Effect.andThen(
379 fs
380 .rename(staging, link)
381 .pipe(Effect.tapError(() => fs.remove(staging).pipe(Effect.ignore))),
382 ),
383 )
384 : fs.symlink(launcher, link)
385 ).pipe(
386 Effect.as(true),
387 Effect.orElseSucceed(() => false),
388 );
389 if (!linked) continue;
390 if (replaced !== undefined && replaced !== link) {
391 yield* fs.remove(replaced).pipe(Effect.ignore);
392 }
393 return yield* state;
394 }
395 return yield* fail(
396 `Another t3 command is already in ~/.local/bin and ~/bin, or neither is writable. Run the launcher directly at ${launcher}.`,
397 );
398 }).pipe(Effect.withSpan("desktop.cliCommand.install"));
399​
400 const uninstall: DesktopCliCommand["Service"]["uninstall"] = Effect.gen(function* () {
401 // A first launch put off for the shell PATH must not bring back what the user removed.
402 yield* fs.writeFileString(firstLaunchMarker, "").pipe(Effect.ignore);
403 if (windows) {
404 if (yield* exists(ownedPathMarker)) {
405 const entries = pathEntries(yield* readUserPath, ";");
406 const kept = entries.filter((entry) => !sameWindowsPath(entry, binDirectory));
407 if (kept.length !== entries.length) yield* writeUserPath(kept.join(";"));
408 yield* fs.remove(ownedPathMarker).pipe(Effect.ignore);
409 }
410 yield* fs.remove(pendingPathMarker).pipe(Effect.ignore);
411 return yield* state;
412 }
413 for (const directory of knownLocations(environment.homeDirectory, environment.platform)) {
414 const link = path.join(directory, "t3");
415 if (yield* isOurLink(link)) {
416 yield* fs.remove(link).pipe(Effect.mapError(() => fail(`Could not remove ${link}.`)));
417 }
418 }
419 return yield* state;
420 }).pipe(Effect.withSpan("desktop.cliCommand.uninstall"));
421​
422 // One at a time, so Settings and onboarding cannot both append the line.
423 const addToPathPermit = yield* Semaphore.make(1);
424 const addToPath: DesktopCliCommand["Service"]["addToPath"] = Effect.gen(function* () {
425 const installed = yield* installedAt;
426 if (Option.isNone(installed) || !(yield* leadsHere(installed.value))) {
427 return yield* fail("Install the t3 command first.");
428 }
429 const setup = startupLine(installed.value);
430 if (setup === undefined) return yield* fail("T3 Code cannot add t3 to this shell's PATH.");
431 const shadowedBy = yield* foreignFirstOnPath;
432 if (Option.isSome(shadowedBy)) {
433 return yield* fail(
434 `Another t3 at ${shadowedBy.value} runs first; T3 Code leaves it in place.`,
435 );
436 }
437 if (!(yield* folderOnPath(installed.value)) && !(yield* hasLine(setup))) {
438 yield* fs.makeDirectory(path.dirname(setup.path), { recursive: true }).pipe(
439 Effect.andThen(
440 fs.writeFileString(setup.path, `\n# Added by T3 Code\n${setup.line}\n`, { flag: "a" }),
441 ),
442 Effect.mapError(() => fail(`Could not add t3 to ${setup.file}.`)),
443 );
444 }
445 return yield* state;
446 }).pipe(addToPathPermit.withPermits(1), Effect.withSpan("desktop.cliCommand.addToPath"));
447​
448 const installOnFirstLaunch: DesktopCliCommand["Service"]["installOnFirstLaunch"] = Effect.gen(
449 function* () {
450 if (!environment.isPackaged || (yield* exists(firstLaunchMarker))) return;
451 // Mark first so a failed or removed install is never retried behind the user's back.
452 yield* fs.writeFileString(firstLaunchMarker, "");
453 if (!freshInstall) {
454 return yield* logInfo("left the t3 command to Settings on an existing install");
455 }
456 // Another T3 home's app owns the existing link; only Install in Settings may take it over.
457 const existing = Option.getOrUndefined(yield* installedAt);
458 if (existing !== undefined) {
459 const target = yield* fs.readLink(existing).pipe(Effect.option);
460 if (Option.getOrUndefined(target) !== launcher) {
461 return yield* logInfo("left another T3 Code app's t3 command in place", {
462 existing,
463 });
464 }
465 }
466 // A t3 that is not ours in these folders, even off PATH, means the user has one already. On
467 // Windows the app never writes there, so any t3 there is someone else's.
468 for (const directory of userCandidates(environment.homeDirectory)) {
469 for (const name of windows ? ["t3.cmd", "t3.exe"] : ["t3"]) {
470 const other = path.join(directory, name);
471 const present =
472 (yield* exists(other)) || Option.isSome(yield* fs.readLink(other).pipe(Effect.option));
473 if (present && (windows || !(yield* isOurLink(other)))) {
474 return yield* logInfo("left the t3 command to Settings beside another t3", { other });
475 }
476 }
477 }
478 const installed = yield* install;
479 yield* logInfo("installed the t3 command on first launch", {
480 installedPath: installed.installedPath,
481 onPath: installed.onPath,
482 });
483 },
484 ).pipe(
485 // Our own messages are short and name only paths; anything else is logged as a category.
486 Effect.catch((error) =>
487 logWarning("did not install the t3 command on first launch", {
488 reason: error._tag === "DesktopCliCommandError" ? error.message : "state-write-failed",
489 }),
490 ),
491 Effect.withSpan("desktop.cliCommand.installOnFirstLaunch"),
492 );
493​
494 return DesktopCliCommand.of({ state, install, uninstall, addToPath, installOnFirstLaunch });
495});
496​
497export const layer = Layer.effect(DesktopCliCommand, make);