tabby-rdp 0.5.2 → 0.5.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -23,6 +23,8 @@ const url_1 = require("url");
23
23
  const targets_1 = require("./targets");
24
24
  const deskScript_1 = require("./deskScript");
25
25
  const audio_1 = require("./audio");
26
+ const ironrdp_1 = require("./ironrdp");
27
+ const h264_1 = require("./h264");
26
28
  const clipboard_1 = require("./clipboard");
27
29
  const connectionStatus_1 = require("./connectionStatus");
28
30
  const microphone_1 = require("./microphone");
@@ -82,8 +84,11 @@ const vendorFile = (f) => path.join(__dirname, '..', 'vendor', f);
82
84
  const vendor = (f) => (0, url_1.pathToFileURL)(vendorFile(f)).href;
83
85
  const STYLE = `
84
86
  .trd-overlay { position: absolute; inset: 0; z-index: 30; display: flex; background: #111; }
87
+ /* Only full-window settings overlays expose their drag strip (see settingsPage.ts). */
88
+ .trd-form-dragbar { display: none; }
85
89
  .trd-host { flex: auto; min-width: 0; min-height: 0; display: flex; }
86
90
  .trd-host iron-remote-desktop { flex: auto; }
91
+ .trd-last-frame { max-width: 100%; max-height: 100%; object-fit: contain; align-self: center; margin: auto; }
87
92
  .trd-status { position: absolute; inset: 0; display: flex; flex-direction: column; gap: 14px; align-items: center;
88
93
  justify-content: center; padding: 2em; text-align: center; color: #bbb; font-size: 13px; white-space: pre-line;
89
94
  pointer-events: none; }
@@ -107,6 +112,10 @@ const STYLE = `
107
112
  .trd-overlay.trd-mic-on > .trd-toast { right: 40px; max-width: min(420px, calc(100% - 52px)); }
108
113
  .trd-floating-mic-on .trd-overlay.trd-broadcast-on::before { top: 40px; }
