Open History to see the last commit
1import type { EDITORS } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Option from "effect/Option";
5import * as Path from "effect/Path";
6import * as Stream from "effect/Stream";
7import { ChildProcess, ChildProcessSpawner } from "effect/process";
8
9import * as HostProcess from "./HostProcess.ts";
10import { isCommandAvailable, resolveCommandPath, resolveCommandPaths } from "./shell.ts";
11
12type Editor = (typeof EDITORS)[number];
13
14// The nearest Zed folder identifies the channel, even below a user named zedpreview.
15const isPrereleaseZedPath = (filePath: string) => {
16 const install = filePath
17 .split(/[\\/]/)
18 .slice(0, -1)
19 .findLast((folder) => folder.toLowerCase().includes("zed"))
20 ?.toLowerCase();
21 return install !== undefined && (install.includes("nightly") || install.includes("preview"));
22};
23
24const installNames: Partial<Record<Editor["id"], ReadonlyArray<string>>> = {
25 vscode: ["Visual Studio Code"],
26 "vscode-insiders": ["Visual Studio Code - Insiders"],
27 // `Antigravity.app` is the separate Hub, not the IDE.
28 antigravity: ["Antigravity IDE"],
29 idea: ["IntelliJ IDEA", "IntelliJ IDEA CE", "IntelliJ IDEA Ultimate"],
30 pycharm: ["PyCharm", "PyCharm CE"],
31 rider: ["Rider", "JetBrains Rider"],
32};
33
34// Prefix-only matches could select Insiders when resolving stable VS Code.
35const isVersionedBundle = (entry: string, name: string) => {
36 if (!entry.startsWith(`${name} `) || !entry.endsWith(".app")) return false;
37 return /^\d[\d.]*$/.test(entry.slice(name.length + 1, -".app".length));
38};
39
40// OpenZFS's event daemon is also named zed, and the Cursor Agent CLI installs a cursor script
41// that fails without an IDE behind it; both reject `--version` instead of starting.
42const isEditorCommand = Effect.fn("editor.isEditorCommand")(
43 function* (command: string, isZed: boolean) {
44 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
45 const handle = yield* spawner.spawn(
46 ChildProcess.make(command, ["--version"], {
47 stdin: "ignore",
48 stderr: "ignore",
49 forceKillAfter: "1 second",
50 }),
51 );
52 const [stdout, exitCode] = yield* Effect.all(
53 [handle.stdout.pipe(Stream.decodeText(), Stream.runHead), handle.exitCode],
54 { concurrency: "unbounded" },
55 );
56 return exitCode === 0 && (!isZed || Option.getOrElse(stdout, () => "").startsWith("Zed"));
57 },
58 Effect.scoped,
59 // A slow first start after an update must not hide a working Cursor.
60 (probe, _command, isZed) =>
61 Effect.timeoutOrElse(probe, { duration: "2 seconds", orElse: () => Effect.succeed(!isZed) }),
62 Effect.catchCause(() => Effect.succeed(false)),
63);
64
65export const resolveEditorCommand = Effect.fn("editor.resolveEditorCommand")(function* (
66 editor: Editor,
67 env: NodeJS.ProcessEnv,
68) {
69 if (editor.commands === null) return Option.none();
70 const baseArgs = "baseArgs" in editor ? editor.baseArgs : [];
71 const platform = yield* HostProcess.Platform;
72 // Prefer Zed's macOS bundle because OpenZFS also installs a zed executable.
73 const preferBundle = platform === "darwin" && editor.id === "zed";
74 const preferZeditor = platform === "linux" && editor.id === "zed";
75 const probeCursor = editor.id === "cursor" && platform !== "win32";
76 if (platform === "win32" && editor.id === "zed") {
77 const isStable = (resolved: string) => !isPrereleaseZedPath(resolved);
78 let firstCommand: string | undefined;
79 for (const command of editor.commands) {
80 const matches = yield* resolveCommandPaths(command, { env, until: isStable });
81 const stable = matches.find(isStable);
82 // Bypass PATH only when stable is behind a prerelease install.
83 if (stable !== undefined) {
84 const isFirst = firstCommand === undefined && stable === matches[0];
85 return Option.some({ command: isFirst ? command : stable, baseArgs });
86 }
87 if (firstCommand === undefined && matches.length > 0) firstCommand = command;
88 }
89 if (firstCommand !== undefined) return Option.some({ command: firstCommand, baseArgs });
90 } else if (!preferBundle && !preferZeditor && !probeCursor) {
91 for (const command of editor.commands) {
92 if (yield* isCommandAvailable(command, { env })) return Option.some({ command, baseArgs });
93 }
94 }
95
96 const path = yield* Path.Path;
97 const fs = yield* FileSystem.FileSystem;
98 const home = env.HOME;
99 const names = installNames[editor.id] ?? [editor.label];
100 const command = editor.commands[0];
101 const jetbrains = editor.launchStyle === "line-column";
102 const candidates: string[] = probeCursor ? [...editor.commands] : [];
103 let toolbox: { dir: string; suffix: string } | undefined;
104
105 if (platform === "darwin") {
106 const roots = [...(home ? [path.join(home, "Applications")] : []), "/Applications"];
107 for (const root of roots) {
108 // JetBrains Toolbox appends versions to bundle names; accept exact and versioned names.
109 const entries = yield* fs.readDirectory(root).pipe(Effect.orElseSucceed(() => []));
110 const bundles = new Set(names.map((name) => `${name}.app`));
111 for (const entry of entries) {
112 if (names.some((name) => entry === `${name}.app` || isVersionedBundle(entry, name))) {
113 bundles.add(entry);
114 }
115 }
116 for (const bundle of bundles) {
117 const contents = path.join(root, bundle, "Contents");
118 candidates.push(
119 ...(jetbrains || editor.id === "zed"
120 ? [path.join(contents, "MacOS", editor.id === "zed" ? "cli" : command)]
121 : [
122 path.join(contents, "Resources/app/bin", command),
123 path.join(contents, "Resources/app/bin/code"),
124 ]),
125 );
126 }
127 }
128 if (home && jetbrains) {
129 toolbox = {
130 dir: path.join(home, "Library/Application Support/JetBrains/Toolbox/scripts"),
131 suffix: "",
132 };
133 candidates.push(path.join(toolbox.dir, command));
134 }
135 } else if (platform === "win32") {
136 const roots = [
137 ...(env.LOCALAPPDATA ? [path.join(env.LOCALAPPDATA, "Programs")] : []),
138 ...[env.ProgramFiles, env["ProgramFiles(x86)"], env.ProgramW6432].filter(
139 (root): root is string => !!root,
140 ),
141 ];
142 if (jetbrains) {
143 if (env.LOCALAPPDATA) {
144 toolbox = { dir: path.join(env.LOCALAPPDATA, "JetBrains/Toolbox/scripts"), suffix: ".cmd" };
145 candidates.push(path.join(toolbox.dir, `${command}.cmd`));
146 }
147 for (const directory of roots.flatMap((root) => [root, path.join(root, "JetBrains")])) {
148 const entries = yield* fs.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));
149 for (const entry of entries) {
150 if (names.some((name) => entry === name || entry.startsWith(`${name} `))) {
151 candidates.push(path.join(directory, entry, "bin", `${command}64.exe`));
152 candidates.push(path.join(directory, entry, "bin", `${command}.exe`));
153 }
154 }
155 }
156 } else {
157 const name =
158 editor.id === "vscode"
159 ? "Microsoft VS Code"
160 : editor.id === "vscode-insiders"
161 ? "Microsoft VS Code Insiders"
162 : editor.label;
163 for (const root of roots) {
164 candidates.push(
165 path.join(root, name, "resources/app/bin", `${command}.cmd`),
166 path.join(root, name, "resources/app/bin/code.cmd"),
167 path.join(root, name, "bin", `${command}.cmd`),
168 path.join(root, name, "bin/code.cmd"),
169 );
170 if (editor.id === "zed") {
171 candidates.push(
172 path.join(root, name, "bin", "zed.exe"),
173 path.join(root, name, "zed.exe"),
174 );
175 }
176 }
177 }
178 } else if (platform === "linux") {
179 const dirs = [
180 ...(home ? [path.join(home, ".local/bin")] : []),
181 "/usr/local/bin",
182 "/usr/bin",
183 "/snap/bin",
184 ];
185 const dataHome = env.XDG_DATA_HOME || (home ? path.join(home, ".local/share") : undefined);
186 if (jetbrains && dataHome) {
187 toolbox = { dir: path.join(dataHome, "JetBrains/Toolbox/scripts"), suffix: "" };
188 dirs.push(toolbox.dir);
189 }
190 if (preferZeditor) {
191 // Linux packages use zeditor because OpenZFS owns the zed command.
192 for (const name of ["zeditor", "zed"]) {
193 candidates.push(name, ...dirs.map((dir) => path.join(dir, name)));
194 }
195 } else {
196 for (const dir of dirs) {
197 for (const name of editor.commands) candidates.push(path.join(dir, name));
198 }
199 }
200 }
201
202 if (preferBundle) candidates.push(...editor.commands);
203 if (toolbox) {
204 // Toolbox names a launch script `idea1`, `idea2`, ... while `idea` is taken, and keeps that
205 // name after the other install is removed. Try these only after every canonical candidate.
206 const { dir, suffix } = toolbox;
207 const entries = yield* fs.readDirectory(dir).pipe(Effect.orElseSucceed(() => []));
208 candidates.push(
209 ...entries
210 .filter(
211 (entry) =>
212 entry.startsWith(command) &&
213 entry.endsWith(suffix) &&
214 /^\d+$/.test(entry.slice(command.length, entry.length - suffix.length)),
215 )
216 .sort((a, b) => a.length - b.length || a.localeCompare(b))
217 .map((entry) => path.join(dir, entry)),
218 );
219 }
220 const probeZed = editor.id === "zed" && platform !== "win32";
221 const rejected = new Set<string>();
222 for (const candidate of candidates) {
223 // An earlier PATH entry can hold OpenZFS zed or the Cursor Agent CLI's cursor script.
224 const matches =
225 (probeZed || probeCursor) && candidate === command
226 ? yield* resolveCommandPaths(candidate, { env, until: () => false })
227 : [yield* resolveCommandPath(candidate, { env })];
228 for (const resolved of matches) {
229 if (resolved === null || rejected.has(resolved)) continue;
230 const probed = probeCursor || (probeZed && path.basename(candidate) === "zed");
231 if (probed && !(yield* isEditorCommand(resolved, probeZed))) {
232 rejected.add(resolved);
233 continue;
234 }
235 return Option.some({
236 command: resolved === matches[0] ? candidate : resolved,
237 baseArgs:
238 editor.id === "kiro" && (platform === "darwin" || platform === "win32") ? [] : baseArgs,
239 });
240 }
241 }
242 return Option.none();
243});