dsh-remote-vs 0.23.0 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.en.md +49 -15
  2. package/README.md +40 -14
  3. package/lib/client.js +45978 -43338
  4. package/lib/index.js +388 -90
  5. package/lib/p2-router-fs.js +1 -1
  6. package/lib/types/client/CodeEditor.d.ts +17 -0
  7. package/lib/types/client/EditorPane.d.ts +16 -5
  8. package/lib/types/client/FloatingPlaceholder.d.ts +16 -5
  9. package/lib/types/client/RemoteEditorView.d.ts +13 -10
  10. package/lib/types/client/RemoteRoot.d.ts +5 -5
  11. package/lib/types/client/SettingsHosts.d.ts +3 -0
  12. package/lib/types/client/TerminalSnippets.d.ts +36 -0
  13. package/lib/types/client/TerminalView.d.ts +1 -1
  14. package/lib/types/client/XTerm.d.ts +33 -0
  15. package/lib/types/client/api.d.ts +4 -1
  16. package/lib/types/client/auto-open-remote.d.ts +41 -0
  17. package/lib/types/client/editor-capability.d.ts +27 -0
  18. package/lib/types/client/i18n.d.ts +1 -1
  19. package/lib/types/client/store.d.ts +59 -4
  20. package/lib/types/client/terminal-input.d.ts +23 -0
  21. package/lib/types/client/terminal-snippets.d.ts +86 -0
  22. package/lib/types/client/use-remote-chat-target.d.ts +2 -0
  23. package/lib/types/client/view-settings.d.ts +40 -0
  24. package/lib/types/client/vsc/breadcrumb.d.ts +30 -0
  25. package/lib/types/client/vsc/editor-caret.d.ts +32 -0
  26. package/lib/types/client/vsc/editor-langs.d.ts +9 -0
  27. package/lib/types/client/vsc/editor-settings.d.ts +55 -0
  28. package/lib/types/client/vsc/image-preview.d.ts +36 -0
  29. package/lib/types/client/vsc/kit.d.ts +2 -0
  30. package/lib/types/client/vsc/terminal-clipboard.d.ts +15 -0
  31. package/lib/types/client/vsc/terminal-line.d.ts +25 -0
  32. package/lib/types/client/vsc/terminal-links.d.ts +62 -0
  33. package/lib/types/client/vsc/terminal-theme.d.ts +22 -0
  34. package/lib/types/client/vsc/terminal-writer.d.ts +52 -0
  35. package/lib/types/paths.d.ts +9 -0
  36. package/lib/types/pool.d.ts +25 -0
  37. package/lib/types/protocol.d.ts +35 -0
  38. package/lib/types/routes.d.ts +7 -0
  39. package/lib/types/terminal.d.ts +25 -1
  40. package/lib/types/view-settings.d.ts +26 -0
  41. package/lib/{worlds-DXdP4SMn.js → worlds-B7gEDBzC.js} +13 -1
  42. package/package.json +36 -36
  43. package/src/client/CodeEditor.tsx +54 -2
  44. package/src/client/EditorPane.tsx +485 -107
  45. package/src/client/FloatingPlaceholder.tsx +34 -5
  46. package/src/client/RemoteEditorView.tsx +14 -11
  47. package/src/client/RemoteRoot.tsx +20 -125
  48. package/src/client/SettingsHosts.tsx +81 -3
  49. package/src/client/TerminalSnippets.tsx +357 -0
  50. package/src/client/TerminalView.tsx +50 -1
  51. package/src/client/XTerm.tsx +228 -58
  52. package/src/client/api.ts +7 -0
  53. package/src/client/auto-open-remote.ts +439 -0
  54. package/src/client/editor-capability.ts +42 -0
  55. package/src/client/i18n.ts +158 -6
  56. package/src/client/index.tsx +30 -6
  57. package/src/client/store.tsx +165 -13
  58. package/src/client/terminal-input.ts +44 -0
  59. package/src/client/terminal-snippets.ts +216 -0
  60. package/src/client/use-remote-chat-target.ts +1 -1
  61. package/src/client/view-settings.ts +99 -0
  62. package/src/client/vsc/breadcrumb.tsx +251 -0
  63. package/src/client/vsc/editor-caret.ts +30 -0
  64. package/src/client/vsc/editor-langs.ts +20 -0
  65. package/src/client/vsc/editor-settings.ts +146 -0
  66. package/src/client/vsc/editor-theme.ts +4 -5
  67. package/src/client/vsc/image-preview.tsx +110 -0
  68. package/src/client/vsc/kit.tsx +20 -1
  69. package/src/client/vsc/terminal-clipboard.ts +19 -0
  70. package/src/client/vsc/terminal-line.ts +101 -0
  71. package/src/client/vsc/terminal-links.ts +166 -0
  72. package/src/client/vsc/terminal-theme.ts +71 -0
  73. package/src/client/vsc/terminal-writer.ts +112 -0
  74. package/src/client/vsc/vsc.css +687 -48
  75. package/src/index.ts +6 -0
  76. package/src/paths.ts +13 -0
  77. package/src/pool.ts +99 -27
  78. package/src/protocol.ts +45 -0
  79. package/src/routes.ts +47 -0
  80. package/src/terminal.ts +160 -6
  81. package/src/view-settings.ts +133 -0
