dsh-remote-vs 0.11.0 → 0.12.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.
@@ -16879,6 +16879,17 @@ const LIST_ENTRY_CAP = 2e4;
16879
16879
  /** Largest single upload accepted (matches the client-side planner cap). */
16880
16880
  const UPLOAD_MAX_BYTES = 2 * 1024 * 1024 * 1024;
16881
16881
  /**
16882
+ * How long one download stream may make no progress before it is failed.
16883
+ *
16884
+ * A download has no wall-clock budget for the same reason an upload does not: a
16885
+ * big file on a slow link is healthy for minutes. What must never happen is a
16886
+ * silently dead stream pinning the SFTP session (and its channel slot) forever,
16887
+ * so progress is the bound — any chunk resets this clock.
16888
+ */
16889
+ const DOWNLOAD_IDLE_MS = 6e4;
16890
+ /** Chunk size for one download stream (one SFTP read at a time). */
16891
+ const DOWNLOAD_CHUNK_BYTES = 256 * 1024;
16892
+ /**
16882
16893
  * Cap for both per-path memory sets below (levels confirmed to exist, listings
16883
16894
  * already reported as truncated). Each only ever saves round trips or a repeat
16884
16895
  * log line, so a small window is enough and a miss costs nothing but the work
@@ -16899,6 +16910,18 @@ function remotePath(path) {
16899
16910
  if (!normalized.startsWith("/")) throw new Error("remote path must be absolute");
16900
16911
  return normalized;
16901
16912
  }
16913
+ /**
16914
+ * `Content-Disposition` for one attachment (RFC 6266 + RFC 5987).
16915
+ *
16916
+ * Receivers prefer `filename*` when both forms are present (RFC 6266 §4.3),
16917
+ * which is why a non-ASCII remote name survives the round trip; the quoted
16918
+ * ASCII copy is the fallback for clients that do not understand the extended
16919
+ * form. Quotes and backslashes are stripped from that fallback so they cannot
16920
+ * break the header.
16921
+ */
16922
+ function attachmentHeader(fileName) {
16923
+ return `attachment; filename="${fileName.replace(/[^\u0020-\u007e]/g, "_").replace(/["\\]/g, "_")}"; filename*=UTF-8''${encodeURIComponent(fileName).replace(/['()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`)}`;
16924
+ }
16902
16925
  var RemoteFiles = class {
16903
16926
  pool;
16904
16927
  /**
@@ -17023,6 +17046,103 @@ var RemoteFiles = class {
17023
17046
  }
17024
17047
  });
17025
17048
  }
17049
+ /**
17050
+ * Stream one remote file into an HTTP response (download to the local machine).
17051
+ *
17052
+ * Streaming, not `read()`: `read()` caps at 8 MiB because it answers a JSON
17053
+ * editor read, while a download is whatever the user pointed at — a log, a
17054
+ * binary, an artifact. The file is opened through one SFTP handle before the
17055
+ * headers are written: symlinks are followed (lstat's size is the link
17056
+ * target's string length, not the file's), directories are refused, and the
17057
+ * content length comes from the same handle the body is read through. The
17058
+ * session has no wall-clock deadline (see `DOWNLOAD_IDLE_MS`); the caller's
17059
+ * response close and stream errors are both handled, so a cancelled download
17060
+ * never leaves the SFTP session or its channel slot pinned.
17061
+ *
17062
+ * @param alias - host alias.
17063
+ * @param file - absolute remote source path.
17064
+ * @param res - HTTP response to write the file into.
17065
+ */
17066
+ async download(alias, file, res) {
17067
+ const path = remotePath(file);
17068
+ await this.pool.withSftp(alias, async (sftp) => {
17069
+ if (isDir((await lstatAsync(sftp, path).catch(async (error) => {
17070
+ throw await explainSftpFailure(sftp, path, "file", error) ?? error;
17071
+ })).mode)) throw new Error(`not a file: ${path} is a directory`);
17072
+ const handle = await openAsync(sftp, path).catch(async (error) => {
17073
+ throw await explainFollowFailure(sftp, path, error) ?? error;
17074
+ });
17075
+ let streamed = false;
17076
+ try {
17077
+ const attrs = await fstatAsync(sftp, handle);
17078
+ if (isDir(attrs.mode)) throw new Error(`not a file: ${path} is a directory`);
17079
+ if (res.destroyed) return;
17080
+ res.writeHead(200, {
17081
+ "content-type": "application/octet-stream",
17082
+ "content-length": String(attrs.size),
17083
+ "content-disposition": attachmentHeader(posix.basename(path)),
17084
+ "cache-control": "no-store",
17085
+ "x-content-type-options": "nosniff"
17086
+ });
17087
+ if (attrs.size <= 0) {
17088
+ res.end();
17089
+ return;
17090
+ }
17091
+ const stream = sftp.createReadStream(path, {
17092
+ handle,
17093
+ start: 0,
17094
+ end: attrs.size - 1,
17095
+ highWaterMark: DOWNLOAD_CHUNK_BYTES
17096
+ });
17097
+ streamed = true;
17098
+ await new Promise((resolve, reject) => {
17099
+ let settled = false;
17100
+ let idle;
17101
+ const finish = (error) => {
17102
+ if (settled) return;
17103
+ settled = true;
17104
+ if (idle !== void 0) clearTimeout(idle);
17105
+ if (error === void 0) {
17106
+ resolve();
17107
+ return;
17108
+ }
17109
+ res.destroy(error);
17110
+ reject(error);
17111
+ };
17112
+ const arm = () => {
17113
+ if (idle !== void 0) clearTimeout(idle);
17114
+ idle = setTimeout(() => {
17115
+ if (stream.isPaused() || res.writableLength > 0) {
17116
+ arm();
17117
+ return;
17118
+ }
17119
+ try {
17120
+ stream.destroy();
17121
+ } catch {}
17122
+ finish(/* @__PURE__ */ new Error(`download stalled: no bytes for ${DOWNLOAD_IDLE_MS / 1e3}s`));
17123
+ }, DOWNLOAD_IDLE_MS);
17124
+ };
17125
+ stream.on("data", arm);
17126
+ res.on("drain", arm);
17127
+ stream.on("error", (error) => {
17128
+ finish(error instanceof Error ? error : new Error(String(error)));
17129
+ });
17130
+ res.on("close", () => {
17131
+ if (res.writableEnded) return;
17132
+ try {
17133
+ stream.destroy();
17134
+ } catch {}
17135
+ finish();
17136
+ });
17137
+ stream.on("end", () => finish());
17138
+ arm();
17139
+ stream.pipe(res);
17140
+ });
17141
+ } finally {
17142
+ if (!streamed) await closeAsync(sftp, handle);
17143
+ }
17144
+ }, { timeoutMs: 0 });
17145
+ }
17026
17146
  async mkdir(alias, dir) {
17027
17147
  const path = remotePath(dir);
17028
17148
  await this.pool.withSftp(alias, async (sftp) => {
@@ -17228,6 +17348,56 @@ function lstatAsync(sftp, path) {
17228
17348
  });
17229
17349
  });
17230
17350
  }
17351
+ function statAsync(sftp, path) {
17352
+ return new Promise((resolve, reject) => {
17353
+ sftp.stat(path, (error, attrs) => {
17354
+ if (error !== void 0 && error !== null) reject(error);
17355
+ else resolve(attrs);
17356
+ });
17357
+ });
17358
+ }
17359
+ function openAsync(sftp, path) {
17360
+ return new Promise((resolve, reject) => {
17361
+ sftp.open(path, "r", (error, handle) => {
17362
+ if (error !== void 0 && error !== null) reject(error);
17363
+ else resolve(handle);
17364
+ });
17365
+ });
17366
+ }
17367
+ function fstatAsync(sftp, handle) {
17368
+ return new Promise((resolve, reject) => {
17369
+ sftp.fstat(handle, (error, attrs) => {
17370
+ if (error !== void 0 && error !== null) reject(error);
17371
+ else resolve(attrs);
17372
+ });
17373
+ });
17374
+ }
17375
+ function closeAsync(sftp, handle) {
17376
+ return new Promise((resolve) => {
17377
+ try {
17378
+ sftp.close(handle, () => resolve());
17379
+ } catch {
17380
+ resolve();
17381
+ }
17382
+ });
17383
+ }
17384
+ /**
17385
+ * Explain an `open` failure after lstat already saw a symlink: lstat reports
17386
+ * the LINK's type, so "the thing at the end of the link is a directory" only
17387
+ * shows up after the follow. `stat` follows the link and answers the question
17388
+ * a raw SFTP status never does.
17389
+ */
17390
+ async function explainFollowFailure(sftp, path, cause) {
17391
+ const code = cause?.code;
17392
+ if (code !== SFTP_NO_SUCH_FILE && code !== SFTP_FAILURE) return void 0;
17393
+ let attrs;
17394
+ try {
17395
+ attrs = await statAsync(sftp, path);
17396
+ } catch (error) {
17397
+ return error?.code === SFTP_NO_SUCH_FILE ? /* @__PURE__ */ new Error(`no such file: ${path}`) : void 0;
17398
+ }
17399
+ if (isDir(attrs.mode)) return /* @__PURE__ */ new Error(`not a file: ${path} is a directory`);
17400
+ }
17231
17401
  /**
17232
17402
  * Read one window of a file.
17233
17403
  *
@@ -18821,4 +18991,4 @@ var RemoteWorlds = class {
18821
18991
  }
18822
18992
  };
18823
18993
  //#endregion
18824
- export { pushPipeline as a, require_lib as c, ensurePrivateDir as d, keysDir as f, probe as i, aliasRoot as l, isWindowsAbsolute as n, seedHelperCache as o, storePath as p, helperAvailability as r, RemoteFiles as s, RemoteWorlds as t, dshHome as u };
18994
+ export { pushPipeline as a, attachmentHeader as c, dshHome as d, ensurePrivateDir as f, probe as i, require_lib as l, storePath as m, isWindowsAbsolute as n, seedHelperCache as o, keysDir as p, helperAvailability as r, RemoteFiles as s, RemoteWorlds as t, aliasRoot as u };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-remote-vs",
3
3
  "description": "VSCode-style remote development for DSH: SSH host manager (key/password), helper deploy pipeline with version check, remote file explorer + editor + terminal in dsh-better-sidebar.",
4
- "version": "0.11.0",
4
+ "version": "0.12.0",
5
5
  "icon": "icon.svg",
6
6
  "keywords": [
7
7
  "dsh",
package/src/archive.ts ADDED
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Remote directory archiving for the download route.
3
+ *
4
+ * The archive is produced ON the remote host (`tar -czf -`) and streamed
5
+ * straight into the HTTP response, so the Host never builds it in memory or
6
+ * writes it to its own disk. Pure string builders (no fs, no exec) so the
7
+ * download gate can pin the exact command shape.
8
+ */
9
+
10
+ import { posix } from 'node:path'
11
+ import { shQuote } from './git-format.ts'
12
+ import { MAX_SELECTION_DOWNLOAD } from './protocol.ts'
13
+
14
+ /** Download file name for one archived directory. */
15
+ export function directoryArchiveName(dir: string): string {
16
+ const trimmed = String(dir).replace(/[\\/]+$/, '')
17
+ const at = Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\'))
18
+ const base = at < 0 ? trimmed : trimmed.slice(at + 1)
19
+ return `${base === '' ? 'root' : base}.tar.gz`
20
+ }
21
+
22
+ /**
23
+ * One POSIX shell command that writes the directory's gzip tar to stdout.
24
+ *
25
+ * The member name is prefixed with `./` so a directory whose name starts with
26
+ * `-` cannot be read as a tar option; `-C` names the parent instead of relying
27
+ * on a shell `cd`, and both paths are single-quoted (`shQuote`) so spaces,
28
+ * quotes and `$()` in a real path cannot escape into the command.
29
+ */
30
+ export function directoryArchiveCommand(dir: string): string {
31
+ const path = String(dir).replace(/\\/g, '/').replace(/\/+$/, '')
32
+ if (path === '' || path === '/') throw new Error('refusing to archive the remote root')
33
+ if (!path.startsWith('/')) throw new Error('remote path must be absolute')
34
+ const parent = posix.dirname(path)
35
+ const name = posix.basename(path)
36
+ return `tar -czf - -C ${shQuote(parent)} ${shQuote(`./${name}`)}`
37
+ }
38
+
39
+ /**
40
+ * One POSIX shell command archiving several selected paths to stdout.
41
+ *
42
+ * GNU tar accepts one `-C` before each member, so every entry is stored as its
43
+ * own bare `./name` while keeping its real parent on the remote side; that is
44
+ * what lets a selection span several directories (mixed files and directories
45
+ * are fine — tar recurses into directories). Two entries with the same basename
46
+ * from different directories collide inside the archive by design: the
47
+ * alternative would be a synthetic directory tree the remote never had.
48
+ */
49
+ export function selectionArchiveCommand(paths: readonly string[]): string {
50
+ if (paths.length === 0) throw new Error('refusing to archive an empty selection')
51
+ if (paths.length > MAX_SELECTION_DOWNLOAD) throw new Error(`too many entries: ${paths.length} (max ${MAX_SELECTION_DOWNLOAD})`)
52
+ let command = 'tar -czf -'
53
+ for (const raw of paths) {
54
+ const path = String(raw).replace(/\\/g, '/').replace(/\/+$/, '')
55
+ if (path === '' || path === '/') throw new Error('refusing to archive the remote root')
56
+ if (!path.startsWith('/')) throw new Error('remote path must be absolute')
57
+ command += ` -C ${shQuote(posix.dirname(path))} ${shQuote(`./${posix.basename(path)}`)}`
58
+ }
59
+ return command
60
+ }
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Download progress dock.
3
+ *
4
+ * Rendered through a PORTAL on `document.body`: the dock starts inside the
5
+ * sidebar's keep-alive slot, and a `position: fixed` descendant of a hidden
6
+ * ancestor disappears with it — which would take the progress bar (and the
7
+ * cancel button) of a running download along when the user switches rail views.
8
+ *
9
+ * The runner lives in `downloads.ts`, outside React, so an unmount of this
10
+ * component never interrupts a transfer; the dock only reads its snapshot.
11
+ */
12
+
13
+ import { useSyncExternalStore, type ReactNode } from 'react'
14
+ import { createPortal } from 'react-dom'
15
+ import { cancelDownload, dismissDownload, downloadsStore, formatByteCount, type DownloadTask } from './downloads.ts'
16
+ import { FileIcon, FolderIcon, IconButton, IconClose, IconStop } from './vsc/kit.tsx'
17
+
18
+ const STATUS_KEY: Record<DownloadTask['status'], string> = {
19
+ running: 'downloads.running',
20
+ done: 'downloads.done',
21
+ failed: 'downloads.failed',
22
+ cancelled: 'downloads.cancelled',
23
+ }
24
+
25
+ /** One line of detail under the bar (bytes, fallback note, or the failure). */
26
+ function detailText(task: DownloadTask, t: (key: string) => string): string {
27
+ if (task.status === 'failed') return task.error ?? t('downloads.failed')
28
+ if (task.status === 'cancelled') return t('downloads.cancelled')
29
+ if (task.status === 'done') {
30
+ return task.via === 'browserDefault' ? t('downloads.browserDefault') : t('downloads.done')
31
+ }
32
+ const loaded = formatByteCount(task.loaded)
33
+ if (task.total === undefined || task.total <= 0) return `${loaded} · ${t('downloads.indeterminate')}`
34
+ return `${loaded} / ${formatByteCount(task.total)}`
35
+ }
36
+
37
+ /** Percent for the bar, or `undefined` while the size is unknown (archives). */
38
+ function percentOf(task: DownloadTask): number | undefined {
39
+ if (task.total === undefined || task.total <= 0) return undefined
40
+ return Math.min(100, Math.round((task.loaded / task.total) * 100))
41
+ }
42
+
43
+ function DownloadRow(props: { task: DownloadTask; t: (key: string) => string }): ReactNode {
44
+ const { task, t } = props
45
+ const percent = percentOf(task)
46
+ return (
47
+ <div className={`rvs-download ${task.status}`}>
48
+ <div className="rvs-download-head">
49
+ <span className="rvs-download-icon">
50
+ {task.directory ? <FolderIcon path={task.name} open={false} size={14} /> : <FileIcon path={task.name} size={14} />}
51
+ </span>
52
+ <span className="rvs-download-name" title={task.name}>{task.name}{task.directory ? '.tar.gz' : ''}</span>
53
+ <span className={`rvs-download-status ${task.status}`}>{t(STATUS_KEY[task.status])}</span>
54
+ {task.status === 'running'
55
+ ? (
56
+ <IconButton title={t('downloads.cancel')} onClick={() => cancelDownload(task.id)}>
57
+ <IconStop size={12} />
58
+ </IconButton>
59
+ )
60
+ : (
61
+ <IconButton title={t('downloads.close')} onClick={() => dismissDownload(task.id)}>
62
+ <IconClose size={12} />
63
+ </IconButton>
64
+ )}
65
+ </div>
66
+ {task.status === 'running' && (
67
+ <div className="rvs-download-bar" aria-hidden="true">
68
+ <div
69
+ className={`rvs-download-fill${percent === undefined ? ' indeterminate' : ''}`}
70
+ style={percent === undefined ? undefined : { width: `${percent}%` }}
71
+ />
72
+ </div>
73
+ )}
74
+ <div className={`rvs-download-meta ${task.status}`} title={task.error}>{detailText(task, t)}</div>
75
+ </div>
76
+ )
77
+ }
78
+
79
+ export function DownloadDock(props: { t: (key: string) => string }): ReactNode {
80
+ const tasks = useSyncExternalStore(downloadsStore.subscribe, downloadsStore.getSnapshot, downloadsStore.getSnapshot)
81
+ if (typeof document === 'undefined') return null
82
+ if (tasks.length === 0) return null
83
+ return createPortal(
84
+ <div className="rvs-downloads" role="status" aria-live="polite">
85
+ {tasks.map(task => <DownloadRow key={task.id} task={task} t={props.t} />)}
86
+ </div>,
87
+ document.body,
88
+ )
89
+ }
@@ -12,8 +12,9 @@
12
12
  */
13
13
  import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
14
14
  import { copyIntoCommand, joinAbs, moveToCommand } from '../fs-ops.ts'
15
- import type { RemoteFileEntry } from '../protocol.ts'
15
+ import { MAX_SELECTION_DOWNLOAD, type RemoteFileEntry } from '../protocol.ts'
16
16
  import { api, uploadFile } from './api.ts'
17
+ import { startDownload, startSelectionDownload } from './downloads.ts'
17
18
  import { insertRemoteReference, sameLocalDir } from './composer.ts'
18
19
  import { repoRelative, useExplorer } from './store.tsx'
19
20
  import { planUpload, withDroppedDirs, type DroppedFile } from './upload-plan.ts'
@@ -987,6 +988,19 @@ export function RemoteExplorer(props: { showHidden: boolean; onToggleHidden: ()
987
988
  // the listeners are re-attached whenever that identity would change.
988
989
  }, [root, alias, uploadFromDataTransfer])
989
990
 
991
+ // ------------------------------------------------------------- download
992
+
993
+ /**
994
+ * Download one remote file, or one directory as a `.tar.gz`.
995
+ *
996
+ * Everything after the click (stat preflight, save dialog, progress, cancel,
997
+ * completion/failure) lives in `downloads.ts`, so the transfer keeps running
998
+ * when this panel is hidden or unmounted.
999
+ */
1000
+ const downloadEntry = (entry: RemoteFileEntry): void => {
1001
+ startDownload(alias, entry.path, { name: entry.name, directory: entry.isDir })
1002
+ }
1003
+
990
1004
  // ---------------------------------------------------------- context menu
991
1005
 
992
1006
  const openMenu = (event: React.MouseEvent, entry: RemoteFileEntry | undefined): void => {
@@ -1073,6 +1087,22 @@ export function RemoteExplorer(props: { showHidden: boolean; onToggleHidden: ()
1073
1087
  })
1074
1088
  entries.push({ label: t('files.copyRel'), onSelect: () => { void copyText(targets.map(item => repoRelative(repoRoot, item.path) || item.path).join('\n')); toast(t('files.copiedClipboard')) }, separated: true })
1075
1089
  entries.push({ label: t('files.copyAbs'), onSelect: () => { void copyText(targets.map(item => item.path).join('\n')); toast(t('files.copiedClipboard')) } })
1090
+ entries.push({
1091
+ label: t('files.download') + (targets.length > 1 ? ` (${targets.length})` : ''),
1092
+ onSelect: () => {
1093
+ if (targets.length === 1) {
1094
+ downloadEntry(entry)
1095
+ return
1096
+ }
1097
+ if (targets.length > MAX_SELECTION_DOWNLOAD) {
1098
+ toast(t('downloads.tooMany'), true)
1099
+ return
1100
+ }
1101
+ // One archive for the whole selection: the user answers ONE save
1102
+ // dialog instead of one per entry, and mixed files/directories work.
1103
+ startSelectionDownload(alias, targets.map(item => item.path))
1104
+ },
1105
+ })
1076
1106
  entries.push({
1077
1107
  label: t('files.referenceFile'),
1078
1108
  onSelect: () => {
@@ -12,6 +12,7 @@ import type { Context } from '@deepseek-ai/cordis'
12
12
  import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react'
13
13
  import { EditorPane } from './EditorPane.tsx'
14
14
  import { FloatingEditorPlaceholder } from './FloatingPlaceholder.tsx'
15
+ import { DownloadDock } from './DownloadDock.tsx'
15
16
  import { RemoteExplorer } from './RemoteExplorer.tsx'
16
17
  import { SearchView } from './SearchView.tsx'
17
18
  import { HistoryPanel } from './scm/HistoryPanel.tsx'
@@ -328,6 +329,7 @@ function Shell(props: { ctx: Context; visible: boolean }): ReactNode {
328
329
 
329
330
  return (
330
331
  <div className="rvs-root" ref={attachRoot}>
332
+ <DownloadDock t={t} />
331
333
  <div className="rvs-rail">
332
334
  {railButton('explorer', t('tab.files'), <IconCode size={17} />)}
333
335
  {railButton('search', t('tab.search'), <IconSearch size={17} />)}
@@ -22,6 +22,7 @@ import {
22
22
  import { searchFiles, type SearchHit } from './scm/actions.ts'
23
23
  import { repoRelative, useExplorer } from './store.tsx'
24
24
  import { api } from './api.ts'
25
+ import { startDownload } from './downloads.ts'
25
26
  import {
26
27
  ContextMenu,
27
28
  FileIcon,
@@ -239,6 +240,12 @@ export function SearchView(): ReactNode {
239
240
  return { abs, dir }
240
241
  }
241
242
 
243
+ /** Download one found path (a file, or a directory as a `.tar.gz`). */
244
+ const downloadHit = (hit: SearchHit): void => {
245
+ const { abs } = nameHitPaths(hit)
246
+ startDownload(alias, abs, { name: baseName(abs), directory: hit.isDir })
247
+ }
248
+
242
249
  /**
243
250
  * Right-click on a name result: what one does with a found path.
244
251
  *
@@ -256,6 +263,7 @@ export function SearchView(): ReactNode {
256
263
  menu.open(event.clientX, event.clientY, [
257
264
  { label: t('files.copyAbs'), onSelect: () => { void copyText(abs); toast(t('files.copiedClipboard')) } },
258
265
  { label: t('files.copyRel'), onSelect: () => { void copyText(rel); toast(t('files.copiedClipboard')) } },
266
+ { label: t('files.download'), onSelect: () => { downloadHit(hit) } },
259
267
  {
260
268
  label: t('files.openInFloat'),
261
269
  onSelect: () => { store.openInFloatEditor(abs) },
package/src/client/api.ts CHANGED
@@ -81,6 +81,43 @@ function throwIfGitFailed(r: RemoteExecResult, timeoutMs: number): void {
81
81
  throw new RemoteApiError(502, friendly ?? (r.stderr.trim() || r.error || `git failed [exit code: ${r.exitCode}]`))
82
82
  }
83
83
 
84
+ /** Query for one remote terminal socket. */
85
+ export interface TerminalSocketQuery {
86
+ alias?: string
87
+ session?: string
88
+ cols: number
89
+ rows: number
90
+ }
91
+
92
+ /**
93
+ * Origin the remote terminal socket dials.
94
+ *
95
+ * `dsh web` serves the app from the Host itself, so `location` already names the
96
+ * Host. DSH Desktop serves the app from `dsh-app://app` and forwards HTTP to its
97
+ * own loopback Host, publishing that Host's origin as
98
+ * `__DSH_TRANSPORT__.streamBaseUrl` (the shell also attaches the Host cookie to
99
+ * `ws://127.0.0.1/*` handshakes). Prefer a published origin; without one keep
100
+ * the page origin, which is exactly the pre-Desktop behaviour.
101
+ */
102
+ export function terminalSocketBase(): string {
103
+ const transport = (globalThis as unknown as { __DSH_TRANSPORT__?: { streamBaseUrl?: unknown } }).__DSH_TRANSPORT__
104
+ const published = transport?.streamBaseUrl
105
+ if (typeof published === 'string' && /^https?:\/\//i.test(published)) return published
106
+ return `${location.protocol}//${location.host}`
107
+ }
108
+
109
+ /** Absolute socket URL for one remote terminal, resolved against `base`. */
110
+ export function terminalSocketUrl(params: TerminalSocketQuery, base = terminalSocketBase()): string {
111
+ const url = new URL(REMOTE_API.terminal, base)
112
+ if (url.protocol === 'http:') url.protocol = 'ws:'
113
+ else if (url.protocol === 'https:') url.protocol = 'wss:'
114
+ if (params.alias !== undefined) url.searchParams.set('alias', params.alias)
115
+ if (params.session !== undefined) url.searchParams.set('session', params.session)
116
+ url.searchParams.set('cols', String(params.cols))
117
+ url.searchParams.set('rows', String(params.rows))
118
+ return url.toString()
119
+ }
120
+
84
121
  /**
85
122
  * Effective remote timeouts (see `src/timeouts.ts`).
86
123
  *
@@ -379,14 +416,6 @@ export const api = {
379
416
  return parseShow(ref, message.stdout, stat.stdout)
380
417
  },
381
418
  },
382
- // -- terminal socket URL
383
- terminalUrl: (params: { alias?: string; session?: string; cols: number; rows: number }) => {
384
- const proto = location.protocol === 'https:' ? 'wss:' : 'ws:'
385
- const url = new URL(`${proto}//${location.host}${REMOTE_API.terminal}`)
386
- if (params.alias !== undefined) url.searchParams.set('alias', params.alias)
387
- if (params.session !== undefined) url.searchParams.set('session', params.session)
388
- url.searchParams.set('cols', String(params.cols))
389
- url.searchParams.set('rows', String(params.rows))
390
- return url.toString()
391
- },
419
+ // -- terminal socket URL (Desktop resolves it against its published Host origin)
420
+ terminalUrl: (params: TerminalSocketQuery) => terminalSocketUrl(params),
392
421
  }