@lethevimlet/sshift 1.6.1 → 1.7.0

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lethevimlet/sshift",
3
- "version": "1.6.1",
3
+ "version": "1.7.0",
4
4
  "description": "Web-based SSH + SFTP terminal client with tabs and bookmarks",
5
5
  "main": "src/server/index.js",
6
6
  "bin": {
@@ -18,7 +18,16 @@
18
18
  const os = require('os');
19
19
  const path = require('path');
20
20
  const fs = require('fs');
21
- const { loadConfig, saveConfig, getSpeechAiConfig, getDefaultWandSystemPrompt } = require('../../utils/config');
21
+ const {
22
+ loadConfig,
23
+ saveConfig,
24
+ getSpeechAiConfig,
25
+ getDefaultWandSystemPrompt,
26
+ listSpeechAiProfiles,
27
+ saveSpeechAiProfile,
28
+ loadSpeechAiProfile,
29
+ deleteSpeechAiProfile
30
+ } = require('../../utils/config');
22
31
 
23
32
  // Use the global fetch (Node 18+) for proxying. Fall back to undici/https for
24
33
  // ancient environments — but Node >=20 is the project floor, so global fetch
@@ -88,6 +97,68 @@ function registerSpeechAiEndpoints(app, io) {
88
97
  res.json({ prompt: getDefaultWandSystemPrompt() });
89
98
  });
90
99
 
100
+ // ---- Profiles ------------------------------------------------------------
101
+ // Named snapshots of the speech-ai settings for fast swapping between
102
+ // endpoint setups (e.g. local Whisper/LLM stack vs a cloud provider).
103
+ // Saving snapshots the ACTIVE server config (raw keys included — they are
104
+ // already server-side); loading applies a snapshot back onto the active
105
+ // config. Raw auth keys never travel through the browser either way.
106
+
107
+ // List profile names.
108
+ app.get('/api/speech-ai/profiles', (req, res) => {
109
+ try {
110
+ res.json({ profiles: listSpeechAiProfiles() });
111
+ } catch (err) {
112
+ console.error('[SPEECH-AI] Failed to list profiles:', err);
113
+ res.status(500).json({ error: 'Failed to list profiles' });
114
+ }
115
+ });
116
+
117
+ // Save (or overwrite) the current active settings as a named profile.
118
+ app.post('/api/speech-ai/profiles', (req, res) => {
119
+ const name = sanitizeProfileName(req.body && req.body.name);
120
+ if (!name) return res.status(400).json({ error: 'Invalid profile name' });
121
+ try {
122
+ if (!saveSpeechAiProfile(name)) {
123
+ return res.status(500).json({ error: 'Failed to save profile' });
124
+ }
125
+ res.json({ ok: true, profiles: listSpeechAiProfiles() });
126
+ } catch (err) {
127
+ console.error('[SPEECH-AI] Failed to save profile:', err);
128
+ res.status(500).json({ error: 'Failed to save profile' });
129
+ }
130
+ });
131
+
132
+ // Apply a named profile to the active settings.
133
+ app.post('/api/speech-ai/profiles/load', (req, res) => {
134
+ const name = sanitizeProfileName(req.body && req.body.name);
135
+ if (!name) return res.status(400).json({ error: 'Invalid profile name' });
136
+ try {
137
+ if (!loadSpeechAiProfile(name)) {
138
+ return res.status(404).json({ error: 'Profile not found' });
139
+ }
140
+ res.json({ ok: true, config: getPublicSpeechAiConfigSafe() });
141
+ } catch (err) {
142
+ console.error('[SPEECH-AI] Failed to load profile:', err);
143
+ res.status(500).json({ error: 'Failed to load profile' });
144
+ }
145
+ });
146
+
147
+ // Delete a named profile.
148
+ app.delete('/api/speech-ai/profiles/:name', (req, res) => {
149
+ const name = sanitizeProfileName(req.params.name);
150
+ if (!name) return res.status(400).json({ error: 'Invalid profile name' });
151
+ try {
152
+ if (!deleteSpeechAiProfile(name)) {
153
+ return res.status(404).json({ error: 'Profile not found' });
154
+ }
155
+ res.json({ ok: true, profiles: listSpeechAiProfiles() });
156
+ } catch (err) {
157
+ console.error('[SPEECH-AI] Failed to delete profile:', err);
158
+ res.status(500).json({ error: 'Failed to delete profile' });
159
+ }
160
+ });
161
+
91
162
  // ---- STT proxy -----------------------------------------------------------
92
163
  // Body: raw audio bytes (any mimetype MediaRecorder produces). We forward
93
164
  // to <sttEndpoint> as multipart/form-data with model=openai/whisper-large-v3
@@ -112,6 +183,15 @@ function registerSpeechAiEndpoints(app, io) {
112
183
  });
113
184
  }
114
185
 
186
+ // Profile names: non-empty trimmed strings up to 64 chars. Anything else
187
+ // (objects, empty strings, oversized names) is rejected with a 400.
188
+ function sanitizeProfileName(raw) {
189
+ if (typeof raw !== 'string') return null;
190
+ const name = raw.trim();
191
+ if (!name || name.length > 64) return null;
192
+ return name;
193
+ }
194
+
115
195
  // Local helper so a save failure (or any error) never crashes the route —
116
196
  // returns empty defaults instead. Auth keys are still never exposed.