package/lib/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { C as ensurePrivateDir, S as dshHome, T as storePath, _ as MIN_TIMEOUT_MS, a as helperAvailability, b as require_lib, c as seedHelperCache, d as attachmentHeader, f as DEFAULT_GIT_TIMEOUT_MS, g as MAX_TIMEOUT_MS, h as DeadlineError, i as drainHostNotices, l as RemoteFiles, m as DEFAULT_TIMEOUTS, n as TombstonedError, o as probe, p as DEFAULT_READ_TIMEOUT_MS, s as pushPipeline, t as RemoteWorlds, u as WriteConflictError, v as clampExecTimeout, w as keysDir, x as aliasRoot, y as resolveTimeouts } from "./worlds-DXdP4SMn.js";
1
+ import { C as ensurePrivateDir, E as viewSettingsPath, S as dshHome, T as storePath, _ as MIN_TIMEOUT_MS, a as helperAvailability, b as require_lib, c as seedHelperCache, d as attachmentHeader, f as DEFAULT_GIT_TIMEOUT_MS, g as MAX_TIMEOUT_MS, h as DeadlineError, i as drainHostNotices, l as RemoteFiles, m as DEFAULT_TIMEOUTS, n as TombstonedError, o as probe, p as DEFAULT_READ_TIMEOUT_MS, s as pushPipeline, t as RemoteWorlds, u as WriteConflictError, v as clampExecTimeout, w as keysDir, x as aliasRoot, y as resolveTimeouts } from "./worlds-B7gEDBzC.js";
2
2
  import z from "@deepseek-ai/schemastery";
3
3
  import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, statSync, writeSync } from "node:fs";
4
4
  import { createHash, randomUUID } from "node:crypto";
@@ -365,6 +365,173 @@ var RemoteStore = class {
365
365
  }
366
366
  };
367
367
  //#endregion
