-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathTerminal.tsx
More file actions
386 lines (324 loc) · 12.9 KB
/
Copy pathTerminal.tsx
File metadata and controls
386 lines (324 loc) · 12.9 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
import { useEffect, useRef, useState, useCallback } from 'react';
// material-ui
import Box from '@mui/material/Box';
import CircularProgress from '@mui/material/CircularProgress';
// xterm
import { Terminal } from '@xterm/xterm';
import { FitAddon } from '@xterm/addon-fit';
import { CanvasAddon } from '@xterm/addon-canvas';
import { WebglAddon } from '@xterm/addon-webgl';
import { WebLinksAddon } from '@xterm/addon-web-links';
import { debounce } from '@/utils/debounce';
// project import
import { ExecClient } from '@omniviewdev/runtime/api';
import { SessionOptions } from '@omniviewdev/runtime/models';
import log from '@/features/logger';
import { bottomDrawerChannel } from '../events';
import { Events } from '@omniviewdev/runtime/runtime';
import { Base64 } from 'js-base64';
import { useSettings, parseAppError } from '@omniviewdev/runtime';
import type { BottomDrawerTab } from '@omniviewdev/runtime';
import TerminalError, { type TerminalErrorInfo } from './TerminalError';
import { getTerminalTheme } from './terminalThemes';
type Props = {
/** The session ID */
sessionId: string;
/** The full tab object (used for retry metadata) */
tab?: BottomDrawerTab;
};
const constructSignalHandler = (signal: string, sessionId: string) => {
return `core/exec/signal/${signal}/${sessionId}`;
};
/**
* Terminal view attaches to an existing terminal session and displays the output, as well as
* allows the user to input commands. This component is used in the terminal tab of the lower
* context area.
*/
export default function TerminalContainer({ sessionId, tab }: Props) {
const { settings } = useSettings();
const tabStatus = tab?.properties?.status as string | undefined;
const settingsThemeBg = getTerminalTheme((settings['terminal.theme'] as string) || 'default').background ?? '#1e1e1e';
// Show loading state while session is being created
if (tabStatus === 'connecting') {
return (
<Box sx={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
height: '100%',
width: '100%',
bgcolor: settingsThemeBg,
gap: 1.5,
}}>
<CircularProgress size={24} sx={{ color: 'grey.500' }} />
<Box sx={{ color: 'grey.500', fontSize: 13, fontFamily: 'monospace' }}>
Connecting...
</Box>
</Box>
);
}
// Show error state if session creation failed
if (tabStatus === 'error') {
const errorMsg = tab?.properties?.error as string | undefined;
return (
<Box sx={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
height: '100%',
width: '100%',
bgcolor: settingsThemeBg,
gap: 1,
}}>
<Box sx={{ color: 'error.main', fontSize: 14, fontFamily: 'monospace', fontWeight: 600 }}>
Connection Failed
</Box>
{errorMsg && (
<Box sx={{ color: 'grey.500', fontSize: 12, fontFamily: 'monospace', maxWidth: 500, textAlign: 'center', px: 2 }}>
{errorMsg}
</Box>
)}
</Box>
);
}
const terminalRef = useRef<HTMLDivElement>(null);
const disposers = useRef<Array<() => void>>([]);
const xtermRef = useRef<Terminal | undefined>(undefined);
const fitAddonRef = useRef<FitAddon | undefined>(undefined);
const canvasAddonRef = useRef<CanvasAddon | undefined>(undefined);
const webglAddonRef = useRef<WebglAddon | undefined>(undefined);
// Error state (set by structured ERROR signal from plugin)
const errorRef = useRef<TerminalErrorInfo | null>(null);
const [error, setError] = useState<TerminalErrorInfo | null>(null);
const textDecoder = new TextDecoder();
const handleFit = () => {
if (fitAddonRef.current !== undefined) {
fitAddonRef.current.fit();
}
};
const handleRetry = useCallback((command: string[]) => {
const props = tab?.properties as Record<string, any> | undefined;
if (!props?.pluginID || !props?.connectionID) {
return;
}
// Build session opts from stored tab properties, overriding command
const opts = SessionOptions.createFrom({
tty: true,
...((props.opts ?? {}) as Record<string, unknown>),
command,
});
bottomDrawerChannel.emit('onCreateSession', {
plugin: props.pluginID as string,
connection: props.connectionID as string,
opts,
label: tab?.title,
});
// Close the errored tab
bottomDrawerChannel.emit('onSessionClosed', { id: sessionId });
}, [tab, sessionId]);
// Keep a ref to the latest settings so the session-lifecycle effect can
// read current values without re-running when settings change.
const settingsRef = useRef(settings);
settingsRef.current = settings;
// Apply settings changes to a live terminal without recreating it.
useEffect(() => {
const term = xtermRef.current;
if (!term) return;
const themeName = (settings['terminal.theme'] as string) || 'default';
term.options.theme = getTerminalTheme(themeName);
term.options.cursorBlink = settings['terminal.cursorBlink'] as boolean;
term.options.cursorStyle = settings['terminal.cursorStyle'] as 'block' | 'underline' | 'bar';
term.options.fontSize = (settings['terminal.fontSize'] as number) || 12;
}, [settings]);
useEffect(() => {
// Don't attempt if the ref is not set
if (terminalRef.current === null) {
return;
}
if (sessionId === '') {
return;
}
// Reset error state on new session
setError(null);
errorRef.current = null;
// Resolve the terminal theme from the ref so we get current values
// without adding settings as a dependency.
const s = settingsRef.current;
const themeName = (s['terminal.theme'] as string) || 'default';
const theme = getTerminalTheme(themeName);
// Initialize Terminal
const terminal = new Terminal({
cursorBlink: s['terminal.cursorBlink'],
cursorStyle: s['terminal.cursorStyle'],
allowProposedApi: true,
allowTransparency: true,
macOptionIsMeta: true,
macOptionClickForcesSelection: true,
fontSize: s['terminal.fontSize'] || 12,
fontFamily: "Consolas,Liberation Mono,Menlo,Courier,monospace",
fontWeight: 'normal',
theme,
});
xtermRef.current = terminal;
const fitAddon = new FitAddon();
terminal.open(terminalRef.current);
fitAddonRef.current = fitAddon;
terminal.loadAddon(fitAddon);
const canvasAddon = new CanvasAddon();
canvasAddonRef.current = canvasAddon;
terminal.loadAddon(canvasAddon);
const webglAddon = new WebglAddon();
webglAddonRef.current = webglAddon;
terminal.loadAddon(webglAddon);
terminal.loadAddon(new WebLinksAddon());
terminal.focus();
const debouncedFit = debounce(() => {
fitAddon.fit();
}, 10);
const handleWindowResize = () => {
handleFit();
};
window.addEventListener('resize', handleWindowResize);
// Re-fit when the bottom drawer finishes a resize transition
const unsubscribeResizeReset = bottomDrawerChannel.on('onResizeReset', () => {
handleFit();
});
const resizeObserver = new ResizeObserver((_val) => {
debouncedFit();
});
resizeObserver.observe(terminalRef.current);
terminal.onResize((event) => {
const rows = event.rows;
const cols = event.cols;
ExecClient.ResizeSession(sessionId, rows, cols).catch((err: unknown) => {
log.error(new Error(parseAppError(err).detail), { event: 'resize_session', sessionId });
});
});
const stdout = `core/exec/stream/stdout/${sessionId}`;
const stderr = `core/exec/stream/stderr/${sessionId}`;
// Track whether the session has been attached so we can distinguish
// fast failures (CLOSE before/during attach) from normal session endings.
const attachedRef = { current: false };
// Setup signal handlers.
// Registered BEFORE attach so we don't miss fast signals on sessions
// that fail immediately (e.g., ERROR followed by CLOSE).
const setupSignalHandlers = () => {
// ERROR signal: structured error from plugin layer
Events.On(constructSignalHandler('ERROR', sessionId), (ev) => {
const errorInfo = ev.data as any;
if (errorInfo && typeof errorInfo === 'object') {
const info: TerminalErrorInfo = {
title: errorInfo.title || errorInfo.Title || 'Session error',
suggestion: errorInfo.suggestion || errorInfo.Suggestion || 'The session encountered an error.',
raw: errorInfo.message || errorInfo.Message || '',
retryable: errorInfo.retryable ?? errorInfo.Retryable ?? false,
retryCommands: errorInfo.retry_commands || errorInfo.RetryCommands || errorInfo.retry_Commands,
};
errorRef.current = info;
setError(info);
}
});
// CLOSE signal: session is done
Events.On(constructSignalHandler('CLOSE', sessionId), () => {
// If an error overlay is already showing, don't auto-close the tab
if (errorRef.current) {
return;
}
// Only auto-close the tab if the session was successfully attached
if (attachedRef.current) {
bottomDrawerChannel.emit('onSessionClosed', { id: sessionId });
}
});
Events.On(constructSignalHandler('SIGINT', sessionId), () => { console.log('SIGINT'); });
Events.On(constructSignalHandler('SIGQUIT', sessionId), () => { console.log('SIGQUIT'); });
Events.On(constructSignalHandler('SIGTERM', sessionId), () => { console.log('SIGTERM'); });
Events.On(constructSignalHandler('SIGKILL', sessionId), () => { console.log('SIGKILL'); });
Events.On(constructSignalHandler('SIGHUP', sessionId), () => { console.log('SIGHUP'); });
Events.On(constructSignalHandler('SIGUSR1', sessionId), () => { console.log('SIGUSR1'); });
Events.On(constructSignalHandler('SIGUSR2', sessionId), () => { console.log('SIGUSR2'); });
Events.On(constructSignalHandler('SIGWINCH', sessionId), () => { console.log('SIGWINCH'); });
};
setupSignalHandlers();
// Function to handle attachment logic
const attachToSession = async () => {
Events.On(stdout, (ev) => {
const data = ev.data;
if (data !== null && data !== undefined) {
const decoded = textDecoder.decode(Base64.toUint8Array(data));
terminal.write(decoded);
}
});
Events.On(stderr, (ev) => {
const data = ev.data;
if (data !== null && data !== undefined) {
const decoded = textDecoder.decode(Base64.toUint8Array(data));
terminal.write(decoded);
}
});
try {
await ExecClient.AttachSession(sessionId);
} catch (e) {
log.error(new Error(parseAppError(e).detail), { event: 'attach_session', sessionId });
}
};
attachToSession().then(() => {
attachedRef.current = true;
fitAddon.fit()
terminal.onData(data => {
ExecClient.WriteSession(sessionId, Base64.encode(data))
.catch((err: unknown) => {
log.error(new Error(parseAppError(err).detail), { event: 'write_session', sessionId });
});
});
}).catch((err: unknown) => {
log.error(new Error(parseAppError(err).detail), { event: 'attach_session', sessionId });
});
// Cleanup function to detach from the session and remove listeners
return () => {
// run our disposers
disposers.current.forEach((disposer) => {
disposer();
});
window.removeEventListener('resize', handleWindowResize);
unsubscribeResizeReset();
try {
canvasAddonRef.current?.dispose();
webglAddonRef.current?.dispose();
terminal.dispose();
} catch (e) {
console.log(e);
}
canvasAddonRef.current = undefined;
webglAddonRef.current = undefined;
if (terminalRef.current !== null) {
resizeObserver.unobserve(terminalRef.current);
}
// cleanup signal handlers
['ERROR', 'CLOSE', 'SIGINT', 'SIGQUIT', 'SIGTERM', 'SIGKILL', 'SIGHUP', 'SIGUSR1', 'SIGUSR2', 'SIGWINCH'].forEach((signal) => {
Events.Off(constructSignalHandler(signal, sessionId));
});
ExecClient.DetachSession(sessionId).then(() => {
}).catch((err: unknown) => {
log.error(new Error(parseAppError(err).detail), { event: 'detach_session', sessionId });
});
};
}, [sessionId]);
const themeName = (settings['terminal.theme'] as string) || 'default';
const bgColor = getTerminalTheme(themeName).background ?? '#1e1e1e';
return (
<div style={{ position: 'relative', height: '100%', width: '100%' }}>
<div
ref={terminalRef}
style={{
backgroundColor: bgColor,
height: '100%',
width: '100%',
}}
/>
{error && <TerminalError error={error} onRetry={handleRetry} backgroundColor={bgColor} />}
</div>
);
}
TerminalContainer.displayName = 'TerminalContainer';