File size: 8,351 Bytes
87a665c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<script lang="ts">
	import { onMount, onDestroy, getContext } from 'svelte';
	import { Terminal } from '@xterm/xterm';
	import { FitAddon } from '@xterm/addon-fit';
	import { WebLinksAddon } from '@xterm/addon-web-links';
	import '@xterm/xterm/css/xterm.css';

	import { terminalServers, settings, selectedTerminalId, user } from '$lib/stores';
	import { WEBUI_API_BASE_URL } from '$lib/constants';
	import Tooltip from '$lib/components/common/Tooltip.svelte';

	const i18n = getContext('i18n');

	export let overlay = false;
	export let chatId: string | null = null;

	let terminalEl: HTMLDivElement;
	let term: Terminal | null = null;
	let fitAddon: FitAddon | null = null;
	let ws: WebSocket | null = null;
	export let connected = false;
	export let connecting = false;
	let resizeObserver: ResizeObserver | null = null;
	let pingInterval: ReturnType<typeof setInterval> | null = null;

	// Resolve the active terminal server's info for the WebSocket URL
	const getTerminalInfo = (): { serverId: string; baseUrl: string } | null => {
		// System terminal (admin-configured, has an `id`)
		const systemTerminals = ($terminalServers ?? []).filter((t: any) => t.id);
		const systemMatch = systemTerminals.find((t: any) => t.id === $selectedTerminalId);
		if (systemMatch) {
			// For system terminals, WS goes through the Open WebUI backend proxy
			return { serverId: systemMatch.id, baseUrl: WEBUI_API_BASE_URL };
		}

		// Direct terminal (user-configured, matched by URL)
		const directTerminals = ($settings?.terminalServers ?? []).filter((s: any) => s.url);
		const directMatch = directTerminals.find((s: any) => s.url === $selectedTerminalId);
		if (directMatch) {
			// For direct terminals, construct WS URL from the server URL directly
			return { serverId: '__direct__', baseUrl: directMatch.url };
		}

		return null;
	};

	const connect = async () => {
		if (ws) disconnect();

		const info = getTerminalInfo();
		if (!info) return;

		connecting = true;

		const token = localStorage.getItem('token') ?? '';

		try {
			let sessionId: string;
			let wsUrl: string;
			let authToken: string;

			if (info.serverId === '__direct__') {
				// Direct connection to open-terminal
				const base = info.baseUrl.replace(/\/$/, '');
				const directTerminals = ($settings?.terminalServers ?? []).filter((s: any) => s.url);
				const directMatch = directTerminals.find((s: any) => s.url === $selectedTerminalId);
				const apiKey = directMatch?.key ?? '';
				authToken = apiKey;

				// Create session
				const createHeaders: Record<string, string> = { Authorization: `Bearer ${apiKey}` };
				if (chatId) createHeaders['X-Session-Id'] = chatId;
				const res = await fetch(`${base}/api/terminals`, {
					method: 'POST',
					headers: createHeaders
				});
				if (!res.ok) throw new Error(`Failed to create session: ${res.status}`);
				const session = await res.json();
				sessionId = session.id;

				const wsBase = base.replace(/^https:/, 'wss:').replace(/^http:/, 'ws:');
				wsUrl = `${wsBase}/api/terminals/${sessionId}`;
			} else {
				// System terminal — proxy through Open WebUI backend
				const base = info.baseUrl.replace(/\/$/, '');
				authToken = token;

				// Create session via proxy
				const proxyHeaders: Record<string, string> = { Authorization: `Bearer ${token}` };
				if (chatId) proxyHeaders['X-Session-Id'] = chatId;
				const res = await fetch(`${base}/terminals/${info.serverId}/api/terminals`, {
					method: 'POST',
					headers: proxyHeaders
				});
				if (!res.ok) throw new Error(`Failed to create session: ${res.status}`);
				const session = await res.json();
				sessionId = session.id;

				const wsBase = base.replace(/^https:/, 'wss:').replace(/^http:/, 'ws:');
				wsUrl = `${wsBase}/terminals/${info.serverId}/api/terminals/${sessionId}`;
			}

			ws = new WebSocket(wsUrl);
			ws.binaryType = 'arraybuffer';

			ws.onopen = () => {
				// First-message auth (no token in URL)
				if (ws) {
					ws.send(JSON.stringify({ type: 'auth', token: authToken }));
				}
				connected = true;
				connecting = false;
				// Focus the terminal so it receives keyboard input immediately
				term?.focus();
				// Send initial resize
				if (term && ws) {
					ws.send(JSON.stringify({ type: 'resize', cols: term.cols, rows: term.rows }));
				}
				// Keepalive ping to prevent idle timeout from proxies/LBs
				if (pingInterval) clearInterval(pingInterval);
				pingInterval = setInterval(() => {
					if (ws && ws.readyState === WebSocket.OPEN) {
						ws.send(JSON.stringify({ type: 'ping' }));
					}
				}, 25000);
			};

			ws.onmessage = (event) => {
				if (term) {
					if (event.data instanceof ArrayBuffer) {
						term.write(new Uint8Array(event.data));
					} else {
						term.write(event.data);
					}
				}
			};

			ws.onclose = () => {
				connected = false;
				connecting = false;
				if (term) {
					term.write('\r\n\x1b[90m[Connection closed]\x1b[0m\r\n');
				}
			};

			ws.onerror = () => {
				connected = false;
				connecting = false;
			};
		} catch (err) {
			connecting = false;
			if (term) {
				term.write(`\r\n\x1b[31m[Error: ${err}]\x1b[0m\r\n`);
			}
		}
	};

	const disconnect = () => {
		if (pingInterval) {
			clearInterval(pingInterval);
			pingInterval = null;
		}
		if (ws) {
			ws.close();
			ws = null;
		}
		connected = false;
		connecting = false;
	};

	const initTerminal = () => {
		if (!terminalEl || term) return;

		term = new Terminal({
			cursorBlink: true,
			fontSize: 13,
			fontFamily:
				"'JetBrains Mono', 'Fira Code', 'Cascadia Code', Menlo, Monaco, 'Courier New', monospace",
			theme: {
				background: '#000000',
				foreground: '#c0c0c0',
				cursor: '#ffffff',
				cursorAccent: '#000000',
				selectionBackground: '#444444',
				selectionForeground: '#ffffff',
				black: '#000000',
				red: '#cd0000',
				green: '#00cd00',
				yellow: '#cdcd00',
				blue: '#0000ee',
				magenta: '#cd00cd',
				cyan: '#00cdcd',
				white: '#e5e5e5',
				brightBlack: '#7f7f7f',
				brightRed: '#ff0000',
				brightGreen: '#00ff00',
				brightYellow: '#ffff00',
				brightBlue: '#5c5cff',
				brightMagenta: '#ff00ff',
				brightCyan: '#00ffff',
				brightWhite: '#ffffff'
			},
			allowProposedApi: true,
			scrollback: 5000
		});

		fitAddon = new FitAddon();
		term.loadAddon(fitAddon);
		term.loadAddon(new WebLinksAddon());

		term.open(terminalEl);

		// Fit after a frame so the container has dimensions
		requestAnimationFrame(() => {
			fitAddon?.fit();
		});

		// Forward keystrokes to WebSocket
		term.onData((data) => {
			if (ws && ws.readyState === WebSocket.OPEN) {
				ws.send(new TextEncoder().encode(data));
			}
		});

		// Forward binary data (e.g. paste with special chars)
		term.onBinary((data) => {
			if (ws && ws.readyState === WebSocket.OPEN) {
				const buffer = new Uint8Array(data.length);
				for (let i = 0; i < data.length; i++) {
					buffer[i] = data.charCodeAt(i) & 0xff;
				}
				ws.send(buffer);
			}
		});

		// Ensure all key events are processed by xterm.js and not intercepted
		// by the browser or surrounding UI (fixes vi/vim keystroke handling).
		term.attachCustomKeyEventHandler(() => true);

		// Handle resize
		term.onResize(({ cols, rows }) => {
			if (ws && ws.readyState === WebSocket.OPEN) {
				ws.send(JSON.stringify({ type: 'resize', cols, rows }));
			}
		});

		// Watch container size changes
		resizeObserver = new ResizeObserver(() => {
			requestAnimationFrame(() => {
				fitAddon?.fit();
			});
		});
		resizeObserver.observe(terminalEl);

		// Connection is handled by the reactive block below (which fires
		// when `term` is set here), so we intentionally do NOT call
		// connect() to avoid creating a duplicate WebSocket whose onclose
		// handler would write a spurious "[Connection closed]" message.
	};

	// Reconnect when the selected terminal changes
	$: if ($selectedTerminalId !== undefined && term) {
		// Clear the terminal screen and reconnect to the new server
		disconnect();
		term.clear();
		if ($selectedTerminalId) {
			connect();
		}
	}

	onMount(() => {
		initTerminal();
	});

	onDestroy(() => {
		disconnect();
		resizeObserver?.disconnect();
		term?.dispose();
		term = null;
		fitAddon = null;
	});
</script>

<div class="h-full min-h-0 relative">
	<div bind:this={terminalEl} class="absolute inset-0 px-0.5" class:pointer-events-none={overlay} />
</div>