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

editor.ts

363 lines11.5 KB

1import * as Schema from "effect/Schema";
2import { PositiveInt, TrimmedNonEmptyString } from "./baseSchemas.ts";
3​
4export const EditorLaunchStyle = Schema.Literals(["direct-path", "goto", "line-column"]);
5export type EditorLaunchStyle = typeof EditorLaunchStyle.Type;
6​
7type EditorDefinition = {
8 readonly id: string;
9 readonly label: string;
10 readonly commands: readonly [string, ...string[]] | null;
11 readonly baseArgs?: readonly string[];
12 readonly launchStyle: EditorLaunchStyle;
13 readonly remoteScheme?: string;
14 readonly jetbrainsProductCode?: string;
15};
16​
17export const EDITORS = [
18 {
19 id: "cursor",
20 label: "Cursor",
21 commands: ["cursor"],
22 // File and workspace opens must target the IDE even when the Agents Window is active.
23 baseArgs: ["--classic"],
24 launchStyle: "goto",
25 remoteScheme: "cursor",
26 },
27 { id: "trae", label: "Trae", commands: ["trae"], launchStyle: "goto" },
28 { id: "kiro", label: "Kiro", commands: ["kiro"], baseArgs: ["ide"], launchStyle: "goto" },
29 {
30 id: "vscode",
31 label: "VS Code",
32 commands: ["code"],
33 launchStyle: "goto",
34 remoteScheme: "vscode",
35 },
36 {
37 id: "vscode-insiders",
38 label: "VS Code Insiders",
39 commands: ["code-insiders"],
40 launchStyle: "goto",
41 remoteScheme: "vscode-insiders",
42 },
43 {
44 id: "vscodium",
45 label: "VSCodium",
46 commands: ["codium"],
47 launchStyle: "goto",
48 remoteScheme: "vscodium",
49 },
50 {
51 id: "zed",
52 label: "Zed",
53 commands: ["zed", "zeditor"],
54 launchStyle: "direct-path",
55 remoteScheme: "zed",
56 },
57 {
58 id: "antigravity",
59 label: "Antigravity",
60 // The IDE ships antigravity-ide; agy is the standalone CLI.
61 commands: ["antigravity-ide", "agy-ide"],
62 launchStyle: "goto",
63 },
64 {
65 id: "idea",
66 label: "IntelliJ IDEA",
67 commands: ["idea"],
68 launchStyle: "line-column",
69 jetbrainsProductCode: "IU",
70 },
71 {
72 id: "aqua",
73 label: "Aqua",
74 commands: ["aqua"],
75 launchStyle: "line-column",
76 jetbrainsProductCode: "QA",
77 },
78 {
79 id: "clion",
80 label: "CLion",
81 commands: ["clion"],
82 launchStyle: "line-column",
83 jetbrainsProductCode: "CL",
84 },
85 {
86 id: "datagrip",
87 label: "DataGrip",
88 commands: ["datagrip"],
89 launchStyle: "line-column",
90 jetbrainsProductCode: "DB",
91 },
92 {
93 id: "dataspell",
94 label: "DataSpell",
95 commands: ["dataspell"],
96 launchStyle: "line-column",
97 jetbrainsProductCode: "DS",
98 },
99 {
100 id: "goland",
101 label: "GoLand",
102 commands: ["goland"],
103 launchStyle: "line-column",
104 jetbrainsProductCode: "GO",
105 },
106 {
107 id: "phpstorm",
108 label: "PhpStorm",
109 commands: ["phpstorm"],
110 launchStyle: "line-column",
111 jetbrainsProductCode: "PS",
112 },
113 {
114 id: "pycharm",
115 label: "PyCharm",
116 commands: ["pycharm"],
117 launchStyle: "line-column",
118 jetbrainsProductCode: "PY",
119 },
120 {
121 id: "rider",
122 label: "Rider",
123 commands: ["rider"],
124 launchStyle: "line-column",
125 jetbrainsProductCode: "RD",
126 },
127 {
128 id: "rubymine",
129 label: "RubyMine",
130 commands: ["rubymine"],
131 launchStyle: "line-column",
132 jetbrainsProductCode: "RM",
133 },
134 {
135 id: "rustrover",
136 label: "RustRover",
137 commands: ["rustrover"],
138 launchStyle: "line-column",
139 jetbrainsProductCode: "RR",
140 },
141 {
142 id: "webstorm",
143 label: "WebStorm",
144 commands: ["webstorm"],
145 launchStyle: "line-column",
146 jetbrainsProductCode: "WS",
147 },
148 { id: "file-manager", label: "File Manager", commands: null, launchStyle: "direct-path" },
149 { id: "devin", label: "Devin", commands: ["devin-desktop"], launchStyle: "goto" },
150] as const satisfies ReadonlyArray<EditorDefinition>;
151​
152export const EditorId = Schema.Literals(EDITORS.map((e) => e.id));
153export type EditorId = typeof EditorId.Type;
154​
155export const FileManagerRevealKind = Schema.Literals(["finder", "file-explorer", "files"]);
156export type FileManagerRevealKind = typeof FileManagerRevealKind.Type;
157​
158export const LaunchEditorInput = Schema.Struct({
159 /** Untrimmed: file names may start or end with spaces. */
160 cwd: Schema.NonEmptyString,
161 editor: EditorId,
162 /** When present, cwd is an exact path; {} opens it without a position. Omit for diagnostic suffix parsing. */
163 position: Schema.optional(
164 Schema.Struct({
165 line: Schema.optional(PositiveInt),
166 column: Schema.optional(PositiveInt),
167 }),
168 ),
169 /** Workspace the target belongs to; JetBrains IDEs open positioned files in this project. */
170 projectRoot: Schema.optional(TrimmedNonEmptyString),
171 /** Only for file-manager; requires the server's shellRevealInFileManager capability. */
172 reveal: Schema.optional(Schema.Boolean),
173});
174export type LaunchEditorInput = typeof LaunchEditorInput.Type;
175​
176const remoteSchemeOf = (editor: EditorDefinition): string | undefined =>
177 editor.remoteScheme ?? (editor.jetbrainsProductCode === undefined ? undefined : "jetbrains");
178​
179export const REMOTE_CAPABLE_EDITOR_IDS: ReadonlyArray<EditorId> = EDITORS.flatMap((editor) =>
180 remoteSchemeOf(editor) !== undefined ? [editor.id] : [],
181);
182​
183export const remoteSchemeForEditor = (id: EditorId): string | undefined => {
184 const editor = EDITORS.find((candidate) => candidate.id === id);
185 return editor === undefined ? undefined : remoteSchemeOf(editor);
186};
187​
188// `goto` editors share VS Code's `file:line:col` addressing, so their remote schemes also open
189// a local file as `<scheme>://file/<absolute path>[:line[:col]]`. Zed and JetBrains differ.
190export const LOCAL_FILE_LINK_SCHEMES: ReadonlyArray<string> = EDITORS.flatMap((editor) =>
191 editor.launchStyle === "goto" && "remoteScheme" in editor ? [editor.remoteScheme] : [],
192);
193​
194export const isLocalEditorFileUrl = (url: URL): boolean =>
195 LOCAL_FILE_LINK_SCHEMES.includes(url.protocol.slice(0, -1)) &&
196 url.host === "file" &&
197 url.username.length === 0 &&
198 url.password.length === 0 &&
199 url.pathname.length > 1;
200​
201export const buildRemoteOpenUrl = (input: {
202 readonly editor: EditorId;
203 readonly host: string;
204 readonly username?: string;
205 readonly absolutePath: string;
206 readonly isFile?: boolean;
207}): string | undefined => {
208 const scheme = remoteSchemeForEditor(input.editor);
209 if (scheme === undefined) {
210 return undefined;
211 }
212 const editor = EDITORS.find((candidate) => candidate.id === input.editor);
213 if (editor !== undefined && "jetbrainsProductCode" in editor) {
214 const params = new URLSearchParams({
215 h: input.host,
216 launchIde: "true",
217 ideHint: editor.jetbrainsProductCode,
218 projectHint: input.absolutePath.replaceAll("\\", "/"),
219 });
220 if (input.username !== undefined) {
221 params.set("u", input.username);
222 }
223 return `${scheme}://gateway/ssh/environment?${params.toString()}`;
224 }
225 // Windows server paths (`C:\...`) appear as `/C:/...` in vscode-remote URIs.
226 const posixPath = input.absolutePath.replaceAll("\\", "/");
227 const rootedPath = posixPath.startsWith("/") ? posixPath : `/${posixPath}`;
228 const encodedHost = encodeURIComponent(input.host);
229 if (input.editor === "zed") {
230 // Zed roots paths on the system drive, so omit the Windows drive prefix.
231 const zedPath = /^[Cc]:[\\/]/.test(input.absolutePath) ? rootedPath.slice(3) : rootedPath;
232 const encodedZedPath = zedPath.split("/").map(encodeURIComponent).join("/");
233 // Zed reads this segment as ssh URL userinfo, so the `@` stays literal.
234 const zedDestination =
235 input.username === undefined
236 ? encodedHost
237 : `${encodeURIComponent(input.username)}@${encodedHost}`;
238 return `${scheme}://ssh/${zedDestination}${encodedZedPath}`;
239 }
240 const encodedPath = rootedPath.split("/").map(encodeURIComponent).join("/");
241 const plainDestination =
242 input.username === undefined ? input.host : `${input.username}@${input.host}`;
243 // Remote-SSH splits the decoded authority on "+", so a destination containing one must use its
244 // hex-encoded JSON form instead.
245 const destination = plainDestination.includes("+")
246 ? Array.from(
247 new TextEncoder().encode(JSON.stringify({ hostName: input.host, user: input.username })),
248 (byte) => byte.toString(16).padStart(2, "0"),
249 ).join("")
250 : plainDestination;
251 // VS Code opens a bare vscode-remote path as a folder; a trailing position makes it open the file.
252 // Without windowId=_blank, a folder link replaces the user's last active window.
253 return `${scheme}://vscode-remote/ssh-remote+${encodeURIComponent(destination)}${encodedPath}${input.isFile ? ":1:1" : "?windowId=_blank"}`;
254};
255​
256export const RemoteOpenTargetKind = Schema.Literals(["tailscale", "mdns"]);
257export type RemoteOpenTargetKind = typeof RemoteOpenTargetKind.Type;
258​
259export const RemoteOpenTarget = Schema.Struct({
260 kind: RemoteOpenTargetKind,
261 host: TrimmedNonEmptyString,
262 username: Schema.optionalKey(TrimmedNonEmptyString),
263});
264export type RemoteOpenTarget = typeof RemoteOpenTarget.Type;
265​
266export class ExternalLauncherUnknownEditorError extends Schema.TaggedError<ExternalLauncherUnknownEditorError>()(
267 "ExternalLauncherUnknownEditorError",
268 {
269 editor: Schema.String,
270 },
271) {
272 override get message(): string {
273 return `Unknown editor: ${this.editor}`;
274 }
276​
277export class ExternalLauncherUnsupportedEditorError extends Schema.TaggedError<ExternalLauncherUnsupportedEditorError>()(
278 "ExternalLauncherUnsupportedEditorError",
279 {
280 editor: EditorId,
281 },
282) {
283 override get message(): string {
284 return `Unsupported editor: ${this.editor}`;
285 }
287​
288export class ExternalLauncherCommandNotFoundError extends Schema.TaggedError<ExternalLauncherCommandNotFoundError>()(
289 "ExternalLauncherCommandNotFoundError",
290 {
291 editor: EditorId,
292 command: Schema.String,
293 },
294) {
295 override get message(): string {
296 return `Editor command not found: ${this.command}`;
297 }
299​
300export class ExternalLauncherUnsupportedTargetError extends Schema.TaggedError<ExternalLauncherUnsupportedTargetError>()(
301 "ExternalLauncherUnsupportedTargetError",
302 {
303 editor: EditorId,
304 },
305) {
306 override get message(): string {
307 return `${this.editor} cannot open a path containing line breaks or double quotes`;
308 }
310​
311export class ExternalLauncherRevealTargetMissingError extends Schema.TaggedError<ExternalLauncherRevealTargetMissingError>()(
312 "ExternalLauncherRevealTargetMissingError",
313 {
314 editor: EditorId,
315 target: Schema.String,
316 },
317) {
318 override get message(): string {
319 return `No file or folder exists at ${this.target}`;
320 }
322​
323const ExternalLauncherSpawnFields = {
324 command: Schema.String,
325 args: Schema.Array(Schema.String),
326 cause: Schema.Defect(),
327};
328​
329export class ExternalLauncherBrowserSpawnError extends Schema.TaggedError<ExternalLauncherBrowserSpawnError>()(
330 "ExternalLauncherBrowserSpawnError",
331 {
332 ...ExternalLauncherSpawnFields,
333 target: Schema.String,
334 },
335) {
336 override get message(): string {
337 return `Failed to launch browser target '${this.target}' with '${[this.command, ...this.args].join(" ")}'`;
338 }
340​
341export class ExternalLauncherEditorSpawnError extends Schema.TaggedError<ExternalLauncherEditorSpawnError>()(
342 "ExternalLauncherEditorSpawnError",
343 {
344 ...ExternalLauncherSpawnFields,
345 editor: EditorId,
346 target: Schema.String,
347 },
348) {
349 override get message(): string {
350 return `Failed to launch '${this.target}' in ${this.editor} with '${[this.command, ...this.args].join(" ")}'`;
351 }
353​
354export const ExternalLauncherError = Schema.Union([
355 ExternalLauncherUnknownEditorError,
356 ExternalLauncherUnsupportedEditorError,
357 ExternalLauncherCommandNotFoundError,
358 ExternalLauncherUnsupportedTargetError,
359 ExternalLauncherRevealTargetMissingError,
360 ExternalLauncherBrowserSpawnError,
361 ExternalLauncherEditorSpawnError,
362]);
363export type ExternalLauncherError = typeof ExternalLauncherError.Type;