forked from Acode-Foundation/Acode
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathindex.js
More file actions
708 lines (632 loc) · 18 KB
/
index.js
File metadata and controls
708 lines (632 loc) · 18 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
import "./styles.scss";
import lspClientManager from "cm/lsp/clientManager";
import { getServerStats } from "cm/lsp/serverLauncher";
import serverRegistry from "cm/lsp/serverRegistry";
import toast from "components/toast";
import actionStack from "lib/actionStack";
import restoreTheme from "lib/restoreTheme";
let dialogInstance = null;
const lspLogs = new Map();
const MAX_LOGS = 200;
const logListeners = new Set();
const IGNORED_LOG_PATTERNS = [
/\$\/progress\b/i,
/\bProgress:/i,
/\bwindow\/workDoneProgress\/create\b/i,
/\bAuto-responded to window\/workDoneProgress\/create\b/i,
];
function shouldIgnoreLog(message) {
if (typeof message !== "string") return false;
return IGNORED_LOG_PATTERNS.some((pattern) => pattern.test(message));
}
function addLspLog(serverId, level, message, details = null) {
if (shouldIgnoreLog(message)) {
return;
}
if (!lspLogs.has(serverId)) {
lspLogs.set(serverId, []);
}
const logs = lspLogs.get(serverId);
const entry = {
timestamp: new Date(),
level,
message,
details,
};
logs.push(entry);
if (logs.length > MAX_LOGS) {
logs.shift();
}
logListeners.forEach((fn) => fn(serverId, entry));
}
function getLspLogs(serverId) {
return lspLogs.get(serverId) || [];
}
function clearLspLogs(serverId) {
lspLogs.delete(serverId);
}
const originalConsoleInfo = console.info;
const originalConsoleWarn = console.warn;
const originalConsoleError = console.error;
function stripAnsi(str) {
if (typeof str !== "string") return str;
return str.replace(/\x1b\[[0-9;]*m/g, "");
}
function extractServerId(message) {
const cleaned = stripAnsi(message);
// Match [LSP:serverId] format
const lspMatch = cleaned?.match?.(/\[LSP:([^\]]+)\]/);
if (lspMatch) return lspMatch[1];
// Match [LSP-STDERR:program] format from axs proxy
const stderrMatch = cleaned?.match?.(/\[LSP-STDERR:([^\]]+)\]/);
if (stderrMatch) {
const program = stderrMatch[1];
return program;
}
return null;
}
function extractLogMessage(message) {
const cleaned = stripAnsi(message);
// Strip [LSP:...] and [LSP-STDERR:...] prefixes
// Strip ISO timestamps like 2026-02-05T08:26:24.745443Z
// Strip log levels like INFO, WARN, ERROR and the source like axs::lsp:
return (
cleaned
?.replace?.(/\[LSP:[^\]]+\]\s*/, "")
?.replace?.(/\[LSP-STDERR:[^\]]+\]\s*/, "")
?.replace?.(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z?\s*/g, "")
?.replace?.(/\s*(INFO|WARN|ERROR|DEBUG|TRACE)\s+/gi, "")
?.replace?.(/[a-z_]+::[a-z_]+:\s*/gi, "")
?.trim() || cleaned
);
}
console.info = function (...args) {
originalConsoleInfo.apply(console, args);
const msg = args[0];
if (
typeof msg === "string" &&
(msg.includes("[LSP:") || msg.includes("[LSP-STDERR:"))
) {
const serverId = extractServerId(msg);
if (serverId) {
addLspLog(serverId, "info", extractLogMessage(msg));
}
}
};
console.warn = function (...args) {
originalConsoleWarn.apply(console, args);
const msg = args[0];
if (
typeof msg === "string" &&
(msg.includes("[LSP:") || msg.includes("[LSP-STDERR:"))
) {
const serverId = extractServerId(msg);
if (serverId) {
// stderr from axs is logged as warn, mark it appropriately
const isStderr = msg.includes("[LSP-STDERR:");
addLspLog(serverId, isStderr ? "stderr" : "warn", extractLogMessage(msg));
}
}
};
console.error = function (...args) {
originalConsoleError.apply(console, args);
const msg = args[0];
if (
typeof msg === "string" &&
(msg.includes("[LSP:") || msg.includes("[LSP-STDERR:"))
) {
const serverId = extractServerId(msg);
if (serverId) {
addLspLog(serverId, "error", extractLogMessage(msg));
}
}
};
function getActiveClients() {
try {
return lspClientManager.getActiveClients();
} catch {
return [];
}
}
function getCurrentFileLanguage() {
try {
const file = window.editorManager?.activeFile;
if (!file || file.type !== "editor") return null;
return file.currentMode?.toLowerCase() || null;
} catch {
return null;
}
}
function getServersForCurrentFile() {
const language = getCurrentFileLanguage();
if (!language) return [];
try {
return serverRegistry.getServersForLanguage(language);
} catch {
return [];
}
}
function getServerStatus(serverId) {
const activeClients = getActiveClients();
const client = activeClients.find((c) => c.server?.id === serverId);
if (!client) return "stopped";
try {
return client.client?.connected !== false ? "active" : "connecting";
} catch {
return "stopped";
}
}
function getClientState(serverId) {
const activeClients = getActiveClients();
return activeClients.find((c) => c.server?.id === serverId) || null;
}
function getStatusColor(status) {
switch (status) {
case "active":
return "var(--lsp-status-active, #22c55e)";
case "connecting":
return "var(--lsp-status-connecting, #f59e0b)";
default:
return "var(--lsp-status-stopped, #6b7280)";
}
}
function copyLogsToClipboard(serverId, serverLabel) {
const logs = getLspLogs(serverId);
if (logs.length === 0) {
toast("No logs to copy");
return;
}
const text = logs
.map((log) => {
const time = log.timestamp.toLocaleTimeString("en-US", {
hour12: false,
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
});
return `[${time}] [${log.level.toUpperCase()}] ${log.message}`;
})
.join("\n");
const header = `=== ${serverLabel} LSP Logs ===\n`;
if (navigator.clipboard?.writeText) {
navigator.clipboard
.writeText(header + text)
.then(() => {
toast("Logs copied");
})
.catch(() => {
toast("Failed to copy");
});
} else if (cordova?.plugins?.clipboard) {
cordova.plugins.clipboard.copy(header + text);
toast("Logs copied");
} else {
toast("Clipboard not available");
}
}
async function restartServer(serverId) {
addLspLog(serverId, "info", "Restart requested by user");
toast("Restarting server...");
try {
const clientState = getClientState(serverId);
if (clientState) {
await clientState.dispose();
}
const { stopManagedServer } = await import("cm/lsp/serverLauncher");
stopManagedServer(serverId);
window.editorManager?.restartLsp?.();
addLspLog(serverId, "info", "Server restarted successfully");
toast("Server restarted");
} catch (err) {
addLspLog(serverId, "error", `Restart failed: ${err.message}`);
toast("Restart failed");
}
}
async function stopServer(serverId) {
addLspLog(serverId, "info", "Stop requested by user");
toast("Stopping...");
try {
const clientState = getClientState(serverId);
if (clientState) {
await clientState.dispose();
}
const { stopManagedServer } = await import("cm/lsp/serverLauncher");
stopManagedServer(serverId);
addLspLog(serverId, "info", "Server stopped");
toast("Server stopped");
} catch (err) {
addLspLog(serverId, "error", `Stop failed: ${err.message}`);
toast("Failed to stop");
}
}
async function startAllServers() {
toast("Starting LSP servers...");
try {
window.editorManager?.restartLsp?.();
toast("Servers started");
} catch (err) {
toast("Failed to start servers");
}
}
async function restartAllServers() {
const activeClients = getActiveClients();
if (!activeClients.length) {
await startAllServers();
return;
}
const count = activeClients.length;
toast(`Restarting ${count} LSP server${count > 1 ? "s" : ""}...`);
try {
await lspClientManager.dispose();
window.editorManager?.restartLsp?.();
toast("All servers restarted");
} catch (err) {
toast("Failed to restart servers");
}
}
async function stopAllServers() {
const activeClients = getActiveClients();
if (!activeClients.length) {
toast("No LSP servers are currently running");
return;
}
const count = activeClients.length;
try {
await lspClientManager.dispose();
toast(`Stopped ${count} LSP server${count > 1 ? "s" : ""}`);
} catch (err) {
toast("Failed to stop servers");
}
}
function showLspInfoDialog() {
if (dialogInstance) {
dialogInstance.hide();
return;
}
const relevantServers = getServersForCurrentFile();
const currentLanguage = getCurrentFileLanguage();
let currentView = "list";
let selectedServer = null;
const $mask = <span className="mask" onclick={hide} />;
const $dialog = (
<div className="prompt lsp-info-dialog">
<div className="title">
<span className="icon zap" style={{ marginRight: "8px" }} />
Language Servers
</div>
<div className="lsp-dialog-body" />
</div>
);
const $body = $dialog.querySelector(".lsp-dialog-body");
function renderList() {
$body.innerHTML = "";
if (relevantServers.length === 0) {
$body.appendChild(
<div className="lsp-empty-state">
<span className="icon code" />
<p>
No language servers for{" "}
<strong>{currentLanguage || "this file"}</strong>
</p>
</div>,
);
return;
}
const $list = <ul className="lsp-server-list" />;
const runningServers = relevantServers.filter(
(s) => getServerStatus(s.id) !== "stopped",
);
const hasRunning = runningServers.length > 0;
const $actions = (
<div className="lsp-list-actions">
<button
type="button"
className="lsp-action-btn"
onclick={async () => {
await restartAllServers();
await new Promise((r) => setTimeout(r, 500));
renderList();
}}
>
<span className="icon autorenew" />
<span>{hasRunning ? "Restart All" : "Start All"}</span>
</button>
{hasRunning && (
<button
type="button"
className="lsp-action-btn danger"
onclick={async () => {
await stopAllServers();
renderList();
}}
>
<span className="icon power_settings_new" />
<span>Stop All</span>
</button>
)}
</div>
);
$body.appendChild($actions);
for (const server of relevantServers) {
const status = getServerStatus(server.id);
const statusColor = getStatusColor(status);
const logs = getLspLogs(server.id);
const errorCount = logs.filter((l) => l.level === "error").length;
const $item = (
<li
className="lsp-server-item"
onclick={() => {
selectedServer = server;
currentView = "details";
renderDetails();
}}
>
<span
className="lsp-status-dot"
style={{ backgroundColor: statusColor }}
/>
<div className="lsp-server-info">
<span className="lsp-server-name">{server.label}</span>
<span className="lsp-server-status">{status}</span>
</div>
{errorCount > 0 && (
<span className="lsp-error-badge">{errorCount}</span>
)}
<span className="icon keyboard_arrow_right lsp-arrow" />
</li>
);
$list.appendChild($item);
}
$body.appendChild($list);
}
function renderDetails() {
if (!selectedServer) return;
$body.innerHTML = "";
const server = selectedServer;
const status = getServerStatus(server.id);
const clientState = getClientState(server.id);
const isRunning = status !== "stopped";
const capabilities = [];
const hasCapabilities = clientState?.client?.serverCapabilities;
if (hasCapabilities) {
const caps = clientState.client.serverCapabilities;
if (caps.completionProvider) capabilities.push("Completion");
if (caps.hoverProvider) capabilities.push("Hover");
if (caps.definitionProvider) capabilities.push("Go to Definition");
if (caps.referencesProvider) capabilities.push("Find References");
if (caps.renameProvider) capabilities.push("Rename");
if (caps.documentFormattingProvider) capabilities.push("Format");
if (caps.signatureHelpProvider) capabilities.push("Signature Help");
if (caps.inlayHintProvider) capabilities.push("Inlay Hints");
if (caps.codeActionProvider) capabilities.push("Code Actions");
if (caps.diagnosticProvider) capabilities.push("Diagnostics");
}
if (isRunning && capabilities.length === 0 && hasCapabilities) {
capabilities.push("Diagnostics");
}
const logs = getLspLogs(server.id);
const $details = (
<div className="lsp-details">
<div className="lsp-details-header">
<button
type="button"
className="lsp-icon-btn"
onclick={() => {
currentView = "list";
selectedServer = null;
renderList();
}}
aria-label="Back"
>
<span className="icon keyboard_arrow_left" />
</button>
<div className="lsp-details-title">
<span
className="lsp-status-dot"
style={{ backgroundColor: getStatusColor(status) }}
/>
<span>{server.label}</span>
</div>
<div className="lsp-header-actions">
<button
type="button"
className="lsp-icon-btn"
onclick={async () => {
await restartServer(server.id);
await new Promise((r) => setTimeout(r, 500));
renderDetails();
}}
aria-label="Restart Server"
title="Restart Server"
>
<span className="icon autorenew" />
</button>
{isRunning && (
<button
type="button"
className="lsp-icon-btn danger"
onclick={async () => {
await stopServer(server.id);
renderDetails();
}}
aria-label="Stop Server"
title="Stop Server"
>
<span className="icon power_settings_new" />
</button>
)}
</div>
</div>
{isRunning && (
<div className="lsp-section">
<div className="lsp-section-label">Capabilities</div>
<div className="lsp-chip-container">
{capabilities.length > 0
? capabilities.map((cap) => (
<span className="lsp-chip">{cap}</span>
))
: !hasCapabilities && (
<span className="lsp-chip">Initializing...</span>
)}
</div>
</div>
)}
<div className="lsp-section">
<div className="lsp-section-label">Supported</div>
<div className="lsp-chip-container">
{server.languages.map((lang) => (
<span className="lsp-chip ext">.{lang}</span>
))}
</div>
</div>
{isRunning && (
<div className="lsp-section">
<div className="lsp-section-label">Project</div>
<div className="lsp-project-path">
{clientState?.rootUri || "(workspace folders mode)"}
</div>
</div>
)}
{isRunning && (
<div className="lsp-section">
<div className="lsp-section-label">Resources</div>
<div className="lsp-stats-container">
<div className="lsp-stat">
<span className="lsp-stat-label">Memory</span>
<span className="lsp-stat-value" id={`lsp-mem-${server.id}`}>
—
</span>
</div>
<div className="lsp-stat">
<span className="lsp-stat-label">Uptime</span>
<span className="lsp-stat-value" id={`lsp-uptime-${server.id}`}>
—
</span>
</div>
<div className="lsp-stat">
<span className="lsp-stat-label">PID</span>
<span className="lsp-stat-value" id={`lsp-pid-${server.id}`}>
—
</span>
</div>
</div>
</div>
)}
</div>
);
$body.appendChild($details);
// Create simple collapsible logs section
const $logsSection = (
<div className="lsp-logs-section collapsed">
<div
className="lsp-logs-header"
onclick={(e) => {
const section = e.currentTarget.closest(".lsp-logs-section");
if (section) {
section.classList.toggle("collapsed");
if (!section.classList.contains("collapsed")) {
const container = section.querySelector(".lsp-logs-container");
if (container) container.scrollTop = container.scrollHeight;
}
}
}}
>
<div className="lsp-logs-title">
<span className="icon expand_more lsp-expand-icon" />
<span>LSP Logs</span>
{logs.length > 0 && (
<span className="lsp-log-count">({logs.length})</span>
)}
</div>
<div className="lsp-logs-actions">
<button
type="button"
className="lsp-icon-btn small"
onclick={(e) => {
e.stopPropagation();
copyLogsToClipboard(server.id, server.label);
}}
aria-label="Copy Logs"
title="Copy Logs"
>
<span className="icon copy" />
</button>
<button
type="button"
className="lsp-icon-btn small lsp-clear-btn"
onclick={(e) => {
e.stopPropagation();
clearLspLogs(server.id);
renderDetails();
}}
aria-label="Clear Logs"
title="Clear Logs"
>
<span className="icon delete" />
</button>
</div>
</div>
<div className="lsp-logs-container">
{logs.length === 0 ? (
<div className="lsp-logs-empty">No logs yet</div>
) : (
logs.slice(-50).map((log) => {
const time = log.timestamp.toLocaleTimeString("en-US", {
hour12: false,
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
});
return (
<div className={`lsp-log ${log.level}`}>
<span className="lsp-log-time">{time}</span>
<span className="lsp-log-text">{log.message}</span>
</div>
);
})
)}
</div>
</div>
);
$body.appendChild($logsSection);
// Fetch and update stats asynchronously
if (isRunning) {
getServerStats(server.id).then((stats) => {
if (!stats) return;
const $mem = document.getElementById(`lsp-mem-${server.id}`);
const $uptime = document.getElementById(`lsp-uptime-${server.id}`);
const $pid = document.getElementById(`lsp-pid-${server.id}`);
if ($mem) $mem.textContent = stats.memoryFormatted;
if ($uptime) $uptime.textContent = stats.uptimeFormatted;
if ($pid) $pid.textContent = stats.pid ? String(stats.pid) : "—";
});
}
}
function hide() {
$dialog.classList.add("hide");
restoreTheme();
actionStack.remove("lsp-info-dialog");
setTimeout(() => {
$dialog.remove();
$mask.remove();
dialogInstance = null;
}, 200);
}
dialogInstance = { hide, element: $dialog };
actionStack.push({
id: "lsp-info-dialog",
action: hide,
});
restoreTheme(true);
document.body.appendChild($dialog);
document.body.appendChild($mask);
if (currentView === "list") {
renderList();
}
}
function hasConnectedServers() {
const relevantServers = getServersForCurrentFile();
return relevantServers.length > 0;
}
export { showLspInfoDialog, hasConnectedServers, addLspLog, getLspLogs };
export default showLspInfoDialog;