117
197
  function getPublicSpeechAiConfigSafe() {
@@ -50,7 +50,12 @@ const defaultConfig = {
50
50
  llmEndpoint: 'https://api.deepinfra.com/v1/openai/chat/completions',
51
51
  llmAuthKey: '',
52
52
  llmModel: 'meta-llama/Llama-3.3-70B-Instruct',
53
- wandSystemPrompt: ''
53
+ wandSystemPrompt: '',
54
+ // Named snapshots of the speech & AI settings above, keyed by profile
55
+ // name. Lets users fast-swap between endpoint setups (e.g. a local
56
+ // Whisper/LLM stack vs a cloud provider). Auth keys are stored inside
57
+ // the snapshots but, like the active keys, never leave the server.
58
+ speechAiProfiles: {}
54
59
  };
55
60
 
56
61
  /**
@@ -390,6 +395,81 @@ function getDefaultWandSystemPrompt() {
390
395
  return DEFAULT_WAND_SYSTEM_PROMPT;
391
396
  }
392
397
 
398
+ // --- Speech & AI profiles ---------------------------------------------------
399
+ // Named snapshots of the speech-ai settings (endpoints, auth keys, language,
400
+ // model, wand prompt) stored server-side in config.json. Saving snapshots the
401
+ // ACTIVE config values (which already hold the raw keys) and loading copies a
402
+ // snapshot back into the active config — so raw auth keys never travel
403
+ // through the browser in either direction.
404
+
405
+ const SPEECH_AI_PROFILE_FIELDS = [
406
+ 'sttEndpoint', 'sttAuthKey', 'sttLanguage',
407
+ 'llmEndpoint', 'llmAuthKey', 'llmModel', 'wandSystemPrompt'
408
+ ];
409
+
410
+ /**
411
+ * List saved speech-ai profile names (sorted).
412
+ * @returns {string[]} Profile names
413
+ */
414
+ function listSpeechAiProfiles() {
415
+ const config = loadConfig();
416
+ const profiles = (config.speechAiProfiles && typeof config.speechAiProfiles === 'object')
417
+ ? config.speechAiProfiles
418
+ : {};
419
+ return Object.keys(profiles).sort((a, b) => a.localeCompare(b));
420
+ }
421
+
422
+ /**
423
+ * Snapshot the current active speech-ai settings under a profile name.
424
+ * Overwrites an existing profile with the same name.
425
+ * @param {string} name - Profile name
426
+ * @returns {boolean} Success status
427
+ */
428
+ function saveSpeechAiProfile(name) {
429
+ const config = loadConfig();
430
+ if (!config.speechAiProfiles || typeof config.speechAiProfiles !== 'object') {
431
+ config.speechAiProfiles = {};
432
+ }
433
+ const snapshot = {};
434
+ for (const field of SPEECH_AI_PROFILE_FIELDS) {
435
+ snapshot[field] = config[field] !== undefined ? config[field] : defaultConfig[field];
436
+ }
437
+ config.speechAiProfiles[name] = snapshot;
438
+ return saveConfig(config);
439
+ }
440
+
441
+ /**
442
+ * Apply a saved profile to the active speech-ai settings.
443
+ * @param {string} name - Profile name
444
+ * @returns {boolean} true if the profile existed and was applied
445
+ */
446
+ function loadSpeechAiProfile(name) {
447
+ const config = loadConfig();
448
+ const profile = config.speechAiProfiles && config.speechAiProfiles[name];
449
+ if (!profile || typeof profile !== 'object') return false;
450
+ for (const field of SPEECH_AI_PROFILE_FIELDS) {
451
+ if (profile[field] !== undefined) {
452
+ config[field] = profile[field];
453
+ }
454
+ }
455
+ return saveConfig(config);
456
+ }
457
+
458
+ /**
459
+ * Delete a saved profile.
460
+ * @param {string} name - Profile name
461
+ * @returns {boolean} true if the profile existed and was deleted
462
+ */
463
+ function deleteSpeechAiProfile(name) {
464
+ const config = loadConfig();
465
+ if (!config.speechAiProfiles || typeof config.speechAiProfiles !== 'object' ||
466
+ !(name in config.speechAiProfiles)) {
467
+ return false;
468
+ }
469
+ delete config.speechAiProfiles[name];
470
+ return saveConfig(config);
471
+ }
472
+
393
473
  module.exports = {
394
474
  defaultConfig,
395
475
  ensureConfig,
@@ -420,5 +500,9 @@ module.exports = {
420
500
  getSpeechAiPublicConfig,
421
501
  getSpeechAiConfig,
422
502
  getDefaultWandSystemPrompt,
503
+ listSpeechAiProfiles,
504
+ saveSpeechAiProfile,
505
+ loadSpeechAiProfile,
506
+ deleteSpeechAiProfile,
423
507
  USER_INSTALL_DIR
424
508
  };
@@ -3985,6 +3985,23 @@ body.dragging-tabs .tabs-container {
3985
3985
  align-items: flex-end;
3986
3986
  }
3987
3987
 
3988
+ /* Speech & AI settings profiles (fast-swap dropdown + save/delete row) */
3989
+ #settings-category-speech-ai .speech-ai-profile-row {
3990
+ display: flex;
3991
+ align-items: center;
3992
+ gap: 8px;
3993
+ }
3994
+
3995
+ #settings-category-speech-ai .speech-ai-profile-row .setting-input {
3996
+ flex: 1;
3997
+ min-width: 0;
3998
+ }
3999
+
4000
+ #settings-category-speech-ai .speech-ai-profile-row .btn {
4001
+ flex-shrink: 0;
4002
+ white-space: nowrap;
4003
+ }
4004
+
3988
4005
  .stt-prompt-textarea {
3989
4006
  width: 100%;
3990
4007
  min-height: 120px;
@@ -1006,6 +1006,35 @@
1006
1006
  <div class="settings-category" id="settings-category-speech-ai" style="display:none;">
1007
1007
  <h3 class="settings-category-title"><i class="fas fa-microphone"></i> Speech &amp; AI</h3>
1008
1008
 
1009
+ <!-- Settings Profiles -->
1010
+ <div class="setting-subgroup">
1011
+ <h4 class="setting-subgroup-title">
1012
+ <i class="fas fa-layer-group"></i> Profiles
1013
+ </h4>
1014
+ <div class="setting-item">
1015
+ <label class="setting-label">
1016
+ <i class="fas fa-bookmark"></i> Settings Profile
1017
+ </label>
1018
+ <div class="setting-description">
1019
+ Save all the fields below as a named profile and swap between endpoint setups (e.g. local vs cloud) in one click. Selecting a profile applies it immediately. Auth keys are stored server-side and never leave the server.
1020
+ </div>
1021
+ <div class="setting-control speech-ai-profile-row">
1022
+ <select id="speechAiProfileSelect" class="setting-input speech-ai-profile-select">
1023
+ <option value="">— Select profile —</option>
1024
+ </select>
1025
+ </div>
1026
+ <div class="setting-control speech-ai-profile-row">
1027
+ <input type="text" id="speechAiProfileName" class="setting-input speech-ai-profile-name" placeholder="Profile name" maxlength="64">
1028
+ <button type="button" class="btn btn-sm btn-secondary" id="saveSpeechAiProfileBtn" title="Save the current Speech &amp; AI fields under this profile name">
1029
+ <i class="fas fa-save"></i> Save
1030
+ </button>
1031
+ <button type="button" class="btn btn-sm btn-secondary" id="deleteSpeechAiProfileBtn" title="Delete the selected profile">
1032
+ <i class="fas fa-trash"></i> Delete
1033
+ </button>
1034
+ </div>
1035
+ </div>
1036
+ </div>
1037
+
1009
1038
  <!-- Speech-to-Text (STT) Endpoint -->
1010
1039
  <div class="setting-subgroup">
1011
1040
  <h4 class="setting-subgroup-title">
@@ -932,9 +932,22 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
932
932
  data = data.replace(/\r\n/g, '\r').replace(/\n/g, '\r');
933
933
 
934
934
  // Wrap in bracketed paste sequences so the remote shell treats this as
935
- // a single paste rather than individual keystrokes.
936
- const BP_START = '\x1b[200~';
937
- const BP_END = '\x1b[201~';
935
+ // a single paste rather than individual keystrokes — but ONLY when the
936
+ // remote application has actually enabled bracketed paste mode
937
+ // (DECSET 2004). Real terminals never send the \x1b[200~ / \x1b[201~
938
+ // markers unconditionally: an application that hasn't opted in (e.g. a
939
+ // plain `read`/`input()` prompt like `gcloud auth login --no-browser`)
940
+ // receives them as literal input, showing "200~...201~" garbage around
941
+ // the pasted text. xterm.js tracks the mode from the output stream
942
+ // (terminal.modes.bracketedPasteMode), and the server's serialized
943
+ // screen-sync state replays DECSET 2004, so the flag stays accurate
944
+ // for joined/resynced sessions too.
945
+ let bracketed = false;
946
+ try {
947
+ bracketed = session.terminal?.modes?.bracketedPasteMode === true;
948
+ } catch (_) { bracketed = false; }
949
+ const BP_START = bracketed ? '\x1b[200~' : '';
950
+ const BP_END = bracketed ? '\x1b[201~' : '';
938
951
 
939
952
  const wrapped = BP_START + data + BP_END;
940
953
 
@@ -945,12 +958,13 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
945
958
 
946
959
  // For large pastes, send the start bracket, then chunk the content,
947
960
  // then send the end bracket. This keeps bracketed paste mode intact
948
- // across all chunks.
961
+ // across all chunks. (When bracketed paste is off, BP_START/BP_END are
962
+ // empty strings and we skip emitting the trailing empty chunk.)
949
963
  let offset = 0;
950
964
  let isFirst = true;
951
965
  const sendNext = () => {
952
966
  if (offset >= data.length) {
953
- this.socket.emit('ssh-data', { sessionId, data: BP_END });
967
+ if (BP_END) this.socket.emit('ssh-data', { sessionId, data: BP_END });
954
968
  return;
955
969
  }
956
970
  let end = Math.min(offset + chunkSize, data.length);
@@ -970,7 +984,7 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
970
984
  this.socket.emit('ssh-data', { sessionId, data: chunk });
971
985
  if (offset < data.length) {
972
986
  setTimeout(sendNext, 5);
973
- } else {
987
+ } else if (BP_END) {
974
988
  this.socket.emit('ssh-data', { sessionId, data: BP_END });
975
989
  }
976
990
  };
@@ -1071,6 +1085,45 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1071
1085
  }
