-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathserverLauncher.ts
More file actions
1320 lines (1171 loc) · 35.2 KB
/
serverLauncher.ts
File metadata and controls
1320 lines (1171 loc) · 35.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import lspStatusBar from "components/lspStatusBar";
import toast from "components/toast";
import alert from "dialogs/alert";
import confirm from "dialogs/confirm";
import loader from "dialogs/loader";
import { buildShellArchCase } from "./installerUtils";
import {
formatCommand,
quoteArg,
runForegroundCommand,
runQuickCommand,
} from "./installRuntime";
import { getServerBundle } from "./serverCatalog";
import type {
BridgeConfig,
InstallCheckResult,
InstallStatus,
LauncherConfig,
LspServerDefinition,
LspServerStats,
LspServerStatsFormatted,
ManagedServerEntry,
PortInfo,
WaitOptions,
} from "./types";
const managedServers = new Map<string, ManagedServerEntry>();
const checkedCommands = new Map<string, InstallStatus>();
const pendingInstallChecks = new Map<string, Promise<boolean>>();
const announcedServers = new Set<string>();
const STATUS_PRESENT: InstallStatus = "present";
const STATUS_DECLINED: InstallStatus = "declined";
const STATUS_FAILED: InstallStatus = "failed";
const AXS_BINARY = "$PREFIX/axs";
let alreadyInformed = false;
function getTerminalRequiredMessage(): string {
return (
strings?.terminal_required_message_for_lsp ??
"Terminal not installed. Please install Terminal first to use LSP servers."
);
}
interface LspError extends Error {
code?: string;
}
function getExecutor(): Executor {
const executor = (globalThis as unknown as { Executor?: Executor }).Executor;
if (!executor) {
throw new Error("Executor plugin is not available");
}
return executor;
}
/**
* Get the background executor
*/
function getBackgroundExecutor(): Executor {
const executor = getExecutor();
return executor.BackgroundExecutor ?? executor;
}
function joinCommand(command: string, args: string[] = []): string {
if (!Array.isArray(args) || !args.length) return quoteArg(command);
return [quoteArg(command), ...args.map((arg) => quoteArg(arg))].join(" ");
}
export { formatCommand } from "./installRuntime";
// ============================================================================
// Auto-Port Discovery
// ============================================================================
// Cache for the filesDir path
let cachedFilesDir: string | null = null;
/**
* Get candidate Terminal data directories from system.getFilesDir().
* Newer Terminal builds keep shared runtime state in public. Older builds used
* alpine/home, and some installs keep it as a symlink for shell compatibility.
*/
async function getTerminalDataDirs(): Promise<string[]> {
if (cachedFilesDir) {
return [`${cachedFilesDir}/public`, `${cachedFilesDir}/alpine/home`];
}
const system = (
globalThis as unknown as {
system?: {
getFilesDir: (
success: (filesDir: string) => void,
error: (error: string) => void,
) => void;
};
}
).system;
if (!system?.getFilesDir) {
throw new Error("System plugin is not available");
}
return new Promise((resolve, reject) => {
system.getFilesDir(
(filesDir: string) => {
cachedFilesDir = filesDir;
resolve([`${filesDir}/public`, `${filesDir}/alpine/home`]);
},
(error: string) => reject(new Error(error)),
);
});
}
/**
* Get the port file path for a given server and session.
* Port file format: ~/.axs/lsp_ports/{serverName}_{session}
*/
async function getPortFilePaths(
serverName: string,
session: string,
): Promise<string[]> {
const dataDirs = await getTerminalDataDirs();
// Use just the binary name (not full path), mirroring axs behavior
const baseName = serverName.split("/").pop() || serverName;
return dataDirs.map(
(dataDir) => `file://${dataDir}/.axs/lsp_ports/${baseName}_${session}`,
);
}
/**
* Read the port from a port file using the filesystem API.
* Returns null if the file doesn't exist or contains invalid data.
*/
async function readPortFromFile(filePath: string): Promise<number | null> {
try {
// Dynamic import to get fsOperation
const { default: fsOperation } = await import("fileSystem");
const fs = fsOperation(filePath);
// Check if file exists first
const exists = await fs.exists();
if (!exists) {
return null;
}
// Read the file content as text
const content = (await fs.readFile("utf-8")) as string;
const port = Number.parseInt(content.trim(), 10);
if (!Number.isFinite(port) || port <= 0 || port > 65535) {
return null;
}
return port;
} catch {
// File doesn't exist or couldn't be read
return null;
}
}
/**
* Get the port for a running LSP server from the axs port file.
* @param serverName - The LSP server binary name (e.g., "typescript-language-server")
* @param session - Session ID for port file naming
*/
export async function getLspPort(
serverName: string,
session: string,
): Promise<PortInfo | null> {
try {
const filePaths = await getPortFilePaths(serverName, session);
for (const filePath of filePaths) {
const port = await readPortFromFile(filePath);
if (port !== null) {
return { port, filePath, session };
}
}
return null;
} catch {
return null;
}
}
/**
* Wait for the server ready signal (when axs prints "listening on").
* The axs proxy writes the port file immediately after binding, then prints the message.
* So once the signal is received, the port file should be available.
*/
async function waitForServerReady(
serverId: string,
timeout = 10000,
): Promise<boolean> {
const deadline = Date.now() + timeout;
const pollInterval = 50;
while (Date.now() < deadline) {
if (serverReadySignals.has(serverId)) {
serverReadySignals.delete(serverId);
return true;
}
await sleep(pollInterval);
}
return false;
}
/**
* Wait for the port file to be available after server signals ready.
* This is the most efficient approach: wait for ready signal, then read port.
*/
async function waitForPort(
serverId: string,
serverName: string,
session: string,
timeout = 10000,
): Promise<PortInfo | null> {
// First, wait for the server to signal it's ready
const ready = await waitForServerReady(serverId, timeout);
if (!ready) {
console.warn(
`[LSP:${serverId}] Server did not signal ready within timeout`,
);
}
// The port file should be available now (axs writes it before printing "listening on")
// Read it directly
const portInfo = await getLspPort(serverName, session);
if (!portInfo && ready) {
// Server signaled ready but port file not found - retry a few times
for (let i = 0; i < 5; i++) {
await sleep(100);
const retryPortInfo = await getLspPort(serverName, session);
if (retryPortInfo) {
return retryPortInfo;
}
}
}
return portInfo;
}
/**
* Quick check if a server is running and connectable.
* Attempts a fast WebSocket connection test.
*/
async function checkServerAlive(url: string, timeout = 1000): Promise<boolean> {
return new Promise((resolve) => {
try {
const ws = new WebSocket(url);
const timer = setTimeout(() => {
try {
ws.close();
} catch {}
resolve(false);
}, timeout);
ws.onopen = () => {
clearTimeout(timer);
try {
ws.close();
} catch {}
resolve(true);
};
ws.onerror = () => {
clearTimeout(timer);
resolve(false);
};
ws.onclose = () => {
clearTimeout(timer);
resolve(false);
};
} catch {
resolve(false);
}
});
}
/**
* Check if we can reuse an existing server by testing the port.
* Returns the port number if the server is alive, null otherwise.
*/
export async function canReuseExistingServer(
server: LspServerDefinition,
session: string,
): Promise<number | null> {
const bridge = server.launcher?.bridge;
const serverName =
resolveServerExecutable(server) ||
bridge?.command ||
server.launcher?.command ||
server.id;
const portInfo = await getLspPort(serverName, session);
if (!portInfo) {
return null;
}
const url = `ws://127.0.0.1:${portInfo.port}/`;
const alive = await checkServerAlive(url, 1000);
if (alive) {
console.info(
`[LSP:${server.id}] Reusing existing server on port ${portInfo.port}`,
);
return portInfo.port;
}
console.info(
`[LSP:${server.id}] Found stale port file, will start new server`,
);
return null;
}
function buildAxsBridgeCommand(
bridge: BridgeConfig | undefined,
commandOverride?: string | null,
session?: string,
): string | null {
if (!bridge || bridge.kind !== "axs") return null;
const binary =
commandOverride || bridge.command
? String(commandOverride || bridge.command)
: (() => {
throw new Error("Bridge requires a command to execute");
})();
const args: string[] = Array.isArray(bridge.args)
? bridge.args.map((arg) => String(arg))
: [];
// Use session ID or bridge session or server command as fallback session
const effectiveSession = session || bridge.session || binary;
const parts = [AXS_BINARY, "lsp"];
// Add --session flag for port file naming
parts.push("--session", quoteArg(effectiveSession));
// Only add --port if explicitly specified
if (
typeof bridge.port === "number" &&
bridge.port > 0 &&
bridge.port <= 65535
) {
parts.push("--port", String(bridge.port));
}
parts.push(quoteArg(binary));
if (args.length) {
parts.push("--");
args.forEach((arg) => parts.push(quoteArg(arg)));
}
return parts.join(" ");
}
function resolveStartCommand(
server: LspServerDefinition,
session?: string,
): string | null {
const launcher = server.launcher;
if (!launcher) return null;
const executable = resolveServerExecutable(server);
if (launcher.startCommand) {
return formatCommand(launcher.startCommand);
}
if (launcher.command) {
return joinCommand(executable || launcher.command, launcher.args);
}
if (launcher.bridge) {
return buildAxsBridgeCommand(launcher.bridge, executable, session);
}
return null;
}
export function getStartCommand(server: LspServerDefinition): string | null {
return resolveStartCommand(server);
}
function getInstallCacheKey(server: LspServerDefinition): string | null {
const checkCommand =
server.launcher?.checkCommand || buildDerivedCheckCommand(server);
if (!checkCommand) return null;
return `${server.id}:${checkCommand}`;
}
function normalizeInstallSpec(server: LspServerDefinition) {
const install = server.launcher?.install;
if (!install) return null;
const packages = Array.isArray(install.packages)
? install.packages
.map((entry) => String(entry || "").trim())
.filter(Boolean)
: [];
const kind =
install.kind ||
(install.binaryPath ? "manual" : null) ||
(install.source === "apk" ? "apk" : null) ||
(install.source === "npm" ? "npm" : null) ||
(install.source === "pip" ? "pip" : null) ||
(install.source === "cargo" ? "cargo" : null) ||
(install.command ? "shell" : null) ||
"shell";
return {
...install,
kind,
packages,
command:
typeof install.command === "string" && install.command.trim()
? install.command.trim()
: undefined,
updateCommand:
typeof install.updateCommand === "string" && install.updateCommand.trim()
? install.updateCommand.trim()
: undefined,
source:
install.source ||
(kind === "shell" ? "custom" : kind === "manual" ? "manual" : kind),
executable:
typeof install.executable === "string" && install.executable.trim()
? install.executable.trim()
: undefined,
binaryPath:
typeof install.binaryPath === "string" && install.binaryPath.trim()
? install.binaryPath.trim()
: undefined,
repo:
typeof install.repo === "string" && install.repo.trim()
? install.repo.trim()
: undefined,
assetNames:
install.assetNames && typeof install.assetNames === "object"
? Object.fromEntries(
Object.entries(install.assetNames)
.map(([key, value]) => [String(key), String(value || "").trim()])
.filter(([, value]) => Boolean(value)),
)
: {},
archiveType: install.archiveType === "binary" ? "binary" : "zip",
extractFile:
typeof install.extractFile === "string" && install.extractFile.trim()
? install.extractFile.trim()
: undefined,
npmCommand:
typeof install.npmCommand === "string" && install.npmCommand.trim()
? install.npmCommand.trim()
: "npm",
pipCommand:
typeof install.pipCommand === "string" && install.pipCommand.trim()
? install.pipCommand.trim()
: "pip",
pythonCommand:
typeof install.pythonCommand === "string" && install.pythonCommand.trim()
? install.pythonCommand.trim()
: "python3",
global: install.global !== false,
breakSystemPackages: install.breakSystemPackages !== false,
};
}
function getInstallerExecutable(server: LspServerDefinition): string | null {
const install = normalizeInstallSpec(server);
if (!install) return null;
return install.binaryPath || install.executable || null;
}
function getProviderExecutable(server: LspServerDefinition): string | null {
const bundle = getServerBundle(server.id);
if (!bundle?.getExecutable) return null;
try {
return bundle.getExecutable(server.id, server) || null;
} catch (error) {
console.warn(`Failed to resolve bundle executable for ${server.id}`, error);
return null;
}
}
function resolveServerExecutable(server: LspServerDefinition): string | null {
return (
getProviderExecutable(server) ||
getInstallerExecutable(server) ||
server.launcher?.bridge?.command ||
server.launcher?.command ||
null
);
}
function getInstallLabel(server: LspServerDefinition): string {
return (
normalizeInstallSpec(server)?.label ||
server.launcher?.install?.label ||
server.label ||
server.id
).trim();
}
function buildUninstallCommand(server: LspServerDefinition): string | null {
const spec = normalizeInstallSpec(server);
if (!spec) return null;
if (spec.uninstallCommand) {
return spec.uninstallCommand;
}
if (server.launcher?.uninstallCommand) {
return server.launcher.uninstallCommand;
}
switch (spec.kind) {
case "apk":
return spec.packages.length
? `apk del ${spec.packages.map((entry) => quoteArg(entry)).join(" ")}`
: null;
case "npm": {
if (!spec.packages.length) return null;
const npmCommand = spec.npmCommand || "npm";
const uninstallFlags =
spec.global !== false ? "uninstall -g" : "uninstall";
return `${npmCommand} ${uninstallFlags} ${spec.packages.map((entry) => quoteArg(entry)).join(" ")}`;
}
case "pip":
return spec.packages.length
? `${spec.pipCommand || "pip"} uninstall -y ${spec.packages.map((entry) => quoteArg(entry)).join(" ")}`
: null;
case "cargo":
return spec.packages.length
? spec.packages
.map((entry) => `cargo uninstall ${quoteArg(entry)}`)
.join(" && ")
: null;
case "github-release":
case "manual":
return spec.binaryPath ? `rm -f ${quoteArg(spec.binaryPath)}` : null;
default:
return null;
}
}
function buildInstallCommand(
server: LspServerDefinition,
mode: "install" | "update" = "install",
): string | null {
const spec = normalizeInstallSpec(server);
if (!spec) return null;
if (mode === "update" && spec.updateCommand) {
return spec.updateCommand;
}
switch (spec.kind) {
case "apk":
return spec.packages.length
? `apk add --no-cache ${spec.packages.map((entry) => quoteArg(entry)).join(" ")}`
: null;
case "npm": {
if (!spec.packages.length) return null;
const npmCommand = spec.npmCommand || "npm";
const installFlags = spec.global !== false ? "install -g" : "install";
return `apk add --no-cache nodejs npm && ${npmCommand} ${installFlags} ${spec.packages.map((entry) => quoteArg(entry)).join(" ")}`;
}
case "pip": {
if (!spec.packages.length) return null;
const pipCommand = spec.pipCommand || "pip";
const breakPackages =
spec.breakSystemPackages !== false
? "PIP_BREAK_SYSTEM_PACKAGES=1 "
: "";
return `apk add --no-cache python3 py3-pip && ${breakPackages}${pipCommand} install ${spec.packages.map((entry) => quoteArg(entry)).join(" ")}`;
}
case "cargo":
return spec.packages.length
? `apk add --no-cache rust cargo && cargo install ${spec.packages.map((entry) => quoteArg(entry)).join(" ")}`
: null;
case "github-release": {
if (!spec.repo || !spec.binaryPath) return null;
const caseLines = buildShellArchCase(spec.assetNames, quoteArg);
if (!caseLines) return null;
const archivePath = '"$TMP_DIR/$ASSET"';
const extractedFile = quoteArg(spec.extractFile || "luau-lsp");
const installTarget = quoteArg(spec.binaryPath);
const downloadUrl = `https://github.com/${spec.repo}/releases/latest/download/$ASSET`;
if (spec.archiveType === "binary") {
return `apk add --no-cache curl && ARCH="$(uname -m)" && case "$ARCH" in\n${caseLines}\n\t*) echo "Unsupported architecture: $ARCH" >&2; exit 1 ;;\nesac && TMP_DIR="$(mktemp -d)" && cleanup() { rm -rf "$TMP_DIR"; } && trap cleanup EXIT && curl -fsSL "${downloadUrl}" -o ${archivePath} && install -Dm755 ${archivePath} ${installTarget}`;
}
return `apk add --no-cache curl unzip && ARCH="$(uname -m)" && case "$ARCH" in\n${caseLines}\n\t*) echo "Unsupported architecture: $ARCH" >&2; exit 1 ;;\nesac && TMP_DIR="$(mktemp -d)" && cleanup() { rm -rf "$TMP_DIR"; } && trap cleanup EXIT && curl -fsSL "${downloadUrl}" -o ${archivePath} && unzip -oq ${archivePath} -d "$TMP_DIR" && install -Dm755 "$TMP_DIR"/${extractedFile} ${installTarget}`;
}
case "manual":
return null;
default:
return spec.command || null;
}
}
function buildDerivedCheckCommand(server: LspServerDefinition): string | null {
const binary = resolveServerExecutable(server)?.trim() || "";
const install = normalizeInstallSpec(server);
if (install?.kind === "manual" && install.binaryPath) {
return `test -x ${quoteArg(install.binaryPath)}`;
}
if (binary.includes("/")) {
return `test -x ${quoteArg(binary)}`;
}
if (binary) {
return `which ${quoteArg(binary)}`;
}
return null;
}
function getUpdateCommand(server: LspServerDefinition): string | null {
const launcher = server.launcher;
if (!launcher) return null;
if (
typeof launcher.updateCommand === "string" &&
launcher.updateCommand.trim()
) {
return launcher.updateCommand.trim();
}
return buildInstallCommand(server, "update");
}
async function readServerVersion(
server: LspServerDefinition,
): Promise<string | null> {
const command = server.launcher?.versionCommand;
if (!command) return null;
try {
const output = await runQuickCommand(command);
const version = String(output || "")
.split("\n")
.map((line) => line.trim())
.find(Boolean);
return version || null;
} catch {
return null;
}
}
export function getInstallCommand(
server: LspServerDefinition,
mode: "install" | "update" = "install",
): string | null {
if (mode === "update") {
return getUpdateCommand(server);
}
return buildInstallCommand(server, "install");
}
export function getInstallSource(server: LspServerDefinition): string | null {
return normalizeInstallSpec(server)?.source || null;
}
export function getUninstallCommand(
server: LspServerDefinition,
): string | null {
return buildUninstallCommand(server);
}
export async function checkServerInstallation(
server: LspServerDefinition,
): Promise<InstallCheckResult> {
const bundle = getServerBundle(server.id);
if (bundle?.checkInstallation) {
try {
const result = await bundle.checkInstallation(server.id, server);
if (result) return result;
} catch (error) {
return {
status: "failed",
version: null,
canInstall: Boolean(getInstallCommand(server, "install")),
canUpdate: Boolean(getInstallCommand(server, "update")),
message: error instanceof Error ? error.message : String(error),
};
}
}
const launcher = server.launcher;
const installCommand = getInstallCommand(server, "install");
const updateCommand = getInstallCommand(server, "update");
const checkCommand =
launcher?.checkCommand || buildDerivedCheckCommand(server);
if (!checkCommand) {
return {
status: "unknown",
version: await readServerVersion(server),
canInstall: Boolean(installCommand),
canUpdate: Boolean(updateCommand),
message: "No install check configured for this server.",
};
}
try {
await runQuickCommand(checkCommand);
return {
status: "present",
version: await readServerVersion(server),
canInstall: Boolean(installCommand),
canUpdate: Boolean(updateCommand),
};
} catch (error) {
return {
status: installCommand ? "missing" : "failed",
version: null,
canInstall: Boolean(installCommand),
canUpdate: Boolean(updateCommand),
message: error instanceof Error ? error.message : String(error),
};
}
}
export function resetInstallState(serverId?: string): void {
if (!serverId) {
checkedCommands.clear();
return;
}
const prefix = `${serverId}:`;
for (const key of Array.from(checkedCommands.keys())) {
if (key.startsWith(prefix)) {
checkedCommands.delete(key);
}
}
}
async function ensureInstalled(server: LspServerDefinition): Promise<boolean> {
const launcher = server.launcher;
const checkCommand =
launcher?.checkCommand || buildDerivedCheckCommand(server);
if (!checkCommand) return true;
const cacheKey = getInstallCacheKey(server);
if (!cacheKey) return true;
// Return cached result if already checked
if (checkedCommands.has(cacheKey)) {
const status = checkedCommands.get(cacheKey);
if (status === STATUS_PRESENT) {
return true;
}
if (status === STATUS_DECLINED) {
return false;
}
checkedCommands.delete(cacheKey);
}
// If there's already a pending check for this server, wait for it
if (pendingInstallChecks.has(cacheKey)) {
const pending = pendingInstallChecks.get(cacheKey);
if (pending) return pending;
}
// Create and track the pending promise
const checkPromise = performInstallCheck(server, launcher, cacheKey);
pendingInstallChecks.set(cacheKey, checkPromise);
try {
return await checkPromise;
} finally {
pendingInstallChecks.delete(cacheKey);
}
}
interface LoaderDialog {
show: () => void;
destroy: () => void;
}
type InstallActionMode = "install" | "update" | "reinstall";
export async function installServer(
server: LspServerDefinition,
mode: InstallActionMode = "install",
options: { promptConfirm?: boolean } = {},
): Promise<boolean> {
const bundle = getServerBundle(server.id);
if (bundle?.installServer) {
return bundle.installServer(server.id, server, mode, options);
}
const { promptConfirm = true } = options;
const cacheKey = getInstallCacheKey(server);
const displayLabel = getInstallLabel(server);
const isUpdate = mode === "update";
const actionLabel = isUpdate ? "Update" : "Install";
const command =
mode === "install"
? getInstallCommand(server, "install")
: getUpdateCommand(server);
if (!command) {
throw new Error(
`${displayLabel} has no ${actionLabel.toLowerCase()} command.`,
);
}
if (promptConfirm) {
const shouldContinue = await confirm(
displayLabel,
`${actionLabel} ${displayLabel} language server?`,
);
if (!shouldContinue) {
if (cacheKey) {
checkedCommands.set(cacheKey, STATUS_DECLINED);
}
return false;
}
}
let loadingDialog: LoaderDialog | null = null;
try {
loadingDialog = loader.create(
displayLabel,
`${actionLabel}ing ${displayLabel}...`,
);
loadingDialog.show();
await runForegroundCommand(command);
resetInstallState(server.id);
const result = await checkServerInstallation(server);
if (cacheKey && result.status === "present") {
checkedCommands.set(cacheKey, STATUS_PRESENT);
}
toast(
result.status === "present"
? `${displayLabel} ${isUpdate ? "updated" : "installed"}`
: `${displayLabel} ${actionLabel.toLowerCase()} finished`,
);
return true;
} catch (error) {
console.error(`Failed to ${actionLabel.toLowerCase()} ${server.id}`, error);
if (cacheKey) {
checkedCommands.set(cacheKey, STATUS_FAILED);
}
toast(strings?.error ?? "Error");
throw error;
} finally {
loadingDialog?.destroy?.();
}
}
export async function uninstallServer(
server: LspServerDefinition,
options: { promptConfirm?: boolean } = {},
): Promise<boolean> {
const bundle = getServerBundle(server.id);
if (bundle?.uninstallServer) {
return bundle.uninstallServer(server.id, server, options);
}
const { promptConfirm = true } = options;
const cacheKey = getInstallCacheKey(server);
const displayLabel = getInstallLabel(server);
const command = getUninstallCommand(server);
if (!command) {
throw new Error(`${displayLabel} has no uninstall command.`);
}
if (promptConfirm) {
const shouldContinue = await confirm(
displayLabel,
`Uninstall ${displayLabel} language server?`,
);
if (!shouldContinue) {
return false;
}
}
let loadingDialog: LoaderDialog | null = null;
try {
loadingDialog = loader.create(
displayLabel,
`Uninstalling ${displayLabel}...`,
);
loadingDialog.show();
await runForegroundCommand(command);
if (cacheKey) {
checkedCommands.delete(cacheKey);
}
resetInstallState(server.id);
stopManagedServer(server.id);
return true;
} catch (error) {
console.error(`Failed to uninstall ${server.id}`, error);
toast(strings?.error ?? "Error");
throw error;
} finally {
loadingDialog?.destroy();
}
}
async function performInstallCheck(
server: LspServerDefinition,
launcher: LauncherConfig | undefined,
cacheKey: string,
): Promise<boolean> {
try {
const checkCommand =
launcher?.checkCommand || buildDerivedCheckCommand(server);
if (checkCommand) {
await runQuickCommand(checkCommand);
}
checkedCommands.set(cacheKey, STATUS_PRESENT);
return true;
} catch (error) {
if (!getInstallCommand(server, "install")) {
checkedCommands.set(cacheKey, STATUS_FAILED);
console.warn(
`LSP server ${server.id} is missing check command result and has no installer.`,
error,
);
throw error;
}
const installed = await installServer(server, "install", {
promptConfirm: true,
});
if (!installed) {
checkedCommands.set(cacheKey, STATUS_DECLINED);
return false;
}
checkedCommands.set(cacheKey, STATUS_PRESENT);
return true;
}
}
async function startInteractiveServer(
command: string,
serverId: string,
): Promise<string> {
const executor = getExecutor();
const callback: ExecutorCallback = (type, data) => {
if (type === "stderr") {
if (/proot warning/i.test(data)) return;
console.warn(`[LSP:${serverId}] ${data}`);
} else if (type === "stdout" && data && data.trim()) {
console.info(`[LSP:${serverId}] ${data}`);
// Detect when the axs proxy signals it's listening
if (/listening on/i.test(data)) {
signalServerReady(serverId);
}
}
};
const uuid = await executor.start(command, callback, true);
managedServers.set(serverId, {
uuid,
command,
startedAt: Date.now(),
});
return uuid;
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/**
* Tracks servers that have signaled they're ready (listening)
* Key: serverId, Value: timestamp when ready
*/
const serverReadySignals = new Map<string, number>();
/**
* Called when stdout contains a "listening" message from the axs proxy.
* This signals that the server is ready to accept connections.
*/
export function signalServerReady(serverId: string): void {
serverReadySignals.set(serverId, Date.now());
}
/**
* Wait for the LSP server to be ready.
*
* This function polls for a ready signal (set when stdout contains "listening")
*/
async function waitForWebSocket(
url: string,
options: WaitOptions = {},
): Promise<void> {
const {