forked from Acode-Foundation/Acode
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathterminalManager.js
More file actions
1115 lines (975 loc) · 28.8 KB
/
terminalManager.js
File metadata and controls
1115 lines (975 loc) · 28.8 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
/**
* Terminal Manager
* Handles terminal session creation and management
*/
import EditorFile from "lib/editorFile";
import TerminalComponent from "./terminal";
import TerminalTouchSelection from "./terminalTouchSelection";
import "@xterm/xterm/css/xterm.css";
import quickTools from "components/quickTools";
import toast from "components/toast";
import alert from "dialogs/alert";
import confirm from "dialogs/confirm";
import openFile from "lib/openFile";
import openFolder from "lib/openFolder";
import appSettings from "lib/settings";
import helpers from "utils/helpers";
const TERMINAL_SESSION_STORAGE_KEY = "acodeTerminalSessions";
class TerminalManager {
constructor() {
this.terminals = new Map();
this.terminalCounter = 0;
}
extractTerminalNumber(name) {
if (!name) return null;
const match = String(name).match(/^Terminal\s+(\d+)(?:\b| - )/i);
if (!match) return null;
const number = Number.parseInt(match[1], 10);
return Number.isInteger(number) && number > 0 ? number : null;
}
getNextAvailableTerminalNumber() {
const usedNumbers = new Set();
for (const terminal of this.terminals.values()) {
const number = terminal?.terminalNumber;
if (Number.isInteger(number) && number > 0) {
usedNumbers.add(number);
}
}
let nextNumber = 1;
while (usedNumbers.has(nextNumber)) {
nextNumber++;
}
return nextNumber;
}
normalizePersistedSessions(stored) {
if (!Array.isArray(stored)) {
return {
sessions: [],
changed: stored != null,
};
}
const sessions = [];
const uniqueSessions = [];
const seenPids = new Set();
let changed = false;
for (const entry of stored) {
if (!entry) {
changed = true;
continue;
}
if (typeof entry === "string") {
sessions.push({
pid: entry,
name: `Terminal ${entry}`,
pinned: false,
});
changed = true;
continue;
}
if (typeof entry !== "object" || !entry.pid) {
changed = true;
continue;
}
const pid = String(entry.pid);
const name =
typeof entry.name === "string" && entry.name.trim()
? entry.name.trim()
: `Terminal ${pid}`;
const pinned = entry.pinned === true;
if (entry.pid !== pid || entry.name !== name || entry.pinned !== pinned) {
changed = true;
}
sessions.push({ pid, name, pinned });
}
for (const session of sessions) {
const pid = String(session.pid);
if (seenPids.has(pid)) {
changed = true;
continue;
}
seenPids.add(pid);
uniqueSessions.push({
pid,
name:
typeof session.name === "string" && session.name.trim()
? session.name.trim()
: `Terminal ${pid}`,
pinned: session.pinned === true,
});
}
if (uniqueSessions.length !== stored.length) {
changed = true;
}
return {
sessions: uniqueSessions,
changed,
};
}
readPersistedSessions() {
try {
return this.normalizePersistedSessions(
helpers.parseJSON(localStorage.getItem(TERMINAL_SESSION_STORAGE_KEY)),
);
} catch (error) {
console.error("Failed to read persisted terminal sessions:", error);
return {
sessions: [],
changed: false,
};
}
}
async getPersistedSessions() {
try {
const { sessions, changed } = this.readPersistedSessions();
if (!sessions.length) {
if (changed) {
this.savePersistedSessions([]);
}
return [];
}
if (!(await Terminal.isAxsRunning())) {
// Once the backend is gone, previously persisted PIDs are invalid.
this.savePersistedSessions([]);
return [];
}
if (changed) {
this.savePersistedSessions(sessions);
}
return sessions;
} catch (error) {
console.error("Failed to read persisted terminal sessions:", error);
return [];
}
}
savePersistedSessions(sessions) {
try {
localStorage.setItem(
TERMINAL_SESSION_STORAGE_KEY,
JSON.stringify(sessions),
);
} catch (error) {
console.error("Failed to persist terminal sessions:", error);
}
}
async persistTerminalSession(pid, name, pinned = false) {
if (!pid) return;
const pidStr = String(pid);
const { sessions } = this.readPersistedSessions();
const existingIndex = sessions.findIndex(
(session) => session.pid === pidStr,
);
const sessionData = {
pid: pidStr,
name: name || `Terminal ${pidStr}`,
pinned: pinned === true,
};
if (existingIndex >= 0) {
sessions[existingIndex] = {
...sessions[existingIndex],
...sessionData,
};
} else {
sessions.push(sessionData);
}
this.savePersistedSessions(sessions);
}
async removePersistedSession(pid) {
if (!pid) return;
const pidStr = String(pid);
const { sessions } = this.readPersistedSessions();
const nextSessions = sessions.filter((session) => session.pid !== pidStr);
if (nextSessions.length !== sessions.length) {
this.savePersistedSessions(nextSessions);
}
}
async restorePersistedSessions() {
const sessions = await this.getPersistedSessions();
if (!sessions.length) return;
const manager = window.editorManager;
const activeFileId = manager?.activeFile?.id;
const restoredTerminals = [];
const failedSessions = [];
for (const session of sessions) {
if (!session?.pid) continue;
if (this.terminals.has(session.pid)) continue;
try {
const instance = await this.createServerTerminal({
pid: session.pid,
name: session.name,
pinned: session.pinned === true,
reconnecting: true,
render: false,
});
if (instance) restoredTerminals.push(instance);
} catch (error) {
console.error(
`Failed to restore terminal session ${session.pid}:`,
error,
);
failedSessions.push(session.name || session.pid);
await this.removePersistedSession(session.pid);
}
}
// Stale session entries are expected after force-closes; keep startup quiet.
if (failedSessions.length > 0) {
const message =
failedSessions.length === 1
? `Skipped unavailable terminal: ${failedSessions[0]}`
: `Skipped ${failedSessions.length} unavailable terminals`;
toast(message);
}
if (activeFileId && manager?.getFile) {
const fileToRestore = manager.getFile(activeFileId, "id");
fileToRestore?.makeActive();
} else if (!manager?.activeFile && restoredTerminals.length) {
restoredTerminals[0]?.file?.makeActive();
}
}
/**
* Create a new terminal session
* @param {object} options - Terminal options
* @returns {Promise<object>} Terminal instance info
*/
async createTerminal(options = {}) {
try {
const { render, serverMode, reconnecting, pinned, ...terminalOptions } =
options;
const shouldRender = render !== false;
const isServerMode = serverMode !== false;
const isReconnecting = reconnecting === true;
const terminalId = `terminal_${++this.terminalCounter}`;
const providedName =
typeof options.name === "string" ? options.name.trim() : "";
const terminalNumber = providedName
? this.extractTerminalNumber(providedName)
: this.getNextAvailableTerminalNumber();
const terminalName = providedName || `Terminal ${terminalNumber}`;
const titlePrefix = terminalNumber
? `Terminal ${terminalNumber}`
: terminalName;
// Check if terminal is installed before proceeding
if (isServerMode) {
const installationResult = await this.checkAndInstallTerminal();
if (!installationResult.success) {
throw new Error(installationResult.error);
}
}
// Create terminal component
const terminalComponent = new TerminalComponent({
serverMode: isServerMode,
...terminalOptions,
});
// Create container
const terminalContainer = tag("div", {
className: "terminal-content",
id: `terminal-${terminalId}`,
});
// Terminal styles (inject once)
if (!document.getElementById("acode-terminal-styles")) {
const terminalStyles = this.getTerminalStyles();
const terminalStyle = tag("style", {
id: "acode-terminal-styles",
textContent: terminalStyles,
});
document.body.appendChild(terminalStyle);
}
// Create EditorFile for terminal
const terminalFile = new EditorFile(terminalName, {
type: "terminal",
content: terminalContainer,
tabIcon: "icon square-terminal",
pinned,
render: shouldRender,
});
// Wait for tab creation and setup
return await new Promise((resolve, reject) => {
setTimeout(async () => {
try {
// Mount terminal component
terminalComponent.mount(terminalContainer);
// Connect to session if in server mode
if (terminalComponent.serverMode) {
await terminalComponent.connectToSession(terminalOptions.pid);
} else {
// For local mode, just write a welcome message
terminalComponent.write(
"Local terminal mode - ready for output\r\n",
);
}
// Use PID as unique ID if available, otherwise fall back to terminalId
const uniqueId = terminalComponent.pid || terminalId;
// Setup event handlers
this.setupTerminalHandlers(
terminalFile,
terminalComponent,
uniqueId,
titlePrefix,
);
const instance = {
id: uniqueId,
name: terminalName,
terminalNumber,
component: terminalComponent,
file: terminalFile,
container: terminalContainer,
};
this.terminals.set(uniqueId, instance);
if (terminalComponent.serverMode && terminalComponent.pid) {
await this.persistTerminalSession(
terminalComponent.pid,
terminalName,
terminalFile.pinned,
);
}
resolve(instance);
} catch (error) {
console.error("Failed to initialize terminal:", error);
// Cleanup on failure - dispose component and remove broken tab
try {
terminalComponent.dispose();
} catch (disposeError) {
console.error(
"Error disposing terminal component:",
disposeError,
);
}
try {
// Force remove the tab without confirmation
terminalFile._skipTerminalCloseConfirm = true;
terminalFile.remove(true, { ignorePinned: true });
} catch (removeError) {
console.error("Error removing terminal tab:", removeError);
}
// Show alert for terminal creation failure
if (!isReconnecting) {
const errorMessage = error?.message || "Unknown error";
alert(
strings["error"],
`Failed to create terminal: ${errorMessage}`,
);
}
reject(error);
}
}, 100);
});
} catch (error) {
console.error("Failed to create terminal:", error);
throw error;
}
}
/**
* Check if terminal is installed and install if needed
* @returns {Promise<{success: boolean, error?: string}>}
*/
async checkAndInstallTerminal() {
try {
// Check if terminal is already installed
const isInstalled = await Terminal.isInstalled();
if (isInstalled) {
return { success: true };
}
// Check if terminal is supported on this device
const isSupported = await Terminal.isSupported();
if (!isSupported) {
return {
success: false,
error: "Terminal is not supported on this device architecture",
};
}
// Create installation progress terminal
const installTerminal = await this.createInstallationTerminal();
// Install terminal with progress logging
const installResult = await Terminal.install(
(message) => {
// Remove stdout/stderr prefix for
const cleanMessage = message.replace(/^(stdout|stderr)\s+/, "");
installTerminal.component.write(`${cleanMessage}\r\n`);
},
(error) => {
// Remove stdout/stderr prefix
const cleanError = error.replace(/^(stdout|stderr)\s+/, "");
installTerminal.component.write(
`\x1b[31mError: ${cleanError}\x1b[0m\r\n`,
);
},
);
// Only return success if Terminal.install() indicates success (exit code 0)
if (installResult === true) {
return { success: true };
} else {
return {
success: false,
error:
"Terminal installation failed - process did not exit with code 0",
};
}
} catch (error) {
console.error("Terminal installation failed:", error);
return {
success: false,
error: `Terminal installation failed: ${error.message}`,
};
}
}
/**
* Create a terminal for showing installation progress
* @returns {Promise<object>} Installation terminal instance
*/
async createInstallationTerminal() {
const terminalId = `install_terminal_${++this.terminalCounter}`;
const terminalName = "Terminal Installation";
// Create terminal component in local mode (no server needed)
const terminalComponent = new TerminalComponent({
serverMode: false,
});
// Create container
const terminalContainer = tag("div", {
className: "terminal-content",
id: `terminal-${terminalId}`,
});
// Terminal styles (inject once)
if (!document.getElementById("acode-terminal-styles")) {
const terminalStyles = this.getTerminalStyles();
const terminalStyle = tag("style", {
id: "acode-terminal-styles",
textContent: terminalStyles,
});
document.body.appendChild(terminalStyle);
}
// Create EditorFile for terminal
const terminalFile = new EditorFile(terminalName, {
type: "terminal",
content: terminalContainer,
tabIcon: "icon save_alt",
render: true,
});
// Wait for tab creation and setup
return await new Promise((resolve, reject) => {
setTimeout(async () => {
try {
// Mount terminal component
terminalComponent.mount(terminalContainer);
// Write initial message
terminalComponent.write("🚀 Installing Terminal Environment...\r\n");
terminalComponent.write(
"This may take a few minutes depending on your connection.\r\n\r\n",
);
// Setup event handlers
this.setupTerminalHandlers(
terminalFile,
terminalComponent,
terminalId,
);
// Set up custom title for installation terminal
terminalFile.setCustomTitle(
() => "Installing Terminal Environment...",
);
const instance = {
id: terminalId,
name: terminalName,
component: terminalComponent,
file: terminalFile,
container: terminalContainer,
};
this.terminals.set(terminalId, instance);
resolve(instance);
} catch (error) {
console.error("Failed to create installation terminal:", error);
reject(error);
}
}, 100);
});
}
/**
* Setup terminal event handlers
* @param {EditorFile} terminalFile - Terminal file instance
* @param {TerminalComponent} terminalComponent - Terminal component
* @param {string} terminalId - Terminal ID
*/
async setupTerminalHandlers(
terminalFile,
terminalComponent,
terminalId,
titlePrefix = terminalId,
) {
const textarea = terminalComponent.terminal?.textarea;
if (textarea) {
const onFocus = () => {
const { $toggler } = quickTools;
$toggler.classList.add("hide");
clearTimeout(this.togglerTimeout);
this.togglerTimeout = setTimeout(() => {
$toggler.style.display = "none";
}, 300);
};
const onBlur = () => {
const { $toggler } = quickTools;
clearTimeout(this.togglerTimeout);
$toggler.style.display = "";
setTimeout(() => {
$toggler.classList.remove("hide");
}, 10);
};
textarea.addEventListener("focus", onFocus);
textarea.addEventListener("blur", onBlur);
terminalComponent.cleanupFocusHandlers = () => {
textarea.removeEventListener("focus", onFocus);
textarea.removeEventListener("blur", onBlur);
};
}
// Handle tab focus/blur
terminalFile.onfocus = () => {
// Guarded fit on focus: only fit if cols/rows would change, then focus
const run = () => {
try {
const pd = terminalComponent.fitAddon?.proposeDimensions?.();
if (
pd &&
(pd.cols !== terminalComponent.terminal.cols ||
pd.rows !== terminalComponent.terminal.rows)
) {
terminalComponent.fitAddon.fit();
}
} catch {}
terminalComponent.focus();
};
if (typeof requestAnimationFrame === "function") {
requestAnimationFrame(run);
} else {
setTimeout(run, 0);
}
};
// Handle tab close
terminalFile.onclose = () => {
this.closeTerminal(terminalId);
};
terminalFile.onpinstatechange = (pinned) => {
if (!terminalComponent.serverMode || !terminalComponent.pid) return;
void this.persistTerminalSession(
terminalComponent.pid,
terminalFile.filename,
pinned,
);
};
terminalFile._skipTerminalCloseConfirm = false;
const originalRemove = terminalFile.remove.bind(terminalFile);
terminalFile.remove = async (force = false, options = {}) => {
if (terminalFile.pinned && !options?.ignorePinned) {
return originalRemove(force, options);
}
if (
!terminalFile._skipTerminalCloseConfirm &&
this.shouldConfirmTerminalClose()
) {
const message = `${strings["close"]} ${strings["terminal"]}?`;
const shouldClose = await confirm(strings["confirm"], message);
if (!shouldClose) return;
}
terminalFile._skipTerminalCloseConfirm = false;
return originalRemove(force, options);
};
// Enhanced resize handling with debouncing
let resizeTimeout = null;
const RESIZE_DEBOUNCE = 200;
let lastResizeTime = 0;
let lastWidth = 0;
let lastHeight = 0;
const resizeObserver = new ResizeObserver((entries) => {
const now = Date.now();
const entry = entries && entries[0];
const cr = entry?.contentRect;
const width = cr?.width ?? terminalFile.content?.clientWidth ?? 0;
const height = cr?.height ?? terminalFile.content?.clientHeight ?? 0;
// Clear any pending resize
if (resizeTimeout) {
clearTimeout(resizeTimeout);
}
// Debounce rapid resize events (common during keyboard open/close)
resizeTimeout = setTimeout(() => {
try {
// Check if terminal is still available and mounted
if (!terminalComponent.terminal || !terminalComponent.container) {
return;
}
// Only fit if actual size changed to reduce reflows
if (
Math.abs(width - lastWidth) > 0.5 ||
Math.abs(height - lastHeight) > 0.5
) {
terminalComponent.fit();
lastWidth = width;
lastHeight = height;
}
// Update last resize time
lastResizeTime = now;
} catch (error) {
console.error(`Resize error for terminal ${terminalId}:`, error);
}
}, RESIZE_DEBOUNCE);
});
// Wait for the terminal container to be available, then observe it
setTimeout(() => {
const containerElement = terminalFile.content;
if (containerElement && containerElement instanceof Element) {
resizeObserver.observe(containerElement);
// store observer so we can disconnect on close
terminalFile._resizeObserver = resizeObserver;
} else {
console.warn("Terminal container not available for ResizeObserver");
}
}, 200);
// Terminal event handlers
terminalComponent.onConnect = () => {
console.log(`Terminal ${terminalId} connected`);
};
terminalComponent.onDisconnect = () => {
console.log(`Terminal ${terminalId} disconnected`);
};
terminalComponent.onError = (error) => {
console.error(`Terminal ${terminalId} error:`, error);
// Close the terminal and remove the tab
this.closeTerminal(terminalId, true);
// Show alert for connection error
const errorMessage = error?.message || "Connection lost";
alert(strings["error"], `Terminal connection error: ${errorMessage}`);
};
terminalComponent.onTitleChange = async (title) => {
if (title) {
// Keep the tab prefix stable for this terminal instance.
const formattedTitle = `${titlePrefix} - ${title}`;
terminalFile.filename = formattedTitle;
if (terminalComponent.serverMode && terminalComponent.pid) {
await this.persistTerminalSession(
terminalComponent.pid,
formattedTitle,
terminalFile.pinned,
);
}
// Refresh the header subtitle if this terminal is active
if (
editorManager.activeFile &&
editorManager.activeFile.id === terminalFile.id
) {
// Force refresh of the header subtitle
terminalFile.setCustomTitle(getTerminalTitle);
}
}
};
terminalComponent.onProcessExit = (exitData) => {
// Format exit message based on exit code and signal
let message;
if (exitData.signal) {
message = `Process terminated by signal ${exitData.signal}`;
} else if (exitData.exit_code === 0) {
message = `Process exited successfully (code ${exitData.exit_code})`;
} else {
message = `Process exited with code ${exitData.exit_code}`;
}
this.closeTerminal(terminalId);
terminalFile._skipTerminalCloseConfirm = true;
terminalFile.remove(true, { ignorePinned: true });
toast(message);
};
// Handle acode CLI open commands (OSC 7777)
terminalComponent.onOscOpen = async (type, path) => {
if (!path) return;
// Convert proot path
const fileUri = this.convertProotPath(path);
// Extract folder/file name from normalized path
const name = this.getPathDisplayName(path);
try {
if (type === "folder") {
// Open folder in sidebar
await openFolder(fileUri, { name, saveState: true, listFiles: true });
toast(`Opened folder: ${name}`);
} else {
// Open file in editor
await openFile(fileUri, { render: true });
}
} catch (error) {
console.error("Failed to open from terminal:", error);
toast(`Failed to open: ${path}`);
}
};
// Store references for cleanup
terminalFile._terminalId = terminalId;
terminalFile.terminalComponent = terminalComponent;
terminalFile._resizeObserver = resizeObserver;
// Set up custom title function for terminal
const getTerminalTitle = () => {
if (terminalComponent.pid) {
return `PID: ${terminalComponent.pid}`;
}
// fallback to terminal name
return `${terminalId}`;
};
terminalFile.setCustomTitle(getTerminalTitle);
}
/**
* Close a terminal session
* @param {string} terminalId - Terminal ID
*/
closeTerminal(terminalId, removeTab = false) {
const terminal = this.terminals.get(terminalId);
if (!terminal) return;
try {
if (terminal.component.serverMode && terminal.component.pid) {
this.removePersistedSession(terminal.component.pid);
}
// Cleanup resize observer
if (terminal.file._resizeObserver) {
terminal.file._resizeObserver.disconnect();
terminal.file._resizeObserver = null;
}
// Cleanup focus handlers
if (terminal.component.cleanupFocusHandlers) {
terminal.component.cleanupFocusHandlers();
}
// Dispose terminal component
terminal.component.dispose();
// Remove from map
this.terminals.delete(terminalId);
// Optionally remove the tab as well
if (removeTab && terminal.file) {
try {
terminal.file._skipTerminalCloseConfirm = true;
terminal.file.remove(true, { ignorePinned: true });
} catch (removeError) {
console.error("Error removing terminal tab:", removeError);
}
}
if (this.getAllTerminals().size <= 0) {
Executor.stopService();
}
console.log(`Terminal ${terminalId} closed`);
} catch (error) {
console.error(`Error closing terminal ${terminalId}:`, error);
}
}
/**
* Get terminal by ID
* @param {string} terminalId - Terminal ID
* @returns {object|null} Terminal instance
*/
getTerminal(terminalId) {
return this.terminals.get(terminalId) || null;
}
/**
* Get all active terminals
* @returns {Map} All terminals
*/
getAllTerminals() {
return this.terminals;
}
/**
* Register a touch-selection "More" menu option.
* @param {object} option
* @returns {string|null}
*/
addTouchSelectionMoreOption(option) {
return TerminalTouchSelection.addMoreOption(option);
}
/**
* Remove a touch-selection "More" menu option.
* @param {string} id
* @returns {boolean}
*/
removeTouchSelectionMoreOption(id) {
return TerminalTouchSelection.removeMoreOption(id);
}
/**
* List touch-selection "More" menu options.
* @returns {Array<object>}
*/
getTouchSelectionMoreOptions() {
return TerminalTouchSelection.getMoreOptions();
}
/**
* Write to a specific terminal
* @param {string} terminalId - Terminal ID
* @param {string} data - Data to write
*/
writeToTerminal(terminalId, data) {
const terminal = this.getTerminal(terminalId);
if (terminal) {
terminal.component.write(data);
}
}
/**
* Clear a specific terminal
* @param {string} terminalId - Terminal ID
*/
clearTerminal(terminalId) {
const terminal = this.getTerminal(terminalId);
if (terminal) {
terminal.component.clear();
}
}
/**
* Get terminal styles for shadow DOM
* @returns {string} CSS styles
*/
getTerminalStyles() {
return `
.terminal-content {
width: 100%;
height: 100%;
box-sizing: border-box;
background: #1e1e1e;
overflow: hidden;
position: relative;
}
.terminal-content .xterm {
padding: 0.25rem;
box-sizing: border-box;
}
`;
}
/**
* Create a local terminal (no server connection)
* @param {object} options - Terminal options
* @returns {Promise<object>} Terminal instance
*/
async createLocalTerminal(options = {}) {
return this.createTerminal({
...options,
serverMode: false,
});
}
/**
* Create a server terminal (with backend connection)
* @param {object} options - Terminal options
* @returns {Promise<object>} Terminal instance
*/
async createServerTerminal(options = {}) {
return this.createTerminal({
...options,
serverMode: true,
});
}
/**
* Handle keyboard resize events for all terminals
* This is called when the virtual keyboard opens/closes on mobile
*/
handleKeyboardResize() {
// Add a small delay to let the UI settle
setTimeout(() => {
this.terminals.forEach((terminal) => {
try {
if (terminal.component && terminal.component.terminal) {
// Force a re-fit for all terminals
terminal.component.fit();
// If terminal has lots of content, try to preserve scroll position
const buffer = terminal.component.terminal.buffer?.active;
if (
buffer &&
buffer.length > terminal.component.terminal.rows * 2
) {
// For content-heavy terminals, ensure we stay near the bottom if we were there
const wasNearBottom =
buffer.viewportY >=
buffer.length - terminal.component.terminal.rows - 5;
if (wasNearBottom) {
// Scroll to bottom after resize
setTimeout(() => {