1072
1086
  }
1073
1087
 
1088
+ // Force the renderer to fully recompute its dimensions and resize its
1089
+ // canvases at the current cell metrics — even when cols/rows and the
1090
+ // measured char size are UNCHANGED.
1091
+ //
1092
+ // Why this exists: both cheaper paths short-circuit in that case —
1093
+ // - fitAddon.fit() returns without calling _renderService.clear()/resize()
1094
+ // when the proposed cols/rows equal the current ones, and
1095
+ // - CharSizeService.measure() only fires onCharSizeChange when the
1096
+ // measured width/height actually changed.
1097
+ // So after take-control / screen-sync, nothing forces the WebGL renderer to
1098
+ // re-run _updateDimensions(): it keeps painting at a stale device cell
1099
+ // pitch and the terminal shows the "interlaced black line" pattern.
1100
+ // Pressing font +/- fixed it because an ACTUAL fontSize change fires
1101
+ // handleCharSizeChanged → renderer.handleResize; a window resize fixed it
1102
+ // because the changed container produces different cols/rows and a real
1103
+ // resize. This helper invokes that same full path directly:
1104
+ // _renderService.handleResize → renderer.handleResize →
1105
+ // _updateDimensions() + device-pixel canvas resize + full refresh —
1106
+ // identical to what xterm.js itself runs on a genuine resize event.
1107
+ _forceRendererDimensionRecompute(session) {
1108
+ if (!session || !session.terminal) return;
1109
+ const term = session.terminal;
1110
+ const core = term._core;
1111
+ // Commit any pending char-size change first so the renderer recomputes
1112
+ // from fresh metrics (no-op when the size didn't change).
1113
+ if (core && core._charSizeService && typeof core._charSizeService.measure === 'function') {
1114
+ try { core._charSizeService.measure(); } catch (_) {}
1115
+ }
1116
+ // Full renderer dimension recompute + canvas resize + full refresh.
1117
+ if (core && core._renderService && typeof core._renderService.handleResize === 'function') {
1118
+ try { core._renderService.handleResize(term.cols, term.rows); } catch (_) {}
1119
+ }
1120
+ // Rebuild the WebGL glyph atlas at the recomputed cell pitch.
1121
+ if (session.webglAddon) {
1122
+ try { session.webglAddon.clearTextureAtlas(); } catch (_) {}
1123
+ }
1124
+ try { term.refresh(0, term.rows - 1); } catch (_) {}
1125
+ }
1126
+
1074
1127
  // Sub-pixel seam mitigation is handled by canvas/WebGL renderer +
