@lethevimlet/sshift 1.8.1 → 1.8.3

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.8.1",
3
+ "version": "1.8.3",
4
4
  "description": "Web-based SSH + SFTP terminal client with tabs and bookmarks",
5
5
  "main": "src/server/index.js",
6
6
  "bin": {
@@ -10,6 +10,7 @@
10
10
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
11
11
  <meta name="apple-mobile-web-app-title" content="SSHIFT">
12
12
  <link rel="manifest" href="/manifest.json?v=__VERSION__">
13
+ <script>window.SSHIFT_VERSION = '__VERSION__';</script>
13
14
  <link rel="icon" type="image/png" sizes="32x32" href="/icons/favicon-32x32.png">
14
15
  <link rel="icon" type="image/png" sizes="16x16" href="/icons/favicon-16x16.png">
15
16
  <link rel="apple-touch-icon" href="/icons/apple-touch-icon.png">
@@ -1568,51 +1569,77 @@
1568
1569
  <script src="/socket.io/socket.io.js"></script>
1569
1570
  <script src="/js/app.js?v=__VERSION__"></script>
1570
1571
  <script>
1572
+ // Service worker lifecycle (v1.8.2).
1573
+ // - sw.js is served with no-store and registered with updateViaCache
1574
+ // 'none', so every update check hits the server.
1575
+ // - Chrome only checks for a new worker on navigations; a PWA that
1576
+ // stays open never navigates, so we also check when the app comes
1577
+ // back to the foreground and once an hour.
1578
+ // - The worker calls skipWaiting()+clients.claim(): the moment a new
1579
+ // version installs it replaces the old one everywhere (never two
1580
+ // versions alive), and every open page reloads exactly once on
1581
+ // controllerchange so HTML, JS, CSS and worker all match.
1571
1582
  if ('serviceWorker' in navigator) {
1572
- window.addEventListener('load', () => {
1573
- navigator.serviceWorker.register('/sw.js').then((reg) => {
1574
- console.log('[SSHIFT] Service Worker registered, scope:', reg.scope);
1575
- window._swRegistration = reg;
1576
- if (reg.active) {
1583
+ const hadController = !!navigator.serviceWorker.controller;
1584
+ let reloading = false;
1585
+ navigator.serviceWorker.addEventListener('controllerchange', () => {
1586
+ if (reloading) return;
1587
+ // First install: this page already has the current assets.
1588
+ if (!hadController && !window.__swUpdateSeen) {
1577
1589
  window._swStatus = 'active';
1578
- } else if (reg.installing) {
1579
- window._swStatus = 'installing';
1580
- } else if (reg.waiting) {
1581
- window._swStatus = 'waiting';
1582
- } else {
1583
- window._swStatus = 'registered';
1590
+ return;
1584
1591
  }
1585
- window._swError = null;
1586
- reg.addEventListener('updatefound', () => {
1587
- const newWorker = reg.installing;
1588
- newWorker.addEventListener('statechange', () => {
1589
- if (newWorker.state === 'activated') {
1590
- window._swStatus = 'active';
1591
- if (navigator.serviceWorker.controller) {
1592
- console.log('[SSHIFT] New service worker activated, reloading for updates');
1593
- window.location.reload();
1594
- }
1595
- } else if (newWorker.state === 'redundant') {
1596
- if (!navigator.serviceWorker.controller) {
1597
- window._swStatus = 'redundant';
1598
- window._swError = 'Service Worker became redundant. This usually means the certificate is not trusted.';
1592
+ reloading = true;
1593
+ console.log('[SSHIFT] New service worker took control, reloading for the new version');
1594
+ window.location.reload();
1595
+ });
1596
+ window.addEventListener('load', () => {
1597
+ navigator.serviceWorker.register('/sw.js', { updateViaCache: 'none' }).then((reg) => {
1598
+ console.log('[SSHIFT] Service Worker registered, scope:', reg.scope);
1599
+ window._swRegistration = reg;
1600
+ if (reg.active) {
1601
+ window._swStatus = 'active';
1602
+ } else if (reg.installing) {
1603
+ window._swStatus = 'installing';
1604
+ } else if (reg.waiting) {
1605
+ window._swStatus = 'waiting';
1606
+ } else {
1607
+ window._swStatus = 'registered';
1608
+ }
1609
+ window._swError = null;
1610
+ reg.addEventListener('updatefound', () => {
1611
+ const newWorker = reg.installing;
1612
+ if (!newWorker) return;
1613
+ // An update while we already had a controller: the coming
1614
+ // controllerchange must reload.
1615
+ if (navigator.serviceWorker.controller) window.__swUpdateSeen = true;
1616
+ newWorker.addEventListener('statechange', () => {
1617
+ if (newWorker.state === 'activated') {
1618
+ window._swStatus = 'active';
1619
+ } else if (newWorker.state === 'redundant') {
1620
+ if (!navigator.serviceWorker.controller) {
1621
+ window._swStatus = 'redundant';
1622
+ window._swError = 'Service Worker became redundant. This usually means the certificate is not trusted.';
1623
+ }
1599
1624
  }
1600
- }
1625
+ });
1601
1626
  });
1627
+ if (navigator.serviceWorker.controller) {
1628
+ window._swStatus = 'active';
1629
+ }
1630
+ const check = () => { reg.update().catch(() => {}); };
1631
+ document.addEventListener('visibilitychange', () => { if (!document.hidden) check(); });
1632
+ setInterval(check, 60 * 60 * 1000);
1633
+ }).catch((err) => {
1634
+ console.warn('[SSHIFT] Service Worker registration failed:', err.message);
1635
+ window._swStatus = 'failed';
1636
+ window._swError = err.message;
1602
1637
  });
1603
- if (navigator.serviceWorker.controller) {
1604
- window._swStatus = 'active';
1605
- }
1606
- }).catch((err) => {
1607
- console.warn('[SSHIFT] Service Worker registration failed:', err.message);
1608
- window._swStatus = 'failed';
1609
- window._swError = err.message;
1610
1638
  });
1611
- });
1612
- } else {
1613
- window._swStatus = 'unsupported';
1614
- window._swError = 'Service Workers not supported in this browser';
1615
- }
1639
+ } else {
1640
+ window._swStatus = 'unsupported';
1641
+ window._swError = 'Service Workers not supported in this browser';
1642
+ }
1616
1643
  </script>
1617
1644
  </body>
1618
1645
  </html>
@@ -20,6 +20,16 @@ class SSHIFTClient {
20
20
  this.activeSessionId = null; // Global active session (for backwards compatibility)
21
21
  this.activeSessionsByPanel = new Map(); // Per-panel active sessions: Map<panelId, sessionId>
22
22
  this._wasDisconnected = false; // Track reconnection state for toast messages
23
+ // Connection toasts (v1.8.2): a disconnect is only announced when it
24
+ // lasts longer than the grace period below while the page is visible;
25
+ // "Reconnected" only follows an announced disconnect; deliberate
26
+ // reconnects (auth token swap) are silent; the initial connect is the
27
+ // normal state and says nothing.
28
+ this._silentReconnect = false;
29
+ this._disconnectToastTimer = null;
30
+ this._disconnectToastShown = false;
31
+ this.DISCONNECT_TOAST_GRACE_MS = 2500;
32
+ this._staleReloadFor = null;
23
33
  this._initReady = false; // Set true once init() completes
24
34
  this._pendingOpenTabs = null; // Deferred open-tabs data
25
35
  this._pendingOpenTabsIsInitial = false;
@@ -269,6 +279,8 @@ class SSHIFTClient {
269
279
  updateSocketAuth() {
270
280
  if (this.socket && this.authToken) {
271
281
  this.socket.auth = { token: this.authToken };
282
+ // Deliberate reconnect: no Disconnected/Reconnected toasts for it.
283
+ this._silentReconnect = true;
272
284
  this.socket.disconnect().connect();
273
285
  }
274
286
  }
@@ -2143,7 +2155,7 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
2143
2155
 
2144
2156
  // Fallback to layouts.json
2145
2157
  try {
2146
- const layoutsResponse = await fetch('/layouts.json');
2158
+ const layoutsResponse = await fetch('/layouts.json?v=' + encodeURIComponent((typeof window !== 'undefined' && window.SSHIFT_VERSION) || ''));
2147
2159
  if (layoutsResponse.ok) {
2148
2160
  const data = await layoutsResponse.json();
2149
2161
  if (data.layouts && Array.isArray(data.layouts)) {
@@ -4583,6 +4595,10 @@ const wheelHandler = (e) => {
4583
4595
  // the rejoin completes (consumed by the ssh-joined handler; guarded
4584
4596
  // there so we never steal control another client acquired meanwhile).
4585
4597
  session._retakeControlOnRejoin = !!session.isController;
4598
+ // Remembered until we hold control again: getting it back (by
4599
+ // retake, or because the server reassigned it to us when our old
4600
+ // socket timed out) is not news worth a toast.
4601
+ session._heldControlBeforeDrop = !!session.isController;
4586
4602
 
4587
4603
  // Mark as restoring so a "Session not found" reply routes into the
4588
4604
  // credential-based auto-reconnect path instead of closing the tab.
@@ -4623,15 +4639,20 @@ const wheelHandler = (e) => {
4623
4639
  console.log('[SSHIFT] Connected to server, socket ID:', this.socket.id);
4624
4640
  const wasDisconnected = this._wasDisconnected;
4625
4641
  this._wasDisconnected = false;
4626
- if (wasDisconnected && !this.isUpdating) {
4627
- this.showToast('Reconnected to server', 'success');
4642
+ this._silentReconnect = false;
4643
+ this._cancelDisconnectToast();
4644
+ if (wasDisconnected) {
4645
+ // Only announce the recovery of an outage that was announced.
4646
+ if (this._disconnectToastShown && !this.isUpdating) {
4647
+ this.showToast('Reconnected to server', 'success');
4648
+ }
4649
+ this._disconnectToastShown = false;
4628
4650
  // The new socket must re-join its sessions (rooms + controller
4629
4651
  // state are keyed by socket.id and were lost with the old socket).
4630
4652
  this.rejoinActiveSessions();
4631
- } else if (!this.isUpdating) {
4632
- this.showToast('Connected to server', 'success');
4633
4653
  }
4634
4654
  this.loadBookmarks();
4655
+ this._checkServerVersion();
4635
4656
  });
4636
4657
 
4637
4658
  this.socket.on('disconnect', (reason) => {
@@ -4640,8 +4661,8 @@ const wheelHandler = (e) => {
4640
4661
  if (reason === 'io server disconnect') {
4641
4662
  // Server intentionally disconnected us (e.g. auth failure) — don't auto-reconnect
4642
4663
  // Socket.IO won't retry after server-initiated disconnect anyway
4643
- } else if (!this.isUpdating) {
4644
- this.showToast('Disconnected from server — will reconnect automatically', 'warning');
4664
+ } else if (!this.isUpdating && !this._silentReconnect) {
4665
+ this._armDisconnectToast();
4645
4666
  }
4646
4667
  });
4647
4668
 
@@ -4653,6 +4674,10 @@ const wheelHandler = (e) => {
4653
4674
  if (!this.socket.connected) {
4654
4675
  console.log('[SSHIFT] Tab visible and socket disconnected, triggering reconnect');
4655
4676
  this.socket.connect();
4677
+ // Give the reconnect the same grace period before complaining.
4678
+ this._armDisconnectToast();
4679
+ } else {
4680
+ this._checkServerVersion();
4656
4681
  }
4657
4682
  this.clearFlashesForVisibleSessions();
4658
4683
  this._refreshAllWebGLSessions();
@@ -4675,6 +4700,10 @@ const wheelHandler = (e) => {
4675
4700
  localStorage.removeItem('sshift_auth_token');
4676
4701
  this.showLockScreen();
4677
4702
  }
4703
+ // A rejected handshake after a server restart is also the first
4704
+ // moment we can learn that the server was updated (the version
4705
+ // check normally runs on connect, which never comes here).
4706
+ this._checkServerVersion();
4678
4707
  // Don't show generic connection error toasts during reconnection —
4679
4708
  // the user already sees "Disconnected" and the auto-reconnect handles it.
4680
4709
  // Only show for explicit user actions (not isUpdating suppresses during update).
@@ -4881,7 +4910,7 @@ const wheelHandler = (e) => {
4881
4910
  // Delay to ensure the session is fully set up
4882
4911
  const delay = 100 + Math.random() * 200; // 100-300ms
4883
4912
  setTimeout(() => {
4884
- this.requestTakeControl(data.sessionId);
4913
+ this.requestTakeControl(data.sessionId, { announce: false });
4885
4914
  }, delay);
4886
4915
  } else {
4887
4916
  console.log('[SSHIFT] Not taking control - another client is already in control');
@@ -5167,8 +5196,14 @@ const wheelHandler = (e) => {
5167
5196
  });
5168
5197
  });
5169
5198
  }
5170
- this.showToast('You are now in control (previous controller left)', 'info');
5171
- } else if (!session.isController) {
5199
+ // Silent when we are only getting our own control back after a
5200
+ // reconnect (the "previous controller" was this device's old
5201
+ // socket, which the server timed out).
5202
+ if (!session._heldControlBeforeDrop) {
5203
+ this.showToast('You are now in control (previous controller left)', 'info');
5204
+ }
5205
+ session._heldControlBeforeDrop = false;
5206
+ } else if (!session.isController && wasController) {
5172
5207
  this.showToast('Another device took control', 'info');
5173
5208
  }
5174
5209
  }
@@ -5273,7 +5308,14 @@ const wheelHandler = (e) => {
5273
5308
  });
5274
5309
  }
5275
5310
 
5276
- this.showToast('You are now in control', 'success');
5311
+ // Automatic take-control (session join, rejoin after a reconnect,
5312
+ // tab restore) is the normal state and stays silent; only an
5313
+ // explicit "Take Control" tap is confirmed.
5314
+ if (session._announceControl) {
5315
+ this.showToast('You are now in control', 'success');
5316
+ }
5317
+ session._announceControl = false;
5318
+ session._heldControlBeforeDrop = false;
5277
5319
  }
5278
5320
  });
5279
5321
 
@@ -5335,6 +5377,7 @@ const wheelHandler = (e) => {
5335
5377
 
5336
5378
  this.socket.on('ssh-error', (data) => {
5337
5379
  console.error('[SSHIFT] SSH Error:', data.message, 'sessionId:', data.sessionId);
5380
+ this._dismissConnectingToasts();
5338
5381
 
5339
5382
  // If session not found and we're restoring, try to reconnect
5340
5383
  if (data.sessionId && data.message === 'Session not found') {
@@ -5428,6 +5471,7 @@ const wheelHandler = (e) => {
5428
5471
  });
5429
5472
 
5430
5473
  this.socket.on('sftp-connected', (data) => {
5474
+ this._dismissConnectingToasts();
5431
5475
  this.onSFTPConnected(data);
5432
5476
  });
5433
5477
 
@@ -5488,6 +5532,7 @@ const wheelHandler = (e) => {
5488
5532
  });
5489
5533
 
5490
5534
  this.socket.on('sftp-error', (data) => {
5535
+ this._dismissConnectingToasts();
5491
5536
  console.error('[SSHIFT] SFTP Error:', data.message, 'sessionId:', data?.sessionId);
5492
5537
 
5493
5538
  // If session not found and we're restoring, try to reconnect
@@ -6915,10 +6960,18 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
6915
6960
  if (dontShow === 'true') return;
6916
6961
 
6917
6962
  const isLocalhost = ['localhost', '127.0.0.1', '::1'].includes(window.location.hostname);
6918
- const swActive = navigator.serviceWorker && navigator.serviceWorker.controller;
6919
- if (isLocalhost || swActive) return;
6963
+ const swOk = () => {
6964
+ if (navigator.serviceWorker && navigator.serviceWorker.controller) return true;
6965
+ // First visit: the worker is still installing/activating (the page
6966
+ // no longer reloads on first install), which is just as healthy.
6967
+ return ['active', 'installing', 'registered'].includes(window._swStatus);
6968
+ };
6969
+ if (isLocalhost || swOk()) return;
6920
6970
 
6921
- setTimeout(() => this.openSecurityInfoDialog(), 1000);
6971
+ setTimeout(() => {
6972
+ if (swOk()) return;
6973
+ this.openSecurityInfoDialog();
6974
+ }, 1500);
6922
6975
  }
6923
6976
 
6924
6977
  openSecurityInfoDialog() {
@@ -8253,7 +8306,7 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
8253
8306
  }
8254
8307
 
8255
8308
  // Show connecting status
8256
- this.showToast(`Connecting to ${host}...`, 'info');
8309
+ this._noteConnectingToast(this.showToast(`Connecting to ${host}...`, 'info'));
8257
8310
 
8258
8311
  if (type === 'ssh') {
8259
8312
  console.log('[SSHIFT] Creating SSH tab...');
@@ -8632,7 +8685,7 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
8632
8685
  takeControlBtn.addEventListener('click', (e) => {
8633
8686
  e.preventDefault();
8634
8687
  e.stopPropagation();
8635
- this.requestTakeControl(sessionId);
8688
+ this.requestTakeControl(sessionId, { announce: true });
8636
8689
  });
8637
8690
 
8638
8691
  controlContent.appendChild(controlIcon);
@@ -8734,6 +8787,11 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
8734
8787
  letterSpacing: 0,
8735
8788
  cursorBlink: false,
8736
8789
  cursorStyle: 'block',
8790
+ // On mobile xterm's own textarea never has focus (the mobile
8791
+ // handler owns keyboard input, see MobileTerminalHandler.
8792
+ // _captureTerminalFocus), so the "inactive" cursor must look like
8793
+ // the active one or the terminal always shows a hollow cursor.
8794
+ cursorInactiveStyle: this.isMobile ? 'block' : 'outline',
8737
8795
  scrollback: this.scrollback || 10000,
8738
8796
  allowProposedApi: true,
8739
8797
  convertEol: true,
@@ -9472,6 +9530,7 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
9472
9530
  // Update control overlay (should be hidden since we're controller)
9473
9531
  this.updateControlOverlay(data.sessionId);
9474
9532
 
9533
+ this._dismissConnectingToasts();
9475
9534
  this.showToast('SSH connection established', 'success');
9476
9535
  console.log('[SSHIFT] Session marked as connected, terminal exists:', !!session.terminal);
9477
9536
 
@@ -13078,7 +13137,7 @@ async syncTabsFromServer(tabs, isInitialSync = false, activeTabsByPanel = null)
13078
13137
  }
13079
13138
 
13080
13139
  // Show connecting status
13081
- this.showToast(`Connecting to ${bookmark.name}...`, 'info');
13140
+ this._noteConnectingToast(this.showToast(`Connecting to ${bookmark.name}...`, 'info'));
13082
13141
 
13083
13142
  if (bookmark.type === 'ssh') {
13084
13143
  console.log('[SSHIFT] Creating SSH tab from bookmark...');
@@ -13447,17 +13506,101 @@ async syncTabsFromServer(tabs, isInitialSync = false, activeTabsByPanel = null)
13447
13506
  }, 50); // 50ms debounce to prevent flashing
13448
13507
  }
13449
13508
 
13450
- requestTakeControl(sessionId) {
13509
+ requestTakeControl(sessionId, opts) {
13451
13510
  const session = this.sessions.get(sessionId);
13452
13511
  if (!session || !session.connected) {
13453
13512
  this.showToast('Session not connected', 'error');
13454
13513
  return;
13455
13514
  }
13456
13515
 
13516
+ session._announceControl = !!(opts && opts.announce);
13457
13517
  console.log('[SSHIFT] Requesting control for session:', sessionId);
13458
13518
  this.socket.emit('ssh-take-control', { sessionId });
13459
13519
  }
13460
13520
 
13521
+ /**
13522
+ * Start the grace timer for the "Disconnected" toast. Socket drops on a
13523
+ * phone are routine (the OS freezes the page, the PWA is reopened, the
13524
+ * auth token is swapped in) and recover within a second or two; only a
13525
+ * lasting, visible outage is worth a toast.
13526
+ */
13527
+ _armDisconnectToast() {
13528
+ this._cancelDisconnectToast();
13529
+ this._disconnectToastTimer = setTimeout(() => {
13530
+ this._disconnectToastTimer = null;
13531
+ if (!this.socket || this.socket.connected) return;
13532
+ if (this.isUpdating || this._silentReconnect) return;
13533
+ // Nobody is looking: the visibilitychange handler re-arms this.
13534
+ if (typeof document !== 'undefined' && document.hidden) return;
13535
+ this._disconnectToastShown = true;
13536
+ this.showToast('Disconnected from server — will reconnect automatically', 'warning');
13537
+ }, this.DISCONNECT_TOAST_GRACE_MS);
13538
+ }
13539
+
13540
+ _cancelDisconnectToast() {
13541
+ if (this._disconnectToastTimer) {
13542
+ clearTimeout(this._disconnectToastTimer);
13543
+ this._disconnectToastTimer = null;
13544
+ }
13545
+ }
13546
+
13547
+ /**
13548
+ * Stale-page detection: compare the version baked into this page
13549
+ * (window.SSHIFT_VERSION, rendered into index.html) with the version
13550
+ * the server reports now. They diverge when the server was updated
13551
+ * while this page stayed open (a PWA can live for days without a
13552
+ * navigation, so the service worker never gets an update check).
13553
+ * Runs after every (re)connect and whenever the page becomes visible.
13554
+ */
13555
+ async _checkServerVersion() {
13556
+ let mine = null;
13557
+ try { mine = typeof window !== 'undefined' ? window.SSHIFT_VERSION : null; } catch (_) {}
13558
+ if (!mine || typeof fetch !== 'function') return;
13559
+ let serverVersion = null;
13560
+ try {
13561
+ const response = await fetch('/api/version', { cache: 'no-store' });
13562
+ if (!response || !response.ok) return;
13563
+ const data = await response.json();
13564
+ serverVersion = data && data.version;
13565
+ } catch (_) {
13566
+ return;
13567
+ }
13568
+ if (!serverVersion || serverVersion === mine) return;
13569
+ this._handleStaleClient(serverVersion, mine);
13570
+ }
13571
+
13572
+ _handleStaleClient(serverVersion, mine) {
13573
+ if (this._staleReloadFor === serverVersion) return;
13574
+ this._staleReloadFor = serverVersion;
13575
+ // One reload per server version per tab: if the page still comes back
13576
+ // with the old version (a proxy caching index.html), stop instead of
13577
+ // reloading forever.
13578
+ try {
13579
+ if (sessionStorage.getItem('sshift_reloaded_for') === serverVersion) {
13580
+ console.warn('[SSHIFT] Already reloaded for', serverVersion, 'but the page is still', mine);
13581
+ return;
13582
+ }
13583
+ sessionStorage.setItem('sshift_reloaded_for', serverVersion);
13584
+ } catch (_) {}
13585
+ console.log('[SSHIFT] Server runs', serverVersion, 'but this page is', mine, '— reloading');
13586
+ if (this.isUpdating) return; // the update flow reloads on its own
13587
+ this.showToast(`Updating to v${serverVersion}…`, 'info');
13588
+ // Let the new service worker install first (it takes over with
13589
+ // skipWaiting + clients.claim and the registration script reloads on
13590
+ // controllerchange); the timer is the fallback when there is no
13591
+ // service worker or the update check is slow.
13592
+ try {
13593
+ if (navigator.serviceWorker && navigator.serviceWorker.getRegistration) {
13594
+ navigator.serviceWorker.getRegistration().then((reg) => reg && reg.update()).catch(() => {});
13595
+ }
13596
+ } catch (_) {}
13597
+ setTimeout(() => {
13598
+ if (typeof window !== 'undefined' && window.location && typeof window.location.reload === 'function') {
13599
+ window.location.reload();
13600
+ }
13601
+ }, 4000);
13602
+ }
13603
+
13461
13604
  // Toast Notifications
13462
13605
  showToast(message, type = 'info') {
13463
13606
  const MAX_TOASTS = 5;
@@ -13491,10 +13634,31 @@ async syncTabsFromServer(tabs, isInitialSync = false, activeTabsByPanel = null)
13491
13634
 
13492
13635
  container.appendChild(toast);
13493
13636
 
13494
- setTimeout(() => {
13495
- toast.style.opacity = '0';
13496
- setTimeout(() => toast.remove(), 300);
13497
- }, 3000);
13637
+ toast._dismissTimer = setTimeout(() => this.dismissToast(toast), 3000);
13638
+ return toast;
13639
+ }
13640
+
13641
+ /** Fade out and remove a toast returned by showToast (safe to call twice). */
13642
+ dismissToast(toast) {
13643
+ if (!toast || toast._dismissed) return;
13644
+ toast._dismissed = true;
13645
+ if (toast._dismissTimer) clearTimeout(toast._dismissTimer);
13646
+ toast.style.opacity = '0';
13647
+ setTimeout(() => toast.remove(), 300);
13648
+ }
13649
+
13650
+ /** Remember a "Connecting to …" toast so the outcome can dismiss it early. */
13651
+ _noteConnectingToast(toast) {
13652
+ if (!toast) return;
13653
+ if (!this._connectingToasts) this._connectingToasts = [];
13654
+ this._connectingToasts.push(toast);
13655
+ }
13656
+
13657
+ /** The connection finished (success or error): drop the pending "Connecting to …" toasts. */
13658
+ _dismissConnectingToasts() {
13659
+ const list = this._connectingToasts || [];
13660
+ this._connectingToasts = [];
13661
+ list.forEach((t) => this.dismissToast(t));
13498
13662
  }
13499
13663
 
13500
13664
  // Utility Functions
@@ -64,6 +64,19 @@ class MobileTerminalHandler {
64
64
  // reproduced on a desktop; this is how device reports become
65
65
  // actionable.
66
66
  this._inputTrace = [];
67
+ // xterm focus capture (see _captureTerminalFocus)
68
+ this._xtermCore = null;
69
+ this._xtermTextareaFocusListener = null;
70
+ // Post-composition catch-up sync timer (see _onCompositionEnd)
71
+ this._deferredSyncTimer = null;
72
+ // True during the blur/focus pair that re-opens a dismissed keyboard:
73
+ // the field content must survive it (see _reshowKeyboard).
74
+ this._suppressBlurReset = false;
75
+ // Tallest layout viewport seen per width: with
76
+ // `interactive-widget=resizes-content` the virtual keyboard shrinks
77
+ // window.innerHeight, so "current height well below the max" means
78
+ // the keyboard is up (see _keyboardProbablyHidden).
79
+ this._maxInnerHeightByWidth = {};
67
80
  this.contextMenuUserPositioned = false; // Track if user has manually positioned the menu
68
81
 
69
82
  // Configuration
@@ -217,12 +230,78 @@ class MobileTerminalHandler {
217
230
  this._createSelectionHandles();
218
231
  this._createContextMenu();
219
232
  this._createHiddenTextarea();
233
+ this._captureTerminalFocus();
234
+ this._noteViewportHeight();
220
235
 
221
236
  // Attach event listeners
222
237
  this._attachEventListeners();
223
238
 
224
239
  console.log('[MobileTerminal] Initialized for session:', this.sessionId);
225
240
  }
241
+
242
+ /**
243
+ * Route every xterm focus request to the hidden textarea (v1.8.2).
244
+ *
245
+ * xterm registers its own `mousedown` listener on the terminal element
246
+ * that focuses ITS helper textarea. On a phone a tap fires
247
+ * touchstart/touchend (our handlers focus the mobile textarea) and then
248
+ * the browser's compatibility mousedown about 1 ms later, which let
249
+ * xterm steal the focus straight back. Verified in headless Chrome with
250
+ * touch emulation: `document.activeElement` ended on
251
+ * `.xterm-helper-textarea` after every tap. Gboard was therefore typing
252
+ * into xterm's textarea, whose Android IME handling (clear the field
253
+ * after every input) is the well-known source of repeated/duplicated
254
+ * words with suggestions, and the diff pipeline below never saw a
255
+ * single keystroke on real devices.
256
+ *
257
+ * The core's `focus()` is shadowed with an own property (the mousedown
258
+ * listener calls `this.focus()` dynamically) and restored in destroy();
259
+ * a focus listener on xterm's textarea is the safety net for any other
260
+ * path that manages to focus it.
261
+ * @private
262
+ */
263
+ _captureTerminalFocus() {
264
+ const t = this.terminal;
265
+ if (!t) return;
266
+ const core = t._core;
267
+ if (core && typeof core.focus === 'function' &&
268
+ !Object.prototype.hasOwnProperty.call(core, 'focus')) {
269
+ this._xtermCore = core;
270
+ core.focus = () => { this._focusHiddenTextarea(); };
271
+ }
272
+ const ta = t.textarea;
273
+ if (ta && typeof ta.addEventListener === 'function') {
274
+ try { ta.tabIndex = -1; } catch (_) {}
275
+ this._xtermTextareaFocusListener = () => {
276
+ if (!this.hiddenTextarea) return;
277
+ this._trace('xterm-focus', {});
278
+ this._focusHiddenTextarea();
279
+ // Could not take it (selection mode): at least keep Gboard off
280
+ // xterm's textarea so no input ever flows through xterm's path.
281
+ if (typeof document !== 'undefined' && document.activeElement === ta &&
282
+ typeof ta.blur === 'function') {
283
+ ta.blur();
284
+ }
285
+ };
286
+ ta.addEventListener('focus', this._xtermTextareaFocusListener);
287
+ }
288
+ }
289
+
290
+ /**
291
+ * Undo _captureTerminalFocus.
292
+ * @private
293
+ */
294
+ _releaseTerminalFocus() {
295
+ if (this._xtermCore) {
296
+ try { delete this._xtermCore.focus; } catch (_) {}
297
+ this._xtermCore = null;
298
+ }
299
+ const ta = this.terminal && this.terminal.textarea;
300
+ if (ta && this._xtermTextareaFocusListener && typeof ta.removeEventListener === 'function') {
301
+ ta.removeEventListener('focus', this._xtermTextareaFocusListener);
302
+ }
303
+ this._xtermTextareaFocusListener = null;
304
+ }
226
305
 
227
306
  /**
228
307
  * Create the selection overlay element
@@ -501,63 +580,181 @@ class MobileTerminalHandler {
501
580
  composing: !!(e.isComposing || this._isComposing)
502
581
  });
503
582
 
504
- // While a composition is in flight we don't send anything; the
505
- // textarea is synced once on compositionend. (Sending live
506
- // composition updates would spam the terminal with backspace/retype
507
- // churn while the IME reshapes the word.)
508
- if (e.isComposing || this._isComposing || e.inputType === 'insertCompositionText') {
509
- return;
510
- }
511
-
512
583
  if (this.touchState.isDragging || this.selection.active) {
513
584
  return;
514
585
  }
515
586
 
587
+ // Sync on EVERY input event, including the ones fired while an IME
588
+ // composition is in flight (v1.8.2). Composition updates are almost
589
+ // always plain appends (one letter, or a whole glided word), so the
590
+ // diff emits just the new characters and the terminal echoes the
591
+ // word as it is typed, exactly like a physical keyboard. When Gboard
592
+ // reshapes the composed word (autocorrect, suggestion tap) the diff
593
+ // erases back to the divergence and retypes, which is what a human
594
+ // would do. Waiting for compositionend (v1.7.x) made every word
595
+ // appear only when the space was pressed and lost the final commit
596
+ // whenever Chrome delivered compositionend before the last DOM
597
+ // update. The diff is idempotent, so extra events cost nothing.
516
598
  this._syncTextareaToTerminal();
517
599
  });
518
600
 
519
601
  // Handle keydown for special keys
520
602
  this.hiddenTextarea.addEventListener('keydown', (e) => {
521
- if (e.key === 'Enter' || e.key === 'Backspace' || e.key === 'Tab') {
522
- this._trace('keydown', { key: e.key, composing: this._isComposing });
603
+ this._handleTextareaKeyDown(e);
604
+ });
605
+
606
+ this._attachTextareaFocusListeners();
607
+ }
608
+
609
+ /**
610
+ * keydown on the hidden textarea. Extracted for unit tests.
611
+ *
612
+ * Text keys are left to the browser (the input diff mirrors them).
613
+ * Enter inserts a newline that the diff turns into \r. Backspace on an
614
+ * empty field is sent straight to the terminal (the browser has nothing
615
+ * to delete, so no input event would follow). Every other non-text key
616
+ * (arrows, Home/End, Delete, F-keys, Ctrl/Alt chords from a physical
617
+ * keyboard) is translated to its escape sequence here, because on
618
+ * mobile xterm's own textarea never has focus any more (see
619
+ * _captureTerminalFocus) and the caret must not move inside the field.
620
+ * @private
621
+ */
622
+ _handleTextareaKeyDown(e) {
623
+ if (e.key === 'Enter' || e.key === 'Backspace' || e.key === 'Tab') {
624
+ this._trace('keydown', { key: e.key, composing: this._isComposing });
625
+ }
626
+ if (this.selection.active) {
627
+ e.preventDefault();
628
+ return;
629
+ }
630
+
631
+ // IME-driven keydowns (keyCode 229 / "Unidentified" / "Process")
632
+ // carry no key; the IME edits the field through input events.
633
+ // Never preventDefault them: on some Gboard builds the Enter key
634
+ // arrives this way while a word is still composing, and swallowing
635
+ // it meant "Enter needs two taps".
636
+ if (e.keyCode === 229 || e.key === 'Unidentified' || e.key === 'Process') {
637
+ return;
638
+ }
639
+
640
+ if (e.key === 'Enter') {
641
+ // Let the browser insert the newline into the textarea. The input
642
+ // diff (_syncTextareaToTerminal) translates it to \r and KEEPS the
643
+ // submitted text in the field. Clearing the field here (the old
644
+ // behaviour) was a programmatic edit that Gboard never sees: its
645
+ // own model of the field still held the previous sentence, and the
646
+ // next suggestion tap re-committed "old sentence + new word" —
647
+ // which the diff then faithfully re-typed into the terminal
648
+ // (the "autocomplete repeats previous sentences" bug). The field
649
+ // is only cleared when the keyboard is collapsed (textarea blurred),
650
+ // at which point the IME session is torn down anyway.
651
+ return;
652
+ } else if (e.key === 'Backspace') {
653
+ // Let the browser handle backspace in the textarea; the input diff
654
+ // will detect the deletion and send \x7f to the terminal.
655
+ // Only prevent default if the textarea is empty (nothing to delete).
656
+ if (!this.hiddenTextarea.value) {
657
+ e.preventDefault();
658
+ this._sendToTerminal('\x7f');
523
659
  }
524
- if (this.selection.active) {
660
+ } else if (e.key === 'Tab') {
661
+ e.preventDefault();
662
+ this._sendToTerminal('\t');
663
+ // No tracking reset: see the Enter comment above.
664
+ } else {
665
+ const seq = this._specialKeySequence(e);
666
+ if (seq) {
525
667
  e.preventDefault();
526
- return;
668
+ this._trace('special', { key: e.key, seq });
669
+ this._sendToTerminal(seq);
527
670
  }
671
+ }
672
+ }
528
673
 
529
- if (this._isComposing) {
530
- e.preventDefault();
531
- return;
674
+ /**
675
+ * Escape sequence for a physical-keyboard special key, or null when the
676
+ * browser should handle the key (plain text, paste/copy/select-all
677
+ * chords that the app handles elsewhere, bare modifiers).
678
+ * @private
679
+ */
680
+ _specialKeySequence(e) {
681
+ const key = e.key;
682
+ if (!key) return null;
683
+ const ctrl = !!e.ctrlKey;
684
+ const alt = !!e.altKey;
685
+ const meta = !!e.metaKey;
686
+ const shift = !!e.shiftKey;
687
+ const mod = 1 + (shift ? 1 : 0) + (alt ? 2 : 0) + (ctrl ? 4 : 0);
688
+ const app = !!(this.terminal && this.terminal.modes && this.terminal.modes.applicationCursorKeysMode);
689
+
690
+ if (key.length === 1) {
691
+ if (!ctrl && !alt && !meta) return null; // typed text → input diff
692
+ if (meta) return null;
693
+ const lower = key.toLowerCase();
694
+ // Ctrl+V / Ctrl+Shift+V paste and Ctrl+A select-all are handled by
695
+ // the document-level handler (_handleKeyDown); Ctrl+C copies when a
696
+ // selection is active (that case returned earlier).
697
+ if (ctrl && !alt && (lower === 'v' || lower === 'a')) return null;
698
+ let seq = null;
699
+ if (ctrl) {
700
+ const code = lower.charCodeAt(0);
701
+ if (code >= 97 && code <= 122) seq = String.fromCharCode(code - 96);
702
+ else if (key === ' ' || key === '@' || key === '2') seq = '\x00';
703
+ else if (key === '[' || key === '3') seq = '\x1b';
704
+ else if (key === '\\' || key === '4') seq = '\x1c';
705
+ else if (key === ']' || key === '5') seq = '\x1d';
706
+ else if (key === '^' || key === '6') seq = '\x1e';
707
+ else if (key === '_' || key === '7' || key === '-') seq = '\x1f';
708
+ else if (key === '8' || key === '?') seq = '\x7f';
709
+ else seq = key;
710
+ } else {
711
+ seq = key;
532
712
  }
713
+ return alt ? '\x1b' + seq : seq;
714
+ }
533
715
 
534
- if (e.key === 'Enter') {
535
- // Let the browser insert the newline into the textarea. The input
536
- // diff (_syncTextareaToTerminal) translates it to \r and KEEPS the
537
- // submitted text in the field. Clearing the field here (the old
538
- // behaviour) was a programmatic edit that Gboard never sees: its
539
- // own model of the field still held the previous sentence, and the
540
- // next suggestion tap re-committed "old sentence + new word" —
541
- // which the diff then faithfully re-typed into the terminal
542
- // (the "autocomplete repeats previous sentences" bug). The field
543
- // is only cleared when the keyboard is collapsed (textarea blurred),
544
- // at which point the IME session is torn down anyway.
545
- return;
546
- } else if (e.key === 'Backspace') {
547
- // Let the browser handle backspace in the textarea; the input diff
548
- // will detect the deletion and send \x7f to the terminal.
549
- // Only prevent default if the textarea is empty (nothing to delete).
550
- if (!this.hiddenTextarea.value) {
551
- e.preventDefault();
552
- this._sendToTerminal('\x7f');
716
+ const cursor = (letter) => {
717
+ if (mod > 1) return '\x1b[1;' + mod + letter;
718
+ return (app ? '\x1bO' : '\x1b[') + letter;
719
+ };
720
+ const tilde = (n) => (mod > 1 ? '\x1b[' + n + ';' + mod + '~' : '\x1b[' + n + '~');
721
+ const fkey = (n) => {
722
+ if (n <= 4) {
723
+ const l = 'PQRS'[n - 1];
724
+ return mod > 1 ? '\x1b[1;' + mod + l : '\x1bO' + l;
725
+ }
726
+ const codes = { 5: 15, 6: 17, 7: 18, 8: 19, 9: 20, 10: 21, 11: 23, 12: 24 };
727
+ return tilde(codes[n]);
728
+ };
729
+
730
+ switch (key) {
731
+ case 'ArrowUp': return cursor('A');
732
+ case 'ArrowDown': return cursor('B');
733
+ case 'ArrowRight': return cursor('C');
734
+ case 'ArrowLeft': return cursor('D');
735
+ case 'Home': return cursor('H');
736
+ case 'End': return cursor('F');
737
+ case 'PageUp': return tilde(5);
738
+ case 'PageDown': return tilde(6);
739
+ case 'Insert': return tilde(2);
740
+ case 'Delete': return tilde(3);
741
+ case 'Escape': return '\x1b';
742
+ default: {
743
+ const m = /^F(\d{1,2})$/.exec(key);
744
+ if (m) {
745
+ const n = parseInt(m[1], 10);
746
+ if (n >= 1 && n <= 12) return fkey(n);
553
747
  }
554
- } else if (e.key === 'Tab') {
555
- e.preventDefault();
556
- this._sendToTerminal('\t');
557
- // No tracking reset: see the Enter comment above.
748
+ return null;
558
749
  }
559
- });
560
-
750
+ }
751
+ }
752
+
753
+ /**
754
+ * The rest of the hidden-textarea listeners (focus/blur/composition).
755
+ * @private
756
+ */
757
+ _attachTextareaFocusListeners() {
561
758
  // Prevent focus when in selection mode or when selection is active
562
759
  this.hiddenTextarea.addEventListener('focus', (e) => {
563
760
  this._trace('focus', {});
@@ -571,13 +768,7 @@ class MobileTerminalHandler {
571
768
 
572
769
  // The blur tears down the IME session: a reset that had to wait for
573
770
  // the field to lose focus (see _resetInputTracking) is applied now.
574
- this.hiddenTextarea.addEventListener('blur', () => {
575
- this._trace('blur', {});
576
- this._isComposing = false;
577
- if (this._pendingTrackingReset) {
578
- this._resetInputTracking();
579
- }
580
- });
771
+ this.hiddenTextarea.addEventListener('blur', () => this._onTextareaBlur());
581
772
 
582
773
  // Composition events for IME/autocomplete handling
583
774
  this.hiddenTextarea.addEventListener('compositionstart', (e) => {
@@ -591,6 +782,21 @@ class MobileTerminalHandler {
591
782
  });
592
783
  }
593
784
 
785
+ /**
786
+ * blur on the hidden textarea: the IME session is gone, so a reset that
787
+ * had to wait for the field to lose focus (see _resetInputTracking) is
788
+ * applied now — except during the blur/focus pair of _reshowKeyboard,
789
+ * which must keep the field exactly as the IME last saw it.
790
+ * @private
791
+ */
792
+ _onTextareaBlur() {
793
+ this._trace('blur', { reshow: this._suppressBlurReset });
794
+ this._isComposing = false;
795
+ if (this._pendingTrackingReset && !this._suppressBlurReset) {
796
+ this._resetInputTracking();
797
+ }
798
+ }
799
+
594
800
  /**
595
801
  * Record one keyboard/IME event (ring buffer, see Debug Info → Copy
596
802
  * Input Trace). Values are trimmed so the trace stays small.
@@ -661,9 +867,29 @@ class MobileTerminalHandler {
661
867
  // diffs to nothing.
662
868
  if (!this.touchState.isDragging) {
663
869
  this._syncTextareaToTerminal();
870
+ // Chrome sometimes commits the final composition text to the DOM
871
+ // AFTER dispatching compositionend (and the matching input event
872
+ // can still carry isComposing=true). A catch-up sync on the next
873
+ // task sees the settled field; idempotent, so harmless otherwise.
874
+ this._scheduleDeferredSync();
664
875
  }
665
876
  }
666
877
 
878
+ /**
879
+ * Run one more diff sync on the next task (see _onCompositionEnd).
880
+ * @private
881
+ */
882
+ _scheduleDeferredSync() {
883
+ if (typeof setTimeout !== 'function') return;
884
+ if (this._deferredSyncTimer) clearTimeout(this._deferredSyncTimer);
885
+ this._deferredSyncTimer = setTimeout(() => {
886
+ this._deferredSyncTimer = null;
887
+ if (!this.hiddenTextarea) return;
888
+ if (this.touchState.isDragging || this.selection.active) return;
889
+ this._syncTextareaToTerminal();
890
+ }, 0);
891
+ }
892
+
667
893
  /**
668
894
  * Reset the textarea input tracking: clear the textarea and the
669
895
  * synced-content baseline together so future diffs start from a clean
@@ -738,20 +964,43 @@ class MobileTerminalHandler {
738
964
 
739
965
  // The field accumulates every submitted line (separated by \n — see
740
966
  // the Enter keydown comment). Lines above the current one were already
741
- // submitted and cannot be edited any more, so a divergence before the
742
- // current line's start must never turn into DELs (in a multi-line TUI
743
- // editor a DEL at column 0 joins lines).
967
+ // submitted and cannot be edited any more.
744
968
  const lineStart = prev.lastIndexOf('\n') + 1;
745
969
 
746
- // Erase back to the divergence point (clamped to the current line).
970
+ let removed;
971
+ let insert;
972
+ if (prefixLen >= lineStart) {
973
+ // Divergence inside the current line: erase back to it and retype.
974
+ removed = prev.substring(prefixLen);
975
+ insert = curr.substring(prefixLen);
976
+ } else if (prev.startsWith(curr)) {
977
+ // Pure deletion reaching back across the line break (Backspace on
978
+ // an empty line, or a swipe-to-delete that crossed it). A physical
979
+ // keyboard sends one DEL per press, so do the same — including one
980
+ // for the newline. On a shell prompt that is a no-op; in a
981
+ // multi-line TUI editor it joins lines, exactly like a real key.
982
+ removed = prev.substring(curr.length);
983
+ insert = '';
984
+ } else {
985
+ // The IME rewrote text on an already submitted line (only a stale
986
+ // keyboard model or a caret jump can do this). Nothing above the
987
+ // current line can be sent any more, so limit the damage to the
988
+ // current line: diff prev's and curr's last lines only.
989
+ const pLine = prev.substring(lineStart);
990
+ const cLine = curr.substring(curr.lastIndexOf('\n') + 1);
991
+ let p = 0;
992
+ const m = Math.min(pLine.length, cLine.length);
993
+ while (p < m && pLine[p] === cLine[p]) p++;
994
+ removed = pLine.substring(p);
995
+ insert = cLine.substring(p);
996
+ }
997
+
747
998
  // Count code points (not UTF-16 units) so astral characters (emoji
748
999
  // etc.) get one DEL each.
749
- const removed = prev.substring(Math.max(prefixLen, lineStart));
750
1000
  const deleteCount = removed ? Array.from(removed).length : 0;
751
1001
 
752
- // Retype the remainder. Translate newlines (some keyboards commit
753
- // Enter through the input path instead of a keydown) into \r.
754
- let insert = curr.substring(prefixLen);
1002
+ // Translate newlines (some keyboards commit Enter through the input
1003
+ // path instead of a keydown) into \r.
755
1004
  const hadNewline = /[\r\n]/.test(insert);
756
1005
  if (hadNewline) {
757
1006
  insert = insert.replace(/\r\n/g, '\r').replace(/\n/g, '\r');
@@ -834,6 +1083,11 @@ class MobileTerminalHandler {
834
1083
  * Detach all event listeners
835
1084
  */
836
1085
  destroy() {
1086
+ this._releaseTerminalFocus();
1087
+ if (this._deferredSyncTimer) {
1088
+ clearTimeout(this._deferredSyncTimer);
1089
+ this._deferredSyncTimer = null;
1090
+ }
837
1091
  if (this.container) {
838
1092
  this.container.removeEventListener('touchstart', this._boundHandleTouchStart);
839
1093
  this.container.removeEventListener('touchmove', this._boundHandleTouchMove);
@@ -1011,19 +1265,28 @@ class MobileTerminalHandler {
1011
1265
  return;
1012
1266
  }
1013
1267
 
1014
- // Single tap - clear selection if exists, otherwise focus for input
1015
- const touch = e.changedTouches[0];
1016
- const timeSinceStart = Date.now() - this.touchState.startTime;
1017
-
1018
- if (timeSinceStart < 200) { // Quick tap
1019
- if (this.selection.active) {
1020
- this.clearSelection();
1021
- } else {
1022
- // Reset selecting mode to allow keyboard input for quick tap
1023
- this.touchState.isSelecting = false;
1024
- // Focus hidden textarea for keyboard input
1025
- this._focusHiddenTextarea();
1026
- }
1268
+ // The long-press window is over: whatever this touch was, it is not
1269
+ // a selection gesture any more. (Leaving isSelecting set — the old
1270
+ // behaviour for taps longer than 200 ms — blocked every later focus
1271
+ // request until the next touch.)
1272
+ this.touchState.isSelecting = false;
1273
+
1274
+ // A cancelled touch (browser took over the gesture) is not a tap.
1275
+ if (e && e.type === 'touchcancel') return;
1276
+
1277
+ // A scroll/drag is not a tap.
1278
+ const touch = e.changedTouches && e.changedTouches[0];
1279
+ if (touch) {
1280
+ const dx = touch.clientX - this.touchState.startX;
1281
+ const dy = touch.clientY - this.touchState.startY;
1282
+ if (Math.sqrt(dx * dx + dy * dy) > 10) return;
1283
+ }
1284
+
1285
+ // Tap: clear the selection if there is one, otherwise focus for input.
1286
+ if (this.selection.active) {
1287
+ this.clearSelection();
1288
+ } else {
1289
+ this._focusHiddenTextarea({ userGesture: true });
1027
1290
  }
1028
1291
  }
1029
1292
 
@@ -1638,7 +1901,7 @@ class MobileTerminalHandler {
1638
1901
  * Focus hidden textarea for keyboard input
1639
1902
  * @private
1640
1903
  */
1641
- _focusHiddenTextarea() {
1904
+ _focusHiddenTextarea(opts) {
1642
1905
  // Don't focus keyboard if we're in selection mode or selection is active
1643
1906
  if (this.touchState.isSelecting || this.selection.active) {
1644
1907
  return;
@@ -1649,7 +1912,15 @@ class MobileTerminalHandler {
1649
1912
  // screen-sync while the keyboard stayed open): leave everything
1650
1913
  // untouched. Re-running the readonly dance or focusing again would
1651
1914
  // at best be a no-op and at worst tear down the IME session.
1915
+ //
1916
+ // Exception: the user tapped the terminal (a real gesture) while
1917
+ // the field is focused but the keyboard was dismissed with the
1918
+ // Android back button. focus() on an already focused element does
1919
+ // not bring the keyboard back, so re-open it explicitly.
1652
1920
  if (document.activeElement === this.hiddenTextarea) {
1921
+ if (opts && opts.userGesture && this._keyboardProbablyHidden()) {
1922
+ this._reshowKeyboard();
1923
+ }
1653
1924
  return;
1654
1925
  }
1655
1926
 
@@ -1681,6 +1952,64 @@ class MobileTerminalHandler {
1681
1952
  }
1682
1953
  }
1683
1954
 
1955
+ /**
1956
+ * Re-open a dismissed virtual keyboard on an already focused field:
1957
+ * blur + focus inside the tap's user gesture. The field content is
1958
+ * deliberately kept across the pair (no pending reset is applied on
1959
+ * this blur) so Gboard's model cannot diverge from the DOM even if
1960
+ * Chrome coalesces the two focus changes into one IME update.
1961
+ * @private
1962
+ */
1963
+ _reshowKeyboard() {
1964
+ const ta = this.hiddenTextarea;
1965
+ if (!ta) return;
1966
+ this._trace('reshow', {});
1967
+ this._suppressBlurReset = true;
1968
+ this._intentionalBlur = true;
1969
+ try { ta.blur(); } finally { this._suppressBlurReset = false; }
1970
+ const len = typeof ta.value === 'string' ? ta.value.length : 0;
1971
+ ta.focus();
1972
+ try { ta.setSelectionRange(len, len); } catch (_) {}
1973
+ this._keyboardCollapsed = false;
1974
+ }
1975
+
1976
+ /**
1977
+ * Remember the tallest layout viewport seen at the current width
1978
+ * (called at init and on every resize / visual-viewport event).
1979
+ * @private
1980
+ */
1981
+ _noteViewportHeight() {
1982
+ if (typeof window === 'undefined') return;
1983
+ const w = window.innerWidth;
1984
+ const h = window.innerHeight;
1985
+ if (!(w > 0 && h > 0)) return;
1986
+ if (!(this._maxInnerHeightByWidth[w] >= h)) {
1987
+ this._maxInnerHeightByWidth[w] = h;
1988
+ }
1989
+ }
1990
+
1991
+ /**
1992
+ * Best-effort "is the virtual keyboard currently dismissed?" for a
1993
+ * focused field. Two signals: an overlay keyboard shrinks the visual
1994
+ * viewport below the layout viewport; a `resizes-content` keyboard
1995
+ * (this app's meta viewport) shrinks the layout viewport itself, which
1996
+ * shows as innerHeight well below the tallest height seen at this
1997
+ * width. When neither says "keyboard up", assume it is hidden — the
1998
+ * cost of a wrong guess is one blur/focus flicker, while a missed
1999
+ * re-open leaves the user with no way to get the keyboard back.
2000
+ * @private
2001
+ */
2002
+ _keyboardProbablyHidden() {
2003
+ if (typeof window === 'undefined') return false;
2004
+ this._noteViewportHeight();
2005
+ const vv = window.visualViewport;
2006
+ if (vv && typeof vv.height === 'number' && window.innerHeight - vv.height > 100) {
2007
+ return false;
2008
+ }
2009
+ const ref = this._maxInnerHeightByWidth[window.innerWidth] || window.innerHeight;
2010
+ return window.innerHeight >= ref - 120;
2011
+ }
2012
+
1684
2013
  /**
1685
2014
  * Collapse keyboard by blurring hidden textarea
1686
2015
  * @private
@@ -1762,6 +2091,7 @@ class MobileTerminalHandler {
1762
2091
  * @private
1763
2092
  */
1764
2093
  _handleResize() {
2094
+ this._noteViewportHeight();
1765
2095
  if (this.selection.active) {
1766
2096
  requestAnimationFrame(() => {
1767
2097
  if (this.selection.active) {
@@ -1777,6 +2107,7 @@ class MobileTerminalHandler {
1777
2107
  */
1778
2108
  _handleVisualViewport() {
1779
2109
  if (!window.visualViewport) return;
2110
+ this._noteViewportHeight();
1780
2111
 
1781
2112
  const viewportHeight = window.visualViewport.height;
1782
2113
  const windowHeight = window.innerHeight;
package/src/webapp/sw.js CHANGED
@@ -1,5 +1,26 @@
1
- const CACHE_NAME = 'sshift-__VERSION__';
1
+ // SSHIFT service worker.
2
+ //
3
+ // Cache busting model (v1.8.2):
4
+ // - __VERSION__ is replaced with the package version by the server on every
5
+ // request, and /sw.js is served with no-store. A new release therefore
6
+ // produces a byte-different worker, which the browser installs as an
7
+ // update.
8
+ // - Every asset the page references carries ?v=<version>; the cache is
9
+ // named after the version too. Old caches (any name that is not this
10
+ // version's) are deleted on activate, so nothing from a previous version
11
+ // can ever be served again.
12
+ // - skipWaiting() + clients.claim(): the new worker replaces the old one as
13
+ // soon as it has installed, for every open page at once. There is never a
14
+ // "waiting" worker and never two versions alive side by side. The page's
15
+ // registration script reloads on controllerchange so HTML, JS and CSS are
16
+ // always from the same version.
17
+ // - Navigations (index.html) are network-first with a versioned offline
18
+ // fallback; everything else same-origin is cache-first because the cache
19
+ // is version-scoped. Socket.IO, the API and the worker script itself are
20
+ // never cached.
2
21
  const VERSION = '__VERSION__';
22
+ const CACHE_NAME = 'sshift-' + VERSION;
23
+ const NAV_CACHE = CACHE_NAME + '-nav';
3
24
 
4
25
  const PRECACHE_URLS = [
5
26
  '/css/style.css?v=' + VERSION,
@@ -9,73 +30,68 @@ const PRECACHE_URLS = [
9
30
  '/manifest.json?v=' + VERSION
10
31
  ];
11
32
 
12
- const NAV_CACHE = CACHE_NAME + '-nav';
13
-
14
33
  self.addEventListener('install', (event) => {
15
34
  event.waitUntil(
16
- caches.open(CACHE_NAME).then((cache) => {
17
- return Promise.allSettled(
35
+ caches.open(CACHE_NAME)
36
+ .then((cache) => Promise.allSettled(
18
37
  PRECACHE_URLS.map((url) =>
19
38
  cache.add(url).catch((e) => {
20
- console.warn('[SW] Failed to precache:', url, e.message);
39
+ console.warn('[SW] Failed to precache:', url, e && e.message);
21
40
  })
22
41
  )
23
- );
24
- })
42
+ ))
43
+ .then(() => self.skipWaiting())
25
44
  );
26
- self.skipWaiting();
27
45
  });
28
46
 
29
47
  self.addEventListener('activate', (event) => {
30
48
  event.waitUntil(
31
- caches.keys().then((cacheNames) =>
32
- Promise.all(
49
+ caches.keys()
50
+ .then((cacheNames) => Promise.all(
33
51
  cacheNames
34
52
  .filter((name) => name !== CACHE_NAME && name !== NAV_CACHE)
35
53
  .map((name) => caches.delete(name))
36
- )
37
- )
54
+ ))
55
+ .then(() => self.clients.claim())
38
56
  );
39
- self.clients.claim();
40
57
  });
41
58
 
42
- self.addEventListener('fetch', (event) => {
43
- if (event.request.method !== 'GET') return;
59
+ function isCacheable(url, request) {
60
+ if (request.method !== 'GET') return false;
61
+ if (url.origin !== self.location.origin) return false;
62
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return false;
63
+ if (url.pathname.startsWith('/socket.io/')) return false;
64
+ if (url.pathname.startsWith('/api/')) return false;
65
+ if (url.pathname === '/sw.js') return false;
66
+ return true;
67
+ }
44
68
 
69
+ self.addEventListener('fetch', (event) => {
45
70
  const url = new URL(event.request.url);
71
+ if (!isCacheable(url, event.request)) return;
46
72
 
47
- if (url.protocol !== 'http:' && url.protocol !== 'https:') return;
48
-
49
- if (url.pathname.startsWith('/socket.io/')) return;
50
- if (url.pathname.startsWith('/api/')) return;
51
- if (url.pathname === '/sw.js') return;
52
-
53
- const isNavigation = event.request.mode === 'navigate';
54
-
55
- if (isNavigation) {
73
+ if (event.request.mode === 'navigate') {
56
74
  event.respondWith(
57
75
  fetch(event.request)
58
76
  .then((response) => {
59
77
  if (response && response.status === 200) {
60
78
  const clone = response.clone();
61
- caches.open(NAV_CACHE).then((cache) => cache.put(event.request, clone));
79
+ caches.open(NAV_CACHE).then((cache) => cache.put(event.request, clone)).catch(() => {});
62
80
  }
63
81
  return response;
64
82
  })
65
- .catch(() => caches.match(event.request))
83
+ .catch(() => caches.match(event.request).then((cached) => cached || Response.error()))
66
84
  );
67
85
  return;
68
86
  }
69
87
 
70
88
  event.respondWith(
71
89
  caches.match(event.request).then((cached) => {
72
- if (cached) {
73
- return cached;
74
- }
90
+ if (cached) return cached;
75
91
  return fetch(event.request).then((response) => {
76
92
  if (response && response.status === 200 && response.type === 'basic') {
77
93
  const clone = response.clone();
78
- caches.open(CACHE_NAME).then((cache) => cache.put(event.request, clone));
94
+ caches.open(CACHE_NAME).then((cache) => cache.put(event.request, clone)).catch(() => {});
79
95
  }
80
96
  return response;
81
97
  });
@@ -84,11 +100,22 @@ self.addEventListener('fetch', (event) => {
84
100
  });
85
101
 
86
102
  self.addEventListener('message', (event) => {
87
- if (event.data && event.data.type === 'CLEAR_CACHES') {
88
- caches.keys().then((names) => {
89
- for (const name of names) {
90
- caches.delete(name);
91
- }
92
- });
103
+ const data = event.data || {};
104
+ const reply = (msg) => {
105
+ try {
106
+ if (event.ports && event.ports[0]) event.ports[0].postMessage(msg);
107
+ else if (event.source && event.source.postMessage) event.source.postMessage(msg);
108
+ } catch (_) {}
109
+ };
110
+ if (data.type === 'CLEAR_CACHES') {
111
+ event.waitUntil(
112
+ caches.keys()
113
+ .then((names) => Promise.all(names.map((name) => caches.delete(name))))
114
+ .then(() => reply({ type: 'CACHES_CLEARED' }))
115
+ );
116
+ } else if (data.type === 'GET_VERSION') {
117
+ reply({ type: 'VERSION', version: VERSION });
118
+ } else if (data.type === 'SKIP_WAITING') {
119
+ self.skipWaiting();
93
120
  }
94
- });
121
+ });