-
-
Notifications
You must be signed in to change notification settings - Fork 953
Expand file tree
/
Copy pathtermwrap.ts
More file actions
844 lines (772 loc) · 31.6 KB
/
termwrap.ts
File metadata and controls
844 lines (772 loc) · 31.6 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
// Copyright 2025, Command Line Inc.
// SPDX-License-Identifier: Apache-2.0
import type { BlockNodeModel } from "@/app/block/blocktypes";
import { getFileSubject } from "@/app/store/wps";
import { sendWSCommand } from "@/app/store/ws";
import { RpcApi } from "@/app/store/wshclientapi";
import { TabRpcClient } from "@/app/store/wshrpcutil";
import { WOS, fetchWaveFile, getApi, getSettingsKeyAtom, globalStore, openLink, recordTEvent } from "@/store/global";
import * as services from "@/store/services";
import { PLATFORM, PlatformMacOS } from "@/util/platformutil";
import { base64ToArray, base64ToString, fireAndForget } from "@/util/util";
import { SearchAddon } from "@xterm/addon-search";
import { SerializeAddon } from "@xterm/addon-serialize";
import { WebLinksAddon } from "@xterm/addon-web-links";
import { WebglAddon } from "@xterm/addon-webgl";
import * as TermTypes from "@xterm/xterm";
import { Terminal } from "@xterm/xterm";
import debug from "debug";
import * as jotai from "jotai";
import { debounce } from "throttle-debounce";
import { FitAddon } from "./fitaddon";
import { createTempFileFromBlob, extractAllClipboardData } from "./termutil";
const dlog = debug("wave:termwrap");
const TermFileName = "term";
const TermCacheFileName = "cache:term:full";
const MinDataProcessedForCache = 100 * 1024;
const Osc52MaxDecodedSize = 75 * 1024; // max clipboard size for OSC 52 (matches common terminal implementations)
const Osc52MaxRawLength = 128 * 1024; // includes selector + base64 + whitespace (rough check)
export const SupportsImageInput = true;
// detect webgl support
function detectWebGLSupport(): boolean {
try {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("webgl");
return !!ctx;
} catch (e) {
return false;
}
}
const WebGLSupported = detectWebGLSupport();
let loggedWebGL = false;
type TermWrapOptions = {
keydownHandler?: (e: KeyboardEvent) => boolean;
useWebGl?: boolean;
sendDataHandler?: (data: string) => void;
nodeModel?: BlockNodeModel;
};
// for xterm OSC handlers, we return true always because we "own" the OSC number.
// even if data is invalid we don't want to propagate to other handlers.
function handleOsc52Command(data: string, blockId: string, loaded: boolean, termWrap: TermWrap): boolean {
if (!loaded) {
return true;
}
const isBlockFocused = termWrap.nodeModel ? globalStore.get(termWrap.nodeModel.isFocused) : false;
if (!document.hasFocus() || !isBlockFocused) {
console.log("OSC 52: rejected, window or block not focused");
return true;
}
if (!data || data.length === 0) {
console.log("OSC 52: empty data received");
return true;
}
if (data.length > Osc52MaxRawLength) {
console.log("OSC 52: raw data too large", data.length);
return true;
}
const semicolonIndex = data.indexOf(";");
if (semicolonIndex === -1) {
console.log("OSC 52: invalid format (no semicolon)", data.substring(0, 50));
return true;
}
const clipboardSelection = data.substring(0, semicolonIndex);
const base64Data = data.substring(semicolonIndex + 1);
// clipboard query ("?") is not supported for security (prevents clipboard theft)
if (base64Data === "?") {
console.log("OSC 52: clipboard query not supported");
return true;
}
if (base64Data.length === 0) {
return true;
}
if (clipboardSelection.length > 10) {
console.log("OSC 52: clipboard selection too long", clipboardSelection);
return true;
}
const estimatedDecodedSize = Math.ceil(base64Data.length * 0.75);
if (estimatedDecodedSize > Osc52MaxDecodedSize) {
console.log("OSC 52: data too large", estimatedDecodedSize, "bytes");
return true;
}
try {
// strip whitespace from base64 data (some terminals chunk with newlines per RFC 4648)
const cleanBase64Data = base64Data.replace(/\s+/g, "");
const decodedText = base64ToString(cleanBase64Data);
// validate actual decoded size (base64 estimate can be off for multi-byte UTF-8)
const actualByteSize = new TextEncoder().encode(decodedText).length;
if (actualByteSize > Osc52MaxDecodedSize) {
console.log("OSC 52: decoded text too large", actualByteSize, "bytes");
return true;
}
fireAndForget(async () => {
try {
await navigator.clipboard.writeText(decodedText);
dlog("OSC 52: copied", decodedText.length, "characters to clipboard");
} catch (err) {
console.error("OSC 52: clipboard write failed:", err);
}
});
} catch (e) {
console.error("OSC 52: base64 decode error:", e);
}
return true;
}
// for xterm handlers, we return true always because we "own" OSC 7.
// even if it is invalid we dont want to propagate to other handlers
function handleOsc7Command(data: string, blockId: string, loaded: boolean): boolean {
if (!loaded) {
return true;
}
if (data == null || data.length == 0) {
console.log("Invalid OSC 7 command received (empty)");
return true;
}
if (data.length > 1024) {
console.log("Invalid OSC 7, data length too long", data.length);
return true;
}
let pathPart: string;
try {
const url = new URL(data);
if (url.protocol !== "file:") {
console.log("Invalid OSC 7 command received (non-file protocol)", data);
return true;
}
pathPart = decodeURIComponent(url.pathname);
// Normalize double slashes at the beginning to single slash
if (pathPart.startsWith("//")) {
pathPart = pathPart.substring(1);
}
// Handle Windows paths (e.g., /C:/... or /D:\...)
if (/^\/[a-zA-Z]:[\\/]/.test(pathPart)) {
// Strip leading slash and normalize to forward slashes
pathPart = pathPart.substring(1).replace(/\\/g, "/");
}
// Handle UNC paths (e.g., /\\server\share)
if (pathPart.startsWith("/\\\\")) {
// Strip leading slash but keep backslashes for UNC
pathPart = pathPart.substring(1);
}
} catch (e) {
console.log("Invalid OSC 7 command received (parse error)", data, e);
return true;
}
setTimeout(() => {
fireAndForget(async () => {
await services.ObjectService.UpdateObjectMeta(WOS.makeORef("block", blockId), {
"cmd:cwd": pathPart,
});
const rtInfo = { "shell:hascurcwd": true };
const rtInfoData: CommandSetRTInfoData = {
oref: WOS.makeORef("block", blockId),
data: rtInfo,
};
await RpcApi.SetRTInfoCommand(TabRpcClient, rtInfoData).catch((e) =>
console.log("error setting RT info", e)
);
// Smart auto-detection: Update tab basedir if not locked
const tabAtom = globalStore.get(atoms.activeTabAtom);
const currentBasedir = tabAtom?.meta?.["tab:basedir"];
const basedirLocked = tabAtom?.meta?.["tab:basedirlock"];
// Set tab basedir if not set yet, or if not locked and this is the first meaningful directory
if (!basedirLocked && (!currentBasedir || currentBasedir === "~")) {
await services.ObjectService.UpdateObjectMeta(
WOS.makeORef("tab", tabAtom.oid),
{
"tab:basedir": pathPart,
}
);
}
});
}, 0);
return true;
}
// some POC concept code for adding a decoration to a marker
function addTestMarkerDecoration(terminal: Terminal, marker: TermTypes.IMarker, termWrap: TermWrap): void {
const decoration = terminal.registerDecoration({
marker: marker,
layer: "top",
});
if (!decoration) {
return;
}
decoration.onRender((el) => {
el.classList.add("wave-decoration");
el.classList.add("bg-ansi-white");
el.dataset.markerline = String(marker.line);
if (!el.querySelector(".wave-deco-line")) {
const line = document.createElement("div");
line.classList.add("wave-deco-line", "bg-accent/20");
line.style.position = "absolute";
line.style.top = "0";
line.style.left = "0";
line.style.width = "500px";
line.style.height = "1px";
el.appendChild(line);
}
});
}
function checkCommandForTelemetry(decodedCmd: string) {
if (!decodedCmd) {
return;
}
if (decodedCmd.startsWith("ssh ")) {
recordTEvent("conn:connect", { "conn:conntype": "ssh-manual" });
return;
}
const editorsRegex = /^(vim|vi|nano|nvim)\b/;
if (editorsRegex.test(decodedCmd)) {
recordTEvent("action:term", { "action:type": "cli-edit" });
return;
}
const tailFollowRegex = /(^|\|\s*)tail\s+-[fF]\b/;
if (tailFollowRegex.test(decodedCmd)) {
recordTEvent("action:term", { "action:type": "cli-tailf" });
return;
}
}
// OSC 16162 - Shell Integration Commands
// See aiprompts/wave-osc-16162.md for full documentation
type ShellIntegrationStatus = "ready" | "running-command";
type Osc16162Command =
| { command: "A"; data: {} }
| { command: "C"; data: { cmd64?: string } }
| { command: "M"; data: { shell?: string; shellversion?: string; uname?: string; integration?: boolean } }
| { command: "D"; data: { exitcode?: number } }
| { command: "I"; data: { inputempty?: boolean } }
| { command: "R"; data: {} };
function handleOsc16162Command(data: string, blockId: string, loaded: boolean, termWrap: TermWrap): boolean {
const terminal = termWrap.terminal;
if (!loaded) {
return true;
}
if (!data || data.length === 0) {
return true;
}
const parts = data.split(";");
const commandStr = parts[0];
const jsonDataStr = parts.length > 1 ? parts.slice(1).join(";") : null;
let parsedData: Record<string, any> = {};
if (jsonDataStr) {
try {
parsedData = JSON.parse(jsonDataStr);
} catch (e) {
console.error("Error parsing OSC 16162 JSON data:", e);
}
}
const cmd: Osc16162Command = { command: commandStr, data: parsedData } as Osc16162Command;
const rtInfo: ObjRTInfo = {};
switch (cmd.command) {
case "A":
rtInfo["shell:state"] = "ready";
globalStore.set(termWrap.shellIntegrationStatusAtom, "ready");
const marker = terminal.registerMarker(0);
if (marker) {
termWrap.promptMarkers.push(marker);
// addTestMarkerDecoration(terminal, marker, termWrap);
marker.onDispose(() => {
const idx = termWrap.promptMarkers.indexOf(marker);
if (idx !== -1) {
termWrap.promptMarkers.splice(idx, 1);
}
});
}
break;
case "C":
rtInfo["shell:state"] = "running-command";
globalStore.set(termWrap.shellIntegrationStatusAtom, "running-command");
getApi().incrementTermCommands();
if (cmd.data.cmd64) {
const decodedLen = Math.ceil(cmd.data.cmd64.length * 0.75);
if (decodedLen > 8192) {
rtInfo["shell:lastcmd"] = `# command too large (${decodedLen} bytes)`;
globalStore.set(termWrap.lastCommandAtom, rtInfo["shell:lastcmd"]);
} else {
try {
const decodedCmd = base64ToString(cmd.data.cmd64);
rtInfo["shell:lastcmd"] = decodedCmd;
globalStore.set(termWrap.lastCommandAtom, decodedCmd);
checkCommandForTelemetry(decodedCmd);
} catch (e) {
console.error("Error decoding cmd64:", e);
rtInfo["shell:lastcmd"] = null;
globalStore.set(termWrap.lastCommandAtom, null);
}
}
} else {
rtInfo["shell:lastcmd"] = null;
globalStore.set(termWrap.lastCommandAtom, null);
}
// also clear lastcmdexitcode (since we've now started a new command)
rtInfo["shell:lastcmdexitcode"] = null;
break;
case "M":
if (cmd.data.shell) {
rtInfo["shell:type"] = cmd.data.shell;
}
if (cmd.data.shellversion) {
rtInfo["shell:version"] = cmd.data.shellversion;
}
if (cmd.data.uname) {
rtInfo["shell:uname"] = cmd.data.uname;
}
if (cmd.data.integration != null) {
rtInfo["shell:integration"] = cmd.data.integration;
}
break;
case "D":
if (cmd.data.exitcode != null) {
rtInfo["shell:lastcmdexitcode"] = cmd.data.exitcode;
} else {
rtInfo["shell:lastcmdexitcode"] = null;
}
break;
case "I":
if (cmd.data.inputempty != null) {
rtInfo["shell:inputempty"] = cmd.data.inputempty;
}
break;
case "R":
globalStore.set(termWrap.shellIntegrationStatusAtom, null);
if (terminal.buffer.active.type === "alternate") {
terminal.write("\x1b[?1049l");
}
break;
}
if (Object.keys(rtInfo).length > 0) {
setTimeout(() => {
fireAndForget(async () => {
const rtInfoData: CommandSetRTInfoData = {
oref: WOS.makeORef("block", blockId),
data: rtInfo,
};
await RpcApi.SetRTInfoCommand(TabRpcClient, rtInfoData).catch((e) =>
console.log("error setting RT info (OSC 16162)", e)
);
});
}, 0);
}
return true;
}
export class TermWrap {
tabId: string;
blockId: string;
ptyOffset: number;
dataBytesProcessed: number;
terminal: Terminal;
connectElem: HTMLDivElement;
fitAddon: FitAddon;
searchAddon: SearchAddon;
serializeAddon: SerializeAddon;
mainFileSubject: SubjectWithRef<WSFileEventData>;
loaded: boolean;
heldData: Uint8Array[];
handleResize_debounced: () => void;
hasResized: boolean;
multiInputCallback: (data: string) => void;
sendDataHandler: (data: string) => void;
onSearchResultsDidChange?: (result: { resultIndex: number; resultCount: number }) => void;
private toDispose: TermTypes.IDisposable[] = [];
pasteActive: boolean = false;
lastUpdated: number;
promptMarkers: TermTypes.IMarker[] = [];
shellIntegrationStatusAtom: jotai.PrimitiveAtom<"ready" | "running-command" | null>;
lastCommandAtom: jotai.PrimitiveAtom<string | null>;
nodeModel: BlockNodeModel; // this can be null
// IME composition state tracking
// Prevents duplicate input when switching input methods during composition (e.g., using Capslock)
// xterm.js sends data during compositionupdate AND after compositionend, causing duplicates
isComposing: boolean = false;
composingData: string = "";
lastCompositionEnd: number = 0;
lastComposedText: string = "";
firstDataAfterCompositionSent: boolean = false;
// Paste deduplication
// xterm.js paste() method triggers onData event, which can cause duplicate sends
lastPasteData: string = "";
lastPasteTime: number = 0;
constructor(
tabId: string,
blockId: string,
connectElem: HTMLDivElement,
options: TermTypes.ITerminalOptions & TermTypes.ITerminalInitOnlyOptions,
waveOptions: TermWrapOptions
) {
this.loaded = false;
this.tabId = tabId;
this.blockId = blockId;
this.sendDataHandler = waveOptions.sendDataHandler;
this.nodeModel = waveOptions.nodeModel;
this.ptyOffset = 0;
this.dataBytesProcessed = 0;
this.hasResized = false;
this.lastUpdated = Date.now();
this.promptMarkers = [];
this.shellIntegrationStatusAtom = jotai.atom(null) as jotai.PrimitiveAtom<"ready" | "running-command" | null>;
this.lastCommandAtom = jotai.atom(null) as jotai.PrimitiveAtom<string | null>;
this.terminal = new Terminal(options);
this.fitAddon = new FitAddon();
this.fitAddon.noScrollbar = PLATFORM === PlatformMacOS;
this.serializeAddon = new SerializeAddon();
this.searchAddon = new SearchAddon();
this.terminal.loadAddon(this.searchAddon);
this.terminal.loadAddon(this.fitAddon);
this.terminal.loadAddon(this.serializeAddon);
this.terminal.loadAddon(
new WebLinksAddon((e, uri) => {
e.preventDefault();
switch (PLATFORM) {
case PlatformMacOS:
if (e.metaKey) {
fireAndForget(() => openLink(uri));
}
break;
default:
if (e.ctrlKey) {
fireAndForget(() => openLink(uri));
}
break;
}
})
);
if (WebGLSupported && waveOptions.useWebGl) {
const webglAddon = new WebglAddon();
this.toDispose.push(
webglAddon.onContextLoss(() => {
webglAddon.dispose();
})
);
this.terminal.loadAddon(webglAddon);
if (!loggedWebGL) {
console.log("loaded webgl!");
loggedWebGL = true;
}
}
// Register OSC handlers
this.terminal.parser.registerOscHandler(7, (data: string) => {
return handleOsc7Command(data, this.blockId, this.loaded);
});
this.terminal.parser.registerOscHandler(52, (data: string) => {
return handleOsc52Command(data, this.blockId, this.loaded, this);
});
this.terminal.parser.registerOscHandler(16162, (data: string) => {
return handleOsc16162Command(data, this.blockId, this.loaded, this);
});
this.terminal.attachCustomKeyEventHandler(waveOptions.keydownHandler);
this.connectElem = connectElem;
this.mainFileSubject = null;
this.heldData = [];
this.handleResize_debounced = debounce(50, this.handleResize.bind(this));
this.terminal.open(this.connectElem);
this.handleResize();
const pasteHandler = this.pasteHandler.bind(this);
this.connectElem.addEventListener("paste", pasteHandler, true);
this.toDispose.push({
dispose: () => {
this.connectElem.removeEventListener("paste", pasteHandler, true);
},
});
}
resetCompositionState() {
this.isComposing = false;
this.composingData = "";
}
private handleCompositionStart = (e: CompositionEvent) => {
dlog("compositionstart", e.data);
this.isComposing = true;
this.composingData = "";
};
private handleCompositionUpdate = (e: CompositionEvent) => {
dlog("compositionupdate", e.data);
this.composingData = e.data || "";
};
private handleCompositionEnd = (e: CompositionEvent) => {
dlog("compositionend", e.data);
this.isComposing = false;
this.lastComposedText = e.data || "";
this.lastCompositionEnd = Date.now();
this.firstDataAfterCompositionSent = false;
};
async initTerminal() {
const copyOnSelectAtom = getSettingsKeyAtom("term:copyonselect");
this.toDispose.push(this.terminal.onData(this.handleTermData.bind(this)));
this.toDispose.push(this.terminal.onKey(this.onKeyHandler.bind(this)));
this.toDispose.push(
this.terminal.onSelectionChange(
debounce(50, () => {
if (!globalStore.get(copyOnSelectAtom)) {
return;
}
const selectedText = this.terminal.getSelection();
if (selectedText.length > 0) {
navigator.clipboard.writeText(selectedText);
}
})
)
);
if (this.onSearchResultsDidChange != null) {
this.toDispose.push(this.searchAddon.onDidChangeResults(this.onSearchResultsDidChange.bind(this)));
}
// Register IME composition event listeners on the xterm.js textarea
const textareaElem = this.connectElem.querySelector("textarea");
if (textareaElem) {
textareaElem.addEventListener("compositionstart", this.handleCompositionStart);
textareaElem.addEventListener("compositionupdate", this.handleCompositionUpdate);
textareaElem.addEventListener("compositionend", this.handleCompositionEnd);
// Handle blur during composition - reset state to avoid stale data
const blurHandler = () => {
if (this.isComposing) {
dlog("Terminal lost focus during composition, resetting IME state");
this.resetCompositionState();
}
};
textareaElem.addEventListener("blur", blurHandler);
this.toDispose.push({
dispose: () => {
textareaElem.removeEventListener("compositionstart", this.handleCompositionStart);
textareaElem.removeEventListener("compositionupdate", this.handleCompositionUpdate);
textareaElem.removeEventListener("compositionend", this.handleCompositionEnd);
textareaElem.removeEventListener("blur", blurHandler);
},
});
}
this.mainFileSubject = getFileSubject(this.blockId, TermFileName);
this.mainFileSubject.subscribe(this.handleNewFileSubjectData.bind(this));
try {
const rtInfo = await RpcApi.GetRTInfoCommand(TabRpcClient, {
oref: WOS.makeORef("block", this.blockId),
});
if (rtInfo && rtInfo["shell:integration"]) {
const shellState = rtInfo["shell:state"] as ShellIntegrationStatus;
globalStore.set(this.shellIntegrationStatusAtom, shellState || null);
} else {
globalStore.set(this.shellIntegrationStatusAtom, null);
}
const lastCmd = rtInfo ? rtInfo["shell:lastcmd"] : null;
globalStore.set(this.lastCommandAtom, lastCmd || null);
} catch (e) {
console.log("Error loading runtime info:", e);
}
try {
await this.loadInitialTerminalData();
} finally {
this.loaded = true;
}
this.runProcessIdleTimeout();
}
dispose() {
this.promptMarkers.forEach((marker) => {
try {
marker.dispose();
} catch (_) {}
});
this.promptMarkers = [];
this.terminal.dispose();
this.toDispose.forEach((d) => {
try {
d.dispose();
} catch (_) {}
});
this.mainFileSubject.release();
}
handleTermData(data: string) {
if (!this.loaded) {
return;
}
// IME Composition Handling
// Block all data during composition - only send the final text after compositionend
// This prevents xterm.js from sending intermediate composition data (e.g., during compositionupdate)
if (this.isComposing) {
dlog("Blocked data during composition:", data);
return;
}
if (this.pasteActive) {
if (this.multiInputCallback) {
this.multiInputCallback(data);
}
}
// IME Deduplication (for Capslock input method switching)
// When switching input methods with Capslock during composition, some systems send the
// composed text twice. We allow the first send and block subsequent duplicates.
const IMEDedupWindowMs = 50;
const now = Date.now();
const timeSinceCompositionEnd = now - this.lastCompositionEnd;
if (timeSinceCompositionEnd < IMEDedupWindowMs && data === this.lastComposedText && this.lastComposedText) {
if (!this.firstDataAfterCompositionSent) {
// First send after composition - allow it but mark as sent
this.firstDataAfterCompositionSent = true;
dlog("First data after composition, allowing:", data);
} else {
// Second send of the same data - this is a duplicate from Capslock switching, block it
dlog("Blocked duplicate IME data:", data);
this.lastComposedText = ""; // Clear to allow same text to be typed again later
this.firstDataAfterCompositionSent = false;
return;
}
}
this.sendDataHandler?.(data);
}
onKeyHandler(data: { key: string; domEvent: KeyboardEvent }) {
if (this.multiInputCallback) {
this.multiInputCallback(data.key);
}
}
addFocusListener(focusFn: () => void) {
this.terminal.textarea.addEventListener("focus", focusFn);
}
handleNewFileSubjectData(msg: WSFileEventData) {
if (msg.fileop == "truncate") {
this.terminal.clear();
this.heldData = [];
} else if (msg.fileop == "append") {
const decodedData = base64ToArray(msg.data64);
if (this.loaded) {
this.doTerminalWrite(decodedData, null);
} else {
this.heldData.push(decodedData);
}
} else {
console.log("bad fileop for terminal", msg);
return;
}
}
doTerminalWrite(data: string | Uint8Array, setPtyOffset?: number): Promise<void> {
let resolve: () => void = null;
let prtn = new Promise<void>((presolve, _) => {
resolve = presolve;
});
this.terminal.write(data, () => {
if (setPtyOffset != null) {
this.ptyOffset = setPtyOffset;
} else {
this.ptyOffset += data.length;
this.dataBytesProcessed += data.length;
}
this.lastUpdated = Date.now();
resolve();
});
return prtn;
}
async loadInitialTerminalData(): Promise<void> {
let startTs = Date.now();
const { data: cacheData, fileInfo: cacheFile } = await fetchWaveFile(this.blockId, TermCacheFileName);
let ptyOffset = 0;
let loadedFromCache = false;
if (cacheFile != null) {
ptyOffset = cacheFile.meta["ptyoffset"] ?? 0;
if (cacheData.byteLength > 0) {
const curTermSize: TermSize = { rows: this.terminal.rows, cols: this.terminal.cols };
const fileTermSize: TermSize = cacheFile.meta["termsize"];
let didResize = false;
if (
fileTermSize != null &&
(fileTermSize.rows != curTermSize.rows || fileTermSize.cols != curTermSize.cols)
) {
console.log("terminal restore size mismatch, temp resize", fileTermSize, curTermSize);
this.terminal.resize(fileTermSize.cols, fileTermSize.rows);
didResize = true;
}
this.doTerminalWrite(cacheData, ptyOffset);
if (didResize) {
this.terminal.resize(curTermSize.cols, curTermSize.rows);
}
loadedFromCache = true;
}
}
// Only load main file data if we didn't load from cache, or load only NEW data after cache
// The cache contains the fully rendered terminal state, so loading from ptyOffset would duplicate data
const { data: mainData, fileInfo: mainFile } = await fetchWaveFile(
this.blockId,
TermFileName,
loadedFromCache ? ptyOffset : 0
);
console.log(
`terminal loaded cachefile:${cacheData?.byteLength ?? 0} main:${mainData?.byteLength ?? 0} bytes (cached=${loadedFromCache}, offset=${ptyOffset}), ${Date.now() - startTs}ms`
);
// If we loaded from cache, only append new data that arrived after the cache was saved
// If no cache, load all data from the beginning
if (mainFile != null && mainData != null && mainData.byteLength > 0) {
await this.doTerminalWrite(mainData, null);
}
}
async resyncController(reason: string) {
dlog("resync controller", this.blockId, reason);
const rtOpts: RuntimeOpts = { termsize: { rows: this.terminal.rows, cols: this.terminal.cols } };
try {
await RpcApi.ControllerResyncCommand(TabRpcClient, {
tabid: this.tabId,
blockid: this.blockId,
rtopts: rtOpts,
});
} catch (e) {
console.log(`error controller resync (${reason})`, this.blockId, e);
}
}
handleResize() {
const oldRows = this.terminal.rows;
const oldCols = this.terminal.cols;
this.fitAddon.fit();
if (oldRows !== this.terminal.rows || oldCols !== this.terminal.cols) {
const termSize: TermSize = { rows: this.terminal.rows, cols: this.terminal.cols };
const wsCommand: SetBlockTermSizeWSCommand = {
wscommand: "setblocktermsize",
blockid: this.blockId,
termsize: termSize,
};
sendWSCommand(wsCommand);
}
dlog("resize", `${this.terminal.rows}x${this.terminal.cols}`, `${oldRows}x${oldCols}`, this.hasResized);
if (!this.hasResized) {
this.hasResized = true;
this.resyncController("initial resize");
}
}
processAndCacheData() {
if (this.dataBytesProcessed < MinDataProcessedForCache) {
return;
}
const serializedOutput = this.serializeAddon.serialize();
const termSize: TermSize = { rows: this.terminal.rows, cols: this.terminal.cols };
console.log("idle timeout term", this.dataBytesProcessed, serializedOutput.length, termSize);
fireAndForget(() =>
services.BlockService.SaveTerminalState(this.blockId, serializedOutput, "full", this.ptyOffset, termSize)
);
this.dataBytesProcessed = 0;
}
runProcessIdleTimeout() {
setTimeout(() => {
window.requestIdleCallback(() => {
this.processAndCacheData();
this.runProcessIdleTimeout();
});
}, 5000);
}
async pasteHandler(e?: ClipboardEvent): Promise<void> {
this.pasteActive = true;
e?.preventDefault();
e?.stopPropagation();
try {
const clipboardData = await extractAllClipboardData(e);
let firstImage = true;
for (const data of clipboardData) {
if (data.image && SupportsImageInput) {
if (!firstImage) {
await new Promise((r) => setTimeout(r, 150));
}
const tempPath = await createTempFileFromBlob(data.image);
this.terminal.paste(tempPath + " ");
firstImage = false;
}
if (data.text) {
this.terminal.paste(data.text);
}
}
} catch (err) {
console.error("Paste error:", err);
} finally {
setTimeout(() => {
this.pasteActive = false;
}, 30);
}
}
}