1075
1128
  // customGlyphs: true, which draws block/box characters as vector fills
1076
1129
  // that meet exactly. letterSpacing nudging doesn't work because xterm.js
@@ -1346,15 +1399,13 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1346
1399
 
1347
1400
  console.log('[SSHIFT] Terminal fitted, cols:', terminal.cols, 'rows:', terminal.rows);
1348
1401
 
1349
- // Resize changes cell metrics; clear the WebGL atlas so glyphs are
1350
- // re-rasterised at the new size rather than stretched from the old cache.
1351
- this._resetWebGLAtlas(session);
1352
-
1353
- // Force a full repaint to flush stale cells from the previous dimensions.
1354
- // This prevents bottom-row garbage and garbled status lines after resize.
1355
- try {
1356
- terminal.refresh(0, terminal.rows - 1);
1357
- } catch (_) {}
1402
+ // Force a full renderer dimension recompute + atlas rebuild + repaint.
1403
+ // A plain atlas clear is NOT enough when fit() proposed the same
1404
+ // cols/rows (fitAddon short-circuits then and the renderer keeps its
1405
+ // stale device cell pitch → interlaced black bands). The recompute
1406
+ // also flushes stale cells from the previous dimensions, preventing
1407
+ // bottom-row garbage and garbled status lines after resize.
1408
+ this._forceRendererDimensionRecompute(session);
1358
1409
 
1359
1410
  return true;
1360
1411
  }
@@ -1432,16 +1483,14 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1432
1483
  console.warn('[SSHIFT] forceResizeLikeRefit: fit failed:', e.message);
1433
1484
  }
1434
1485
 
1435
- // (d) Rebuild the WebGL glyph atlas at the committed cell pitch + repaint.
1436
- // This is the step that actually clears the interlace bands: a stale
1437
- // atlas rasters glyphs at the old (smaller) row pitch and the renderer
1438
- // paints them at the new (taller) pitch, leaving every other row dark.
1439
- if (session.terminal) {
1440
- if (session.webglAddon) {
1441
- try { session.webglAddon.clearTextureAtlas(); } catch (_) {}
1442
- }
1443
- try { session.terminal.refresh(0, session.terminal.rows - 1); } catch (_) {}
1444
- }
1486
+ // (d) Force a full renderer dimension recompute + canvas resize + atlas
1487
+ // rebuild + repaint. This is the step that actually clears the
1488
+ // interlace bands. Crucially it also covers the case where fit()
1489
+ // produced the SAME cols/rows (fitAddon short-circuits then, so
1490
+ // nothing else would force the renderer to re-run
1491
+ // _updateDimensions(), and the stale device cell pitch keeps
1492
+ // painting every other row dark).
1493
+ this._forceRendererDimensionRecompute(session);
1445
1494
 
1446
1495
  // (e) Notify the remote PTY of the corrected dimensions. Mirror the
1447
1496
  // debounced onResize handler but fire immediately so the server's
@@ -4258,6 +4307,63 @@ const wheelHandler = (e) => {
4258
4307
  }
4259
4308
 
4260
4309
  // Socket.IO Listeners