368
+ //#region src/protocol.ts
369
+ /**
370
+ * Wire contract between the host half (routes.ts) and the browser half
371
+ * (client/api.ts). Pure types + path constants only — imported by both
372
+ * halves, bundled into each, no runtime identity to share.
373
+ */
374
+ /** API route table (all loopback-only). */
375
+ const REMOTE_API = {
376
+ hosts: "/api/dsh-remote/hosts",
377
+ test: "/api/dsh-remote/test",
378
+ /** Per-alias SSH connection health for the client's status indicator. */
379
+ status: "/api/dsh-remote/status",
380
+ keygen: "/api/dsh-remote/keygen",
381
+ exec: "/api/dsh-remote/exec",
382
+ /** Streaming exec (server-sent events) for the long network verbs. */
383
+ execStream: "/api/dsh-remote/exec-stream",
384
+ files: "/api/dsh-remote/files",
385
+ /** Streaming binary upload: raw request body, host and path in the query. */
386
+ upload: "/api/dsh-remote/upload",
387
+ /** Streaming binary download: raw response body, host and path in the query. */
388
+ download: "/api/dsh-remote/download",
389
+ /** Streaming directory download: a remote `tar -czf -` of the directory. */
390
+ downloadDir: "/api/dsh-remote/download-dir",
391
+ /** Streaming multi-selection download: one remote tar of repeated `path` params. */
392
+ downloadMany: "/api/dsh-remote/download-many",
393
+ workspaces: "/api/dsh-remote/workspaces",
394
+ deploy: "/api/dsh-remote/deploy",
395
+ importSshConfig: "/api/dsh-remote/import-ssh-config",
396
+ importDshSsh: "/api/dsh-remote/import-dsh-ssh",
397
+ terminal: "/api/dsh-remote/terminal",
398
+ terminalClose: "/api/dsh-remote/terminal-close",
399
+ routing: "/api/dsh-remote/routing",
400
+ /** Client view preferences (auto-open the remote page + its width share). */
401
+ viewSettings: "/api/dsh-remote/view-settings",
402
+ /** Current working directory of one live session (click resolution helper). */
403
+ sessionCwd: "/api/dsh-remote/session-cwd",
404
+ /** What one live session changed on its remote host (the review panel). */
405
+ changes: "/api/dsh-remote/changes",
406
+ /** Local TCP forwards (`ssh -L` semantics) for the port panel. */
407
+ forwards: "/api/dsh-remote/forwards",
408
+ /** Remote listening TCP sockets for the port panel (one bounded probe). */
409
+ listenPorts: "/api/dsh-remote/listen-ports",
410
+ /** Live system metrics for the monitor panel (one bounded probe per host). */
411
+ metrics: "/api/dsh-remote/metrics"
412
+ };
413
+ /** Suggested/attachment file name for one multi-selection archive. */
414
+ function selectionDownloadName(count) {
415
+ return `selection-${count}.tar.gz`;
416
+ }
417
+ /** The answers a fresh profile gets before anything is saved. */
418
+ const REMOTE_VIEW_SETTINGS_DEFAULTS = {
419
+ autoOpenRemoteWorkspace: false,
420
+ remoteWorkspaceWidthRatio: .45
421
+ };
422
+ /** Narrowest useful share of the frame width (a smaller panel hides its tools). */
423
+ const REMOTE_VIEW_WIDTH_MIN = .2;
424
+ /** Widest share the column itself allows (DSH caps the column at 70 %). */
425
+ const REMOTE_VIEW_WIDTH_MAX = .7;
426
+ /**
427
+ * Clamp one width share into the allowed band.
428
+ *
429
+ * Pure and shared by both halves: the Host validates what it stores, and the
430
+ * browser clamps what it applies (an older Host may omit or round the field).
431
+ */
432
+ function clampViewWidthRatio(value) {
433
+ return Math.min(REMOTE_VIEW_WIDTH_MAX, Math.max(REMOTE_VIEW_WIDTH_MIN, value));
434
+ }
435
+ //#endregion
436
+ //#region src/view-settings.ts
437
+ /**
438
+ * Durable store for the two client view preferences: `$DSH_HOME/dsh-remote-view.json`.
439
+ *
440
+ * Why a file of its own (and not the routing store, nor a browser-local key):
441
+ * - the settings describe how the PLUGIN behaves in the right panel, and they
442
+ * must apply to every Web/Desktop window of this profile — the browser's
443
+ * localStorage is per origin/per machine and would drift;
444
+ * - they are GUI behaviour, not routing facts: keeping them out of
445
+ * `dsh-remote.json` means a hand-edited preference can never break the store
446
+ * the routers read on every remote operation.
447
+ *
448
+ * Shape of the file (`version: 1`), written atomically (tmp + rename, 0600):
449
+ *
450
+ * { "version": 1, "autoOpenRemoteWorkspace": false, "remoteWorkspaceWidthRatio": 0.45 }
451
+ *
452
+ * Field-by-field validation with defaults on READ (so a missing, older or
453
+ * half-edited field costs only that field), and a flat PATCH on write (unknown
454
+ * keys are ignored — the browser is the only writer, and a stale tab must not be
455
+ * able to corrupt the file with an extra key).
456
+ */
457
+ /** Defaults as a fresh copy (callers may own the object). */
458
+ function defaults() {
459
+ return { ...REMOTE_VIEW_SETTINGS_DEFAULTS };
460
+ }
461
+ /** A finite width share, clamped into the allowed band; anything else is a miss. */
462
+ function readWidthRatio(value) {
463
+ if (typeof value !== "number" || !Number.isFinite(value)) return void 0;
464
+ return clampViewWidthRatio(value);
465
+ }
466
+ var RemoteViewSettingsStore = class {
467
+ file;
468
+ constructor(file = viewSettingsPath()) {
469
+ this.file = file;
470
+ }
471
+ /**
472
+ * The current preferences (a missing file answers the defaults).
473
+ *
474
+ * Read from disk on every call: the file is tiny, GET hands it to a page load,
475
+ * and two processes sharing `$DSH_HOME` (desktop + `dsh web`) must see each
476
+ * other's edit without a restart.
477
+ */
478
+ get() {
479
+ if (!existsSync(this.file)) return defaults();
480
+ let parsed;
481
+ try {
482
+ parsed = JSON.parse(readFileSync(this.file, "utf8"));
483
+ } catch (error) {
484
+ throw new Error(`cannot parse ${this.file}: ${error instanceof Error ? error.message : String(error)}`);
485
+ }
486
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error(`${this.file}: root must be an object`);
487
+ const doc = parsed;
488
+ if (doc.version !== void 0 && doc.version !== 1) throw new Error(`${this.file}: unsupported version ${String(doc.version)}`);
489
+ return {
490
+ autoOpenRemoteWorkspace: typeof doc.autoOpenRemoteWorkspace === "boolean" ? doc.autoOpenRemoteWorkspace : REMOTE_VIEW_SETTINGS_DEFAULTS.autoOpenRemoteWorkspace,
491
+ remoteWorkspaceWidthRatio: readWidthRatio(doc.remoteWorkspaceWidthRatio) ?? REMOTE_VIEW_SETTINGS_DEFAULTS.remoteWorkspaceWidthRatio
492
+ };
493
+ }
494
+ /**
495
+ * Merge one flat patch into the stored preferences and persist the result.
496
+ *
497
+ * Unknown keys are ignored and an unusable value of a known field keeps the
498
+ * stored one: the browser's controls only ever send valid values, so a bad
499
+ * field means a stale client, not something the user should be told about.
500
+ *
501
+ * @param patch - a partial document straight from the POST body.
502
+ * @returns the settings as stored.
503
+ */
504
+ patch(patch) {
505
+ const current = this.get();
506
+ const next = {
507
+ autoOpenRemoteWorkspace: typeof patch.autoOpenRemoteWorkspace === "boolean" ? patch.autoOpenRemoteWorkspace : current.autoOpenRemoteWorkspace,
508
+ remoteWorkspaceWidthRatio: readWidthRatio(patch.remoteWorkspaceWidthRatio) ?? current.remoteWorkspaceWidthRatio
509
+ };
510
+ this.save(next);
511
+ return next;
512
+ }
513
+ /** Write one document atomically: a crash never leaves a half-written file. */
514
+ save(settings) {
515
+ const doc = {
516
+ version: 1,
517
+ ...settings
518
+ };
519
+ const payload = `${JSON.stringify(doc, null, 2)}\n`;
520
+ mkdirSync(dirname(this.file), { recursive: true });
521
+ const tmp = `${this.file}.${process.pid}.tmp`;
522
+ const fd = openSync(tmp, "w", 384);
523
+ try {
524
+ writeSync(fd, payload);
525
+ try {
526
+ fsyncSync(fd);
527
+ } catch {}
528
+ } finally {
529
+ closeSync(fd);
530
+ }
531
+ renameSync(tmp, this.file);
532
+ }
533
+ };
534
+ //#endregion
368
535
  //#region src/pool.ts