109
114
  `;
115
+ /** A file's name as it is shown: it comes with the file, and what could reorder or hide part of it shows as �. */
116
+ function showableFileName(raw) {
117
+ return raw.replace(new RegExp(unshowable_1.UNSHOWABLE.source, 'gu'), '�');
118
+ }
110
119
  /**
111
120
  * The name a desktop connected to directly goes by, as its certificate is checked against it (see
112
121
  * RDCleanPathOptions.serverName): an address as it is, a host name as it resolves (lower case, punycode, without a
@@ -261,11 +270,24 @@ class DesktopSession {
261
270
  /** Keys this desktop was sent and not yet let go of (by `code`): see RemoteDesktopService.broadcastKey. */
262
271
  this.keysDown = new Map();
263
272
  this.reclaimFocus = (event) => {
264
- if (this.visible && !this.overlay.contains(event.target)) {
273
+ if (!this.visible) {
274
+ return;
275
+ }
276
+ if (!this.overlay.contains(event.target)) {
265
277
  this.focusSoon();
278
+ return;
279
+ }
280
+ // The focus came to the desktop while its pane isn't the one the user is in: IronRDP's canvas takes it as the
281
+ // pointer passes over it (its `mouseenter`), without a click, and with it the keys typed and this computer's
282
+ // clipboard (its monitor follows the focus). It goes back where it came from. A click hands it over still:
283
+ // Tabby makes the pane the one in front on the click, and the pane's focus gives the desktop the keyboard. (The
284
+ // layer's own fields and buttons, a sign-in form's, send nothing anywhere until they are used.)
285
+ if (event.target?.tagName === 'IRON-REMOTE-DESKTOP' && !this.inFront()) {
286
+ this.letGo(event.relatedTarget);
266
287
  }
267
288
  };
268
289
  this.disposers = [];
290
+ this.connectionDisposers = [];
269
291
  this.disposed = new Promise(resolve => { this.markDisposed = resolve; });
270
292
  this.overlay = document.createElement('div');
271
293
  this.overlay.className = 'trd-overlay';
@@ -304,7 +326,9 @@ class DesktopSession {
304
326
  }
305
327
  /**
306
328
  * Lets go of every key still held on this desktop. For when their keyups won't reach it: view only coming on, or
307
- * typing into all going off, by a shortcut whose modifiers are down at that moment. They would stay down there.
329
+ * typing into all going off, by a shortcut whose modifiers are down at that moment, or the user leaving its pane
330
+ * by one (see RemoteDesktopService.letGoUnlessInFront). They would stay down there. Sent through IronRDP's
331
+ * component, which takes a key sent this way whether or not it has the focus.
308
332
  */
309
333
  releaseKeys() {
310
334
  for (const [code, init] of [...this.keysDown]) {
@@ -334,6 +358,33 @@ class DesktopSession {
334
358
  canvas() {
335
359
  return this.host.querySelector('iron-remote-desktop')?.shadowRoot?.querySelector('canvas') ?? null;
336
360
  }
361
+ /** Whether the focus is on the desktop: IronRDP's component, its sign-in form, a question's buttons. */
362
+ holdsFocus() {
363
+ return this.overlay.contains(document.activeElement);
364
+ }
365
+ /**
366
+ * Takes the focus from the desktop, if it has it, back to `to` (where it came from) when that is still there to
367
+ * take it, or else to nothing. On IronRDP's component it is its canvas, in the component's shadow root, that has
368
+ * it, and has to let go. The keys held on the remote stay held: IronRDP lets go of them as the window loses the
369
+ * focus or the pointer leaves the canvas, not as the canvas loses the focus. Where the focus goes back to the
370
+ * desktop in front (the pointer passed over this one), their keyups still come from there, copied when typing
371
+ * into all; where the user left the pane, they don't, and the keys are let go of (see
372
+ * RemoteDesktopService.letGoUnlessInFront).
373
+ */
374
+ letGo(to) {
375
+ const active = document.activeElement;
376
+ if (!active || !this.overlay.contains(active)) {
377
+ return;
378
+ }
379
+ const back = to;
380
+ if (typeof back?.focus === 'function' && back.isConnected !== false && !this.overlay.contains(back)) {
381
+ back.focus({ preventScroll: true });
382
+ }
383
+ if (this.overlay.contains(document.activeElement)) {
384
+ ;
385
+ (active.shadowRoot?.activeElement ?? active).blur();
386
+ }
387
+ }
337
388
  /**
338
389
  * Focuses the remote desktop in a moment, if it is still in the pane the user is in then (see inFront). `visible`
339
390
  * stays true in a tab in the background, and a focus that was waiting (a retry, or Tabby's re-focus of the terminal
@@ -386,6 +437,58 @@ class DesktopSession {
386
437
  onDispose(f) {
387
438
  this.disposers.push(f);
388
439
  }
440
+ onConnectionEnd(f) {
441
+ this.connectionDisposers.push(f);
442
+ }
443
+ /** Release browser resources and references to one backend, including when its WASM has trapped. */
444
+ endConnection(keepPicture = true) {
445
+ const clean = (f) => {
446
+ try {
447
+ f();
448
+ }
449
+ catch (error) {
450
+ this.log.push(`cleanup: ${error?.message ?? error}`);
451
+ }
452
+ };
453
+ let picture = keepPicture ? this.host.querySelector('.trd-last-frame') : null;
454
+ // Preserve the dimmed disconnect picture as plain pixels, without the component's backend or listeners.
455
+ clean(() => {
456
+ const frame = keepPicture ? this.canvas() : null;
457
+ if (!frame?.width || !frame.height) {
458
+ return;
459
+ }
460
+ const copy = document.createElement('canvas');
461
+ copy.width = frame.width;
462
+ copy.height = frame.height;
463
+ copy.className = 'trd-last-frame';
464
+ const rect = frame.getBoundingClientRect();
465
+ copy.style.width = `${rect.width || frame.width}px`;
466
+ copy.style.height = `${rect.height || frame.height}px`;
467
+ const ctx = copy.getContext('2d');
468
+ if (ctx) {
469
+ ctx.drawImage(frame, 0, 0);
470
+ picture = copy;
471
+ }
472
+ });
473
+ this.connectionDisposers.splice(0).forEach(clean);
474
+ clean(() => this.indicator?.setActive(false));
475
+ clean(() => this.ui?.shutdown());
476
+ // Removing the component stops its clipboard loop and removes its global listeners.
477
+ clean(() => this.host.replaceChildren(...picture ? [picture] : []));
478
+ this.ui = null;
479
+ this.stopSending = null;
480
+ clean(() => this.audio?.close());
481
+ this.audio = null;
482
+ clean(() => this.h264?.close());
483
+ this.h264 = null;
484
+ clean(() => this.mic?.close());
485
+ this.mic = null;
486
+ clean(() => this.files?.dispose());
487
+ this.files = null;
488
+ clean(() => this.drives?.dispose());
489
+ this.drives = null;
490
+ this.remoteSize = null;
491
+ }
389
492
  /** Focuses the remote desktop. IronRDP reveals its canvas asynchronously, so retry for about half a second. */
390
493
  focusDesktop(attempts = 30) {
391
494
  // While the sign-in form shows, it is what takes focus back (the user name, or the password once filled).
@@ -417,16 +520,7 @@ class DesktopSession {
417
520
  clearTimeout(this.labelTimer);
418
521
  this.container.removeEventListener('focusin', this.reclaimFocus, true);
419
522
  this.disposers.forEach(f => f());
420
- this.indicator?.dispose();
421
- try {
422
- this.ui?.shutdown();
423
- }
424
- catch { }
425
- this.audio?.close();
426
- this.h264?.close();
427
- this.mic?.close();
428
- this.files?.dispose();
429
- this.drives?.dispose();
523
+ this.endConnection(false);
430
524
  this.proxy?.close();
431
525
  this.overlay.remove();
432
526
  }
@@ -451,7 +545,13 @@ let RemoteDesktopService = RemoteDesktopService_1 = class RemoteDesktopService {
451
545
  /** Emits whenever a pane's desktop is opened, shown, hidden, connected, ended or disconnected. */
452
546
  this.changed$ = new rxjs_1.Subject();
453
547
  this.sessions = new Map();
454
- this.ironrdp = null;
548
+ this.ironrdp = new ironrdp_1.IronRDPLoader(async () => {
549
+ const [factory, bytes] = await Promise.all([
550
+ importESM(vendor('iron-remote-desktop.js')).then(() => importESM(vendor('ironrdp-factory.js'))),
551
+ fs.promises.readFile(vendorFile('ironrdp_web_bg.wasm')),
552
+ ]);
553
+ return { module: await WebAssembly.compile(bytes), createBackend: factory.createBackend };
554
+ });
455
555
  /** Whether the browser decodes H.264 (asked once). */
456
556
  this.h264Support = null;
457
557
  /** Desktops (session keys) where H.264 decoding failed: they connect without it until Tabby restarts. */
@@ -849,10 +949,14 @@ let RemoteDesktopService = RemoteDesktopService_1 = class RemoteDesktopService {
849
949
  // Names as text whatever the config holds (see entryText): the accounts list and the question before removing
850
950
  // one show them all.
851
951
  const desktops = this.configuredDesktops().flatMap((d, i) => (0, desktops_1.isDesktopEntry)(d) && (d.account === id || d.gatewayAccount === id) ? [{ name: (0, desktops_1.entryText)(d).name, desktopIndex: i }] : []);
852
- const groups = this.config.store.groups ?? [];
853
- const inherited = (p) => p.options?.account === undefined && groups.find(g => g.id === p.group)?.defaults?.[targets_1.RDP_PROFILE_TYPE]?.options?.account === id;
854
952
  const profiles = (this.config.store.profiles ?? [])
855
- .filter((p) => p?.type === targets_1.RDP_PROFILE_TYPE && (p.options?.account === id || p.options?.gatewayAccount === id || inherited(p)))
953
+ .filter((p) => {
954
+ if (p?.type !== targets_1.RDP_PROFILE_TYPE) {
955
+ return false;
956
+ }
957
+ const options = this.profiles.getConfigProxyForProfile(p).options;
958
+ return options?.account === id || options?.gatewayAccount === id;
959
+ })
856
960
  .map((p) => ({ name: (0, desktops_1.configText)(p.name) || (0, desktops_1.configText)(p.options?.host), profileId: (0, desktops_1.configText)(p.id) || undefined }));
857
961
  return [...desktops, ...profiles];
858
962
  }
@@ -971,9 +1075,9 @@ let RemoteDesktopService = RemoteDesktopService_1 = class RemoteDesktopService {
971
1075
  if (rest.account === id) {
972
1076
  delete rest.account;
973
1077
  }
974
- // A gateway that signed in with it takes the desktop's sign-in from now on.
1078
+ // Keep the gateway's credentials separate after its saved account is removed.
975
1079
  if (rest.gatewayAccount === id) {
976
- delete rest.gatewayAccount;
1080
+ rest.gatewayAccount = accounts_1.ASK_GATEWAY_ACCOUNT;
977
1081
  }
978
1082
  return rest;
979
1083
  });
@@ -984,15 +1088,19 @@ let RemoteDesktopService = RemoteDesktopService_1 = class RemoteDesktopService {
984
1088
  profile.options.account = null;
985
1089
  }
986
1090
  if (profile?.type === targets_1.RDP_PROFILE_TYPE && profile.options?.gatewayAccount === id) {
987
- profile.options.gatewayAccount = null;
1091
+ profile.options.gatewayAccount = accounts_1.ASK_GATEWAY_ACCOUNT;
988
1092
  }
989
1093
  }
990
- // A profile group's default for remote desktop profiles, too.
991
- for (const group of this.config.store.groups ?? []) {
992
- const options = group?.defaults?.[targets_1.RDP_PROFILE_TYPE]?.options;
1094
+ // Group and global defaults keep separate gateway authentication for their inheriting profiles, too.
1095
+ const defaults = [this.config.store.profileDefaults, ...(this.config.store.groups ?? []).map((group) => group?.defaults)];
1096
+ for (const entry of defaults) {
1097
+ const options = entry?.[targets_1.RDP_PROFILE_TYPE]?.options;
993
1098
  if (options?.account === id) {
994
1099
  options.account = '';
995
1100
  }
1101
+ if (options?.gatewayAccount === id) {
1102
+ options.gatewayAccount = accounts_1.ASK_GATEWAY_ACCOUNT;
1103
+ }
996
1104
  }
997
1105
  await this.config.save();
998
1106
  this.changed$.next();
@@ -1170,6 +1278,10 @@ let RemoteDesktopService = RemoteDesktopService_1 = class RemoteDesktopService {
1170
1278
  }
1171
1279
  }
1172
1280
  }
1281
+ /** Says that the .rdp file named `rawFileName` is too large to be one (see MAX_RDP_FILE). */
1282
+ refuseLargeRdp(rawFileName, size) {
1283
+ this.notifications.error(`${showableFileName(rawFileName)}: at ${Math.ceil(size / 1024)} KB, far larger than an .rdp file is, so it wasn't imported`);
1284
+ }
1173
1285
  /** "Import an .rdp file…": picks one and adds it as a remote desktop profile (see importRdp). */
