@lethevimlet/sshift 1.6.1 → 1.7.1
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 +1 -1
- package/src/server/endpoints/rest/speech-ai.js +81 -1
- package/src/server/utils/config.js +85 -1
- package/src/webapp/css/style.css +17 -0
- package/src/webapp/index.html +29 -0
- package/src/webapp/js/app.js +361 -67
- package/src/webapp/js/mobile-terminal.js +126 -112
package/package.json
CHANGED
|
@@ -18,7 +18,16 @@
|
|
|
18
18
|
const os = require('os');
|
|
19
19
|
const path = require('path');
|
|
20
20
|
const fs = require('fs');
|
|
21
|
-
const {
|
|
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
|
};
|
package/src/webapp/css/style.css
CHANGED
|
@@ -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;
|
package/src/webapp/index.html
CHANGED
|
@@ -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 & 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 & 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">
|
package/src/webapp/js/app.js
CHANGED
|
@@ -49,7 +49,7 @@ class SSHIFTClient {
|
|
|
49
49
|
this.sftpClipboard = null; // For cut/copy/paste: { action: 'cut'|'copy', path: string, name: string, sessionId: string }
|
|
50
50
|
this.terminalClipboardContent = null; // Pre-read clipboard content for context menu paste
|
|
51
51
|
this.osc52Buffer = null; // Buffered OSC 52 clipboard content pending write
|
|
52
|
-
this.terminalColorOverride =
|
|
52
|
+
this.terminalColorOverride = false; // Default OFF — loaded per theme in initThemeAndAccent
|
|
53
53
|
this.terminalBgColor = '#0d1117';
|
|
54
54
|
this.terminalFgColor = '#e6edf3';
|
|
55
55
|
this.terminalSelectionColor = '#264f78';
|
|
@@ -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
|
-
|
|
937
|
-
|
|
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
|
-
//
|
|
1350
|
-
//
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
//
|
|
1354
|
-
//
|
|
1355
|
-
|
|
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)
|
|
1436
|
-
// This is the step that actually clears the
|
|
1437
|
-
//
|
|
1438
|
-
//
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
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
|
|
@@ -1609,13 +1658,20 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
|
|
|
1609
1658
|
return defaultTheme;
|
|
1610
1659
|
}
|
|
1611
1660
|
|
|
1612
|
-
// When override is enabled, use custom colors from settings
|
|
1661
|
+
// When override is enabled, use custom colors from settings.
|
|
1662
|
+
// Sanitize each color: a corrupt value (e.g. the literal string
|
|
1663
|
+
// "undefined" persisted by old buggy saves) is truthy, so a plain
|
|
1664
|
+
// `value || default` passes it straight to xterm.js — which renders
|
|
1665
|
+
// unparseable colors as #000000 (black-on-black = "override broken").
|
|
1666
|
+
const bg = this._sanitizeHexColor(this.terminalBgColor, '#0d1117');
|
|
1667
|
+
const fg = this._sanitizeHexColor(this.terminalFgColor, '#e6edf3');
|
|
1668
|
+
const sel = this._sanitizeHexColor(this.terminalSelectionColor, '#264f78');
|
|
1613
1669
|
const customTheme = {
|
|
1614
|
-
background:
|
|
1615
|
-
foreground:
|
|
1670
|
+
background: bg,
|
|
1671
|
+
foreground: fg,
|
|
1616
1672
|
cursor: '#c10059',
|
|
1617
|
-
cursorAccent:
|
|
1618
|
-
selectionBackground: this.hexToRgba(
|
|
1673
|
+
cursorAccent: bg,
|
|
1674
|
+
selectionBackground: this.hexToRgba(sel, 0.5),
|
|
1619
1675
|
black: isDark ? '#484f58' : '#6e7681',
|
|
1620
1676
|
red: '#f85149',
|
|
1621
1677
|
green: '#3fb950',
|
|
@@ -4258,6 +4314,63 @@ const wheelHandler = (e) => {
|
|
|
4258
4314
|
}
|
|
4259
4315
|
|
|
4260
4316
|
// Socket.IO Listeners
|
|
4317
|
+
// Re-join all live sessions after a Socket.IO reconnect.
|
|
4318
|
+
//
|
|
4319
|
+
// A reconnect gives this client a NEW socket.id. Server-side, the old
|
|
4320
|
+
// socket was removed from every `session-<id>` room and from
|
|
4321
|
+
// session.sockets, and any controller slot it held was reassigned or
|
|
4322
|
+
// cleared. Nothing re-registers the new socket automatically — so without
|
|
4323
|
+
// this, the client keeps its terminal tabs but is no longer part of the
|
|
4324
|
+
// session: it stops receiving reliable output, its controller state goes
|
|
4325
|
+
// stale, and all input is silently dropped by the server's controller
|
|
4326
|
+
// check ("can't type after a stale connection until page reload").
|
|
4327
|
+
// A page reload "fixed" it because the restore path emits ssh-join; this
|
|
4328
|
+
// makes a reconnect equivalent to that reload, without losing the tabs.
|
|
4329
|
+
rejoinActiveSessions() {
|
|
4330
|
+
this.sessions.forEach((session, sessionId) => {
|
|
4331
|
+
// Sessions still mid-connect will complete via their own ssh-connect
|
|
4332
|
+
// flow; only re-join sessions that were already live on the server.
|
|
4333
|
+
if (!session.connected) return;
|
|
4334
|
+
console.log('[SSHIFT] Rejoining SSH session after reconnect:', sessionId);
|
|
4335
|
+
|
|
4336
|
+
// If we held control before the connection dropped, re-take it after
|
|
4337
|
+
// the rejoin completes (consumed by the ssh-joined handler; guarded
|
|
4338
|
+
// there so we never steal control another client acquired meanwhile).
|
|
4339
|
+
session._retakeControlOnRejoin = !!session.isController;
|
|
4340
|
+
|
|
4341
|
+
// Mark as restoring so a "Session not found" reply routes into the
|
|
4342
|
+
// credential-based auto-reconnect path instead of closing the tab.
|
|
4343
|
+
session.isRestoring = true;
|
|
4344
|
+
|
|
4345
|
+
// Block ssh-data writes until the fresh ssh-screen-sync (sent by the
|
|
4346
|
+
// server on join) has been applied, with the same watchdog/retry
|
|
4347
|
+
// pattern used by the createSSHTab restore path.
|
|
4348
|
+
session.syncing = true;
|
|
4349
|
+
session._syncRetries = 0;
|
|
4350
|
+
if (session.syncTimeout) {
|
|
4351
|
+
clearTimeout(session.syncTimeout);
|
|
4352
|
+
}
|
|
4353
|
+
session.syncTimeout = setTimeout(() => {
|
|
4354
|
+
console.warn('[SSHIFT] Sync timeout after rejoin for session:', sessionId);
|
|
4355
|
+
session.syncing = false;
|
|
4356
|
+
if (session.connected) {
|
|
4357
|
+
this.requestScreenSync(sessionId);
|
|
4358
|
+
}
|
|
4359
|
+
}, 5000);
|
|
4360
|
+
|
|
4361
|
+
this.socket.emit('ssh-join', { sessionId });
|
|
4362
|
+
});
|
|
4363
|
+
|
|
4364
|
+
// SFTP sessions: re-register with the server-side session so viewer
|
|
4365
|
+
// counting and sticky/grace teardown timers see this client again.
|
|
4366
|
+
this.sftpSessions.forEach((session, sessionId) => {
|
|
4367
|
+
if (session.connecting) return;
|
|
4368
|
+
console.log('[SSHIFT] Rejoining SFTP session after reconnect:', sessionId);
|
|
4369
|
+
session.isRestoring = true;
|
|
4370
|
+
this.socket.emit('sftp-join', { sessionId });
|
|
4371
|
+
});
|
|
4372
|
+
}
|
|
4373
|
+
|
|
4261
4374
|
setupSocketListeners() {
|
|
4262
4375
|
this.socket.on('connect', () => {
|
|
4263
4376
|
console.log('[SSHIFT] Connected to server, socket ID:', this.socket.id);
|
|
@@ -4265,6 +4378,9 @@ const wheelHandler = (e) => {
|
|
|
4265
4378
|
this._wasDisconnected = false;
|
|
4266
4379
|
if (wasDisconnected && !this.isUpdating) {
|
|
4267
4380
|
this.showToast('Reconnected to server', 'success');
|
|
4381
|
+
// The new socket must re-join its sessions (rooms + controller
|
|
4382
|
+
// state are keyed by socket.id and were lost with the old socket).
|
|
4383
|
+
this.rejoinActiveSessions();
|
|
4268
4384
|
} else if (!this.isUpdating) {
|
|
4269
4385
|
this.showToast('Connected to server', 'success');
|
|
4270
4386
|
}
|
|
@@ -4328,6 +4444,12 @@ const wheelHandler = (e) => {
|
|
|
4328
4444
|
this.theme = data.theme;
|
|
4329
4445
|
this.saveTheme(data.theme);
|
|
4330
4446
|
this.updateThemeIcon(data.theme);
|
|
4447
|
+
// Terminal color settings are stored PER THEME — load the new
|
|
4448
|
+
// theme's set before repainting, otherwise the previous theme's
|
|
4449
|
+
// override/colors leak into this theme (and a later save would
|
|
4450
|
+
// persist them under the wrong key).
|
|
4451
|
+
this.loadTerminalColorSettings();
|
|
4452
|
+
this.updateTerminalColorOverrideUI();
|
|
4331
4453
|
this.updateTerminalThemes(data.theme);
|
|
4332
4454
|
}
|
|
4333
4455
|
}
|
|
@@ -4472,6 +4594,11 @@ const wheelHandler = (e) => {
|
|
|
4472
4594
|
this.theme = data.theme;
|
|
4473
4595
|
this.saveTheme(data.theme);
|
|
4474
4596
|
this.updateThemeIcon(data.theme);
|
|
4597
|
+
// Load the new theme's per-theme terminal color settings before
|
|
4598
|
+
// repainting (mirrors toggleTheme) so override/colors don't leak
|
|
4599
|
+
// between themes.
|
|
4600
|
+
this.loadTerminalColorSettings();
|
|
4601
|
+
this.updateTerminalColorOverrideUI();
|
|
4475
4602
|
this.updateTerminalThemes(data.theme);
|
|
4476
4603
|
}
|
|
4477
4604
|
});
|
|
@@ -4555,22 +4682,26 @@ const wheelHandler = (e) => {
|
|
|
4555
4682
|
// Show/hide control overlay based on controller status
|
|
4556
4683
|
this.updateControlOverlay(data.sessionId);
|
|
4557
4684
|
|
|
4558
|
-
// If takeControlDefault is enabled
|
|
4559
|
-
//
|
|
4560
|
-
//
|
|
4561
|
-
|
|
4685
|
+
// If takeControlDefault is enabled (or we held control before a
|
|
4686
|
+
// socket reconnect — see rejoinActiveSessions) and we're not the
|
|
4687
|
+
// controller, take control BUT only if there's no controller OR
|
|
4688
|
+
// we're the only client in the session. This prevents "control wars"
|
|
4689
|
+
// where multiple clients keep taking control from each other.
|
|
4690
|
+
const retakeAfterRejoin = !!session._retakeControlOnRejoin;
|
|
4691
|
+
session._retakeControlOnRejoin = false;
|
|
4692
|
+
if ((this.takeControlDefault || retakeAfterRejoin) && !data.isController) {
|
|
4562
4693
|
const noController = !data.controllerSocket;
|
|
4563
4694
|
const onlyClient = data.socketCount === 1;
|
|
4564
4695
|
|
|
4565
4696
|
if (noController || onlyClient) {
|
|
4566
|
-
console.log('[SSHIFT]
|
|
4697
|
+
console.log('[SSHIFT] Taking control (takeControlDefault:', this.takeControlDefault, 'retakeAfterRejoin:', retakeAfterRejoin, ')...');
|
|
4567
4698
|
// Delay to ensure the session is fully set up
|
|
4568
4699
|
const delay = 100 + Math.random() * 200; // 100-300ms
|
|
4569
4700
|
setTimeout(() => {
|
|
4570
|
-
this.requestTakeControl(sessionId);
|
|
4701
|
+
this.requestTakeControl(data.sessionId);
|
|
4571
4702
|
}, delay);
|
|
4572
4703
|
} else {
|
|
4573
|
-
console.log('[SSHIFT]
|
|
4704
|
+
console.log('[SSHIFT] Not taking control - another client is already in control');
|
|
4574
4705
|
}
|
|
4575
4706
|
}
|
|
4576
4707
|
|
|
@@ -4661,10 +4792,13 @@ const wheelHandler = (e) => {
|
|
|
4661
4792
|
// produce the "interlaced / every-other-row blank" bug
|
|
4662
4793
|
// (visible after "Take Control" on a just-refreshed
|
|
4663
4794
|
// browser tab; fixed when the user manually resizes the
|
|
4664
|
-
// window because that re-runs
|
|
4665
|
-
//
|
|
4666
|
-
//
|
|
4667
|
-
|
|
4795
|
+
// window because that re-runs the renderer resize path).
|
|
4796
|
+
// Note: when the terminal is ALREADY at data.cols/rows the
|
|
4797
|
+
// resize() above short-circuits inside xterm.js, so a plain
|
|
4798
|
+
// atlas clear is not enough — force the full renderer
|
|
4799
|
+
// dimension recompute (same path as a real resize) so the
|
|
4800
|
+
// device cell pitch is recomputed and the atlas rebuilt.
|
|
4801
|
+
this._forceRendererDimensionRecompute(session);
|
|
4668
4802
|
|
|
4669
4803
|
// Clear the resyncing flag after a short delay
|
|
4670
4804
|
setTimeout(() => {
|
|
@@ -6047,6 +6181,11 @@ const wheelHandler = (e) => {
|
|
|
6047
6181
|
console.error('[SSHIFT] Failed to load Speech & AI config:', err);
|
|
6048
6182
|
});
|
|
6049
6183
|
|
|
6184
|
+
// Load Speech & AI profile names into the fast-swap dropdown.
|
|
6185
|
+
this.loadSpeechAiProfiles().catch(err => {
|
|
6186
|
+
console.error('[SSHIFT] Failed to load Speech & AI profiles:', err);
|
|
6187
|
+
});
|
|
6188
|
+
|
|
6050
6189
|
// Reset to first category
|
|
6051
6190
|
this.switchSettingsCategory('sessions');
|
|
6052
6191
|
|
|
@@ -6134,6 +6273,120 @@ const wheelHandler = (e) => {
|
|
|
6134
6273
|
}
|
|
6135
6274
|
}
|
|
6136
6275
|
|
|
6276
|
+
// ---- Speech & AI: settings profiles -----------------------------------
|
|
6277
|
+
// Named snapshots of the Speech & AI tab, stored server-side (auth keys
|
|
6278
|
+
// included — they never travel through the browser). The dropdown swaps
|
|
6279
|
+
// the active settings in one click; Save snapshots the current fields
|
|
6280
|
+
// under a name; Delete removes a snapshot.
|
|
6281
|
+
|
|
6282
|
+
async loadSpeechAiProfiles(selectedName = null) {
|
|
6283
|
+
const select = document.getElementById('speechAiProfileSelect');
|
|
6284
|
+
if (!select) return;
|
|
6285
|
+
|
|
6286
|
+
const res = await fetch('/api/speech-ai/profiles');
|
|
6287
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
6288
|
+
const data = await res.json();
|
|
6289
|
+
const profiles = Array.isArray(data.profiles) ? data.profiles : [];
|
|
6290
|
+
|
|
6291
|
+
const keep = selectedName !== null ? selectedName : select.value;
|
|
6292
|
+
|
|
6293
|
+
select.innerHTML = '';
|
|
6294
|
+
const placeholder = document.createElement('option');
|
|
6295
|
+
placeholder.value = '';
|
|
6296
|
+
placeholder.textContent = '— Select profile —';
|
|
6297
|
+
select.appendChild(placeholder);
|
|
6298
|
+
|
|
6299
|
+
for (const name of profiles) {
|
|
6300
|
+
const opt = document.createElement('option');
|
|
6301
|
+
opt.value = name;
|
|
6302
|
+
opt.textContent = name;
|
|
6303
|
+
select.appendChild(opt);
|
|
6304
|
+
}
|
|
6305
|
+
|
|
6306
|
+
select.value = (keep && profiles.includes(keep)) ? keep : '';
|
|
6307
|
+
}
|
|
6308
|
+
|
|
6309
|
+
initSpeechAiProfileHandlers() {
|
|
6310
|
+
const select = document.getElementById('speechAiProfileSelect');
|
|
6311
|
+
const nameInput = document.getElementById('speechAiProfileName');
|
|
6312
|
+
const saveBtn = document.getElementById('saveSpeechAiProfileBtn');
|
|
6313
|
+
const deleteBtn = document.getElementById('deleteSpeechAiProfileBtn');
|
|
6314
|
+
|
|
6315
|
+
// Selecting a profile applies it immediately (fast swap): the server
|
|
6316
|
+
// copies the snapshot into the active config, then we re-fetch the
|
|
6317
|
+
// (redacted) config so the tab fields reflect the loaded profile.
|
|
6318
|
+
if (select) {
|
|
6319
|
+
select.addEventListener('change', async () => {
|
|
6320
|
+
const name = select.value;
|
|
6321
|
+
if (nameInput) nameInput.value = name;
|
|
6322
|
+
if (!name) return;
|
|
6323
|
+
try {
|
|
6324
|
+
const res = await fetch('/api/speech-ai/profiles/load', {
|
|
6325
|
+
method: 'POST',
|
|
6326
|
+
headers: { 'Content-Type': 'application/json' },
|
|
6327
|
+
body: JSON.stringify({ name })
|
|
6328
|
+
});
|
|
6329
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
6330
|
+
await this.loadSpeechAiConfig();
|
|
6331
|
+
this.showToast(`Loaded Speech & AI profile "${name}"`, 'success');
|
|
6332
|
+
} catch (err) {
|
|
6333
|
+
console.error('[SSHIFT] Failed to load Speech & AI profile:', err);
|
|
6334
|
+
this.showToast('Failed to load profile', 'error');
|
|
6335
|
+
}
|
|
6336
|
+
});
|
|
6337
|
+
}
|
|
6338
|
+
|
|
6339
|
+
if (saveBtn) {
|
|
6340
|
+
saveBtn.addEventListener('click', async () => {
|
|
6341
|
+
const name = ((nameInput && nameInput.value) || (select && select.value) || '').trim();
|
|
6342
|
+
if (!name) {
|
|
6343
|
+
this.showToast('Enter a profile name first', 'warning');
|
|
6344
|
+
return;
|
|
6345
|
+
}
|
|
6346
|
+
try {
|
|
6347
|
+
// Persist the on-screen fields to the active config first so the
|
|
6348
|
+
// profile snapshots exactly what the user sees. Auth keys left
|
|
6349
|
+
// blank are preserved server-side via the __UNCHANGED__ sentinel.
|
|
6350
|
+
await this.saveSpeechAiConfig();
|
|
6351
|
+
const res = await fetch('/api/speech-ai/profiles', {
|
|
6352
|
+
method: 'POST',
|
|
6353
|
+
headers: { 'Content-Type': 'application/json' },
|
|
6354
|
+
body: JSON.stringify({ name })
|
|
6355
|
+
});
|
|
6356
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
6357
|
+
await this.loadSpeechAiProfiles(name);
|
|
6358
|
+
this.showToast(`Saved Speech & AI profile "${name}"`, 'success');
|
|
6359
|
+
} catch (err) {
|
|
6360
|
+
console.error('[SSHIFT] Failed to save Speech & AI profile:', err);
|
|
6361
|
+
this.showToast('Failed to save profile', 'error');
|
|
6362
|
+
}
|
|
6363
|
+
});
|
|
6364
|
+
}
|
|
6365
|
+
|
|
6366
|
+
if (deleteBtn) {
|
|
6367
|
+
deleteBtn.addEventListener('click', async () => {
|
|
6368
|
+
const name = ((select && select.value) || (nameInput && nameInput.value) || '').trim();
|
|
6369
|
+
if (!name) {
|
|
6370
|
+
this.showToast('Select a profile to delete', 'warning');
|
|
6371
|
+
return;
|
|
6372
|
+
}
|
|
6373
|
+
if (!confirm(`Delete Speech & AI profile "${name}"? The active settings are not changed.`)) return;
|
|
6374
|
+
try {
|
|
6375
|
+
const res = await fetch(`/api/speech-ai/profiles/${encodeURIComponent(name)}`, {
|
|
6376
|
+
method: 'DELETE'
|
|
6377
|
+
});
|
|
6378
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
6379
|
+
if (nameInput) nameInput.value = '';
|
|
6380
|
+
await this.loadSpeechAiProfiles('');
|
|
6381
|
+
this.showToast(`Deleted profile "${name}"`, 'success');
|
|
6382
|
+
} catch (err) {
|
|
6383
|
+
console.error('[SSHIFT] Failed to delete Speech & AI profile:', err);
|
|
6384
|
+
this.showToast('Failed to delete profile', 'error');
|
|
6385
|
+
}
|
|
6386
|
+
});
|
|
6387
|
+
}
|
|
6388
|
+
}
|
|
6389
|
+
|
|
6137
6390
|
initSettingsModalHandlers() {
|
|
6138
6391
|
// Settings category navigation (sidebar + mobile dropdown)
|
|
6139
6392
|
const navItems = document.querySelectorAll('.settings-nav-item');
|
|
@@ -6142,6 +6395,9 @@ const wheelHandler = (e) => {
|
|
|
6142
6395
|
this.switchSettingsCategory(item.dataset.category);
|
|
6143
6396
|
});
|
|
6144
6397
|
});
|
|
6398
|
+
|
|
6399
|
+
// Speech & AI profile dropdown (load/save/delete)
|
|
6400
|
+
this.initSpeechAiProfileHandlers();
|
|
6145
6401
|
|
|
6146
6402
|
const categorySelect = document.getElementById('settingsCategorySelect');
|
|
6147
6403
|
if (categorySelect) {
|
|
@@ -7246,46 +7502,84 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
|
|
|
7246
7502
|
}
|
|
7247
7503
|
}
|
|
7248
7504
|
|
|
7249
|
-
|
|
7250
|
-
|
|
7251
|
-
|
|
7252
|
-
|
|
7253
|
-
|
|
7254
|
-
|
|
7255
|
-
|
|
7505
|
+
// Validate a persisted color value. Historically, saves could run while
|
|
7506
|
+
// the color properties (or this.theme) were still undefined, writing the
|
|
7507
|
+
// literal string "undefined" into localStorage. Such garbage is truthy,
|
|
7508
|
+
// so it survived `value || default` fallbacks and reached xterm.js —
|
|
7509
|
+
// which silently renders unparseable colors as #000000. With both bg and
|
|
7510
|
+
// fg corrupted, enabling the override painted the terminal black-on-black
|
|
7511
|
+
// (invisible), i.e. "the color override stopped working". Sanitizing on
|
|
7512
|
+
// every load/save self-heals those clients.
|
|
7513
|
+
_sanitizeHexColor(value, fallback) {
|
|
7514
|
+
if (typeof value === 'string' && /^#[0-9a-fA-F]{6}$/.test(value.trim())) {
|
|
7515
|
+
return value.trim().toLowerCase();
|
|
7516
|
+
}
|
|
7517
|
+
return fallback;
|
|
7256
7518
|
}
|
|
7257
7519
|
|
|
7258
|
-
|
|
7259
|
-
//
|
|
7260
|
-
|
|
7261
|
-
|
|
7262
|
-
// Default colors for each theme
|
|
7520
|
+
_terminalColorDefaults(themeKey) {
|
|
7521
|
+
// Default colors for each theme. Override defaults to OFF: out of the
|
|
7522
|
+
// box the terminal keeps its standard colors and remote ANSI palette;
|
|
7523
|
+
// the user opts in explicitly per theme.
|
|
7263
7524
|
const defaults = {
|
|
7264
7525
|
dark: {
|
|
7265
|
-
override:
|
|
7526
|
+
override: false,
|
|
7266
7527
|
bg: '#0d1117',
|
|
7267
7528
|
fg: '#e6edf3',
|
|
7268
7529
|
selection: '#264f78'
|
|
7269
7530
|
},
|
|
7270
7531
|
light: {
|
|
7271
|
-
override:
|
|
7532
|
+
override: false,
|
|
7272
7533
|
bg: '#ffffff',
|
|
7273
7534
|
fg: '#1f2328',
|
|
7274
7535
|
selection: '#b6e3ff'
|
|
7275
7536
|
}
|
|
7276
7537
|
};
|
|
7277
|
-
|
|
7278
|
-
|
|
7279
|
-
|
|
7280
|
-
|
|
7281
|
-
//
|
|
7282
|
-
|
|
7283
|
-
|
|
7538
|
+
return defaults[themeKey] || defaults.dark;
|
|
7539
|
+
}
|
|
7540
|
+
|
|
7541
|
+
saveTerminalColorSettings() {
|
|
7542
|
+
// Save settings for current theme
|
|
7543
|
+
const themeKey = this.theme; // 'dark' or 'light'
|
|
7544
|
+
if (themeKey !== 'dark' && themeKey !== 'light') {
|
|
7545
|
+
// this.theme not initialized yet — writing now would create
|
|
7546
|
+
// "terminalBgColor_undefined" style keys (and losing the real ones).
|
|
7547
|
+
console.warn('[SSHIFT] Skipping terminal color save — theme not initialized yet');
|
|
7548
|
+
return;
|
|
7284
7549
|
}
|
|
7285
|
-
|
|
7286
|
-
|
|
7287
|
-
|
|
7288
|
-
|
|
7550
|
+
const defaultSet = this._terminalColorDefaults(themeKey);
|
|
7551
|
+
// The override flag uses a v2 key: the legacy key was written as "true"
|
|
7552
|
+
// by every color save while override still defaulted to ON, so it can't
|
|
7553
|
+
// distinguish "user chose ON" from "old default". Ignoring it resets
|
|
7554
|
+
// everyone to the new default (OFF) exactly once; an explicit toggle
|
|
7555
|
+
// re-enables and persists under the v2 key.
|
|
7556
|
+
localStorage.setItem(`terminalColorOverrideV2_${themeKey}`, this.terminalColorOverride ? 'true' : 'false');
|
|
7557
|
+
localStorage.setItem(`terminalBgColor_${themeKey}`, this._sanitizeHexColor(this.terminalBgColor, defaultSet.bg));
|
|
7558
|
+
localStorage.setItem(`terminalFgColor_${themeKey}`, this._sanitizeHexColor(this.terminalFgColor, defaultSet.fg));
|
|
7559
|
+
localStorage.setItem(`terminalSelectionColor_${themeKey}`, this._sanitizeHexColor(this.terminalSelectionColor, defaultSet.selection));
|
|
7560
|
+
}
|
|
7561
|
+
|
|
7562
|
+
loadTerminalColorSettings() {
|
|
7563
|
+
// Load settings for current theme
|
|
7564
|
+
const themeKey = (this.theme === 'dark' || this.theme === 'light') ? this.theme : 'dark';
|
|
7565
|
+
const defaultSet = this._terminalColorDefaults(themeKey);
|
|
7566
|
+
|
|
7567
|
+
// Clean up junk keys written by historical saves that ran before
|
|
7568
|
+
// this.theme was initialized (e.g. "terminalBgColor_undefined").
|
|
7569
|
+
try {
|
|
7570
|
+
['terminalColorOverride', 'terminalColorOverrideV2', 'terminalBgColor', 'terminalFgColor', 'terminalSelectionColor']
|
|
7571
|
+
.forEach(k => localStorage.removeItem(`${k}_undefined`));
|
|
7572
|
+
} catch (_) {}
|
|
7573
|
+
|
|
7574
|
+
// Override is opt-in: only an explicit persisted 'true' (v2 key) turns
|
|
7575
|
+
// it on. Anything else — missing key, legacy key, garbage — means OFF.
|
|
7576
|
+
this.terminalColorOverride = localStorage.getItem(`terminalColorOverrideV2_${themeKey}`) === 'true';
|
|
7577
|
+
|
|
7578
|
+
// Colors: sanitize persisted values so corrupt entries (e.g. the
|
|
7579
|
+
// literal string "undefined") can never reach xterm.js again.
|
|
7580
|
+
this.terminalBgColor = this._sanitizeHexColor(localStorage.getItem(`terminalBgColor_${themeKey}`), defaultSet.bg);
|
|
7581
|
+
this.terminalFgColor = this._sanitizeHexColor(localStorage.getItem(`terminalFgColor_${themeKey}`), defaultSet.fg);
|
|
7582
|
+
this.terminalSelectionColor = this._sanitizeHexColor(localStorage.getItem(`terminalSelectionColor_${themeKey}`), defaultSet.selection);
|
|
7289
7583
|
}
|
|
7290
7584
|
|
|
7291
7585
|
updateTerminalColors() {
|
|
@@ -55,11 +55,10 @@ class MobileTerminalHandler {
|
|
|
55
55
|
this.contextMenu = null;
|
|
56
56
|
this.hiddenTextarea = null;
|
|
57
57
|
this._isComposing = false;
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
this.
|
|
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
|
-
//
|
|
468
|
-
//
|
|
469
|
-
//
|
|
470
|
-
//
|
|
471
|
-
//
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
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.
|
|
483
|
-
this._previousTextareaValue = '';
|
|
490
|
+
this._resetInputTracking();
|
|
484
491
|
return;
|
|
485
492
|
}
|
|
486
493
|
|
|
487
|
-
|
|
488
|
-
|
|
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
|
-
|
|
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.
|
|
567
|
-
this._previousTextareaValue = '';
|
|
524
|
+
this._resetInputTracking();
|
|
568
525
|
} else if (e.key === 'Backspace') {
|
|
569
|
-
// Let the browser handle backspace in the textarea; the
|
|
570
|
-
//
|
|
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.
|
|
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', (
|
|
555
|
+
this.hiddenTextarea.addEventListener('compositionend', () => {
|
|
606
556
|
this._isComposing = false;
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
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.
|
|
1483
|
-
this._previousTextareaValue = '';
|
|
1497
|
+
this._resetInputTracking();
|
|
1484
1498
|
this.hiddenTextarea.focus();
|
|
1485
1499
|
}
|
|
1486
1500
|
}
|