369
536
  /**
370
537
  * Persistent ssh2 connection pool: one long-lived connection per host alias,
@@ -490,6 +657,24 @@ function isConnectionFailure(error) {
490
657
  var RemotePool = class {
491
658
  store;
492
659
  conns = /* @__PURE__ */ new Map();
660
+ /**
661
+ * Dedicated connections for PTY shells (one per alias).
662
+ *
663
+ * Why a SECOND connection instead of a channel on the shared one: ssh2
664
+ * multiplexes channels over ONE TCP connection, and SSH has no per-channel
665
+ * priority or flow control. A large SFTP transfer / git output on that
666
+ * connection therefore delays everything else on it — including the echo of a
667
+ * keystroke — which is exactly the "typing stutters when something else is
668
+ * moving data" report. A terminal gets its own connection, so its bytes never
669
+ * queue behind browse/exec traffic, and shells stop consuming the shared
670
+ * connection's channel budget as well.
671
+ *
672
+ * Cost: one extra SSH handshake per alias the first time a terminal opens,
673
+ * plus one held TCP connection per host with a terminal. `shell()` falls back
674
+ * to the shared connection if this one cannot be established at all, so a host
675
+ * that refuses extra connections still gets a working terminal.
676
+ */
677
+ shellConns = /* @__PURE__ */ new Map();
493
678
  /** TOFU fingerprints observed this process (alias -> sha256). */
494
679
  hostKeys = /* @__PURE__ */ new Map();
495
680
  /** Per-alias `setsid --wait` capability, probed once (see supportsSetsid). */
