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.
@@ -0,0 +1,212 @@
1
+ /**
2
+ * Download one remote file or directory to the local machine.
3
+ *
4
+ * The Host streams the bytes over `REMOTE_API.download` (file) or
5
+ * `REMOTE_API.downloadDir` (one remote `tar -czf -` archive). When the browser
6
+ * offers the File System Access API the user picks the destination in a native
7
+ * "save as" dialog and the response body is written chunk by chunk into that
8
+ * file — streamed, never assembled into a Blob — which is also what feeds the
9
+ * progress meter. Without the API (Firefox, some Electron shells) the download
10
+ * falls back to an anchor click, i.e. the browser's configured download folder,
11
+ * with no progress to report.
12
+ *
13
+ * The runner (`downloads.ts`) preflights with `files` op=stat, so a vanished or
14
+ * unreadable path shows the Host's real error instead of an empty saved file.
15
+ */
16
+
17
+ import { REMOTE_API, selectionDownloadName } from '../protocol.ts'
18
+
19
+ /** What one download attempt ended as. */
20
+ export type DownloadOutcome = 'saved' | 'downloaded'
21
+
22
+ /** One progress sample: `total` is absent for a streamed archive (chunked). */
23
+ export interface DownloadProgress {
24
+ loaded: number
25
+ total?: number
26
+ }
27
+
28
+ /** Hooks the runner uses for the progress panel and its cancel button. */
29
+ export interface SaveOptions {
30
+ onProgress?: (progress: DownloadProgress) => void
31
+ signal?: AbortSignal
32
+ }
33
+
34
+ /** The writable file the save picker hands back (FileSystemWritableFileStream). */
35
+ interface SaveFileWritable {
36
+ write: (chunk: Uint8Array) => Promise<void>
37
+ close: () => Promise<void>
38
+ abort: () => Promise<void>
39
+ }
40
+
41
+ /** Minimal shape of the File System Access save picker (Chromium/Edge). */
42
+ interface SaveFileHandle {
43
+ createWritable: () => Promise<SaveFileWritable>
44
+ remove?: () => Promise<void>
45
+ }
46
+
47
+ interface SaveFilePickerApi {
48
+ showSaveFilePicker?: (options: { suggestedName?: string }) => Promise<SaveFileHandle>
49
+ }
50
+
51
+ /** File name a remote POSIX path should be saved as. */
52
+ export function downloadFileName(path: string): string {
53
+ const trimmed = path.replace(/[\\/]+$/, '')
54
+ const at = Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\'))
55
+ return at < 0 ? trimmed : trimmed.slice(at + 1)
56
+ }
57
+
58
+ /**
59
+ * Same-origin URL of the streaming download route for one remote file.
60
+ *
61
+ * Deliberately RELATIVE, including on Desktop: the page origin there is
62
+ * `dsh-app://app` and the Electron shell proxies app-origin HTTP to its Host,
63
+ * so the click stays same-origin (the `download` attribute applies) and passes
64
+ * the route's loopback/same-origin fence. Naming the published loopback origin
65
+ * instead would make it a cross-site GET, which that fence rejects.
66
+ */
67
+ export function downloadUrl(alias: string, path: string): string {
68
+ return `${REMOTE_API.download}?${new URLSearchParams({ alias, path }).toString()}`
69
+ }
70
+
71
+ /** Same-origin URL of the streaming directory-archive route. */
72
+ export function downloadDirUrl(alias: string, path: string): string {
73
+ return `${REMOTE_API.downloadDir}?${new URLSearchParams({ alias, path }).toString()}`
74
+ }
75
+
76
+ /** Same-origin URL of the multi-selection archive route (one `path` per entry). */
77
+ export function downloadManyUrl(alias: string, paths: readonly string[]): string {
78
+ const query = new URLSearchParams({ alias })
79
+ for (const path of paths) query.append('path', path)
80
+ return `${REMOTE_API.downloadMany}?${query.toString()}`
81
+ }
82
+
83
+ /**
84
+ * Hand one download to the browser (fallback when no save picker exists).
85
+ *
86
+ * The element is attached to the document on purpose: a detached anchor is
87
+ * ignored by some Chromium versions, and Desktop's shell hooks the download at
88
+ * the document level.
89
+ */
90
+ export function triggerDownload(href: string, fileName: string): void {
91
+ const anchor = document.createElement('a')
92
+ anchor.href = href
93
+ anchor.download = fileName
94
+ anchor.rel = 'noopener'
95
+ anchor.style.display = 'none'
96
+ document.body.append(anchor)
97
+ try {
98
+ anchor.click()
99
+ } finally {
100
+ anchor.remove()
101
+ }
102
+ }
103
+
104
+ /** An error shaped like the one `AbortSignal` consumers expect. */
105
+ function abortError(): Error {
106
+ const error = new Error('download cancelled')
107
+ error.name = 'AbortError'
108
+ return error
109
+ }
110
+
111
+ /** Delete the just-created target after a failed transfer (best effort). */
112
+ async function discard(handle: SaveFileHandle): Promise<void> {
113
+ try {
114
+ await handle.remove?.()
115
+ } catch {
116
+ // The browser may keep the handle locked for a moment; an empty file is a
117
+ // better outcome than masking the real error.
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Save one streamed URL to a destination the user picks.
123
+ *
124
+ * The picker runs while the click's transient activation is still valid, so it
125
+ * must come before the network work. A picker that refuses the call (expired
126
+ * activation, policy) falls back to the browser download flow instead of
127
+ * failing the download outright.
128
+ *
129
+ * @returns `'saved'` for the picked destination, `'downloaded'` for the
130
+ * browser-default fallback.
131
+ */
132
+ export async function saveRemoteUrl(href: string, fileName: string, options: SaveOptions = {}): Promise<DownloadOutcome> {
133
+ const picker = (globalThis as unknown as SaveFilePickerApi).showSaveFilePicker
134
+ if (typeof picker !== 'function') {
135
+ if (options.signal?.aborted === true) throw abortError()
136
+ triggerDownload(href, fileName)
137
+ return 'downloaded'
138
+ }
139
+ let handle: SaveFileHandle
140
+ try {
141
+ handle = await picker.call(globalThis, { suggestedName: fileName })
142
+ } catch (error) {
143
+ if (error instanceof Error && error.name === 'AbortError') throw error
144
+ if (error instanceof Error && (error.name === 'SecurityError' || error.name === 'NotAllowedError')) {
145
+ if (options.signal?.aborted === true) throw abortError()
146
+ triggerDownload(href, fileName)
147
+ return 'downloaded'
148
+ }
149
+ throw error
150
+ }
151
+ const signal = options.signal
152
+ let response: Response
153
+ try {
154
+ response = await fetch(href, signal === undefined ? undefined : { signal })
155
+ } catch (error) {
156
+ await discard(handle)
157
+ throw error
158
+ }
159
+ if (!response.ok || response.body === null) {
160
+ const detail = await response.text().catch(() => '')
161
+ await discard(handle)
162
+ throw new Error(detail.trim() === '' ? `HTTP ${response.status}` : detail.trim())
163
+ }
164
+ const lengthHeader = response.headers.get('content-length')
165
+ const parsedTotal = lengthHeader === null ? Number.NaN : Number(lengthHeader)
166
+ const total = Number.isFinite(parsedTotal) && parsedTotal >= 0 ? parsedTotal : undefined
167
+ const writable = await handle.createWritable()
168
+ const reader = response.body.getReader()
169
+ let loaded = 0
170
+ try {
171
+ options.onProgress?.({ loaded, ...(total === undefined ? {} : { total }) })
172
+ for (;;) {
173
+ if (signal?.aborted === true) throw abortError()
174
+ const { done, value } = await reader.read()
175
+ if (done) break
176
+ loaded += value.byteLength
177
+ await writable.write(value)
178
+ options.onProgress?.({ loaded, ...(total === undefined ? {} : { total }) })
179
+ }
180
+ await writable.close()
181
+ } catch (error) {
182
+ try {
183
+ await reader.cancel()
184
+ } catch {
185
+ // Stream already gone.
186
+ }
187
+ try {
188
+ await writable.abort()
189
+ } catch {
190
+ // Already closed.
191
+ }
192
+ await discard(handle)
193
+ throw error
194
+ }
195
+ return 'saved'
196
+ }
197
+
198
+ /** Save one remote file (fresh name from its POSIX basename). */
199
+ export function saveRemoteFile(alias: string, path: string, options: SaveOptions = {}): Promise<DownloadOutcome> {
200
+ return saveRemoteUrl(downloadUrl(alias, path), downloadFileName(path), options)
201
+ }
202
+
203
+ /** Save one remote directory as a single `.tar.gz`. */
204
+ export function saveRemoteDir(alias: string, path: string, options: SaveOptions = {}): Promise<DownloadOutcome> {
205
+ const name = downloadFileName(path) || 'root'
206
+ return saveRemoteUrl(downloadDirUrl(alias, path), `${name}.tar.gz`, options)
207
+ }
208
+
209
+ /** Save several selected entries as one `.tar.gz` archive. */
210
+ export function saveRemoteMany(alias: string, paths: readonly string[], options: SaveOptions = {}): Promise<DownloadOutcome> {
211
+ return saveRemoteUrl(downloadManyUrl(alias, paths), selectionDownloadName(paths.length), options)
212
+ }
@@ -0,0 +1,175 @@
1
+ /**
2
+ * Download runner and its tiny observable store.
3
+ *
4
+ * The explorer/search menus start one download each; this module owns the
5
+ * stat preflight, the file-vs-directory choice, the cancel handle and the
6
+ * progress/status snapshot the dock renders. Kept outside React on purpose:
7
+ * the dock is portaled to `<body>` and may unmount with its sidebar tab, while
8
+ * a download already streaming must keep running to completion.
9
+ */
10
+
11
+ import { api } from './api.ts'
12
+ import { saveRemoteDir, saveRemoteFile, saveRemoteMany, type DownloadOutcome } from './download.ts'
13
+
14
+ /** One download's lifecycle state. */
15
+ export type DownloadStatus = 'running' | 'done' | 'failed' | 'cancelled'
16
+
17
+ /** One task as the dock renders it. */
18
+ export interface DownloadTask {
19
+ id: string
20
+ /** Basename of the remote path (or `selection-N` for a multi-selection). */
21
+ name: string
22
+ /** Resolved from the stat preflight; `hint.directory` until then. */
23
+ directory: boolean
24
+ /** Entries in a multi-selection archive; absent for a single path. */
25
+ selection?: number
26
+ status: DownloadStatus
27
+ loaded: number
28
+ /** Absent for a streamed archive (chunked, size unknown). */
29
+ total?: number
30
+ /** Failure text, or the note shown for the browser-default fallback. */
31
+ error?: string
32
+ /** `browserDefault` means no save dialog existed and the file went to Downloads. */
33
+ via?: 'picker' | 'browserDefault'
34
+ startedAt: number
35
+ finishedAt?: number
36
+ }
37
+
38
+ /** Human byte size for the progress line. */
39
+ export function formatByteCount(bytes: number): string {
40
+ if (!Number.isFinite(bytes) || bytes < 0) return '0 B'
41
+ if (bytes < 1024) return `${Math.round(bytes)} B`
42
+ const units = ['KiB', 'MiB', 'GiB', 'TiB']
43
+ let value = bytes / 1024
44
+ let unit = 0
45
+ while (value >= 1024 && unit < units.length - 1) {
46
+ value /= 1024
47
+ unit += 1
48
+ }
49
+ return `${value >= 100 ? Math.round(value) : value.toFixed(1)} ${units[unit]}`
50
+ }
51
+
52
+ let tasks: readonly DownloadTask[] = []
53
+ const listeners = new Set<() => void>()
54
+ const controllers = new Map<string, AbortController>()
55
+ let sequence = 0
56
+
57
+ const notify = (): void => {
58
+ for (const listener of [...listeners]) listener()
59
+ }
60
+
61
+ const patch = (id: string, next: Partial<DownloadTask>): void => {
62
+ tasks = tasks.map(task => (task.id === id ? { ...task, ...next } : task))
63
+ notify()
64
+ }
65
+
66
+ /** Store surface: `useSyncExternalStore(subscribe, getSnapshot, getSnapshot)`. */
67
+ export const downloadsStore = {
68
+ subscribe(listener: () => void): () => void {
69
+ listeners.add(listener)
70
+ return () => {
71
+ listeners.delete(listener)
72
+ }
73
+ },
74
+ getSnapshot(): readonly DownloadTask[] {
75
+ return tasks
76
+ },
77
+ }
78
+
79
+ /** Progress sink handed to every starter. */
80
+ interface RunnerOptions {
81
+ signal: AbortSignal
82
+ onProgress: (progress: { loaded: number; total?: number }) => void
83
+ }
84
+
85
+ /**
86
+ * Run one task body: progress patches, terminal status, cancel mapping.
87
+ *
88
+ * The task row is published by the caller before any await, so the dock shows
89
+ * the row immediately and only the numbers move afterwards.
90
+ */
91
+ const launch = (id: string, controller: AbortController, run: (options: RunnerOptions) => Promise<DownloadOutcome>): void => {
92
+ void (async () => {
93
+ try {
94
+ const outcome = await run({
95
+ signal: controller.signal,
96
+ onProgress: (progress) => {
97
+ if (controller.signal.aborted) return
98
+ patch(id, {
99
+ loaded: progress.loaded,
100
+ ...(progress.total === undefined ? {} : { total: progress.total }),
101
+ })
102
+ },
103
+ })
104
+ patch(id, {
105
+ status: 'done',
106
+ finishedAt: Date.now(),
107
+ via: outcome === 'downloaded' ? 'browserDefault' : 'picker',
108
+ })
109
+ } catch (error) {
110
+ const aborted = controller.signal.aborted || (error instanceof Error && error.name === 'AbortError')
111
+ patch(id, {
112
+ status: aborted ? 'cancelled' : 'failed',
113
+ finishedAt: Date.now(),
114
+ ...(aborted ? {} : { error: error instanceof Error ? error.message : String(error) }),
115
+ })
116
+ } finally {
117
+ controllers.delete(id)
118
+ }
119
+ })()
120
+ }
121
+
122
+ /** Publish one running task and return its id plus cancel handle. */
123
+ const newTask = (task: Pick<DownloadTask, 'name' | 'directory'> & Partial<Pick<DownloadTask, 'selection'>>): { id: string; controller: AbortController } => {
124
+ const id = `download-${++sequence}`
125
+ const controller = new AbortController()
126
+ controllers.set(id, controller)
127
+ tasks = [...tasks, { ...task, id, status: 'running', loaded: 0, startedAt: Date.now() }]
128
+ notify()
129
+ return { id, controller }
130
+ }
131
+
132
+ /**
133
+ * Start one download (file or directory) and return its task id.
134
+ *
135
+ * The stat preflight runs here — not in the menus — so a deleted/unreadable
136
+ * remote path becomes a failed task with the Host's real message, and the
137
+ * file-vs-directory decision comes from the Host rather than a possibly stale
138
+ * tree row.
139
+ */
140
+ export function startDownload(alias: string, path: string, hint: { name: string; directory: boolean }): string {
141
+ const { id, controller } = newTask({ name: hint.name, directory: hint.directory })
142
+ launch(id, controller, async (options) => {
143
+ const entry = await api.fileOp.stat(alias, path)
144
+ patch(id, { directory: entry.isDir })
145
+ return entry.isDir ? await saveRemoteDir(alias, path, options) : await saveRemoteFile(alias, path, options)
146
+ })
147
+ return id
148
+ }
149
+
150
+ /**
151
+ * Start one multi-selection download.
152
+ *
153
+ * The Host archives every selected entry into a single `.tar.gz`, so the user
154
+ * picks one destination instead of answering N save dialogs; mixed files and
155
+ * directories are fine (tar recurses). Entry validation happens Host-side
156
+ * before the archive starts, so no client preflight round trip is needed.
157
+ */
158
+ export function startSelectionDownload(alias: string, paths: readonly string[]): string {
159
+ const { id, controller } = newTask({ name: `selection-${paths.length}`, directory: true, selection: paths.length })
160
+ launch(id, controller, options => saveRemoteMany(alias, paths, options))
161
+ return id
162
+ }
163
+
164
+ /** Cancel one running download (the panel's stop button). */
165
+ export function cancelDownload(id: string): void {
166
+ controllers.get(id)?.abort()
167
+ }
168
+
169
+ /** Drop one task from the dock (finished tasks only in practice). */
170
+ export function dismissDownload(id: string): void {
171
+ controllers.get(id)?.abort()
172
+ controllers.delete(id)
173
+ tasks = tasks.filter(task => task.id !== id)
174
+ notify()
175
+ }
@@ -27,6 +27,9 @@ export const DYNAMIC_KEYS = [
27
27
  'history.details',
28
28
  'history.content',
29
29
  'history.diff',
30
+ // Reached through the `STATUS_KEY` lookup in `DownloadDock.tsx` (running is
31
+ // the only status the detail line never prints as a literal `t()` call).
32
+ 'downloads.running',
30
33
  ] as const
31
34
 
32
35
  const zh: Record<string, string> = {
@@ -191,6 +194,16 @@ const zh: Record<string, string> = {
191
194
  'files.cutClipboard': '已剪切到剪贴板',
192
195
  'files.copyRel': '复制相对路径',
193
196
  'files.copyAbs': '复制绝对路径',
197
+ 'files.download': '下载到本地',
198
+ 'downloads.running': '下载中',
199
+ 'downloads.done': '下载完成',
200
+ 'downloads.failed': '下载失败',
201
+ 'downloads.cancelled': '已取消',
202
+ 'downloads.cancel': '取消下载',
203
+ 'downloads.close': '关闭',
204
+ 'downloads.browserDefault': '已保存到浏览器默认下载目录',
205
+ 'downloads.indeterminate': '正在打包…',
206
+ 'downloads.tooMany': '选择项过多(最多 100 项),请改为下载所在目录',
194
207
  'files.copied': '已复制',
195
208
  'files.moved': '已移动',
196
209
  'files.pasteFailed': '操作失败',
@@ -608,6 +621,16 @@ const en: Record<string, string> = {
608
621
  'files.cutClipboard': 'Cut to clipboard',
609
622
  'files.copyRel': 'Copy relative path',
610
623
  'files.copyAbs': 'Copy absolute path',
624
+ 'files.download': 'Download to Local',
625
+ 'downloads.running': 'Downloading',
626
+ 'downloads.done': 'Downloaded',
627
+ 'downloads.failed': 'Download failed',
628
+ 'downloads.cancelled': 'Cancelled',
629
+ 'downloads.cancel': 'Cancel download',
630
+ 'downloads.close': 'Dismiss',
631
+ 'downloads.browserDefault': 'Saved to the browser download folder',
632
+ 'downloads.indeterminate': 'Packaging…',
633
+ 'downloads.tooMany': 'Too many entries (max 100); download the containing folder instead',
611
634
  'files.copied': 'Copied',
612
635
  'files.moved': 'Moved',
613
636
  'files.pasteFailed': 'operation failed',
@@ -3604,3 +3604,127 @@ body[data-ds-dark-theme] .rvs-execpanel {
3604
3604
  font-size: 11px;
3605
3605
  }
3606
3606
 
3607
+ /* --------------------------------------------------------- download dock */
3608
+ /* PORTALed to <body>, i.e. OUTSIDE `.rvs-root` where the tokens are declared:
3609
+ declare the subset this panel uses (same rule as `.rvs-execpanel`). */
3610
+ .rvs-downloads {
3611
+ --rvs-fg: var(--dsw-alias-label-primary, #e6e6e6);
3612
+ --rvs-fg2: var(--dsw-alias-label-secondary, #b9b9b9);
3613
+ --rvs-fg3: var(--dsw-alias-label-tertiary, #8b8b8b);
3614
+ --rvs-border: var(--dsw-alias-border-l1, rgba(127, 127, 127, .25));
3615
+ --rvs-border2: var(--dsw-alias-border-l2, rgba(127, 127, 127, .38));
3616
+ --rvs-overlay: var(--dsw-alias-bg-overlay, #24262e);
3617
+ --rvs-brand: var(--dsw-alias-brand-primary, #4d6bfe);
3618
+ --rvs-danger: var(--dsw-alias-state-error-primary, #e05555);
3619
+ --rvs-git-m: #e2b714;
3620
+ --rvs-git-a: #4ec9b0;
3621
+ position: fixed;
3622
+ /* Bottom-RIGHT, not over the sidebar's own footer (first screenshot: the
3623
+ dock sat on the usage/account block). `bottom: 64px` keeps it above the
3624
+ transient toast stack (right 16 / bottom 18 / z 100001) and above the
3625
+ network exec panel (right 16 / bottom 16 / z 45), so neither covers it. */
3626
+ right: 16px;
3627
+ bottom: 64px;
3628
+ z-index: 100000;
3629
+ animation: rvsFade .12s ease;
3630
+ width: min(380px, calc(100vw - 32px));
3631
+ max-height: min(45vh, 420px);
3632
+ overflow-y: auto;
3633
+ display: flex;
3634
+ flex-direction: column;
3635
+ gap: 6px;
3636
+ padding: 8px;
3637
+ border: 1px solid var(--rvs-border2);
3638
+ border-radius: 10px;
3639
+ background: var(--rvs-overlay);
3640
+ color: var(--rvs-fg);
3641
+ box-shadow: 0 18px 60px rgba(0, 0, 0, .45), 0 2px 8px rgba(0, 0, 0, .28);
3642
+ }
3643
+
3644
+ .rvs-download {
3645
+ display: flex;
3646
+ flex-direction: column;
3647
+ gap: 4px;
3648
+ padding: 6px 8px;
3649
+ border: 1px solid var(--rvs-border);
3650
+ border-radius: 8px;
3651
+ background: rgba(127, 127, 127, .06);
3652
+ }
3653
+
3654
+ .rvs-download-head {
3655
+ display: flex;
3656
+ align-items: center;
3657
+ gap: 6px;
3658
+ min-width: 0;
3659
+ }
3660
+
3661
+ .rvs-download-icon {
3662
+ flex: none;
3663
+ display: flex;
3664
+ align-items: center;
3665
+ color: var(--rvs-fg2);
3666
+ }
3667
+
3668
+ .rvs-download-name {
3669
+ flex: 1;
3670
+ min-width: 0;
3671
+ overflow: hidden;
3672
+ text-overflow: ellipsis;
3673
+ white-space: nowrap;
3674
+ font-size: 12px;
3675
+ font-weight: 600;
3676
+ }
3677
+
3678
+ .rvs-download-status {
3679
+ flex: none;
3680
+ font-size: 11px;
3681
+ color: var(--rvs-fg3);
3682
+ }
3683
+
3684
+ .rvs-download-status.done { color: var(--rvs-git-a); }
3685
+ .rvs-download-status.failed { color: var(--rvs-danger); }
3686
+ .rvs-download-status.cancelled { color: var(--rvs-git-m); }
3687
+
3688
+ .rvs-download-bar {
3689
+ height: 4px;
3690
+ overflow: hidden;
3691
+ border-radius: 2px;
3692
+ background: rgba(127, 127, 127, .22);
3693
+ }
3694
+
3695
+ .rvs-download-fill {
3696
+ height: 100%;
3697
+ width: 0;
3698
+ border-radius: 2px;
3699
+ background: var(--rvs-brand);
3700
+ transition: width .12s linear;
3701
+ }
3702
+
3703
+ .rvs-download-fill.indeterminate {
3704
+ width: 35%;
3705
+ animation: rvs-download-slide 1.2s ease-in-out infinite;
3706
+ }
3707
+
3708
+ @keyframes rvs-download-slide {
3709
+ from { transform: translateX(-120%); }
3710
+ to { transform: translateX(320%); }
3711
+ }
3712
+
3713
+ @media (prefers-reduced-motion: reduce) {
3714
+ .rvs-download-fill.indeterminate { animation-duration: 2.4s; }
3715
+ .rvs-download-fill { transition: none; }
3716
+ }
3717
+
3718
+ .rvs-download-meta {
3719
+ overflow: hidden;
3720
+ color: var(--rvs-fg3);
3721
+ font-size: 11px;
3722
+ text-overflow: ellipsis;
3723
+ white-space: nowrap;
3724
+ }
3725
+
3726
+ .rvs-download-meta.failed { color: var(--rvs-danger); white-space: normal; word-break: break-word; }
3727
+ .rvs-download-meta.done { color: var(--rvs-fg2); }
3728
+ .rvs-download-meta.cancelled { color: var(--rvs-git-m); }
3729
+
3730
+