@lethevimlet/sshift 1.9.3 → 1.9.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -271,6 +271,19 @@ Add plugins to your `config.json`:
271
271
 
272
272
  See [Configuration > Plugins](docs/configuration.md#plugins) for full details.
273
273
 
274
+ ### Remote Control (local assistants)
275
+
276
+ The opt-in `remote-control` plugin exposes a **loopback-only, token-protected** HTTP API so a
277
+ local assistant (for example a voice assistant's MCP server) can list, switch and rename tabs, open
278
+ bookmarks, read a terminal's screen as plain text, type text and press keys. Typing never
279
+ presses Enter; submitting is always a separate, explicit key request.
280
+
281
+ ```json
282
+ { "plugins": [{ "name": "remote-control", "enabled": true, "config": { "port": 8044 } }] }
283
+ ```
284
+
285
+ See [Configuration > Remote Control](docs/configuration.md#remote-control-plugin).
286
+
274
287
  ## 🛠️ Technology Stack
275
288
 
276
289
  **Backend:** Node.js, Express, Socket.IO, ssh2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lethevimlet/sshift",
3
- "version": "1.9.3",
3
+ "version": "1.9.5",
4
4
  "description": "Web-based SSH + SFTP terminal client with tabs and bookmarks",
5
5
  "main": "src/server/index.js",
6
6
  "bin": {
@@ -0,0 +1,315 @@
1
+ /**
2
+ * remote-control Plugin
3
+ *
4
+ * A small HTTP API for LOCAL automation, e.g. a voice assistant's MCP
5
+ * server: list and switch tabs, open bookmarks, read a session's screen as
6
+ * plain text, type text and send named keys.
7
+ *
8
+ * Security model:
9
+ * - Binds to a loopback address only (non-loopback `host` is refused).
10
+ * - Every request needs `Authorization: Bearer <token>`. The token lives in
11
+ * `<dataDir>/remote-control.token` (mode 0600), generated on first start.
12
+ * Anyone who can read that file can type into your sessions.
13
+ * - Text input never contains control characters. Multi-line text is only
14
+ * accepted when the target application enabled bracketed paste, so a
15
+ * newline can never execute a shell line on its own. Enter is a separate,
16
+ * explicit key request — callers decide when to submit.
17
+ * - Credentials are never returned (bookmarks are listed by name/type).
18
+ *
19
+ * Config (config.json → plugins[] entry "remote-control"):
20
+ * { "port": 8044, "host": "127.0.0.1", "tokenFile": "<optional path>" }
21
+ *
22
+ * Endpoints (JSON):
23
+ * GET /v1/health
24
+ * GET /v1/tabs → { activeSessionId, tabs: [...] }
25
+ * GET /v1/bookmarks → { bookmarks: [{ id, name, type, folder }] }
26
+ * GET /v1/screen?sessionId=&history=N
27
+ * POST /v1/switch { sessionId }
28
+ * POST /v1/rename { sessionId, name } → renames the tab on every browser
29
+ * POST /v1/open { bookmarkId } → opens it on ONE connected browser
30
+ * POST /v1/type { sessionId?, text }
31
+ * POST /v1/key { sessionId?, key, repeat? }
32
+ * sessionId defaults to the focused tab.
33
+ */
34
+
35
+ const http = require('http');
36
+ const fs = require('fs');
37
+ const path = require('path');
38
+ const crypto = require('crypto');
39
+
40
+ const LOOPBACK = new Set(['127.0.0.1', '::1', 'localhost']);
41
+ const MAX_BODY = 64 * 1024;
42
+ const MAX_TEXT = 8000;
43
+
44
+ // Named keys. Cursor keys depend on DECCKM (application cursor mode).
45
+ const KEYS = {
46
+ enter: '\r',
47
+ tab: '\t',
48
+ 'shift-tab': '\x1b[Z',
49
+ escape: '\x1b',
50
+ backspace: '\x7f',
51
+ delete: '\x1b[3~',
52
+ space: ' ',
53
+ 'ctrl-a': '\x01',
54
+ 'ctrl-c': '\x03',
55
+ 'ctrl-d': '\x04',
56
+ 'ctrl-e': '\x05',
57
+ 'ctrl-k': '\x0b',
58
+ 'ctrl-l': '\x0c',
59
+ 'ctrl-r': '\x12',
60
+ 'ctrl-u': '\x15',
61
+ 'ctrl-w': '\x17',
62
+ 'ctrl-z': '\x1a',
63
+ 'page-up': '\x1b[5~',
64
+ 'page-down': '\x1b[6~',
65
+ };
66
+ const CURSOR_KEYS = { up: 'A', down: 'B', right: 'C', left: 'D', home: 'H', end: 'F' };
67
+ const KEY_NAMES = [...Object.keys(KEYS), ...Object.keys(CURSOR_KEYS)];
68
+
69
+ // App hints so callers can find "the claude tab" or "the opencode tab".
70
+ // Case-sensitive wordmarks, mirroring the attention plugins' signatures.
71
+ const APP_PATTERNS = [
72
+ ['claude', /\? for shortcuts|esc to interrupt|⏵⏵|accept edits on|bypass permissions on|shift\+tab to cycle|Claude Code/],
73
+ ['opencode', /OpenCode|ctrl\+p commands/],
74
+ ];
75
+
76
+ function detectApp(text) {
77
+ if (!text) return null;
78
+ const tail = text.lines.slice(-30).join('\n');
79
+ for (const [app, pattern] of APP_PATTERNS) if (pattern.test(tail)) return app;
80
+ return text.alternateScreen ? 'fullscreen' : 'shell';
81
+ }
82
+
83
+ class HttpError extends Error {
84
+ constructor(status, message) { super(message); this.status = status; }
85
+ }
86
+
87
+ class RemoteControlPlugin {
88
+ constructor(ctx, config = {}) {
89
+ this.ctx = ctx;
90
+ this.config = config;
91
+ this.server = null;
92
+ }
93
+
94
+ init() {
95
+ const host = this.config.host || '127.0.0.1';
96
+ const port = Number(this.config.port) || 8044;
97
+ if (!LOOPBACK.has(host)) {
98
+ console.error(`[remote-control] Refusing non-loopback host "${host}"; plugin disabled.`);
99
+ return;
100
+ }
101
+ try {
102
+ this.token = this._loadToken();
103
+ } catch (err) {
104
+ console.error('[remote-control] Cannot prepare token file:', err.message);
105
+ return;
106
+ }
107
+ this.server = http.createServer((req, res) => this._handle(req, res));
108
+ this.server.on('error', err => console.error('[remote-control] Server error:', err.message));
109
+ this.server.listen(port, host, () => console.log(`[remote-control] Listening on http://${host}:${port}`));
110
+ }
111
+
112
+ destroy() {
113
+ if (this.server) this.server.close();
114
+ this.server = null;
115
+ }
116
+
117
+ _tokenFile() {
118
+ return this.config.tokenFile || path.join(this.ctx.getDataDir(), 'remote-control.token');
119
+ }
120
+
121
+ _loadToken() {
122
+ const file = this._tokenFile();
123
+ try {
124
+ const token = fs.readFileSync(file, 'utf8').trim();
125
+ if (token.length >= 32) return token;
126
+ } catch (err) {
127
+ if (err.code !== 'ENOENT') throw err;
128
+ }
129
+ const token = crypto.randomBytes(32).toString('hex');
130
+ fs.mkdirSync(path.dirname(file), { recursive: true });
131
+ fs.writeFileSync(file, token + '\n', { mode: 0o600 });
132
+ fs.chmodSync(file, 0o600);
133
+ console.log(`[remote-control] Generated access token in ${file}`);
134
+ return token;
135
+ }
136
+
137
+ _authorized(req) {
138
+ const header = req.headers.authorization || '';
139
+ const match = /^Bearer (\S+)$/.exec(header);
140
+ if (!match || !this.token) return false;
141
+ const a = Buffer.from(match[1]);
142
+ const b = Buffer.from(this.token);
143
+ return a.length === b.length && crypto.timingSafeEqual(a, b);
144
+ }
145
+
146
+ async _handle(req, res) {
147
+ const send = (status, body) => {
148
+ res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
149
+ res.end(JSON.stringify(body));
150
+ };
151
+ try {
152
+ // Browsers must never drive this API (DNS rebinding / CSRF).
153
+ if (req.headers.origin) throw new HttpError(403, 'Browser requests are not allowed');
154
+ if (!this._authorized(req)) throw new HttpError(401, 'Unauthorized');
155
+ const url = new URL(req.url, 'http://localhost');
156
+ const route = `${req.method} ${url.pathname}`;
157
+ const body = req.method === 'POST' ? await this._readBody(req) : {};
158
+ switch (route) {
159
+ case 'GET /v1/health': return send(200, { ok: true });
160
+ case 'GET /v1/tabs': return send(200, this.tabs());
161
+ case 'GET /v1/bookmarks': return send(200, { bookmarks: this.ctx.getBookmarks() });
162
+ case 'GET /v1/screen': return send(200, this.screen(url.searchParams.get('sessionId'), url.searchParams.get('history')));
163
+ case 'POST /v1/switch': return send(200, this.switchTab(body.sessionId));
164
+ case 'POST /v1/rename': return send(200, this.renameTab(body.sessionId, body.name));
165
+ case 'POST /v1/open': return send(200, await this.open(body.bookmarkId));
166
+ case 'POST /v1/type': return send(200, await this.type(body.sessionId, body.text));
167
+ case 'POST /v1/key': return send(200, await this.key(body.sessionId, body.key, body.repeat));
168
+ default: throw new HttpError(404, 'Not found');
169
+ }
170
+ } catch (err) {
171
+ const status = err.status || 500;
172
+ if (status === 500) console.error('[remote-control] Request failed:', err.message);
173
+ send(status, { error: status === 500 ? 'Internal error' : err.message });
174
+ }
175
+ }
176
+
177
+ _readBody(req) {
178
+ return new Promise((resolve, reject) => {
179
+ let size = 0;
180
+ const chunks = [];
181
+ req.on('data', chunk => {
182
+ size += chunk.length;
183
+ if (size > MAX_BODY) { reject(new HttpError(413, 'Body too large')); req.destroy(); return; }
184
+ chunks.push(chunk);
185
+ });
186
+ req.on('end', () => {
187
+ if (!chunks.length) return resolve({});
188
+ try {
189
+ const value = JSON.parse(Buffer.concat(chunks).toString('utf8'));
190
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error();
191
+ resolve(value);
192
+ } catch { reject(new HttpError(400, 'Invalid JSON body')); }
193
+ });
194
+ req.on('error', reject);
195
+ });
196
+ }
197
+
198
+ tabs() {
199
+ const { activeSessionId, tabs } = this.ctx.getTabs();
200
+ return {
201
+ activeSessionId,
202
+ tabs: tabs.map(tab => ({
203
+ ...tab,
204
+ focused: tab.sessionId === activeSessionId,
205
+ app: tab.type === 'ssh' && tab.connected ? detectApp(this.ctx.getTerminalText(tab.sessionId)) : null,
206
+ })),
207
+ };
208
+ }
209
+
210
+ _target(sessionId) {
211
+ const { activeSessionId, tabs } = this.ctx.getTabs();
212
+ let id = sessionId;
213
+ if (!id) {
214
+ const ssh = tabs.filter(t => t.type === 'ssh' && t.connected);
215
+ id = activeSessionId || (ssh.length === 1 ? ssh[0].sessionId : null);
216
+ if (!id) throw new HttpError(409, 'No focused tab; specify sessionId');
217
+ }
218
+ const tab = tabs.find(t => t.sessionId === id);
219
+ if (!tab) throw new HttpError(404, 'Tab not found');
220
+ if (tab.type !== 'ssh') throw new HttpError(409, 'Only SSH terminal tabs accept input');
221
+ if (!tab.connected) throw new HttpError(409, 'The tab is not connected');
222
+ return tab;
223
+ }
224
+
225
+ screen(sessionId, history) {
226
+ const tab = this._target(sessionId);
227
+ const text = this.ctx.getTerminalText(tab.sessionId, { history: Math.min(Number(history) || 0, 500) });
228
+ if (!text) throw new HttpError(409, 'Screen unavailable');
229
+ return { sessionId: tab.sessionId, name: tab.name, app: detectApp(text), ...text };
230
+ }
231
+
232
+ switchTab(sessionId) {
233
+ if (typeof sessionId !== 'string' || !sessionId) throw new HttpError(400, 'sessionId required');
234
+ if (!this.ctx.switchTab(sessionId)) throw new HttpError(404, 'Tab not found');
235
+ const tab = this.ctx.getTabs().tabs.find(t => t.sessionId === sessionId);
236
+ return { switched: true, sessionId, name: tab?.name || null };
237
+ }
238
+
239
+ renameTab(sessionId, name) {
240
+ if (typeof sessionId !== 'string' || !sessionId) throw new HttpError(400, 'sessionId required');
241
+ const clean = typeof name === 'string' ? name.trim().replace(/\s+/g, ' ') : '';
242
+ if (!clean || clean.length > 40 || /[\x00-\x1f\x7f-\x9f]/.test(clean)) throw new HttpError(400, 'name must be 1-40 printable characters');
243
+ if (typeof this.ctx.renameTab !== 'function' || !this.ctx.renameTab(sessionId, clean)) throw new HttpError(404, 'Tab not found');
244
+ return { renamed: true, sessionId, name: clean };
245
+ }
246
+
247
+ async open(bookmarkId) {
248
+ const bookmark = this.ctx.getBookmarks().find(b => b.id === bookmarkId);
249
+ if (!bookmark) throw new HttpError(404, 'Bookmark not found');
250
+ if (!['ssh', 'sftp'].includes(bookmark.type)) throw new HttpError(409, 'Only SSH/SFTP bookmarks can be opened');
251
+ const before = new Set(this.ctx.getTabs().tabs.map(t => t.sessionId));
252
+ const claim = await this.ctx.requestClientAction('remote-open-bookmark', { bookmarkId });
253
+ if (!claim.claimed) {
254
+ throw new HttpError(409, 'No sshift browser page is open to connect the bookmark; open sshift first');
255
+ }
256
+ const deadline = Date.now() + 10000;
257
+ while (Date.now() < deadline) {
258
+ const tab = this.ctx.getTabs().tabs.find(t => !before.has(t.sessionId));
259
+ if (tab) {
260
+ // The opening client's tabs-save can arrive before the tab exists on
261
+ // the server, leaving no focused session; focus the new tab here.
262
+ this.ctx.switchTab(tab.sessionId);
263
+ return { opened: true, sessionId: tab.sessionId, name: tab.name, connected: tab.connected };
264
+ }
265
+ await new Promise(resolve => setTimeout(resolve, 200));
266
+ }
267
+ return { opened: true, sessionId: null, name: bookmark.name, pending: true };
268
+ }
269
+
270
+ async _inputLine(sessionId) {
271
+ await new Promise(resolve => setTimeout(resolve, 150));
272
+ const text = this.ctx.getTerminalText(sessionId);
273
+ if (!text) return null;
274
+ return (text.lines[text.cursorLine] || '').trimEnd().slice(-300);
275
+ }
276
+
277
+ async type(sessionId, text) {
278
+ if (typeof text !== 'string' || !text.length) throw new HttpError(400, 'text required');
279
+ if (text.length > MAX_TEXT) throw new HttpError(413, 'text too long');
280
+ const normalized = text.replace(/\r\n?/g, '\n');
281
+ if (/[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(normalized)) {
282
+ throw new HttpError(400, 'text must not contain control characters; use /v1/key for keys');
283
+ }
284
+ const tab = this._target(sessionId);
285
+ const multiLine = normalized.includes('\n');
286
+ let data = normalized;
287
+ if (multiLine) {
288
+ const screen = this.ctx.getTerminalText(tab.sessionId);
289
+ if (!screen || !screen.bracketedPaste) {
290
+ throw new HttpError(409, 'This application does not accept pasted multi-line text; send one line at a time');
291
+ }
292
+ data = `\x1b[200~${normalized}\x1b[201~`;
293
+ }
294
+ this.ctx.sendInput(tab.sessionId, data);
295
+ return { typed: true, sessionId: tab.sessionId, name: tab.name, pasted: multiLine, submitted: false, inputLine: await this._inputLine(tab.sessionId) };
296
+ }
297
+
298
+ async key(sessionId, key, repeat = 1) {
299
+ if (!KEY_NAMES.includes(key)) throw new HttpError(400, `Unknown key; use one of: ${KEY_NAMES.join(', ')}`);
300
+ const times = Number.isInteger(repeat) ? repeat : 1;
301
+ if (times < 1 || times > 20) throw new HttpError(400, 'repeat must be 1-20');
302
+ const tab = this._target(sessionId);
303
+ let sequence = KEYS[key];
304
+ if (!sequence) {
305
+ const screen = this.ctx.getTerminalText(tab.sessionId);
306
+ sequence = (screen && screen.applicationCursorKeys ? '\x1bO' : '\x1b[') + CURSOR_KEYS[key];
307
+ }
308
+ this.ctx.sendInput(tab.sessionId, sequence.repeat(times));
309
+ return { sent: true, sessionId: tab.sessionId, name: tab.name, key, repeat: times, inputLine: await this._inputLine(tab.sessionId) };
310
+ }
311
+ }
312
+
313
+ RemoteControlPlugin.KEY_NAMES = KEY_NAMES;
314
+ RemoteControlPlugin.detectApp = detectApp;
315
+ module.exports = RemoteControlPlugin;
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "remote-control",
3
+ "version": "1.0.0",
4
+ "description": "Loopback, token-protected HTTP API for local assistants: list/switch tabs, open bookmarks, read the screen, type text and send keys",
5
+ "type": "sshift-plugin"
6
+ }
@@ -336,6 +336,7 @@ async function initializeServer() {
336
336
 
337
337
  // Sync flash state for tabs that need attention
338
338
  pluginManager.syncFlashState(socket);
339
+ pluginManager.registerSocket(socket);
339
340
 
340
341
  // Register all WebSocket handlers
341
342
  ws.registerAllWSHandlers(socket, io);
@@ -22,6 +22,17 @@
22
22
  * - ctx.getTerminalViewport(sessionId) - Get the visible screen only (cheap)
23
23
  * - ctx.getActiveSessions() - Get list of active session IDs
24
24
  * - ctx.getConfig() - Get current server config
25
+ * - ctx.sendInput(sessionId, data) - Write input on the user's behalf (fires onUserInput)
26
+ * - ctx.getTerminalText(sessionId, options) - Plain-text screen (+ history) and input modes
27
+ * - ctx.getTabs() - Open tabs in order, with the focused session
28
+ * - ctx.switchTab(sessionId) - Focus a tab on every connected client
29
+ * - ctx.renameTab(sessionId, name) - Rename a tab on the server and every client
30
+ * - ctx.getBookmarks() - Bookmark names/types (never credentials)
31
+ * - ctx.requestClientAction(event, data, opts) - Ask exactly ONE connected client to act
32
+ * - ctx.getDataDir() - User data directory (private plugin state)
33
+ *
34
+ * Plugins that hold resources (servers, timers) should implement destroy();
35
+ * it is called before a reload replaces the instance.
25
36
  */
26
37
 
27
38
  const path = require('path');
@@ -44,6 +55,7 @@ class PluginManager {
44
55
  this.config = null;
45
56
  this._lineBuffers = new Map();
46
57
  this.flashingSessions = new Map(); // sessionId -> options
58
+ this.pendingClaims = new Map(); // requestId -> { resolve, timer }
47
59
  }
48
60
 
49
61
  discoverPlugins() {
@@ -87,6 +99,11 @@ class PluginManager {
87
99
 
88
100
  for (const [name, pluginEntry] of this.plugins.entries()) {
89
101
  const instance = pluginEntry.instance;
102
+ if (instance && typeof instance.destroy === 'function') {
103
+ try { instance.destroy(); } catch (e) {
104
+ console.error(`[PLUGINS] Error destroying plugin "${name}":`, e.message);
105
+ }
106
+ }
90
107
  if (instance && typeof instance.onSessionDisconnect === 'function') {
91
108
  for (const sessionId of this._lineBuffers.keys()) {
92
109
  try { instance.onSessionDisconnect(sessionId); } catch (e) { /* ignore */ }
@@ -255,9 +272,125 @@ class PluginManager {
255
272
  getPluginConfig() {
256
273
  return pluginConfig.config || {};
257
274
  },
275
+
276
+ sendInput(sessionId, data) {
277
+ if (!self.sshManager || !self.sshManager.hasSession(sessionId)) return false;
278
+ self.sshManager.write(sessionId, data);
279
+ self.onUserInput(sessionId, data);
280
+ return true;
281
+ },
282
+
283
+ getTerminalText(sessionId, options = {}) {
284
+ if (self.sshManager && typeof self.sshManager.getTerminalText === 'function') {
285
+ return self.sshManager.getTerminalText(sessionId, options);
286
+ }
287
+ return null;
288
+ },
289
+
290
+ getTabs() {
291
+ return self.getTabs();
292
+ },
293
+
294
+ switchTab(sessionId) {
295
+ const tm = self.tabManager;
296
+ if (!tm || !tm.getTab(sessionId)) return false;
297
+ tm.setActiveSession(sessionId);
298
+ const tab = tm.getTab(sessionId);
299
+ if (tab.panelId) tm.setActiveTab(tab.panelId, sessionId);
300
+ if (self.io) self.io.emit('remote-switch-tab', { sessionId });
301
+ return true;
302
+ },
303
+
304
+ renameTab(sessionId, name) {
305
+ const tm = self.tabManager;
306
+ if (!tm || !tm.getTab(sessionId)) return false;
307
+ tm.updateTabName(sessionId, name);
308
+ if (self.io) self.io.emit('tab-renamed', { sessionId, name });
309
+ return true;
310
+ },
311
+
312
+ getBookmarks() {
313
+ const { loadConfig } = require('../utils/config');
314
+ const config = loadConfig();
315
+ const folders = new Map((config.folders || []).map(f => [f.id, f.name]));
316
+ return (config.bookmarks || []).map(b => ({
317
+ id: b.id,
318
+ name: b.name,
319
+ type: b.type || 'ssh',
320
+ folder: b.folderId ? folders.get(b.folderId) || null : null,
321
+ }));
322
+ },
323
+
324
+ requestClientAction(event, data = {}, options = {}) {
325
+ return self.requestClientAction(event, data, options);
326
+ },
327
+
328
+ getDataDir() {
329
+ const { getDataDir } = require('../utils/config');
330
+ return getDataDir();
331
+ },
332
+ };
333
+ }
334
+
335
+ getTabs() {
336
+ const tm = this.tabManager;
337
+ if (!tm) return { activeSessionId: null, tabs: [] };
338
+ const openTabs = tm.getOpenTabs();
339
+ const order = tm.getTabOrder().filter(id => openTabs.has(id));
340
+ for (const id of openTabs.keys()) if (!order.includes(id)) order.push(id);
341
+ const activeByPanel = tm.getActiveTabsByPanel();
342
+ return {
343
+ activeSessionId: tm.getActiveSession(),
344
+ tabs: order.map((sessionId, index) => {
345
+ const tab = openTabs.get(sessionId);
346
+ return {
347
+ sessionId,
348
+ position: index + 1,
349
+ name: tab.name || tab.connectionData?.name || tab.connectionData?.host || 'Tab',
350
+ type: tab.type,
351
+ host: tab.connectionData?.host || null,
352
+ username: tab.connectionData?.username || null,
353
+ panelId: tab.panelId || 'panel-0',
354
+ activeInPanel: activeByPanel.get(tab.panelId || 'panel-0') === sessionId,
355
+ connected: tab.type === 'ssh' ? !!this.sshManager?.hasSession(sessionId) : true,
356
+ viewers: tab.activeSockets ? tab.activeSockets.size : 0,
357
+ };
358
+ }),
258
359
  };
259
360
  }
260
361
 
362
+ // Broadcast an action request and let exactly one client claim it (the
363
+ // first to answer). Clients answer quickly when visible and with a delay
364
+ // when hidden, so the device the user is looking at normally wins and an
365
+ // action like "open a tab" never runs once per open browser.
366
+ requestClientAction(event, data = {}, { timeoutMs = 4000 } = {}) {
367
+ if (!this.io || this.io.sockets.sockets.size === 0) {
368
+ return Promise.resolve({ claimed: false, reason: 'no-clients' });
369
+ }
370
+ const requestId = require('crypto').randomUUID();
371
+ return new Promise(resolve => {
372
+ const timer = setTimeout(() => {
373
+ this.pendingClaims.delete(requestId);
374
+ resolve({ claimed: false, reason: 'timeout', requestId });
375
+ }, timeoutMs);
376
+ this.pendingClaims.set(requestId, { resolve, timer });
377
+ this.io.emit(event, { ...data, requestId });
378
+ });
379
+ }
380
+
381
+ registerSocket(socket) {
382
+ socket.on('remote-action-claim', (data, ack) => {
383
+ const pending = data && this.pendingClaims.get(data.requestId);
384
+ const granted = !!pending;
385
+ if (pending) {
386
+ this.pendingClaims.delete(data.requestId);
387
+ clearTimeout(pending.timer);
388
+ pending.resolve({ claimed: true, requestId: data.requestId, socketId: socket.id });
389
+ }
390
+ if (typeof ack === 'function') ack({ granted });
391
+ });
392
+ }
393
+
261
394
  _processLineBuffer(sessionId, dataStr) {
262
395
  if (!this._lineBuffers.has(sessionId)) {
263
396
  this._lineBuffers.set(sessionId, '');
@@ -607,6 +607,41 @@ if (this.io) {
607
607
  return this.sessions.has(sessionId);
608
608
  }
609
609
 
610
+ // Plain-text view of the active buffer for remote-control/automation
611
+ // plugins: the visible screen plus up to `history` earlier lines, with
612
+ // the input modes a client needs to send correct key sequences. Reads the
613
+ // headless terminal directly — no ANSI serialization.
614
+ getTerminalText(sessionId, { history = 0 } = {}) {
615
+ const session = this.sessions.get(sessionId);
616
+ if (!session || !session.terminal) return null;
617
+ try {
618
+ const terminal = session.terminal;
619
+ const buffer = terminal.buffer.active;
620
+ const extra = Math.max(0, Math.min(Number(history) || 0, 2000));
621
+ const start = Math.max(0, buffer.baseY - extra);
622
+ const end = buffer.baseY + terminal.rows;
623
+ const lines = [];
624
+ for (let y = start; y < end; y++) {
625
+ const line = buffer.getLine(y);
626
+ lines.push(line ? line.translateToString(true) : '');
627
+ }
628
+ while (lines.length && !lines[lines.length - 1].trim()) lines.pop();
629
+ const modes = terminal.modes || {};
630
+ return {
631
+ lines,
632
+ cursorLine: buffer.baseY + buffer.cursorY - start,
633
+ alternateScreen: buffer.type === 'alternate',
634
+ bracketedPaste: !!modes.bracketedPasteMode,
635
+ applicationCursorKeys: !!modes.applicationCursorKeysMode,
636
+ cols: session.cols,
637
+ rows: session.rows
638
+ };
639
+ } catch (err) {
640
+ console.error(`[SSH] Error reading terminal text:`, err.message);
641
+ return null;
642
+ }
643
+ }
644
+
610
645
  // Serialize a session's screen for a client sync, shrinking the amount
611
646
  // of scrollback until the payload fits under `maxBytes`.
612
647
  //
@@ -240,12 +240,14 @@ function getActiveTabsByPanel() {
240
240
  return activeTabsByPanel;
241
241
  }
242
242
 
243
+ // Keep the id even if the tab is not registered yet: a client that opens a
244
+ // tab can report focus before its ssh-connect completes on the server.
243
245
  function setActiveSession(sessionId) {
244
- activeSessionId = sessionId && openTabs.has(sessionId) ? sessionId : null;
246
+ activeSessionId = sessionId || null;
245
247
  }
246
248
 
247
249
  function getActiveSession() {
248
- return activeSessionId;
250
+ return activeSessionId && openTabs.has(activeSessionId) ? activeSessionId : null;
249
251
  }
250
252
 
251
253
  /**
@@ -4873,7 +4873,7 @@ const wheelHandler = (e) => {
4873
4873
  if (tab) {
4874
4874
  const nameSpan = tab.querySelector('.tab-name');
4875
4875
  if (nameSpan) {
4876
- nameSpan.textContent = this.escapeHtml(data.name);
4876
+ nameSpan.textContent = data.name; // textContent is already safe; escaping here showed "&amp;"
4877
4877
  }
4878
4878
  }
4879
4879
 
@@ -5800,6 +5800,27 @@ const wheelHandler = (e) => {
5800
5800
  this.socket.on('tab-flash-stop', (data) => {
5801
5801
  this.stopTabFlash(data.sessionId);
5802
5802
  });
5803
+
5804
+ // Remote-control plugin requests (e.g. voice assistants). Switching is
5805
+ // applied by every client, like a tabs-sync. Opening a bookmark must
5806
+ // happen exactly once: clients claim the request (visible ones first)
5807
+ // and only the client the server grants it to connects.
5808
+ this.socket.on('remote-switch-tab', (data) => {
5809
+ if (data && data.sessionId && this.sessions.has(data.sessionId)) {
5810
+ this.switchTab(data.sessionId);
5811
+ }
5812
+ });
5813
+
5814
+ this.socket.on('remote-open-bookmark', (data) => {
5815
+ const bookmark = data && this.bookmarks.find(b => b.id === data.bookmarkId);
5816
+ if (!bookmark || !data.requestId) return;
5817
+ const delay = document.visibilityState === 'visible' ? 0 : 1500;
5818
+ setTimeout(() => {
5819
+ this.socket.emit('remote-action-claim', { requestId: data.requestId }, (response) => {
5820
+ if (response && response.granted) this.connectFromBookmark(bookmark);
5821
+ });
5822
+ }, delay);
5823
+ });
5803
5824
  }
5804
5825
 
5805
5826
  // Event Listeners