-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAblyCliTerminal.tsx
More file actions
3843 lines (3427 loc) · 131 KB
/
AblyCliTerminal.tsx
File metadata and controls
3843 lines (3427 loc) · 131 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 React, {
useEffect,
useRef,
useState,
useCallback,
useImperativeHandle,
forwardRef,
} from "react";
import { Terminal } from "@xterm/xterm";
import { FitAddon } from "@xterm/addon-fit";
import "@xterm/xterm/css/xterm.css";
import TerminalOverlay, { OverlayVariant } from "./TerminalOverlay";
import {
drawBox,
clearBox,
updateLine,
colour as boxColour,
colour,
type TerminalBox,
} from "./terminal-box";
import {
getAttempts as grGetAttempts,
getMaxAttempts as grGetMaxAttempts,
isCancelledState as grIsCancelledState,
isMaxAttemptsReached as grIsMaxAttemptsReached,
resetState as grResetState,
cancelReconnect as grCancelReconnect,
scheduleReconnect as grScheduleReconnect,
setCountdownCallback as grSetCountdownCallback,
setMaxAttempts as grSetMaxAttempts,
successfulConnectionReset as grSuccessfulConnectionReset,
increment as grIncrement,
} from "./global-reconnect";
import { useTerminalVisibility } from "./use-terminal-visibility.js";
import { SplitSquareHorizontal, X } from "lucide-react";
import { hashCredentials } from "./utils/crypto";
import { getConnectionMessage } from "./connection-messages";
import {
HandshakeFilterState,
createHandshakeFilterState,
filterDockerHandshake,
createTerminal,
createFitAddon,
safeFit,
createAuthPayload,
parseControlMessage,
messageDataToUint8Array,
clearConnectingMessage,
showConnectingMessage,
debugLog as sharedDebugLog,
CONTROL_MESSAGE_PREFIX,
MAX_PTY_BUFFER_LENGTH,
TERMINAL_PROMPT_PATTERN,
} from "./terminal-shared";
/**
* Simple debounce utility function to prevent rapid successive calls
*/
function debounce<T extends (...arguments_: any[]) => any>(
function_: T,
wait: number,
): (...arguments_: Parameters<T>) => void {
let timeout: ReturnType<typeof setTimeout> | null = null;
return function (...arguments_: Parameters<T>): void {
if (timeout !== null) {
clearTimeout(timeout);
}
timeout = setTimeout(() => {
function_(...arguments_);
timeout = null;
}, wait);
};
}
export type ConnectionStatus =
| "initial"
| "connecting"
| "connected"
| "disconnected"
| "reconnecting"
| "error";
// Prompts that indicate the terminal is ready for input
const TERMINAL_PROMPT_IDENTIFIER = "ably> "; // Basic prompt
// Shared CLI installation tip
const CLI_INSTALL_TIP = {
lines: [
"Pro tip: Want full control and speed? Install the CLI locally",
" $ npm install -g @ably/cli",
],
};
export interface AblyCliTerminalProperties {
websocketUrl: string;
ablyAccessToken?: string;
ablyApiKey?: string;
initialCommand?: string;
onConnectionStatusChange?: (status: ConnectionStatus) => void;
onSessionEnd?: (reason: string) => void;
/**
* Called once when the server sends the initial "hello" message containing the sessionId.
* This is useful for embedding apps that want to display or persist the current session.
*/
onSessionId?: (sessionId: string) => void;
/**
* When true, the component stores the current sessionId in localStorage on
* page unload and attempts to resume that session on the next mount.
*/
resumeOnReload?: boolean;
maxReconnectAttempts?: number;
/**
* CI authentication token for bypassing rate limits in tests
*/
ciAuthToken?: string;
/**
* When true, enables split-screen mode with a second independent terminal.
* A split icon will be displayed in the top-right corner when in single-pane mode.
*/
enableSplitScreen?: boolean;
/**
* When true (default), shows the internal split control button.
* Set to false when controlling split externally to hide the internal UI affordance.
*/
showSplitControl?: boolean;
/**
* An optional value to set as the ABLY_ENDPOINT environment variable when
* starting the CLI, which controls which endpoint the SDK client uses.
*
* For example, to start the CLI configured to use the sandbox cluster, set
* ablyEndpoint to 'nonprod:sandbox'.
*
* When unset, the CLI will use the main production endpoint.
*
* See https://sdk.ably.com/builds/ably/specification/main/features/#endpoint-configuration
*/
ablyEndpoint?: string;
/**
* An optional value to set as the ABLY_CONTROL_HOST environment variable
* when starting the CLI, which controls which hostname the CLI uses to
* connect to the Control API.
*
* For example, to start the CLI configured to use the staging Control API,
* set ablyControlHost to 'staging-control.ably-dev.net'.
*
* When unset, the CLI uses the production Control API at control.ably.net.
*/
ablyControlHost?: string;
}
export interface AblyCliTerminalHandle {
/** Enable split-screen mode programmatically. No-op if split-screen is disabled by props. */
enableSplitScreen: () => void;
/** Disable split-screen mode programmatically (closes secondary terminal). */
disableSplitScreen: () => void;
/** Toggle split-screen mode. */
toggleSplitScreen: () => void;
/** Set split position as a percentage (0-100). Values are clamped. */
setSplitPosition: (percent: number) => void;
/** Read current split state. */
getSplitState: () => { isSplit: boolean; splitPosition: number };
}
// Use shared debug logging
const debugLog = sharedDebugLog;
// Automatically enable debug logging if ?cliDebug=true is present in the URL
if (globalThis.window !== undefined) {
try {
const urlFlag = new URLSearchParams(globalThis.location.search).get(
"cliDebug",
);
if (urlFlag === "true") {
(globalThis as any).ABLY_CLI_DEBUG = true;
}
} catch {
/* ignore URL parsing errors in non-browser env */
}
}
// Import isHijackMetaChunk from shared module for backward compatibility
import { isHijackMetaChunk } from "./terminal-shared";
const AblyCliTerminalInner = (
{
websocketUrl,
ablyAccessToken,
ablyApiKey,
initialCommand,
onConnectionStatusChange,
onSessionEnd,
onSessionId,
resumeOnReload,
maxReconnectAttempts,
enableSplitScreen = false,
showSplitControl = true,
ablyEndpoint,
ablyControlHost,
}: AblyCliTerminalProperties,
reference: React.Ref<AblyCliTerminalHandle>,
) => {
const [componentConnectionStatus, setComponentConnectionStatusState] =
useState<ConnectionStatus>("initial");
const [isSessionActive, setIsSessionActive] = useState(false);
const [connectionHelpMessage, setConnectionHelpMessage] = useState("");
const [reconnectAttemptMessage, setReconnectAttemptMessage] = useState("");
const [countdownMessage, setCountdownMessage] = useState("");
const [overlay, setOverlay] = useState<null | {
variant: OverlayVariant;
title: string;
lines: string[];
drawer?: { lines: string[] };
}>(null);
const [connectionStartTime, setConnectionStartTime] = useState<number | null>(
null,
);
const [showInstallInstructions, setShowInstallInstructions] = useState(false);
// -------------------------------------------------------------
// Split-screen UI state
// -------------------------------------------------------------
/**
* `isSplit` controls whether the UI is currently displaying a secondary pane.
* We now initialize a second terminal session when this is enabled.
*/
const [isSplit, setIsSplit] = useState<boolean>(() => {
if (
resumeOnReload &&
globalThis.window !== undefined &&
enableSplitScreen
) {
return globalThis.sessionStorage.getItem("ably.cli.isSplit") === "true";
}
return false;
});
/**
* `splitPosition` controls the relative width of the left pane as a percentage (0-100)
*/
const [splitPosition, setSplitPosition] = useState<number>(() => {
if (
resumeOnReload &&
globalThis.window !== undefined &&
enableSplitScreen
) {
const saved = globalThis.sessionStorage.getItem("ably.cli.splitPosition");
return saved ? Number.parseFloat(saved) : 50; // Default to 50% if not found
}
return 50; // Default to 50% split
});
// Track whether we're currently dragging the divider
const [isDragging, setIsDragging] = useState(false);
// Ref to the outer container for calculating percentages
const outerContainerReference = useRef<HTMLDivElement>(null);
// Updated handler to initialize the secondary terminal
const handleSplitScreenWithSecondTerminal = useCallback(() => {
// First update the UI state
setIsSplit(true);
// Save split state to session storage if resume enabled
if (resumeOnReload && globalThis.window !== undefined) {
globalThis.sessionStorage.setItem("ably.cli.isSplit", "true");
}
// Secondary terminal will be initialized in useEffect that watches isSplit
}, [resumeOnReload]);
/** Toggle into split-screen mode with terminal session */
const handleSplitScreen = useCallback(() => {
// We now use the handler that will initialize a second terminal session
handleSplitScreenWithSecondTerminal();
}, [handleSplitScreenWithSecondTerminal]);
/** Close both terminals and reset the split */
const handleCloseSplit = useCallback(() => {
// When closing the split, clean up the secondary terminal
if (
secondarySocketReference.current &&
secondarySocketReference.current.readyState < WebSocket.CLOSING
) {
secondarySocketReference.current.close();
secondarySocketReference.current = null;
}
if (secondaryTerm.current) {
secondaryTerm.current.dispose();
secondaryTerm.current = null;
}
// Reset secondary terminal state
updateSecondaryConnectionStatus("initial");
setIsSecondarySessionActive(false);
setSecondaryShowManualReconnectPrompt(false);
setSecondarySessionId(null);
setSecondaryOverlay(null);
// Return to single-pane mode
setIsSplit(false);
// Clear split state in session storage
if (resumeOnReload && globalThis.window !== undefined) {
globalThis.sessionStorage.removeItem("ably.cli.isSplit");
globalThis.sessionStorage.removeItem("ably.cli.secondarySessionId");
}
// Resize the primary terminal after a delay
setTimeout(() => {
if (term.current && fitAddon.current) {
try {
fitAddon.current.fit();
} catch (error) {
console.warn(
"Error fitting primary terminal after closing split:",
error,
);
}
}
}, 50);
}, []);
// Imperative handle for external control of split operations
useImperativeHandle(
reference,
() => ({
enableSplitScreen: () => {
if (!enableSplitScreen) {
console.warn(
"[AblyCLITerminal] enableSplitScreen prop is false; cannot enable split.",
);
return;
}
if (!isSplit) {
handleSplitScreenWithSecondTerminal();
}
},
disableSplitScreen: () => {
if (isSplit) {
handleCloseSplit();
}
},
toggleSplitScreen: () => {
if (!enableSplitScreen) {
console.warn(
"[AblyCLITerminal] enableSplitScreen prop is false; cannot toggle split.",
);
return;
}
if (isSplit) {
handleCloseSplit();
} else {
handleSplitScreenWithSecondTerminal();
}
},
setSplitPosition: (percent: number) => {
const clamped = Math.max(0, Math.min(100, Number(percent)));
setSplitPosition(clamped);
},
getSplitState: () => ({ isSplit, splitPosition }),
}),
[
enableSplitScreen,
handleSplitScreenWithSecondTerminal,
handleCloseSplit,
isSplit,
splitPosition,
],
);
/** Handle clicking Close on Terminal 1 (primary) */
const handleClosePrimary = useCallback(() => {
// When closing the primary terminal but keeping the secondary one,
// make sure the secondary terminal is properly displayed
if (secondaryTerm.current && secondarySocketReference.current) {
debugLog("[AblyCLITerminal] Closing primary terminal, keeping secondary");
// Close the primary socket cleanly
if (
socketReference.current &&
socketReference.current.readyState < WebSocket.CLOSING
) {
debugLog("[AblyCLITerminal] Closing primary socket");
socketReference.current.close(1000, "user-closed-primary");
socketReference.current = null;
}
// Store the secondary values before reset
const temporarySocket = secondarySocketReference.current;
const temporaryTerm = secondaryTerm.current;
const temporaryFitAddon = secondaryFitAddon.current;
const temporarySessionId = secondarySessionId;
const temporaryIsActive = isSecondarySessionActive;
// Dispose the primary terminal if it exists
if (term.current) {
term.current.dispose();
term.current = null;
}
// Clear the secondary terminal's state AFTER saving references
secondarySocketReference.current = null;
secondaryTerm.current = null;
secondaryFitAddon.current = undefined;
// Ensure we properly transfer the DOM element
// This is critical - we need to move the secondary terminal's
// DOM element to the primary terminal's container
if (
rootReference.current &&
temporaryTerm &&
secondaryRootReference.current
) {
// Get the xterm DOM element from the secondary container
const xtermElement =
secondaryRootReference.current.querySelector(".xterm");
if (xtermElement) {
// Clear the primary container
while (rootReference.current.firstChild) {
rootReference.current.firstChild.remove();
}
// Move the xterm element to the primary container
rootReference.current.append(xtermElement);
debugLog(
"[AblyCLITerminal] Moved secondary terminal DOM element to primary container",
);
}
}
// Swap references
term.current = temporaryTerm;
fitAddon.current = temporaryFitAddon;
socketReference.current = temporarySocket;
// Update state
setIsSplit(false);
setSessionId(temporarySessionId);
updateSessionActive(temporaryIsActive);
// Reset secondary terminal state
updateSecondaryConnectionStatus("initial");
setIsSecondarySessionActive(false);
setSecondaryShowManualReconnectPrompt(false);
setSecondarySessionId(null);
setSecondaryOverlay(null);
// Clear split state in session storage
if (resumeOnReload && globalThis.window !== undefined) {
globalThis.sessionStorage.removeItem("ably.cli.isSplit");
globalThis.sessionStorage.removeItem("ably.cli.secondarySessionId");
}
// Resize the terminal after a delay
setTimeout(() => {
if (term.current && fitAddon.current) {
try {
fitAddon.current.fit();
} catch (error) {
console.warn(
"Error fitting terminal after closing primary:",
error,
);
}
}
}, 50);
} else {
// If there's no secondary terminal, just close everything (same as handleCloseSplit)
handleCloseSplit();
}
}, [handleCloseSplit, resumeOnReload]);
/** Close the secondary pane and return to single-pane mode */
const handleCloseSecondary = useCallback(() => {
// When closing the secondary terminal, clean it up but keep the primary one
if (
secondarySocketReference.current &&
secondarySocketReference.current.readyState < WebSocket.CLOSING
) {
debugLog("[AblyCLITerminal] Closing secondary socket");
secondarySocketReference.current.close(1000, "user-closed-secondary");
secondarySocketReference.current = null;
}
if (secondaryTerm.current) {
secondaryTerm.current.dispose();
secondaryTerm.current = null;
}
// Reset secondary terminal state
updateSecondaryConnectionStatus("initial");
setIsSecondarySessionActive(false);
setSecondaryShowManualReconnectPrompt(false);
setSecondarySessionId(null);
setSecondaryOverlay(null);
// Return to single-pane mode
setIsSplit(false);
// Clear split state in session storage
if (resumeOnReload && globalThis.window !== undefined) {
globalThis.sessionStorage.removeItem("ably.cli.isSplit");
globalThis.sessionStorage.removeItem("ably.cli.secondarySessionId");
}
// Resize the primary terminal after a delay
setTimeout(() => {
if (term.current && fitAddon.current) {
try {
fitAddon.current.fit();
} catch (error) {
console.warn(
"Error fitting primary terminal after closing split:",
error,
);
}
}
}, 50);
}, [resumeOnReload]);
// Track the current sessionId received from the server (if any)
const [sessionId, setSessionId] = useState<string | null>(null);
const [credentialHash, setCredentialHash] = useState<string | null>(null);
const [credentialsInitialized, setCredentialsInitialized] = useState(false);
const [sessionIdInitialized, setSessionIdInitialized] = useState(false);
// Track the second terminal's sessionId
const [secondarySessionId, setSecondarySessionId] = useState<string | null>(
() => {
if (
resumeOnReload &&
globalThis.window !== undefined &&
globalThis.sessionStorage.getItem("ably.cli.isSplit") === "true"
) {
return globalThis.sessionStorage.getItem("ably.cli.secondarySessionId");
}
return null;
},
);
const [socket, setSocket] = useState<WebSocket | null>(null);
const [showManualReconnectPrompt, setShowManualReconnectPrompt] =
useState(false);
const rootReference = useRef<HTMLDivElement>(null);
// Determine if terminal is visible (drawer open & tab visible)
const isVisible = useTerminalVisibility(rootReference);
const term = useRef<Terminal | null>(null);
const fitAddon = useRef<FitAddon>();
const ptyBuffer = useRef("");
const handshakeFilterState = useRef<HandshakeFilterState>(
createHandshakeFilterState(),
);
// Keep a ref in sync with the latest connection status so event handlers have up-to-date value
const connectionStatusReference = useRef<ConnectionStatus>("initial");
// Store cleanup function for terminal resize handler
const termCleanupReference = useRef<() => void>(() => {});
// Ref to track manual reconnect prompt visibility inside stable event handlers
const showManualReconnectPromptReference = useRef<boolean>(false);
// Guard to ensure we do NOT double-count a failed attempt when both the
// `error` and the subsequent `close` events fire for the *same* socket.
const reconnectScheduledThisCycleReference = useRef<boolean>(false);
// Keep a ref in sync with session active state for use in closures
const isSessionActiveReference = useRef<boolean>(false);
// Keep a ref for sessionId to use in closures
const sessionIdReference = useRef<string | null>(sessionId);
// Use block-based spinner where empty dots are invisible in most monospace fonts
const spinnerFrames = ["● ", " ● ", " ●", " ● "];
const spinnerIntervalReference = useRef<ReturnType<
typeof setInterval
> | null>(null);
const spinnerIndexReference = useRef<number>(0);
const spinnerPrefixReference = useRef<string>("");
const statusBoxReference = useRef<TerminalBox | null>(null);
// ANSI colour / style helpers
const colour = {
reset: "\u001B[0m",
bold: "\u001B[1m",
dim: "\u001B[2m",
red: "\u001B[31m",
green: "\u001B[32m",
yellow: "\u001B[33m",
blue: "\u001B[34m",
magenta: "\u001B[35m",
cyan: "\u001B[36m",
} as const;
const clearStatusDisplay = useCallback(() => {
if (spinnerIntervalReference.current) {
clearInterval(spinnerIntervalReference.current);
spinnerIntervalReference.current = null;
}
spinnerIndexReference.current = 0;
if (statusBoxReference.current && term.current) {
clearBox(statusBoxReference.current);
statusBoxReference.current = null;
/* status box cleared */
}
setOverlay(null);
/* clearStatusDisplay completed */
}, []);
/**
* Clears spinner interval and the xterm drawn box **without** touching the React overlay.
* Useful when we want the overlay to persist between automatic reconnect attempts.
*/
const clearTerminalBoxOnly = useCallback(() => {
// Intentionally keep the spinner interval running so the overlay continues
// to animate between failed attempts. Only the ANSI/xterm box is cleared.
if (statusBoxReference.current && term.current) {
clearBox(statusBoxReference.current);
statusBoxReference.current = null;
/* Terminal box cleared (overlay retained) */
}
}, []);
// Keep the ref in sync with React state so key handlers can rely on it
useEffect(() => {
showManualReconnectPromptReference.current = showManualReconnectPrompt;
}, [showManualReconnectPrompt]);
const updateConnectionStatusAndExpose = useCallback(
(status: ConnectionStatus) => {
// updateConnectionStatusAndExpose debug removed
setComponentConnectionStatusState(status);
// (window as any).componentConnectionStatusForTest = status; // Keep for direct inspection if needed, but primary is below
// console.log(`[AblyCLITerminal] (window as any).componentConnectionStatusForTest SET TO: ${status}`);
connectionStatusReference.current = status;
// Only report status changes from the primary terminal
if (
typeof (globalThis as any).setWindowTestFlagOnStatusChange ===
"function"
) {
(globalThis as any).setWindowTestFlagOnStatusChange(status);
}
if (onConnectionStatusChange) {
onConnectionStatusChange(status);
}
},
[onConnectionStatusChange],
);
useEffect(() => {
connectionStatusReference.current = componentConnectionStatus;
}, [componentConnectionStatus]);
useEffect(() => {
if (isSessionActive) {
setConnectionHelpMessage("Connected to Ably CLI terminal server");
} else {
setConnectionHelpMessage(""); // Clear help message when not active
}
}, [isSessionActive]);
// Keep sessionId ref in sync
useEffect(() => {
sessionIdReference.current = sessionId;
}, [sessionId]);
const clearPtyBuffer = useCallback(() => {
debugLog(
`⚠️ DIAGNOSTIC: Clearing PTY buffer, current size: ${ptyBuffer.current.length}`,
);
if (ptyBuffer.current.length > 0) {
const sanitizedBuffer = ptyBuffer.current
.replaceAll("\r", "\\r")
.replaceAll("\n", "\\n")
.slice(-100); // Only show last 100 chars to avoid log bloat
debugLog(
`⚠️ DIAGNOSTIC: Buffer content before clear: "${sanitizedBuffer}"`,
);
}
ptyBuffer.current = "";
}, []);
// Helper to update both session active state and ref
const updateSessionActive = useCallback((active: boolean) => {
debugLog(`⚠️ DIAGNOSTIC: Updating session active to: ${active}`);
setIsSessionActive(active);
isSessionActiveReference.current = active;
}, []);
// Connection timeout management
const connectionTimeoutReference = useRef<NodeJS.Timeout | null>(null);
const CONNECTION_TIMEOUT_MS = 30_000; // 30 seconds
const installInstructionsTimerReference = useRef<NodeJS.Timeout | null>(null);
const SHOW_INSTALL_AFTER_MS = 6000; // 6 seconds
const clearConnectionTimeout = useCallback(() => {
if (connectionTimeoutReference.current) {
clearTimeout(connectionTimeoutReference.current);
connectionTimeoutReference.current = null;
}
}, []);
const clearInstallInstructionsTimer = useCallback(() => {
if (installInstructionsTimerReference.current) {
clearTimeout(installInstructionsTimerReference.current);
installInstructionsTimerReference.current = null;
}
}, []);
// Ref to track if we should send initial command when prompt is detected
const pendingInitialCommandReference = useRef<string | null>(null);
// Timeout reference for prompt detection fallback
const promptDetectionTimeoutReference = useRef<NodeJS.Timeout | null>(null);
const PROMPT_DETECTION_TIMEOUT_MS = 5000; // 5 seconds
const clearPromptDetectionTimeout = useCallback(() => {
if (promptDetectionTimeoutReference.current) {
clearTimeout(promptDetectionTimeoutReference.current);
promptDetectionTimeoutReference.current = null;
}
}, []);
// Shared logic for activating session (called by both prompt detection and timeout)
const activateSessionAndSendCommand = useCallback(() => {
updateSessionActive(true);
grSuccessfulConnectionReset();
updateConnectionStatusAndExpose("connected");
if (term.current) {
debugLog(`⚠️ DIAGNOSTIC: Session is now active, focusing terminal`);
term.current.focus();
}
// Reset connection tracking
setConnectionStartTime(null);
setShowInstallInstructions(false);
clearInstallInstructionsTimer();
clearPromptDetectionTimeout();
// Send initial command if one is pending
if (pendingInitialCommandReference.current) {
const commandToSend = pendingInitialCommandReference.current;
pendingInitialCommandReference.current = null;
debugLog(
`⚠️ DIAGNOSTIC: Sending pending initial command: "${commandToSend}"`,
);
setTimeout(() => {
if (
socketReference.current &&
socketReference.current.readyState === WebSocket.OPEN
) {
socketReference.current.send(`${commandToSend}\r`);
}
}, 100);
}
}, [
updateSessionActive,
updateConnectionStatusAndExpose,
clearInstallInstructionsTimer,
clearPromptDetectionTimeout,
]);
const handlePtyData = useCallback(
(data: string) => {
// Always log what data we receive
const sanitizedData = data
.replaceAll("\r", "\\r")
.replaceAll("\n", "\\n")
.replaceAll("\t", "\\t");
debugLog(
`⚠️ DIAGNOSTIC: handlePtyData called. isSessionActive: ${isSessionActiveReference.current}, data: "${sanitizedData}"`,
);
if (!isSessionActiveReference.current) {
ptyBuffer.current += data;
debugLog(
`⚠️ DIAGNOSTIC: Received PTY data (session inactive): "${sanitizedData}"`,
);
debugLog(
`⚠️ DIAGNOSTIC: Current connection status: ${connectionStatusReference.current}, sessionId: ${sessionIdReference.current}`,
);
if (ptyBuffer.current.length > MAX_PTY_BUFFER_LENGTH) {
ptyBuffer.current = ptyBuffer.current.slice(
ptyBuffer.current.length - MAX_PTY_BUFFER_LENGTH,
);
}
// Strip ANSI colour/formatting codes before looking for the prompt
const cleanBuf = ptyBuffer.current.replaceAll(
/\u001B\[[0-9;]*[mGKHF]/g,
"",
);
debugLog(
`⚠️ DIAGNOSTIC: Clean buffer (${cleanBuf.length} chars): "${cleanBuf.slice(-50)}"`,
);
// Only detect the prompt if it appears at the end of the buffer,
// not somewhere in the middle of previous output
// Also check for common Ably CLI prompts
const hasShellPrompt = TERMINAL_PROMPT_PATTERN.test(cleanBuf);
const hasAblyPrompt =
cleanBuf.endsWith("ably> ") ||
cleanBuf.endsWith("> ") ||
cleanBuf.endsWith("$ ");
debugLog(
`⚠️ DIAGNOSTIC: Checking for prompt. hasShellPrompt: ${hasShellPrompt}, hasAblyPrompt: ${hasAblyPrompt}, buffer end: "${cleanBuf.slice(-20)}"`,
);
if (hasShellPrompt || hasAblyPrompt) {
debugLog(
`⚠️ DIAGNOSTIC: Prompt detected at end of buffer (shell: ${hasShellPrompt}, ably: ${hasAblyPrompt})`,
);
clearStatusDisplay(); // Clear the status box as per plan
// Only set active if not already active to prevent multiple state updates
if (!isSessionActiveReference.current) {
activateSessionAndSendCommand();
}
clearPtyBuffer();
}
} else {
debugLog(`⚠️ DIAGNOSTIC: Session already active, not buffering data`);
}
},
[
updateConnectionStatusAndExpose,
updateSessionActive,
clearPtyBuffer,
clearStatusDisplay,
clearInstallInstructionsTimer,
activateSessionAndSendCommand,
],
);
// Secondary terminal instance references
const secondaryRootReference = useRef<HTMLDivElement>(null);
const secondaryTerm = useRef<Terminal | null>(null);
const secondaryFitAddon = useRef<FitAddon>();
const secondarySocketReference = useRef<WebSocket | null>(null);
const secondaryPtyBuffer = useRef("");
const secondaryHandshakeFilterState = useRef<HandshakeFilterState>(
createHandshakeFilterState(),
);
const secondaryTermCleanupReference = useRef<() => void>(() => {});
// Secondary terminal state
const [secondarySocket, setSecondarySocket] = useState<WebSocket | null>(
null,
);
const [isSecondarySessionActive, setIsSecondarySessionActive] =
useState(false);
const [secondaryOverlay, setSecondaryOverlay] = useState<null | {
variant: OverlayVariant;
title: string;
lines: string[];
}>(null);
// Secondary terminal refs - need their own copies for event handlers
const secondaryConnectionStatusReference =
useRef<ConnectionStatus>("initial");
const [secondaryConnectionStatus, setSecondaryConnectionStatus] =
useState<ConnectionStatus>("initial");
const secondarySpinnerPrefixReference = useRef<string>("");
const secondarySpinnerIndexReference = useRef<number>(0);
const secondaryStatusBoxReference = useRef<TerminalBox | null>(null);
const secondarySpinnerIntervalReference = useRef<ReturnType<
typeof setInterval
> | null>(null);
const secondaryShowManualReconnectPromptReference = useRef<boolean>(false);
const [
secondaryShowManualReconnectPrompt,
setSecondaryShowManualReconnectPrompt,
] = useState(false);
const secondaryReconnectScheduledThisCycleReference = useRef<boolean>(false);
// Secondary terminal: pending initial command and timeout refs
const pendingSecondaryInitialCommandReference = useRef<string | null>(null);
const secondaryPromptDetectionTimeoutReference =
useRef<NodeJS.Timeout | null>(null);
// Extracted control message handler to avoid duplication
const handleControlMessage = useCallback(
(message: any) => {
if (message.type === "hello" && typeof message.sessionId === "string") {
debugLog(
`⚠️ DIAGNOSTIC: Received hello message with sessionId=${message.sessionId}`,
);
const wasReconnecting =
connectionStatusReference.current === "reconnecting";
const wasConnecting =
connectionStatusReference.current === "connecting";
setSessionId(message.sessionId);
if (onSessionId) onSessionId(message.sessionId);
debugLog(
"Received hello. sessionId=",
message.sessionId,
" (was:",
sessionId,
")",
);
// Clear the "Connecting..." message and status box
if (term.current) {
clearConnectingMessage(term.current);
term.current.focus();
}
// Clear the status box
clearStatusDisplay();
// Check if this is a resumed session (we sent a sessionId in auth payload)
const isResumedSession =
sessionId !== null && sessionId === message.sessionId;
if (isResumedSession) {
// For resumed sessions, activate immediately without waiting for prompt
debugLog(
`⚠️ DIAGNOSTIC: Resumed existing session ${message.sessionId} - activating immediately`,
);
updateConnectionStatusAndExpose("connected");
// Activate session immediately for resumed sessions
if (!isSessionActiveReference.current) {
activateSessionAndSendCommand();
}
} else {
// For new sessions, wait for prompt detection
debugLog(
`⚠️ DIAGNOSTIC: New session ${message.sessionId} - waiting for prompt before activating`,
);
updateConnectionStatusAndExpose("connected");
}
// Don't clear the buffer yet - let prompt detection handle it (for new sessions)
// Persist to session storage if enabled (domain-scoped)
if (resumeOnReload && globalThis.window !== undefined) {
const urlDomain = new URL(websocketUrl).host;
globalThis.sessionStorage.setItem(
`ably.cli.sessionId.${urlDomain}`,
message.sessionId,
);
// Store credential hash if it's already computed
if (credentialHash) {
globalThis.sessionStorage.setItem(
`ably.cli.credentialHash.${urlDomain}`,
credentialHash,
);
}
}
return;
}
if (message.type === "status") {
debugLog(
`⚠️ DIAGNOSTIC: Received server status message: ${message.payload}`,
);
// Handle different status payloads
if (message.payload === "connected") {
debugLog(`⚠️ DIAGNOSTIC: Handling 'connected' status message`);
clearStatusDisplay();
// Clear the "Connecting..." message
if (term.current) {
debugLog(
`⚠️ DIAGNOSTIC: Clearing connecting message and focusing terminal`,
);
clearConnectingMessage(term.current);
term.current.focus();
}
// Check if we're resuming an existing session
const isResuming = sessionIdReference.current !== null;
if (isResuming) {
// For resumed sessions, activate immediately
debugLog(
`⚠️ DIAGNOSTIC: Resuming session ${sessionIdReference.current} - activating immediately`,
);
updateConnectionStatusAndExpose("connected");
if (!isSessionActiveReference.current) {
activateSessionAndSendCommand();
}
} else {
// For new sessions, wait for prompt detection
debugLog(
`⚠️ DIAGNOSTIC: New session - waiting for prompt before activating`,
);