4310
+ // Re-join all live sessions after a Socket.IO reconnect.
4311
+ //
4312
+ // A reconnect gives this client a NEW socket.id. Server-side, the old
4313
+ // socket was removed from every `session-<id>` room and from
4314
+ // session.sockets, and any controller slot it held was reassigned or
4315
+ // cleared. Nothing re-registers the new socket automatically — so without
4316
+ // this, the client keeps its terminal tabs but is no longer part of the
4317
+ // session: it stops receiving reliable output, its controller state goes
4318
+ // stale, and all input is silently dropped by the server's controller
4319
+ // check ("can't type after a stale connection until page reload").
4320
+ // A page reload "fixed" it because the restore path emits ssh-join; this
4321
+ // makes a reconnect equivalent to that reload, without losing the tabs.
4322
+ rejoinActiveSessions() {
4323
+ this.sessions.forEach((session, sessionId) => {
4324
+ // Sessions still mid-connect will complete via their own ssh-connect
4325
+ // flow; only re-join sessions that were already live on the server.
4326
+ if (!session.connected) return;
4327
+ console.log('[SSHIFT] Rejoining SSH session after reconnect:', sessionId);
4328
+
4329
+ // If we held control before the connection dropped, re-take it after
4330
+ // the rejoin completes (consumed by the ssh-joined handler; guarded
4331
+ // there so we never steal control another client acquired meanwhile).
4332
+ session._retakeControlOnRejoin = !!session.isController;
4333
+
4334
+ // Mark as restoring so a "Session not found" reply routes into the
4335
+ // credential-based auto-reconnect path instead of closing the tab.
4336
+ session.isRestoring = true;
4337
+
4338
+ // Block ssh-data writes until the fresh ssh-screen-sync (sent by the
4339
+ // server on join) has been applied, with the same watchdog/retry
4340
+ // pattern used by the createSSHTab restore path.
4341
+ session.syncing = true;
4342
+ session._syncRetries = 0;
4343
+ if (session.syncTimeout) {
4344
+ clearTimeout(session.syncTimeout);
4345
+ }
4346
+ session.syncTimeout = setTimeout(() => {
4347
+ console.warn('[SSHIFT] Sync timeout after rejoin for session:', sessionId);
4348
+ session.syncing = false;
4349
+ if (session.connected) {
4350
+ this.requestScreenSync(sessionId);
4351
+ }
4352
+ }, 5000);
4353
+
4354
+ this.socket.emit('ssh-join', { sessionId });
4355
+ });
4356
+
4357
+ // SFTP sessions: re-register with the server-side session so viewer
4358
+ // counting and sticky/grace teardown timers see this client again.
4359
+ this.sftpSessions.forEach((session, sessionId) => {
4360
+ if (session.connecting) return;
4361
+ console.log('[SSHIFT] Rejoining SFTP session after reconnect:', sessionId);
4362
+ session.isRestoring = true;
4363
+ this.socket.emit('sftp-join', { sessionId });
4364
+ });
4365
+ }
4366
+
4261
4367
  setupSocketListeners() {
4262
4368
  this.socket.on('connect', () => {
4263
4369
  console.log('[SSHIFT] Connected to server, socket ID:', this.socket.id);
@@ -4265,6 +4371,9 @@ const wheelHandler = (e) => {
4265
4371
  this._wasDisconnected = false;
4266
4372
  if (wasDisconnected && !this.isUpdating) {
4267
4373
  this.showToast('Reconnected to server', 'success');
4374
+ // The new socket must re-join its sessions (rooms + controller
4375
+ // state are keyed by socket.id and were lost with the old socket).
4376
+ this.rejoinActiveSessions();
4268
4377
  } else if (!this.isUpdating) {
4269
4378
  this.showToast('Connected to server', 'success');
4270
4379
  }
@@ -4555,22 +4664,26 @@ const wheelHandler = (e) => {
4555
4664
  // Show/hide control overlay based on controller status
4556
4665
  this.updateControlOverlay(data.sessionId);
4557
4666
 
4558
- // If takeControlDefault is enabled and we're not the controller, take control
4559
- // BUT only if there's no controller OR we're the only client in the session
4560
- // This prevents "control wars" where multiple clients keep taking control from each other
4561
- if (this.takeControlDefault && !data.isController) {
4667
+ // If takeControlDefault is enabled (or we held control before a
4668
+ // socket reconnect — see rejoinActiveSessions) and we're not the
4669
+ // controller, take control BUT only if there's no controller OR
4670
+ // we're the only client in the session. This prevents "control wars"
4671
+ // where multiple clients keep taking control from each other.
4672
+ const retakeAfterRejoin = !!session._retakeControlOnRejoin;
4673
+ session._retakeControlOnRejoin = false;
4674
+ if ((this.takeControlDefault || retakeAfterRejoin) && !data.isController) {
4562
4675
  const noController = !data.controllerSocket;
4563
4676
  const onlyClient = data.socketCount === 1;
4564
4677
 
4565
4678
  if (noController || onlyClient) {
4566
- console.log('[SSHIFT] takeControlDefault enabled, taking control (no controller or only client)...');
4679
+ console.log('[SSHIFT] Taking control (takeControlDefault:', this.takeControlDefault, 'retakeAfterRejoin:', retakeAfterRejoin, ')...');
4567
4680
  // Delay to ensure the session is fully set up
4568
4681
  const delay = 100 + Math.random() * 200; // 100-300ms
4569
4682
  setTimeout(() => {
4570
- this.requestTakeControl(sessionId);
4683
+ this.requestTakeControl(data.sessionId);
4571
4684
  }, delay);
4572
4685
  } else {
4573
- console.log('[SSHIFT] takeControlDefault enabled but not taking control - another client is already in control');
4686
+ console.log('[SSHIFT] Not taking control - another client is already in control');
4574
4687
  }
4575
4688
  }
4576
4689
 
@@ -4661,10 +4774,13 @@ const wheelHandler = (e) => {
4661
4774
  // produce the "interlaced / every-other-row blank" bug
4662
4775
  // (visible after "Take Control" on a just-refreshed
4663
4776
  // browser tab; fixed when the user manually resizes the
4664
- // window because that re-runs _fitTerminal → _resetWebGLAtlas).
4665
- // Clear the atlas here so the renderer re-rasterises at
4666
- // the post-sync cell dimensions.
4667
- this._resetWebGLAtlas(session);
4777
+ // window because that re-runs the renderer resize path).
4778
+ // Note: when the terminal is ALREADY at data.cols/rows the
4779
+ // resize() above short-circuits inside xterm.js, so a plain
4780
+ // atlas clear is not enough — force the full renderer
4781
+ // dimension recompute (same path as a real resize) so the
4782
+ // device cell pitch is recomputed and the atlas rebuilt.
4783
+ this._forceRendererDimensionRecompute(session);
4668
4784
 
4669
4785
  // Clear the resyncing flag after a short delay
4670
4786
  setTimeout(() => {
@@ -6047,6 +6163,11 @@ const wheelHandler = (e) => {
6047
6163
  console.error('[SSHIFT] Failed to load Speech & AI config:', err);
6048
6164
  });
6049
6165
 
6166
+ // Load Speech & AI profile names into the fast-swap dropdown.
6167
+ this.loadSpeechAiProfiles().catch(err => {
6168
+ console.error('[SSHIFT] Failed to load Speech & AI profiles:', err);
6169
+ });
6170
+
6050
6171
  // Reset to first category
6051
6172
  this.switchSettingsCategory('sessions');
6052
6173
 
@@ -6134,6 +6255,120 @@ const wheelHandler = (e) => {
6134
6255
  }
6135
6256
  }
6136
6257
 
6258
+ // ---- Speech & AI: settings profiles -----------------------------------
6259
+ // Named snapshots of the Speech & AI tab, stored server-side (auth keys
6260
+ // included — they never travel through the browser). The dropdown swaps
6261
+ // the active settings in one click; Save snapshots the current fields
6262
+ // under a name; Delete removes a snapshot.
6263
+
6264
+ async loadSpeechAiProfiles(selectedName = null) {
6265
+ const select = document.getElementById('speechAiProfileSelect');
6266
+ if (!select) return;
6267
+
6268
+ const res = await fetch('/api/speech-ai/profiles');
6269
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
6270
+ const data = await res.json();
6271
+ const profiles = Array.isArray(data.profiles) ? data.profiles : [];
6272
+
6273
+ const keep = selectedName !== null ? selectedName : select.value;
6274
+
6275
+ select.innerHTML = '';
6276
+ const placeholder = document.createElement('option');
6277
+ placeholder.value = '';
6278
+ placeholder.textContent = '— Select profile —';
6279
+ select.appendChild(placeholder);
6280
+
6281
+ for (const name of profiles) {
6282
+ const opt = document.createElement('option');
6283
+ opt.value = name;
6284
+ opt.textContent = name;
6285
+ select.appendChild(opt);
6286
+ }
6287
+
6288
+ select.value = (keep && profiles.includes(keep)) ? keep : '';
6289
+ }
6290
+
6291
+ initSpeechAiProfileHandlers() {
6292
+ const select = document.getElementById('speechAiProfileSelect');
6293
+ const nameInput = document.getElementById('speechAiProfileName');
6294
+ const saveBtn = document.getElementById('saveSpeechAiProfileBtn');
6295
+ const deleteBtn = document.getElementById('deleteSpeechAiProfileBtn');
6296
+
6297
+ // Selecting a profile applies it immediately (fast swap): the server
6298
+ // copies the snapshot into the active config, then we re-fetch the
6299
+ // (redacted) config so the tab fields reflect the loaded profile.
6300
+ if (select) {
6301
+ select.addEventListener('change', async () => {
6302
+ const name = select.value;
6303
+ if (nameInput) nameInput.value = name;
6304
+ if (!name) return;
6305
+ try {
6306
+ const res = await fetch('/api/speech-ai/profiles/load', {
6307
+ method: 'POST',
6308
+ headers: { 'Content-Type': 'application/json' },
6309
+ body: JSON.stringify({ name })
6310
+ });
6311
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
6312
+ await this.loadSpeechAiConfig();
6313
+ this.showToast(`Loaded Speech & AI profile "${name}"`, 'success');
6314
+ } catch (err) {
6315
+ console.error('[SSHIFT] Failed to load Speech & AI profile:', err);
6316
+ this.showToast('Failed to load profile', 'error');
6317
+ }
6318
+ });
6319
+ }
6320
+
6321
+ if (saveBtn) {
6322
+ saveBtn.addEventListener('click', async () => {
6323
+ const name = ((nameInput && nameInput.value) || (select && select.value) || '').trim();
6324
+ if (!name) {
6325
+ this.showToast('Enter a profile name first', 'warning');
6326
+ return;
6327
+ }
6328
+ try {
6329
+ // Persist the on-screen fields to the active config first so the
6330
+ // profile snapshots exactly what the user sees. Auth keys left
6331
+ // blank are preserved server-side via the __UNCHANGED__ sentinel.
6332
+ await this.saveSpeechAiConfig();
6333
+ const res = await fetch('/api/speech-ai/profiles', {
6334
+ method: 'POST',
6335
+ headers: { 'Content-Type': 'application/json' },
6336
+ body: JSON.stringify({ name })
6337
+ });
6338
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
6339
+ await this.loadSpeechAiProfiles(name);
6340
+ this.showToast(`Saved Speech & AI profile "${name}"`, 'success');
6341
+ } catch (err) {
6342
+ console.error('[SSHIFT] Failed to save Speech & AI profile:', err);
6343
+ this.showToast('Failed to save profile', 'error');
6344
+ }
6345
+ });
6346
+ }
6347
+
6348
+ if (deleteBtn) {
6349
+ deleteBtn.addEventListener('click', async () => {
6350
+ const name = ((select && select.value) || (nameInput && nameInput.value) || '').trim();
6351
+ if (!name) {
6352
+ this.showToast('Select a profile to delete', 'warning');
6353
+ return;
6354
+ }
6355
+ if (!confirm(`Delete Speech & AI profile "${name}"? The active settings are not changed.`)) return;
6356
+ try {
6357
+ const res = await fetch(`/api/speech-ai/profiles/${encodeURIComponent(name)}`, {
6358
+ method: 'DELETE'
6359
+ });
6360
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
6361
+ if (nameInput) nameInput.value = '';
6362
+ await this.loadSpeechAiProfiles('');
6363
+ this.showToast(`Deleted profile "${name}"`, 'success');
6364
+ } catch (err) {
6365
+ console.error('[SSHIFT] Failed to delete Speech & AI profile:', err);
6366
+ this.showToast('Failed to delete profile', 'error');
6367
+ }
6368
+ });
6369
+ }
6370
+ }
6371
+
6137
6372
  initSettingsModalHandlers() {
6138
6373
  // Settings category navigation (sidebar + mobile dropdown)
6139
6374
  const navItems = document.querySelectorAll('.settings-nav-item');
@@ -6142,6 +6377,9 @@ const wheelHandler = (e) => {
6142
6377
  this.switchSettingsCategory(item.dataset.category);
6143
6378
  });
6144
6379
  });
6380
+
6381
+ // Speech & AI profile dropdown (load/save/delete)
6382
+ this.initSpeechAiProfileHandlers();
6145
6383
 
6146
6384
  const categorySelect = document.getElementById('settingsCategorySelect');
6147
6385
  if (categorySelect) {
@@ -55,11 +55,10 @@ class MobileTerminalHandler {
55
55
  this.contextMenu = null;
56
56
  this.hiddenTextarea = null;
57
57
  this._isComposing = false;
58
- this._compositionText = '';
59
- this._compositionEndTs = 0;
60
- this._lastSentInput = '';
61
- this._lastSentInputTs = 0;
62
- this._previousTextareaValue = '';
58
+ // Full textarea content that has already been synced (sent) to the
59
+ // terminal. All input diffing runs against this persistent baseline —
60
+ // see _syncTextareaToTerminal().
61
+ this._sentValue = '';
63
62
  this.contextMenuUserPositioned = false; // Track if user has manually positioned the menu
64
63
 
65
64
  // Configuration
@@ -464,88 +463,47 @@ class MobileTerminalHandler {
464
463
  });
465
464
 
466
465
  // Handle input events (for virtual keyboard)
467
- // We let the textarea accumulate text so that Gboard autocorrect can
468
- // operate on it (replacing a misspelled word with the correction).
469
- // Diff tracking between beforeinput and input events computes the delta
470
- // to send to the terminal, handling insertText, deleteContentBackward,
471
- // and insertReplacementText (Gboard autocorrect) uniformly.
472
- this.hiddenTextarea.addEventListener('beforeinput', (e) => {
473
- if (e.isComposing) return;
474
- if (this._isComposing) return;
475
- if (e.inputType === 'insertCompositionText') return;
476
- this._previousTextareaValue = this.hiddenTextarea.value;
477
- });
478
-
466
+ //
467
+ // The textarea accumulates what the user typed so IME/autocorrect
468
+ // keyboards (Gboard etc.) can operate on real text (replacing a
469
+ // misspelled word with the correction, inserting suggestions, ...).
470
+ //
471
+ // We mirror the textarea into the terminal by diffing its content
472
+ // against `_sentValue` — the content we've already sent — inside
473
+ // _syncTextareaToTerminal(). Diffing against a PERSISTENT baseline
474
+ // (instead of a per-event `beforeinput` snapshot) makes the sync
475
+ // idempotent: Gboard fires input/composition events in
476
+ // device-specific orders around suggestion taps, sometimes without a
477
+ // matching beforeinput, and any event sequence now converges to the
478
+ // textarea content being sent exactly once.
479
+ //
480
+ // This fixes the "each autocomplete tap re-types the whole line" loop:
481
+ // the old per-event snapshot was reset to '' after every input and on
482
+ // compositionend, so an input event arriving without a fresh snapshot
483
+ // treated the ENTIRE textarea as newly-appended text and re-sent it.
484
+ // Worse, a post-compositionend guard overwrote the textarea with that
485
+ // empty snapshot, desyncing Gboard's own state from the textarea and
486
+ // making it re-insert the full text on the next suggestion tap.
479
487
  this.hiddenTextarea.addEventListener('input', (e) => {
480
488
  if (this.touchState.isSelecting) {
481
489
  e.preventDefault();
482
- this.hiddenTextarea.value = '';
483
- this._previousTextareaValue = '';
490
+ this._resetInputTracking();
484
491
  return;
485
492
  }
486
493
 
487
- if (e.isComposing) {
488
- return;
489
- }
490
-
491
- if (this._isComposing) {
492
- return;
493
- }
494
-
495
- if (e.inputType === 'insertCompositionText') {
496
- return;
497
- }
498
-
499
- // Guard against double-sending after compositionend.
500
- if (this._compositionEndTs && (Date.now() - this._compositionEndTs) < 300) {
501
- this.hiddenTextarea.value = this._previousTextareaValue;
502
- this._previousTextareaValue = '';
494
+ // While a composition is in flight we don't send anything; the
495
+ // textarea is synced once on compositionend. (Sending live
496
+ // composition updates would spam the terminal with backspace/retype
497
+ // churn while the IME reshapes the word.)
498
+ if (e.isComposing || this._isComposing || e.inputType === 'insertCompositionText') {
503
499
  return;
504
500
  }
505
501
 
506
502
  if (this.touchState.isDragging) {
507
- this._previousTextareaValue = '';
508
503
  return;
509
504
  }
510
505
 
511
- const prev = this._previousTextareaValue;
512
- const curr = this.hiddenTextarea.value;
513
-
514
- if (curr === prev) {
515
- // No change, nothing to send.
516
- } else if (curr.length > prev.length && curr.startsWith(prev)) {
517
- // Simple append: previous text unchanged, new text appended.
518
- this._sendToTerminal(curr.substring(prev.length));
519
- this._lastSentInput = curr.substring(curr.length - 1);
520
- this._lastSentInputTs = Date.now();
521
- } else {
522
- // Complex change (replacement, deletion, or mixed).
523
- // Find common prefix and suffix to minimize the diff.
524
- let prefixLen = 0;
525
- while (prefixLen < prev.length && prefixLen < curr.length && prev[prefixLen] === curr[prefixLen]) {
526
- prefixLen++;
527
- }
528
- let suffixLen = 0;
529
- while (
530
- suffixLen < (prev.length - prefixLen) &&
531
- suffixLen < (curr.length - prefixLen) &&
532
- prev[prev.length - 1 - suffixLen] === curr[curr.length - 1 - suffixLen]
533
- ) {
534
- suffixLen++;
535
- }
536
- const deletedCount = prev.length - prefixLen - suffixLen;
537
- const inserted = curr.substring(prefixLen, curr.length - suffixLen);
538
- if (deletedCount > 0) {
539
- this._sendToTerminal('\x7f'.repeat(deletedCount));
540
- }
541
- if (inserted) {
542
- this._sendToTerminal(inserted);
543
- }
544
- this._lastSentInput = inserted || '';
545
- this._lastSentInputTs = Date.now();
546
- }
547
-
548
- this._previousTextareaValue = '';
506
+ this._syncTextareaToTerminal();
549
507
  });
550
508
 
551
509
  // Handle keydown for special keys
@@ -563,11 +521,10 @@ class MobileTerminalHandler {
563
521
  if (e.key === 'Enter') {
564
522
  e.preventDefault();
565
523
  this._sendToTerminal('\r');
566
- this.hiddenTextarea.value = '';
567
- this._previousTextareaValue = '';
524
+ this._resetInputTracking();
568
525
  } else if (e.key === 'Backspace') {
569
- // Let the browser handle backspace in the textarea; the beforeinput/input
570
- // diff will detect the deletion and send \x7f to the terminal.
526
+ // Let the browser handle backspace in the textarea; the input diff
527
+ // will detect the deletion and send \x7f to the terminal.
571
528
  // Only prevent default if the textarea is empty (nothing to delete).
572
529
  if (!this.hiddenTextarea.value) {
573
530
  e.preventDefault();
@@ -576,8 +533,7 @@ class MobileTerminalHandler {
576
533
  } else if (e.key === 'Tab') {
577
534
  e.preventDefault();
578
535
  this._sendToTerminal('\t');
579
- this.hiddenTextarea.value = '';
580
- this._previousTextareaValue = '';
536
+ this._resetInputTracking();
581
537
  }
582
538
  });
583
539
 
@@ -594,42 +550,101 @@ class MobileTerminalHandler {
594
550
  // Composition events for IME/autocomplete handling
595
551
  this.hiddenTextarea.addEventListener('compositionstart', () => {
596
552
  this._isComposing = true;
597
- this._compositionText = '';
598
- this._previousTextareaValue = '';
599
- });
600
-
601
- this.hiddenTextarea.addEventListener('compositionupdate', (e) => {
602
- this._compositionText = e.data || '';
603
553
  });
604
554
 
605
- this.hiddenTextarea.addEventListener('compositionend', (e) => {
555
+ this.hiddenTextarea.addEventListener('compositionend', () => {
606
556
  this._isComposing = false;
607
- this._compositionEndTs = Date.now();
608
- const composed = e.data || this._compositionText;
609
- if (composed && !this.touchState.isDragging) {
610
- // Avoid re-sending text that was already sent via an input event
611
- // that fired before compositionstart (Gboard timing quirk).
612
- if (this._lastSentInput && (Date.now() - this._lastSentInputTs) < 500) {
613
- if (composed === this._lastSentInput) {
614
- this._lastSentInput = '';
615
- this._lastSentInputTs = 0;
616
- } else if (composed.startsWith(this._lastSentInput)) {
617
- this._sendToTerminal(composed.substring(this._lastSentInput.length));
618
- this._lastSentInput = '';
619
- this._lastSentInputTs = 0;
620
- } else {
621
- this._sendToTerminal(composed);
622
- }
623
- } else {
624
- this._sendToTerminal(composed);
625
- }
557
+ // Sync whatever the composition left in the textarea. Because the
558
+ // diff runs against the persistent _sentValue baseline, this is
559
+ // idempotent: text that was already sent by an input event firing
560
+ // before compositionstart (a Gboard timing quirk) is not re-sent,
561
+ // and a duplicate input event firing right after compositionend
562
+ // diffs to nothing.
563
+ if (!this.touchState.isDragging) {
564
+ this._syncTextareaToTerminal();
626
565
  }
627
- this._compositionText = '';
628
- this._lastSentInput = '';
629
- this._lastSentInputTs = 0;
630
- this._previousTextareaValue = '';
631
566
  });
632
567
  }
568
+
569
+ /**
570
+ * Reset the textarea input tracking: clear the textarea and the
571
+ * synced-content baseline together so future diffs start from a clean
572
+ * state. Must be used everywhere the textarea is cleared — clearing one
573
+ * without the other makes the next diff re-send or drop text.
574
+ * @private
575
+ */
576
+ _resetInputTracking() {
577
+ if (this.hiddenTextarea) {
578
+ this.hiddenTextarea.value = '';
579
+ }
580
+ this._sentValue = '';
581
+ }
582
+
583
+ /**
584
+ * Diff the textarea content against what has already been sent to the
585
+ * terminal (_sentValue) and emit only the delta.
586
+ *
587
+ * The terminal cursor sits at the end of the text we've sent, so a
588
+ * change at position P is realised as: erase back to P with DEL (\x7f),
589
+ * then retype everything from P onward. (Erasing only the changed middle
590
+ * span — like the previous implementation did — is impossible with a
591
+ * cursor at the end and corrupted the line on mid-word autocorrect.)
592
+ *
593
+ * The sync is idempotent: calling it twice in a row sends nothing the
594
+ * second time. This property is what makes Gboard's unpredictable
595
+ * input/composition event interleavings safe.
596
+ * @private
597
+ */
598
+ _syncTextareaToTerminal() {
599
+ if (!this.hiddenTextarea) return;
600
+ const prev = this._sentValue;
601
+ const curr = this.hiddenTextarea.value;
602
+ if (curr === prev) return;
603
+
604
+ // Longest common prefix.
605
+ let prefixLen = 0;
606
+ const minLen = Math.min(prev.length, curr.length);
607
+ while (prefixLen < minLen && prev[prefixLen] === curr[prefixLen]) {
608
+ prefixLen++;
609
+ }
610
+ // Never split a surrogate pair: if the common prefix ends between a
611
+ // high and low surrogate, back off one unit so the deletion count and
612
+ // the retyped text operate on whole code points.
613
+ if (prefixLen > 0 && prefixLen < prev.length && prefixLen < curr.length) {
614
+ const beforeCode = prev.charCodeAt(prefixLen - 1);
615
+ if (beforeCode >= 0xD800 && beforeCode <= 0xDBFF) {
616
+ prefixLen--;
617
+ }
618
+ }
619
+
620
+ // Erase back to the divergence point. Count code points (not UTF-16
621
+ // units) so astral characters (emoji etc.) get one DEL each.
622
+ const removed = prev.substring(prefixLen);
623
+ const deleteCount = removed ? Array.from(removed).length : 0;
624
+
625
+ // Retype the remainder. Translate newlines (some keyboards commit
626
+ // Enter through the input path instead of a keydown) into \r.
627
+ let insert = curr.substring(prefixLen);
628
+ const hadNewline = /[\r\n]/.test(insert);
629
+ if (hadNewline) {
630
+ insert = insert.replace(/\r\n/g, '\r').replace(/\n/g, '\r');
631
+ }
632
+
633
+ if (deleteCount > 0) {
634
+ this._sendToTerminal('\x7f'.repeat(deleteCount));
635
+ }
636
+ if (insert) {
637
+ this._sendToTerminal(insert);
638
+ }
639
+
640
+ if (hadNewline) {
641
+ // The line was submitted — start from a clean slate (mirrors the
642
+ // Enter keydown path).
643
+ this._resetInputTracking();
644
+ } else {
645
+ this._sentValue = curr;
646
+ }
647
+ }
633
648
 
634
649
  /**
635
650
  * Attach event listeners to terminal element
@@ -1479,8 +1494,7 @@ class MobileTerminalHandler {
1479
1494
  // starts from a clean state. Gboard autocorrect operates on the
1480
1495
  // textarea content, so stale text from a previous focus would
1481
1496
  // produce incorrect diffs.
1482
- this.hiddenTextarea.value = '';
1483
- this._previousTextareaValue = '';
1497
+ this._resetInputTracking();
1484
1498
  this.hiddenTextarea.focus();
1485
1499
  }
1486
1500
  }