1174
1286
  async importRdpFile() {
1175
1287
  const file = await new Promise(resolve => {
@@ -1183,6 +1295,11 @@ let RemoteDesktopService = RemoteDesktopService_1 = class RemoteDesktopService {
1183
1295
  input.click();
1184
1296
  });
1185
1297
  if (file) {
1298
+ // Not even read when it is far larger than an .rdp file is (see importRdp).
1299
+ if (file.size > rdpFile_1.MAX_RDP_FILE) {
1300
+ this.refuseLargeRdp(file.name, file.size);
1301
+ return;
1302
+ }
1186
1303
  // A reading or parsing failure is shown, not dropped as an unhandled rejection: this is the user's action.
1187
1304
  try {
1188
1305
  await this.importRdp(new Uint8Array(await file.arrayBuffer()), file.name);
@@ -1216,8 +1333,12 @@ let RemoteDesktopService = RemoteDesktopService_1 = class RemoteDesktopService {
1216
1333
  * and opens it; or opens the profile that already has that address, user and domain. Returns the profile, or null.
1217
1334
  */
1218
1335
  async importRdp(data, rawFileName) {
1219
- // The file's name comes with the file, and is shown: what could reorder or hide part of it shows as �.
1220
- const fileName = rawFileName.replace(new RegExp(unshowable_1.UNSHOWABLE.source, 'gu'), '�');
1336
+ const fileName = showableFileName(rawFileName);
1337
+ // Far larger than an .rdp file is: not parsed, on the thread that runs Tabby's window (see MAX_RDP_FILE).
1338
+ if (data.length > rdpFile_1.MAX_RDP_FILE) {
1339
+ this.refuseLargeRdp(rawFileName, data.length);
1340
+ return null;
1341
+ }
1221
1342
  const parsed = (0, rdpFile_1.parseRdpFile)(data);
1222
1343
  if (!parsed) {
1223
1344
  this.notifications.error(`${fileName}: no address ("full address") in it`);
@@ -1542,6 +1663,16 @@ let RemoteDesktopService = RemoteDesktopService_1 = class RemoteDesktopService {
1542
1663
  }
1543
1664
  });
1544
1665
  created.onDispose(() => focused.unsubscribe());
1666
+ // The pane is no longer the one the user is in: another tab, another pane of the split. Tabby only moves a
1667
+ // tab it leaves off screen, and a tab that takes no focus of its own (Settings, the welcome tab) leaves the
1668
+ // focus where it was: on the desktop, which would go on taking the keys typed and this computer's
1669
+ // clipboard. It lets go then, of the keys it holds on the remote too: the user left by a shortcut whose
1670
+ // modifier is still down, and its keyup goes where they went. A moment later: Tabby says so before it says
1671
+ // which tab is the active one.
1672
+ const blurred = pane.blurred$.subscribe(() => {
1673
+ setTimeout(() => this.letGoUnlessInFront(created));
1674
+ });
1675
+ created.onDispose(() => blurred.unsubscribe());
1545
1676
  this.connect(pane, target, spec, created);
1546
1677
  }
1547
1678
  if (options.background) {
@@ -1609,10 +1740,29 @@ let RemoteDesktopService = RemoteDesktopService_1 = class RemoteDesktopService {
1609
1740
  inFront(pane) {
1610
1741
  return (0, targets_1.desktopPaneOf)(this.app.activeTab) === pane;
1611
1742
  }
1612
- /** Whether `session` is the desktop of the pane the user is in (see inFront). */
1743
+ /**
1744
+ * Whether `session` is the desktop of the pane the user is in (see inFront), and not behind a pane maximized over
1745
+ * it (see behindMaximized).
1746
+ */
1613
1747
  showsInFront(session) {
1614
1748
  const pane = (0, targets_1.desktopPaneOf)(this.app.activeTab);
1615
- return !!pane && this.sessions.get(pane) === session;
1749
+ return !!pane && this.sessions.get(pane) === session && !this.behindMaximized(pane);
1750
+ }
1751
+ /**
1752
+ * A desktop whose pane stopped being the one the user is in (see showsInFront): the focus is taken from it, if it
1753
+ * has it, and the keys it holds on the remote are let go of. Their keyups go where the user went, whether the
1754
+ * desktop kept the focus until now (a tab that takes none) or lost it to what they went to (a terminal), and
1755
+ * IronRDP lets go of nothing as its canvas loses the focus (see DesktopSession.letGo). With typing broadcast to
1756
+ * every desktop of the tab, leaving the tab leaves all of its panes, so each of them is let go of here too.
1757
+ */
1758
+ letGoUnlessInFront(session) {
1759
+ if (this.showsInFront(session)) {
1760
+ return;
1761
+ }
1762
+ if (session.holdsFocus()) {
1763
+ session.letGo();
1764
+ }
1765
+ session.releaseKeys();
1616
1766
  }
1617
1767
  /**
1618
1768
  * Gives a desktop that just connected the keyboard, if it shows in the pane the user is in. Not when another pane is
@@ -2175,7 +2325,7 @@ let RemoteDesktopService = RemoteDesktopService_1 = class RemoteDesktopService {
2175
2325
  timer = setTimeout(() => this.followPane(pane, session), 300);
2176
2326
  });
2177
2327
  observer.observe(session.overlay);
2178
- session.onDispose(() => {
2328
+ session.onConnectionEnd(() => {
2179
2329
  clearTimeout(timer);
2180
2330
  observer.disconnect();
2181
2331
  });
@@ -2650,25 +2800,12 @@ let RemoteDesktopService = RemoteDesktopService_1 = class RemoteDesktopService {
2650
2800
  return this.sessions.get(pane)?.log ?? [];
2651
2801
  }
2652
2802
  loadIronRDP() {
2653
- this.ironrdp ??= (async () => {
2654
- // The WebAssembly ships as its own file (not inlined in the bundle). It is read here and handed to init,
2655
- // rather than fetched by the bundle from next to itself: fetch() of file:// URLs is up to the Electron
2656
- // build (a fuse turns it off), and a plain file path needs no URL escaping for spaces or drive letters.
2657
- const [rdp, wasm] = await Promise.all([
2658
- importESM(vendor('iron-remote-desktop.js')).then(() => importESM(vendor('iron-remote-desktop-rdp.js'))),
2659
- fs.promises.readFile(vendorFile('ironrdp_web_bg.wasm')),
2660
- ]);
2661
- // Troubleshooting: localStorage.trdLogLevel = 'DEBUG' (or TRACE), then restart Tabby.
2662
- let level = 'INFO';
2663
- try {
2664
- level = localStorage.getItem('trdLogLevel') || level;
2665
- }
2666
- catch { }
2667
- await rdp.init(level, wasm);
2668
- return rdp;
2669
- })();
2670
- this.ironrdp.catch(() => { this.ironrdp = null; });
2671
- return this.ironrdp;
2803
+ let level = 'INFO';
2804
+ try {
2805
+ level = localStorage.getItem('trdLogLevel') || level;
2806
+ }
2807
+ catch { }
2808
+ return this.ironrdp.create(level);
2672
2809
  }
2673
2810
  /**
2674
2811
  * Where to connect and as whom. The host's own desktop: the setup script (grd, generated credentials), or, where
@@ -2919,35 +3056,35 @@ let RemoteDesktopService = RemoteDesktopService_1 = class RemoteDesktopService {
2919
3056
  }
2920
3057
  /**
2921
3058
  * The sign-in to a desktop's RD Gateway with the saved account it names: the account's password from the keychain,
2922
- * or asked for (when none is saved, or `retryError`: the gateway just refused it). Undefined when that account no
2923
- * longer exists (the desktop's own sign-in is then tried); null when the form was cancelled.
3059
+ * or asked for (when none is saved, or `retryError`: the gateway just refused it). A removed or missing account
3060
+ * always asks for separate credentials; null when the form was cancelled.
2924
3061
  */
2925
3062
  async gatewayAccountFor(spec, session, gateway, retryError) {
2926
3063
  const account = this.accounts().find(a => a.id === spec.gatewayAccount);
2927
3064
  if (!account) {
2928
- session.log.push('gateway: its saved account no longer exists; signing in with the desktop\'s');
2929
- return undefined;
3065
+ session.log.push('gateway: asking for a separate account');
2930
3066
  }
2931
- const signIn = { domain: account.domain, saveKey: (0, accounts_1.accountKey)(account.id), saveLabel: `saved account ${account.name}`, saveFor: (0, accounts_1.signInName)(account), accountRevision: this.accountRevisions.capture(account) };
2932
- const saved = retryError ? null : await (0, signin_1.loadCredentials)(signIn.saveKey);
2933
- if (saved && saved.username === (0, accounts_1.signInName)(account)) {
3067
+ const signIn = account ? { domain: account.domain, saveKey: (0, accounts_1.accountKey)(account.id), saveLabel: `saved account ${account.name}`, saveFor: (0, accounts_1.signInName)(account), accountRevision: this.accountRevisions.capture(account) } : undefined;
3068
+ const saved = !retryError && signIn ? await (0, signin_1.loadCredentials)(signIn.saveKey) : null;
3069
+ if (saved && account && saved.username === (0, accounts_1.signInName)(account)) {
2934
3070
  session.log.push(`gateway: the saved account "${account.name}"`);
2935
3071
  return { ...signIn, credentials: { username: (0, accounts_1.signInName)(account), password: saved.password }, remember: false };
2936
3072
  }
2937
3073
  session.status('');
2938
3074
  const asked = (0, signin_1.askCredentials)(session.overlay, {
2939
3075
  title: `Sign in to the gateway ${gateway.host}, to reach ${spec.name}`,
2940
- username: (0, accounts_1.signInName)(account),
2941
- error: [retryError, signIn.accountRevision === undefined ? accountRevisions_1.ACCOUNT_REMEMBER_UNAVAILABLE : ''].filter(Boolean).join(' '),
2942
- canRemember: signIn.accountRevision !== undefined,
2943
- account: account.name,
3076
+ username: account ? (0, accounts_1.signInName)(account) : '',
3077
+ error: [retryError, !account && spec.gatewayAccount !== accounts_1.ASK_GATEWAY_ACCOUNT ? 'The saved gateway account no longer exists. Enter a separate account for the gateway.' : '',
3078
+ account && signIn?.accountRevision === undefined ? accountRevisions_1.ACCOUNT_REMEMBER_UNAVAILABLE : ''].filter(Boolean).join(' '),
3079
+ canRemember: !!signIn && signIn.accountRevision !== undefined,
3080
+ account: account?.name,
2944
3081
  }, session.disposed);
2945
3082
  // Only in the pane in front (see endpointFor).
2946
3083
  if (session.visible && this.showsInFront(session)) {
2947
3084
  setTimeout(() => session.visible && this.showsInFront(session) && session.focusDesktop());
2948
3085
  }
2949
3086
  const entered = await asked;
2950
- return entered && { ...signIn, credentials: entered, remember: entered.remember };
3087
+ return entered && { ...signIn, credentials: entered, remember: !!signIn && entered.remember };
2951
3088
  }
2952
3089
  /**
2953
3090
  * The proxy's stream to a desktop behind an RD Gateway (see gateway.ts): to the gateway as the SSH host (or this
@@ -2956,14 +3093,18 @@ let RemoteDesktopService = RemoteDesktopService_1 = class RemoteDesktopService {
2956
3093
  async throughGateway(target, spec, session, gateway, endpoint, signal) {
2957
3094
  session.gatewayRefused = null;
2958
3095
  const own = endpoint.gatewayAccount;
3096
+ if (spec.gatewayAccount && !own) {
3097
+ throw new Error('A separate gateway sign-in is required before connecting.');
3098
+ }
2959
3099
  const credentials = own?.credentials ?? endpoint.credentials;
2960
- session.log.push(`gateway: ${gateway.host}:${gateway.port}, signing in with ${own ? 'its saved account' : 'the desktop\'s sign-in'}`);
3100
+ session.log.push(`gateway: ${gateway.host}:${gateway.port}, signing in with ${own ? 'its separate account' : 'the desktop\'s sign-in'}`);
2961
3101
  try {
2962
3102
  const stream = await (0, gateway_1.openThroughGateway)(() => target.openTcp(gateway.host, gateway.port), gateway, { username: credentials.username, password: credentials.password, domain: (own ? own.domain : endpoint.domain ?? spec.domain) || undefined }, { host: endpoint.host, port: endpoint.port }, (fingerprint, valid, reason, details) => this.checkGatewayCertificate(session, gateway, fingerprint, valid, reason, details), { log: m => session.log.push(m), clientName: os.hostname(), signal });
2963
3103
  // Entered a moment ago and taken by the gateway: kept, while the account is still what it was signed in as.
2964
- if (own?.remember) {
3104
+ if (own?.remember && own.saveKey) {
2965
3105
  own.remember = false;
2966
- (0, signin_1.saveCredentialsIf)(own.saveKey, own.credentials, () => this.accountCurrent(own.saveKey, own.saveFor, own.accountRevision), own.saveLabel).then(saved => session.log.push(saved ? `gateway: saved as the account's password in ${(0, signin_1.storeName)()}` : 'gateway: not saved: the account changed meanwhile'), e => session.log.push(`gateway: ${(0, signin_1.storeName)()}: ${e?.message ?? e}`));
3106
+ const saveKey = own.saveKey;
3107
+ (0, signin_1.saveCredentialsIf)(saveKey, own.credentials, () => this.accountCurrent(saveKey, own.saveFor, own.accountRevision), own.saveLabel).then(saved => session.log.push(saved ? `gateway: saved as the account's password in ${(0, signin_1.storeName)()}` : 'gateway: not saved: the account changed meanwhile'), e => session.log.push(`gateway: ${(0, signin_1.storeName)()}: ${e?.message ?? e}`));
2967
3108
  }
2968
3109
  return stream;
2969
3110
  }
@@ -3421,8 +3562,40 @@ let RemoteDesktopService = RemoteDesktopService_1 = class RemoteDesktopService {
3421
3562
  }
3422
3563
  /** One RDP connection attempt, until it ends. */
3423
3564
  async run(pane, target, spec, session, rdp, endpoint) {
3565
+ const attempt = new AbortController();
3566
+ let connectedAt;
3567
+ let unwatch;
3568
+ const trapped = new Promise(resolve => {
3569
+ unwatch = rdp.runtime?.onTrap((error) => {
3570
+ session.log.push(`wasm: this desktop's instance trapped: ${error.message}`);
3571
+ // Drop the socket even if Rust's run() promise can no longer settle after a trap.
3572
+ session.proxy?.close();
3573
+ session.proxy = null;
3574
+ resolve({ connected: session.state === 'connected', error: `WebAssembly instance failed: ${error.message}` });
3575
+ });
3576
+ });
3577
+ try {
3578
+ return await Promise.race([
3579
+ this.runConnection(pane, target, spec, session, rdp, endpoint, attempt.signal, at => { connectedAt = at; }),
3580
+ trapped,
3581
+ session.disposed.then(() => ({ connected: false })),
3582
+ ]);
3583
+ }
3584
+ finally {
3585
+ attempt.abort();
3586
+ unwatch?.();
3587
+ // Rust's run() can stay pending after an asynchronous trap. Account for the completed attempt here,
3588
+ // exactly once, and never update retry state belonging to a replacement session in this pane.
3589
+ if (connectedAt !== undefined && this.sessions.get(pane) === session) {
3590
+ this.reconnectedUntilNow(pane, connectedAt);
3591
+ }
3592
+ session.endConnection?.();
3593
+ rdp.runtime?.dispose?.();
3594
+ }
3595
+ }
3596
+ async runConnection(pane, target, spec, session, rdp, endpoint, signal, onConnected) {
3424
3597
  const credentials = endpoint.credentials;
3425
- const alive = () => this.sessions.get(pane) === session;
3598
+ const alive = () => !signal.aborted && this.sessions.get(pane) === session;
3426
3599
  session.certificateProblem = null;
3427
3600
  session.gatewayRefused = null;
3428
3601
  session.withoutNla = false;
@@ -3436,7 +3609,9 @@ let RemoteDesktopService = RemoteDesktopService_1 = class RemoteDesktopService {
3436
3609
  session.host.replaceChildren(el);
3437
3610
  // The element only gets ready in the page: one whose desktop was closed meanwhile (the layer gone) never does.
3438
3611
  // Closed as it got ready, it isn't given the clipboard, files and the rest that closing it has ended already.
3439
- session.ui = await Promise.race([ready, session.disposed.then(() => null)]);
3612
+ session.ui = await Promise.race([ready, session.disposed.then(() => null), new Promise(resolve => {
3613
+ signal.addEventListener('abort', () => resolve(null), { once: true });
3614
+ })]);
3440
3615
  if (!session.ui || !alive()) {
3441
3616
  return { connected: false };
3442
3617
  }
@@ -3499,7 +3674,9 @@ let RemoteDesktopService = RemoteDesktopService_1 = class RemoteDesktopService {
3499
3674
  return { connected: false };
3500
3675
  }
3501
3676
  if (h264) {
3502
- session.h264 = new rdp.WebCodecsH264Decoder({ onFailure: (reason) => session.log.push(`h264: failed: ${reason}`) });
3677
+ // The vendor owns surface retirement and all resource accounting; its public option bounds the
3678
+ // browser decoders without wrapping away lifecycle notifications (see h264.ts).
3679
+ session.h264 = (0, h264_1.createH264Decoder)(rdp.WebCodecsH264Decoder, { onFailure: (reason) => session.log.push(`h264: failed: ${reason}`) });
3503
3680
  config.withExtension(rdp.h264Decoder(session.h264));
3504
3681
  }
3505
3682
  // GNOME Remote Desktop requires the graphics pipeline. Windows (and xrdp) do better with bitmaps than with
@@ -3576,6 +3753,8 @@ let RemoteDesktopService = RemoteDesktopService_1 = class RemoteDesktopService {
3576
3753
  if (!alive()) {
3577
3754
  return { connected: false };
3578
3755
  }
3756
+ const connectedAt = Date.now();
3757
+ onConnected(connectedAt);
3579
3758
  session.ui.setVisibility(true);
3580
3759
  this.applyKeyboardMode(session);
3581
3760
  session.remoteSize = { width, height, scale: 100 };
@@ -3617,12 +3796,14 @@ let RemoteDesktopService = RemoteDesktopService_1 = class RemoteDesktopService {
3617
3796
  }, e => session.log.push(`sign-in: ${(0, signin_1.storeName)()}: ${e?.message ?? e}`));
3618
3797
  }
3619
3798
  this.focusIfInFront(pane, session);
3620
- const connectedAt = Date.now();
3621
3799
  let end;
3622
3800
  try {
3623
3801
  end = await info.run();
3624
3802
  }
3625
3803
  catch (e) {
3804
+ if (!alive()) {
3805
+ return { connected: false };
3806
+ }
3626
3807
  if (session.h264?.failed) {
3627
3808
  // Reconnects (automatically, like any dropped connection) without H.264, unless the browser only
3628
3809
  // took an idle decoder back (a hidden window): then with it, as a new stream starts with a key frame.
@@ -3643,15 +3824,7 @@ let RemoteDesktopService = RemoteDesktopService_1 = class RemoteDesktopService {
3643
3824
  }
3644
3825
  return { connected: true, error };
3645
3826
  }
3646
- finally {
3647
- // The server can't close the microphone, or its files, once the connection is gone.
3648
- session.mic?.close();
3649
- session.drives?.dispose();
3650
- if (alive()) {
3651
- this.reconnectedUntilNow(pane, connectedAt);
3652
- }
3653
- }
3654
- return { connected: true, reason: end?.reason?.() };
3827
+ return alive() ? { connected: true, reason: end?.reason?.() } : { connected: false };
3655
3828
  }
3656
3829
  catch (e) {
3657
3830
  return { connected: false, error: e?.message ?? String(e) };
@@ -3677,45 +3850,12 @@ exports.RemoteDesktopService = RemoteDesktopService = RemoteDesktopService_1 = _
3677
3850
  tabby_core_1.PlatformService])
3678
3851
  ], RemoteDesktopService);
3679
3852
  let styleInstalled = false;
3680
- function installStyle(compat) {
3853
+ function installStyle() {
3681
3854
  if (styleInstalled) {
3682
3855
  return;
3683
3856
  }
3684
3857
  styleInstalled = true;
3685
3858
  const style = document.createElement('style');
3686
- style.textContent = STYLE + signin_1.STYLE + fileTransfer_1.STYLE + connectionStatus_1.STYLE + osd_1.OSD_STYLE + DRAGBAR_STYLE + accountForm_1.STYLE;
3859
+ style.textContent = STYLE + signin_1.STYLE + fileTransfer_1.STYLE + connectionStatus_1.STYLE + osd_1.OSD_STYLE + accountForm_1.STYLE;
3687
3860
  document.head.appendChild(style);
3688
- keepWindowDraggable(compat);
3689
- }
3690
- /** A strip the height of the tab bar that stays a window drag region over a dialog (the plugin's, and Tabby's). */
3691
- const DRAGBAR_STYLE = `
3692
- .trd-form-dragbar { display: none; }
3693
- .modal > .trd-form-dragbar { display: block; position: fixed; left: 0; right: 0; top: 0; height: var(--tabs-height, 38px); -webkit-app-region: drag; }
3694
- `;
3695
- /**
3696
- * Older Tabby dialogs cover the tab bar without a drag region. Supply their fallback strip, deferring to the host's
3697
- * modal pseudo-element when it provides one. The plugin's own dialogs still need their strips (see settingsPage.ts).
3698
- */
3699
- function keepWindowDraggable(compat) {
3700
- const strip = (modal) => {
3701
- if (compat.hasNativeModalDragRegion(modal)) {
3702
- return;
3703
- }
3704
- if (!modal.querySelector(':scope > .trd-form-dragbar')) {
3705
- const bar = document.createElement('div');
3706
- bar.className = 'trd-form-dragbar';
3707
- modal.prepend(bar);
3708
- }
3709
- };
3710
- // ng-bootstrap appends each dialog (ngb-modal-window.modal) to the body itself: only the body's children are watched.
3711
- document.querySelectorAll('body > .modal').forEach(strip);
3712
- new MutationObserver(records => {
3713
- for (const record of records) {
3714
- record.addedNodes.forEach(node => {
3715
- if (node instanceof Element && node.classList.contains('modal')) {
3716
- strip(node);
3717
- }
3718
- });
3719
- }
3720
- }).observe(document.body, { childList: true });
3721
3861
  }
@@ -110,13 +110,13 @@ function askDesktop(pane, options) {
110
110
  account.hidden = account.options.length < 2;
111
111
  }
112
112
  ownAccount();
113
- // The gateway's own account: offered once there is a gateway and a saved account to choose.
113
+ // The gateway's own account, including a separate prompt when no saved account is chosen.
114
114
  const gateway = field('gateway');
115
115
  const gatewayAccount = field('gatewayAccount');
116
116
  gateway.value = (0, desktops_1.configText)(initial.gateway);
117
- gatewayAccount.append(new Option('Gateway account: the same as the desktop\'s', ''), ...accounts.map(a => new Option(`Gateway account: ${a.name} (${(0, accounts_1.signInName)(a)})`, a.id)));
117
+ gatewayAccount.append(new Option('Gateway account: the same as the desktop\'s', ''), new Option('Gateway account: ask when connecting', accounts_1.ASK_GATEWAY_ACCOUNT), ...accounts.map(a => new Option(`Gateway account: ${a.name} (${(0, accounts_1.signInName)(a)})`, a.id)));
118
118
  const initialGatewayAccount = (0, desktops_1.configText)(initial.gatewayAccount);
119
- if (initialGatewayAccount && !accounts.some(a => a.id === initialGatewayAccount)) {
119
+ if (initialGatewayAccount && initialGatewayAccount !== accounts_1.ASK_GATEWAY_ACCOUNT && !accounts.some(a => a.id === initialGatewayAccount)) {
120
120
  gatewayAccount.append(new Option('(a saved account that no longer exists)', initialGatewayAccount));
121
121
  }
122
122
  gatewayAccount.value = initialGatewayAccount;