@@ -506,18 +691,13 @@ var RemotePool = class {
506
691
  /** Drop one pooled connection (call after host update/delete). */
507
692
  drop(alias) {
508
693
  this.evictBrowse(alias);
509
- const pooled = this.conns.get(alias);
510
694
  this.setsidProbes.delete(alias);
511
- if (pooled === void 0) return;
512
- this.conns.delete(alias);
513
- if (pooled.timer !== void 0) clearTimeout(pooled.timer);
514
- try {
515
- pooled.conn.end();
516
- } catch {}
695
+ this.evictFrom(this.conns, alias);
696
+ this.evictFrom(this.shellConns, alias);
517
697
  }
518
698
  /** Close every pooled connection. */
519
699
  dispose() {
520
- for (const alias of [...this.conns.keys()]) this.drop(alias);
700
+ for (const alias of /* @__PURE__ */ new Set([...this.conns.keys(), ...this.shellConns.keys()])) this.drop(alias);
521
701
  }
522
702
  /**
523
703
  * Forget one alias's connection HEALTH (host edited/removed), not just its
@@ -548,7 +728,7 @@ var RemotePool = class {
548
728
  return {
549
729
  alias,
550
730
  state: entry?.state ?? "idle",
551
- open: pooled !== void 0 && pooled.connecting === void 0,
731
+ open: pooled !== void 0 && pooled.connecting === void 0 || this.shellConns.get(alias)?.connecting === void 0 && this.shellConns.has(alias),
552
732
  ...entry?.okAt === void 0 ? {} : { okAt: entry.okAt },
553
733
  ...entry?.errorAt === void 0 ? {} : { errorAt: entry.errorAt },
554
734
  ...entry?.error === void 0 ? {} : { error: entry.error }
@@ -880,8 +1060,23 @@ var RemotePool = class {
880
1060
  }
881
1061
  /** Open an interactive PTY shell. The caller owns the channel lifecycle. */
882
1062
  async shell(alias, opts = {}) {
883
- const conn = await this.acquire(alias);
884
- this.hold(alias);
1063
+ /**
1064
+ * Prefer the DEDICATED PTY connection so terminal bytes never queue behind
1065
+ * SFTP/git/exec traffic on the shared one (SSH has no channel priority).
1066
+ * A host that refuses the extra connection still gets a terminal: the fallback
1067
+ * is the shared connection, exactly the old behaviour.
1068
+ */
1069
+ let conn;
1070
+ let dedicated = true;
1071
+ try {
1072
+ conn = await this.acquireShell(alias);
1073
+ this.holdIn(this.shellConns, alias);
1074
+ } catch (error) {
1075
+ dedicated = false;
1076
+ conn = await this.acquire(alias);
1077
+ this.hold(alias);
1078
+ if (!(error instanceof Error) || !isConnectionFailure(error)) console.warn("[dsh-remote-vs] dedicated PTY connection failed; using the shared one:", error);
1079
+ }
885
1080
  try {
886
1081
  const channel = await new Promise((resolve, reject) => {
887
1082
  conn.shell({
@@ -893,11 +1088,15 @@ var RemotePool = class {
893
1088
  else resolve(stream);
894
1089
  });
895
1090
  });
896
- channel.once("close", () => this.release(alias));
1091
+ channel.once("close", () => {
1092
+ if (dedicated) this.releaseIn(this.shellConns, alias);
1093
+ else this.release(alias);
1094
+ });
897
1095
  this.markOk(alias);
898
1096
  return channel;
899
1097
  } catch (error) {
900
- this.release(alias);
1098
+ if (dedicated) this.releaseIn(this.shellConns, alias);
1099
+ else this.release(alias);
901
1100
  if (isConnectionFailure(error)) this.markError(alias, error);
902
1101
  throw error;
903
1102
  }
@@ -1437,7 +1636,10 @@ var RemotePool = class {
1437
1636
  }
1438
1637
  /** Hold the connection against idle eviction (balanced by release). */
1439
1638
  hold(alias) {
1440
- const pooled = this.conns.get(alias);
1639
+ this.holdIn(this.conns, alias);
1640
+ }
1641
+ holdIn(map, alias) {
1642
+ const pooled = map.get(alias);
1441
1643
  if (pooled === void 0) return;
1442
1644
  pooled.held += 1;
1443
1645
  pooled.lastUse = Date.now();
@@ -1447,17 +1649,27 @@ var RemotePool = class {
1447
1649
  }
1448
1650
  }
1449
1651
  release(alias) {
1450
- const pooled = this.conns.get(alias);
1652
+ this.releaseIn(this.conns, alias);
1653
+ }
1654
+ releaseIn(map, alias) {
1655
+ const pooled = map.get(alias);
1451
1656
  if (pooled === void 0) return;
1452
1657
  if (pooled.held > 0) pooled.held -= 1;
1453
1658
  pooled.lastUse = Date.now();
1454
1659
  if (pooled.held > 0) return;
1455
1660
  if (pooled.timer !== void 0) clearTimeout(pooled.timer);
1456
- pooled.timer = setTimeout(() => this.drop(alias), IDLE_MS);
1661
+ pooled.timer = setTimeout(() => this.evictFrom(map, alias), IDLE_MS);
1457
1662
  if (typeof pooled.timer === "object" && "unref" in pooled.timer) pooled.timer.unref();
1458
1663
  }
1459
1664
  async acquire(alias) {
1460
- const pooled = this.conns.get(alias);
1665
+ return this.acquireIn(this.conns, alias);
1666
+ }
1667
+ /** `acquire` for the dedicated PTY connection map. */
1668
+ async acquireShell(alias) {
1669
+ return this.acquireIn(this.shellConns, alias);
1670
+ }
1671
+ async acquireIn(map, alias) {
1672
+ const pooled = map.get(alias);
1461
1673
  if (pooled !== void 0 && pooled.connecting !== void 0) return pooled.connecting;
1462
1674
  if (pooled !== void 0) {
1463
1675
  pooled.lastUse = Date.now();
@@ -1470,7 +1682,7 @@ var RemotePool = class {
1470
1682
  connecting: void 0,
1471
1683
  held: 0
1472
1684
  };
1473
- this.conns.set(alias, entry);
1685
+ map.set(alias, entry);
1474
1686
  /**
1475
1687
  * The entry object IS the ownership token: `drop()` deletes it and a later
1476
1688
  * `acquire()` creates a NEW one, so comparing identity answers "does this
@@ -1483,7 +1695,7 @@ var RemotePool = class {
1483
1695
  * failure check, a failed OLD dial deletes the NEW entry by alias.
1484
1696
  */
1485
1697
  entry.connecting = this.dial(alias).then((conn) => {
1486
- if (this.conns.get(alias) !== entry) {
1698
+ if (map.get(alias) !== entry) {
1487
1699
  try {
1488
1700
  conn.end();
1489
1701
  } catch {}
@@ -1493,24 +1705,34 @@ var RemotePool = class {
1493
1705
  entry.connecting = void 0;
1494
1706
  this.markOk(alias);
1495
1707
  conn.on("close", () => {
1496
- if (this.conns.get(alias) !== entry) return;
1708
+ if (map.get(alias) !== entry) return;
1497
1709
  this.markError(alias, /* @__PURE__ */ new Error("connection closed"));
1498
- this.drop(alias);
1710
+ this.evictFrom(map, alias);
1499
1711
  });
1500
1712
  conn.on("error", (error) => {
1501
- if (this.conns.get(alias) !== entry) return;
1713
+ if (map.get(alias) !== entry) return;
1502
1714
  this.markError(alias, error);
1503
- this.drop(alias);
1715
+ this.evictFrom(map, alias);
1504
1716
  });
1505
- this.release(alias);
1717
+ this.releaseIn(map, alias);
1506
1718
  return conn;
1507
1719
  }, (error) => {
1508
- if (this.conns.get(alias) === entry) this.conns.delete(alias);
1720
+ if (map.get(alias) === entry) map.delete(alias);
1509
1721
  this.markError(alias, error);
1510
1722
  throw error;
1511
1723
  });
1512
1724
  return entry.connecting;
1513
1725
  }
1726
+ /** Evict ONE alias from ONE map (host removal drops both maps explicitly). */
1727
+ evictFrom(map, alias) {
1728
+ const pooled = map.get(alias);
1729
+ if (pooled === void 0) return;
1730
+ map.delete(alias);
1731
+ if (pooled.timer !== void 0) clearTimeout(pooled.timer);
1732
+ try {
1733
+ pooled.conn.end();
1734
+ } catch {}
1735
+ }
1514
1736
  /**
1515
1737
  * The ssh2 client factory.
1516
1738
  *
@@ -2158,54 +2380,6 @@ function isLoopbackRequest(request) {
2158
2380
  }
2159
2381
  }
2160
2382
  //#endregion
2161
- //#region src/protocol.ts
2162
- /**
2163
- * Wire contract between the host half (routes.ts) and the browser half
2164
- * (client/api.ts). Pure types + path constants only — imported by both
2165
- * halves, bundled into each, no runtime identity to share.
2166
- */
2167
- /** API route table (all loopback-only). */
2168
- const REMOTE_API = {
2169
- hosts: "/api/dsh-remote/hosts",
2170
- test: "/api/dsh-remote/test",
2171
- /** Per-alias SSH connection health for the client's status indicator. */
2172
- status: "/api/dsh-remote/status",
2173
- keygen: "/api/dsh-remote/keygen",
2174
- exec: "/api/dsh-remote/exec",
2175
- /** Streaming exec (server-sent events) for the long network verbs. */
2176
- execStream: "/api/dsh-remote/exec-stream",
2177
- files: "/api/dsh-remote/files",
2178
- /** Streaming binary upload: raw request body, host and path in the query. */
2179
- upload: "/api/dsh-remote/upload",
2180
- /** Streaming binary download: raw response body, host and path in the query. */
2181
- download: "/api/dsh-remote/download",
2182
- /** Streaming directory download: a remote `tar -czf -` of the directory. */
2183
- downloadDir: "/api/dsh-remote/download-dir",
2184
- /** Streaming multi-selection download: one remote tar of repeated `path` params. */
2185
- downloadMany: "/api/dsh-remote/download-many",
2186
- workspaces: "/api/dsh-remote/workspaces",
2187
- deploy: "/api/dsh-remote/deploy",
2188
- importSshConfig: "/api/dsh-remote/import-ssh-config",
2189
- importDshSsh: "/api/dsh-remote/import-dsh-ssh",
2190
- terminal: "/api/dsh-remote/terminal",
2191
- terminalClose: "/api/dsh-remote/terminal-close",
2192
- routing: "/api/dsh-remote/routing",
2193
- /** Current working directory of one live session (click resolution helper). */
2194
- sessionCwd: "/api/dsh-remote/session-cwd",
2195
- /** What one live session changed on its remote host (the review panel). */
2196
- changes: "/api/dsh-remote/changes",
2197
- /** Local TCP forwards (`ssh -L` semantics) for the port panel. */
2198
- forwards: "/api/dsh-remote/forwards",
2199
- /** Remote listening TCP sockets for the port panel (one bounded probe). */
2200
- listenPorts: "/api/dsh-remote/listen-ports",
2201
- /** Live system metrics for the monitor panel (one bounded probe per host). */
2202
- metrics: "/api/dsh-remote/metrics"
2203
- };
2204
- /** Suggested/attachment file name for one multi-selection archive. */
2205
- function selectionDownloadName(count) {
2206
- return `selection-${count}.tar.gz`;
2207
- }
2208
- //#endregion
2209
2383
  //#region src/git-format.ts
2210
2384
  /** Wrap a value for POSIX sh single-quote context. */
2211
2385
  function shQuote(value) {
@@ -2616,12 +2790,44 @@ const EMPTY_SOCKET_TTL_MS = 10 * 6e4;
2616
2790
  * The retained ceiling is therefore this mark plus ssh2's window (2 MiB) plus
2617
2791
  * whatever is in flight — bounded, but not exactly 4 MiB.
2618
2792
  *
2793
+ * The mark is RESPONSIVENESS, not just memory: everything already handed to a
2794
+ * socket has to be parsed and painted by the browser before a later keystroke's
2795
+ * echo can appear, so a large mark means "type during a huge dump and wait
2796
+ * seconds". 2 MiB still absorbs a burst comfortably (a keystroke is bytes) while
2797
+ * keeping the worst-case echo delay down; ssh2's own 2 MiB window is the part we
2798
+ * cannot shrink from here.
2799
+ *
2619
2800
  * The counter is per session, not per socket: one lagging socket pauses the
2620
2801
  * channel for every socket attached to that shell. That is deliberate — the
2621
2802
  * alternative is letting the slowest consumer grow the host process.
2622
2803
  */
2623
- const OUT_HIGH_WATER = 4 * 1024 * 1024;
2624
- const OUT_LOW_WATER = 1 * 1024 * 1024;
2804
+ const OUT_HIGH_WATER = 2 * 1024 * 1024;
2805
+ const OUT_LOW_WATER = 512 * 1024;
2806
+ /** Default window for coalescing output frames (0 = one frame per chunk). */
2807
+ const OUT_COALESCE_MS = 8;
2808
+ /**
2809
+ * Flush immediately past this much buffered text (measured in UTF-16 code
2810
+ * units, i.e. `String.length`): a producer faster than the window must not turn
2811
+ * into an unbounded string copy (the channel backpressure bounds the bytes
2812
+ * handed to the SOCKETS, not this buffer).
2813
+ *
2814
+ * Code units rather than bytes on purpose: converting to a byte count would
2815
+ * copy the whole buffer on every chunk just to compare a threshold. CJK/emoji
2816
+ * output therefore flushes at up to ~3x this many bytes, which is still far
2817
+ * below the 1 MiB client-frame cap this path never approaches (it is the
2818
+ * client→host direction).
2819
+ */
2820
+ const OUT_COALESCE_CHARS = 64 * 1024;
2821
+ /**
2822
+ * How long the output must have been quiet for the NEXT chunk to be sent at once.
2823
+ *
2824
+ * A terminal echoes what the user types. Holding that echo for the coalescing
2825
+ * window is invisible at 8 ms — but under load the window itself is a timer in
2826
+ * an event loop shared with the agent, and the delay adds up. After a quiet
2827
+ * period the chunk is therefore flushed synchronously; only a running stream
2828
+ * (where `lastFlushAt` is fresh) is batched.
2829
+ */
2830
+ const OUT_ECHO_IDLE_MS = 24;
2625
2831
  /**
2626
2832
  * The largest client frame accepted, in bytes.
2627
2833
  *
@@ -2642,9 +2848,15 @@ const TERMINAL_MAX_FRAME_BYTES = 1024 * 1024;
2642
2848
  const WS_OPEN = 1;
2643
2849
  var TerminalSessionRegistry = class {
2644
2850
  pool;
2851
+ options;
2645
2852
  sessions = /* @__PURE__ */ new Map();
2646
- constructor(pool) {
2853
+ constructor(pool, options = {}) {
2647
2854
  this.pool = pool;
2855
+ this.options = options;
2856
+ }
2857
+ /** The window this registry coalesces within (`0` = every chunk is a frame). */
2858
+ get coalesceMs() {
2859
+ return this.options.coalesceMs ?? OUT_COALESCE_MS;
2648
2860
  }
2649
2861
  /** Open a shell and attach the first socket. */
2650
2862
  async open(ws, alias, cols, rows) {
@@ -2674,6 +2886,10 @@ var TerminalSessionRegistry = class {
2674
2886
  sockets: /* @__PURE__ */ new Set(),
2675
2887
  pending: 0,
2676
2888
  paused: false,
2889
+ outBuffer: "",
2890
+ outTimer: void 0,
2891
+ lastFlushAt: 0,
2892
+ outstanding: /* @__PURE__ */ new Map(),
2677
2893
  reap: void 0,
2678
2894
  outDecoder: new StringDecoder("utf8"),
2679
2895
  errDecoder: new StringDecoder("utf8")
@@ -2681,25 +2897,17 @@ var TerminalSessionRegistry = class {
2681
2897
  this.sessions.set(id, session);
2682
2898
  channel.on("data", (chunk) => {
2683
2899
  const text = session.outDecoder.write(chunk);
2684
- if (text !== "") this.broadcast(session, {
2685
- t: "out",
2686
- d: text
2687
- });
2900
+ if (text !== "") this.queueOut(session, text);
2688
2901
  });
2689
2902
  channel.stderr.on("data", (chunk) => {
2690
2903
  const text = session.errDecoder.write(chunk);
2691
- if (text !== "") this.broadcast(session, {
2692
- t: "out",
2693
- d: text
2694
- });
2904
+ if (text !== "") this.queueOut(session, text);
2695
2905
  });
2696
2906
  channel.on("close", (code) => {
2697
2907
  session.alive = false;
2698
2908
  session.exitCode = code;
2699
- for (const tail of [session.outDecoder.end(), session.errDecoder.end()]) if (tail !== "") this.broadcast(session, {
2700
- t: "out",
2701
- d: tail
2702
- });
2909
+ for (const tail of [session.outDecoder.end(), session.errDecoder.end()]) if (tail !== "") this.queueOut(session, tail);
2910
+ this.flushOut(session);
2703
2911
  this.broadcast(session, {
2704
2912
  t: "exit",
2705
2913
  code
@@ -2733,6 +2941,7 @@ var TerminalSessionRegistry = class {
2733
2941
  const session = this.sessions.get(id);
2734
2942
  if (session === void 0 || !session.alive) return false;
2735
2943
  this.hookSocket(session, ws);
2944
+ this.flushOut(session);
2736
2945
  this.send(ws, {
2737
2946
  t: "ready",
2738
2947
  id
@@ -2745,6 +2954,7 @@ var TerminalSessionRegistry = class {
2745
2954
  if (session === void 0) return false;
2746
2955
  this.sessions.delete(id);
2747
2956
  this.cancelReap(session);
2957
+ this.flushOut(session);
2748
2958
  try {
2749
2959
  session.channel.close();
2750
2960
  } catch {}
@@ -2752,6 +2962,8 @@ var TerminalSessionRegistry = class {
2752
2962
  socket.close(1e3);
2753
2963
  } catch {}
2754
2964
  session.sockets.clear();
2965
+ session.outstanding.clear();
2966
+ session.pending = 0;
2755
2967
  return true;
2756
2968
  }
2757
2969
  /** Close every session (plugin unload). */
@@ -2790,9 +3002,17 @@ var TerminalSessionRegistry = class {
2790
3002
  } catch {}
2791
3003
  });
2792
3004
  const detach = () => {
3005
+ this.flushOut(session);
3006
+ const unsettled = session.outstanding.get(ws);
3007
+ if (unsettled !== void 0) {
3008
+ session.outstanding.delete(ws);
3009
+ session.pending = Math.max(0, session.pending - unsettled);
3010
+ if (session.pending <= OUT_LOW_WATER) this.setPaused(session, false);
3011
+ }
2793
3012
  session.sockets.delete(ws);
2794
3013
  if (session.sockets.size > 0) return;
2795
3014
  session.pending = 0;
3015
+ session.outstanding.clear();
2796
3016
  this.setPaused(session, false);
2797
3017
  this.armReap(session);
2798
3018
  };
@@ -2825,6 +3045,45 @@ var TerminalSessionRegistry = class {
2825
3045
  clearTimeout(session.reap);
2826
3046
  session.reap = void 0;
2827
3047
  }
3048
+ /**
3049
+ * Queue one output chunk and schedule the coalesced frame.
3050
+ *
3051
+ * `coalesceMs === 0` broadcasts immediately (the checks rely on that
3052
+ * synchrony). A chunk that arrives after an idle gap is also sent at once —
3053
+ * that is the interactive echo path (a keystroke must not wait for the
3054
+ * window) — while a stream that keeps producing coalesces.
3055
+ */
3056
+ queueOut(session, text) {
3057
+ if (text === "") return;
3058
+ const idle = Date.now() - session.lastFlushAt >= OUT_ECHO_IDLE_MS;
3059
+ session.outBuffer += text;
3060
+ if (session.outBuffer.length >= OUT_COALESCE_CHARS || this.coalesceMs <= 0 || idle) {
3061
+ this.flushOut(session);
3062
+ return;
3063
+ }
3064
+ if (session.outTimer !== void 0) return;
3065
+ const timer = setTimeout(() => {
3066
+ session.outTimer = void 0;
3067
+ this.flushOut(session);
3068
+ }, this.coalesceMs);
3069
+ timer.unref?.();
3070
+ session.outTimer = timer;
3071
+ }
3072
+ /** Send the buffered output as ONE `out` frame (no-op when empty). */
3073
+ flushOut(session) {
3074
+ if (session.outTimer !== void 0) {
3075
+ clearTimeout(session.outTimer);
3076
+ session.outTimer = void 0;
3077
+ }
3078
+ if (session.outBuffer === "") return;
3079
+ const text = session.outBuffer;
3080
+ session.outBuffer = "";
3081
+ session.lastFlushAt = Date.now();
3082
+ this.broadcast(session, {
3083
+ t: "out",
3084
+ d: text
3085
+ });
3086
+ }
2828
3087
  setPaused(session, paused) {
2829
3088
  if (session.paused === paused) return;
2830
3089
  session.paused = paused;
@@ -2846,10 +3105,16 @@ var TerminalSessionRegistry = class {
2846
3105
  const done = () => {
2847
3106
  if (settled) return;
2848
3107
  settled = true;
3108
+ const left = session.outstanding.get(socket);
3109
+ if (left === void 0) return;
3110
+ const remaining = Math.max(0, left - size);
3111
+ if (remaining === 0) session.outstanding.delete(socket);
3112
+ else session.outstanding.set(socket, remaining);
2849
3113
  session.pending = Math.max(0, session.pending - size);
2850
3114
  if (session.pending <= OUT_LOW_WATER) this.setPaused(session, false);
2851
3115
  };
2852
3116
  session.pending += size;
3117
+ session.outstanding.set(socket, (session.outstanding.get(socket) ?? 0) + size);
2853
3118
  try {
2854
3119
  socket.send(text, done);
2855
3120
  } catch {
@@ -3557,6 +3822,7 @@ function makeRoutes(deps) {
3557
3822
  const terminalSessions = new TerminalSessionRegistry(pool);
3558
3823
  const monitor = new HostMonitor(pool);
3559
3824
  const forwards = deps.forwards;
3825
+ const viewSettings = deps.viewSettings ?? new RemoteViewSettingsStore();
3560
3826
  /**
3561
3827
  * Stream one remote `tar -czf -` command into a `.tar.gz` download response.
3562
3828
  *
@@ -4378,6 +4644,36 @@ function makeRoutes(deps) {
4378
4644
  }
4379
4645
  }
4380
4646
  },
4647
+ {
4648
+ kind: "exact",
4649
+ path: REMOTE_API.viewSettings,
4650
+ handler: async (req, res) => {
4651
+ if (!isLoopbackRequest(req)) {
4652
+ writeJson(res, 403, { error: "forbidden: loopback-only" });
4653
+ return;
4654
+ }
4655
+ const method = req.method ?? "GET";
4656
+ if (method === "GET") {
4657
+ try {
4658
+ writeJson(res, 200, { settings: viewSettings.get() });
4659
+ } catch (error) {
4660
+ writeRouteError(res, error);
4661
+ }
4662
+ return;
4663
+ }
4664
+ if (method !== "POST") {
4665
+ writeJson(res, 405, { error: `method not allowed: ${method}` });
4666
+ return;
4667
+ }
4668
+ const read = await readBodyOrError(req, res, { objectOnly: true });
4669
+ if (!read.ok) return;
4670
+ try {
4671
+ writeJson(res, 200, { settings: viewSettings.patch(read.body ?? {}) });
4672
+ } catch (error) {
4673
+ writeRouteError(res, error);
4674
+ }
4675
+ }
4676
+ },
4381
4677
  {
4382
4678
  kind: "exact",
4383
4679
  path: REMOTE_API.deploy,
@@ -6878,6 +7174,7 @@ function workspaceMappingText(worlds, store, cwd) {
6878
7174
  }
6879
7175
  function apply(ctx, config) {
6880
7176
  const store = new RemoteStore();
7177
+ const viewSettings = new RemoteViewSettingsStore();
6881
7178
  const pool = new RemotePool(store);
6882
7179
  const worlds = new RemoteWorlds(ctx, {
6883
7180
  store,
@@ -7013,7 +7310,8 @@ function apply(ctx, config) {
7013
7310
  ctx,
7014
7311
  timeouts: resolveTimeoutsNow,
7015
7312
  changes,
7016
- forwards
7313
+ forwards,
7314
+ viewSettings
7017
7315
  });
7018
7316
  /**
7019
7317
  * PTY sessions own their own lifetime, separate from route registration.