dsh-remote-vs 0.13.0 → 0.15.1

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 (128) hide show
  1. package/README.en.md +455 -443
  2. package/README.md +408 -396
  3. package/lib/client.js +8062 -2651
  4. package/lib/index.js +1058 -288
  5. package/lib/p2-router-fs.js +1 -1
  6. package/lib/p2-router-refs.js +89 -10
  7. package/lib/p2-router-spill.js +73 -1
  8. package/lib/p2-router-subprocess.js +18 -6
  9. package/lib/spill-retention-BwKEWrl5.js +115 -0
  10. package/lib/{ssh-proc-arI5lm4W.js → ssh-proc-VKWn_LZC.js} +17 -0
  11. package/lib/types/archive.d.ts +1 -1
  12. package/lib/types/changes/recorder.d.ts +34 -2
  13. package/lib/types/client/CodeEditor.d.ts +12 -0
  14. package/lib/types/client/ConnectionStatus.d.ts +17 -0
  15. package/lib/types/client/DirectoryFlow.d.ts +2 -0
  16. package/lib/types/client/DoctorPanel.d.ts +25 -0
  17. package/lib/types/client/QuickOpen.d.ts +17 -0
  18. package/lib/types/client/RemoteExplorer.d.ts +192 -1
  19. package/lib/types/client/RemoteRoot.d.ts +17 -0
  20. package/lib/types/client/SearchView.d.ts +55 -0
  21. package/lib/types/client/TerminalView.d.ts +38 -0
  22. package/lib/types/client/WorkspaceWizard.d.ts +17 -0
  23. package/lib/types/client/api.d.ts +54 -4
  24. package/lib/types/client/changes/undo-affordance.d.ts +16 -0
  25. package/lib/types/client/changes/undo-context.d.ts +14 -18
  26. package/lib/types/client/changes/undo-target.d.ts +78 -0
  27. package/lib/types/client/connection.d.ts +111 -0
  28. package/lib/types/client/doctor.d.ts +122 -0
  29. package/lib/types/client/download.d.ts +35 -5
  30. package/lib/types/client/downloads.d.ts +18 -1
  31. package/lib/types/client/file-open-probe.d.ts +64 -0
  32. package/lib/types/client/i18n.d.ts +1 -1
  33. package/lib/types/client/quickopen-model.d.ts +332 -0
  34. package/lib/types/client/scm/DiffView.d.ts +34 -0
  35. package/lib/types/client/scm/actions.d.ts +18 -0
  36. package/lib/types/client/scm/diff-model.d.ts +17 -1
  37. package/lib/types/client/scm/git-cache.d.ts +10 -2
  38. package/lib/types/client/scm/read-queue.d.ts +2 -1
  39. package/lib/types/client/scm/stage-queue.d.ts +13 -0
  40. package/lib/types/client/scm/status-map.d.ts +3 -1
  41. package/lib/types/client/store.d.ts +114 -5
  42. package/lib/types/client/vsc/FindWidget.d.ts +7 -0
  43. package/lib/types/client/vsc/save-shortcut.d.ts +57 -0
  44. package/lib/types/deploy.d.ts +44 -2
  45. package/lib/types/git-format.d.ts +15 -0
  46. package/lib/types/http.d.ts +44 -0
  47. package/lib/types/p2/file-refs.d.ts +39 -2
  48. package/lib/types/p2/helper-rpc.d.ts +26 -0
  49. package/lib/types/p2/router-spill.d.ts +19 -0
  50. package/lib/types/p2/router-subprocess.d.ts +2 -0
  51. package/lib/types/p2/spill-retention.d.ts +74 -0
  52. package/lib/types/p2/worlds.d.ts +11 -0
  53. package/lib/types/pool.d.ts +73 -11
  54. package/lib/types/protocol.d.ts +63 -0
  55. package/lib/types/routes.d.ts +18 -0
  56. package/lib/types/sftp.d.ts +114 -8
  57. package/lib/types/store.d.ts +34 -0
  58. package/lib/types/timeouts.d.ts +14 -0
  59. package/lib/{worlds-C6Xha1mQ.js → worlds-Be1YE2Ot.js} +727 -78
  60. package/package.json +1 -1
  61. package/src/archive.ts +41 -9
  62. package/src/changes/recorder.ts +227 -31
  63. package/src/changes/status.ts +37 -1
  64. package/src/client/CodeEditor.tsx +84 -2
  65. package/src/client/ConnectionStatus.tsx +130 -0
  66. package/src/client/DirectoryFlow.tsx +40 -5
  67. package/src/client/DoctorPanel.tsx +202 -0
  68. package/src/client/DownloadDock.tsx +13 -25
  69. package/src/client/EditorPane.tsx +291 -7
  70. package/src/client/HostsView.tsx +17 -8
  71. package/src/client/QuickOpen.tsx +371 -0
  72. package/src/client/RemoteDirectoryPicker.tsx +54 -3
  73. package/src/client/RemoteExplorer.tsx +879 -160
  74. package/src/client/RemoteRoot.tsx +178 -1
  75. package/src/client/SearchView.tsx +180 -6
  76. package/src/client/SettingsHosts.tsx +1 -1
  77. package/src/client/TerminalView.tsx +174 -9
  78. package/src/client/WorkspaceWizard.tsx +110 -16
  79. package/src/client/WorkspacesView.tsx +22 -6
  80. package/src/client/api.ts +197 -11
  81. package/src/client/changes/ChangesDock.tsx +35 -8
  82. package/src/client/changes/undo-affordance.ts +33 -0
  83. package/src/client/changes/undo-context.ts +14 -18
  84. package/src/client/changes/undo-target.ts +139 -0
  85. package/src/client/connection.ts +264 -0
  86. package/src/client/doctor.ts +441 -0
  87. package/src/client/download.ts +148 -12
  88. package/src/client/downloads.ts +43 -2
  89. package/src/client/file-open-probe.ts +83 -0
  90. package/src/client/i18n.ts +244 -0
  91. package/src/client/index.tsx +5 -2
  92. package/src/client/quickopen-model.ts +778 -0
  93. package/src/client/remote-file-open.ts +21 -33
  94. package/src/client/scm/DiffView.tsx +116 -6
  95. package/src/client/scm/ScmPanel.tsx +19 -0
  96. package/src/client/scm/actions.ts +34 -2
  97. package/src/client/scm/diff-model.ts +33 -37
  98. package/src/client/scm/git-cache.ts +61 -4
  99. package/src/client/scm/read-queue.ts +33 -2
  100. package/src/client/scm/stage-queue.ts +72 -1
  101. package/src/client/scm/status-map.ts +22 -1
  102. package/src/client/store.tsx +704 -21
  103. package/src/client/vsc/FindWidget.tsx +20 -0
  104. package/src/client/vsc/kit.tsx +115 -6
  105. package/src/client/vsc/reveal-line.ts +33 -14
  106. package/src/client/vsc/save-shortcut.ts +131 -0
  107. package/src/client/vsc/vsc.css +419 -0
  108. package/src/deploy.ts +185 -33
  109. package/src/git-format.ts +136 -22
  110. package/src/git-ops.ts +14 -6
  111. package/src/http.ts +80 -12
  112. package/src/importers.ts +80 -21
  113. package/src/index.ts +21 -1
  114. package/src/p2/file-refs.ts +112 -10
  115. package/src/p2/helper-rpc.ts +73 -36
  116. package/src/p2/router-spill.ts +96 -1
  117. package/src/p2/router-subprocess.ts +18 -5
  118. package/src/p2/spill-retention.ts +134 -0
  119. package/src/p2/ssh-proc.ts +22 -0
  120. package/src/p2/worlds.ts +24 -0
  121. package/src/pool.ts +329 -47
  122. package/src/protocol.ts +66 -0
  123. package/src/routes.ts +251 -43
  124. package/src/sftp.ts +486 -26
  125. package/src/store.ts +207 -85
  126. package/src/terminal.ts +38 -2
  127. package/src/timeouts.ts +14 -0
  128. package/src/tools.ts +14 -5
@@ -0,0 +1,441 @@
1
+ /**
2
+ * Remote environment doctor: ONE POSIX `sh` line that probes what the remote
3
+ * actually has, plus the pure parser that turns its output into three-state
4
+ * rows.
5
+ *
6
+ * Why this module exists
7
+ * ----------------------
8
+ * The client already depends on remote tools whose absence is invisible until
9
+ * something behaves worse than it should: without `rg` a content search falls
10
+ * back to a recursive `grep` that never finishes on a large tree; without
11
+ * `setsid --wait` a timeout can no longer end the remote command group and the
12
+ * only trace is a host-console warning; a full `$HOME` shows up as a failed
13
+ * push. Each of those was already documented as a known limit — this puts the
14
+ * same evidence on one screen instead of leaving it to guesswork.
15
+ *
16
+ * The three-state rule
17
+ * --------------------
18
+ * `missing` is a POSITIVE fact: the remote answered "no such command". Every
19
+ * other outcome — no marker line, an empty capture, an unparseable row, a
20
+ * link that dropped before the exit status, a budget that ran out — is
21
+ * IGNORANCE and must be reported as `unknown` with the reason. Encoding
22
+ * ignorance as a negative result is the incident-index defect this feature
23
+ * exists to avoid: a user who is told "rg is not installed" when the answer is
24
+ * actually "the probe did not run" will install the wrong thing and still be
25
+ * broken.
26
+ *
27
+ * Where the evidence comes from
28
+ * -----------------------------
29
+ * Every probe line carries a marker (`@@RVS-DOC <key> <state> <detail>`) so
30
+ * the parser never has to guess from human-readable output, and the shell
31
+ * folds each detail onto one line — output content can therefore never forge
32
+ * or split a marker. The script merges stderr into the capture (`2>&1`) and
33
+ * never uses `2>/dev/null`: dropping stderr is how the "permission denied"
34
+ * case used to look exactly like "not installed" (the incident index calls
35
+ * that out by name).
36
+ *
37
+ * What the tools' own failures look like
38
+ * --------------------------------------
39
+ * A shell reports exit 127 BOTH for "no such command" and for a binary that
40
+ * exists but cannot start (missing shared library, broken interpreter). The
41
+ * first is a positive answer, the second is ignorance — so the probe asks
42
+ * `command -v` which one happened instead of assuming. `sshd` is looked up at
43
+ * its absolute locations first: on Debian-family hosts a non-root login PATH
44
+ * does not contain `/usr/sbin`, and a bare lookup would report a running sshd
45
+ * as missing.
46
+ *
47
+ * Pure module: no React, no DOM, no i18n copy (labels are i18n KEYS; the panel
48
+ * translates them, so this file can be gate-evaluated in plain node).
49
+ */
50
+
51
+ export type DoctorState = 'ok' | 'missing' | 'unknown'
52
+
53
+ /** One row of the report. */
54
+ export interface DoctorItem {
55
+ /** Stable probe id (`os`, `rg`, …) — also what the copied report groups by. */
56
+ key: string
57
+ /** i18n key for the row label. Translated by the panel, not here. */
58
+ label: string
59
+ state: DoctorState
60
+ /**
61
+ * Evidence: the remote's own words, or the reason this probe could not
62
+ * decide. Never empty for `unknown` — an unexplainable unknown is noise.
63
+ */
64
+ detail: string
65
+ }
66
+
67
+ export interface DoctorProbe {
68
+ key: string
69
+ label: string
70
+ }
71
+
72
+ /**
73
+ * Probe order is report order: environment first, then the tools the client
74
+ * actually depends on, then the host-side facts (disk, helper installs).
75
+ */
76
+ export const DOCTOR_PROBES: readonly DoctorProbe[] = [
77
+ { key: 'os', label: 'doctor.item.os' },
78
+ { key: 'libc', label: 'doctor.item.libc' },
79
+ { key: 'git', label: 'doctor.item.git' },
80
+ { key: 'rg', label: 'doctor.item.rg' },
81
+ { key: 'tar', label: 'doctor.item.tar' },
82
+ { key: 'setsid', label: 'doctor.item.setsid' },
83
+ { key: 'disk', label: 'doctor.item.disk' },
84
+ { key: 'nproc', label: 'doctor.item.nproc' },
85
+ { key: 'memory', label: 'doctor.item.memory' },
86
+ { key: 'helpers', label: 'doctor.item.helpers' },
87
+ { key: 'sshd', label: 'doctor.item.sshd' },
88
+ ]
89
+
90
+ /** Prefix of every probe line. Keep in sync with the script below. */
91
+ export const DOCTOR_MARK = '@@RVS-DOC'
92
+
93
+ /**
94
+ * State words for the badge and the copied report. Kept beside the parser
95
+ * because both the panel and `formatDoctorReport` need the same mapping; the
96
+ * values are listed in `DYNAMIC_KEYS` since no literal `t()` call reaches them.
97
+ */
98
+ export const DOCTOR_STATE_KEY: Record<DoctorState, string> = {
99
+ ok: 'doctor.state.ok',
100
+ missing: 'doctor.state.missing',
101
+ unknown: 'doctor.state.unknown',
102
+ }
103
+
104
+ /**
105
+ * Budget for the whole probe line. It is a handful of local commands over one
106
+ * exec channel; 20 s leaves room for a slow sshd/`ldd` start without keeping
107
+ * the panel spinning behind a dead link.
108
+ */
109
+ export const DOCTOR_TIMEOUT_MS = 20_000
110
+
111
+ /**
112
+ * Remote install root, mirrored from `REMOTE_ROOT` in `src/deploy.ts`.
113
+ *
114
+ * The client bundle CANNOT import that module (`deploy.ts` pulls `node:crypto`,
115
+ * `node:fs` and the SFTP/SSH layer, which the client build's purity gate in
116
+ * `tsdown.config.ts` rejects), so the literal has to live here.
117
+ * `scripts/check-doctor.mjs` imports `REMOTE_ROOT` from `deploy.ts` and fails
118
+ * when the two drift. That cross-check matters: the first version of this probe
119
+ * looked for a file name the deploy pipeline never writes, so every real host
120
+ * reported "no helper installed" — a self-check that guesses the layout is
121
+ * worse than none.
122
+ */
123
+ export const HELPER_ROOT = '~/.dsh-helpers'
124
+
125
+ /**
126
+ * The remote probe line.
127
+ *
128
+ * Written as one script rather than one exec call per probe: the round trip
129
+ * (and the channel slot) is the expensive part, and a partial report is still
130
+ * useful. Every branch emits exactly one marker line, and the line ends with
131
+ * `exit 0` so a stray tool's exit code cannot turn a complete report into a
132
+ * failed one.
133
+ *
134
+ * `rv_emit` folds the detail onto ONE line: a multi-line capture would either
135
+ * lose its tail in the report or, worse, let decoded output masquerade as a
136
+ * marker for another probe.
137
+ */
138
+ const SCRIPT = `export LC_ALL=C
139
+ rv_emit() {
140
+ rv_state=$2
141
+ rv_detail=$3
142
+ rv_detail=$(printf '%s' "$rv_detail" | tr '\\n\\r\\t' ' ' | cut -c1-800)
143
+ if [ -z "$rv_detail" ]; then rv_detail='-'; fi
144
+ printf '@@RVS-DOC %s %s %s\\n' "$1" "$rv_state" "$rv_detail"
145
+ }
146
+ rv_cmd() {
147
+ rv_key=$1
148
+ shift
149
+ rv_out=$("$@" 2>&1)
150
+ rv_rc=$?
151
+ if [ "$rv_rc" -eq 127 ]; then
152
+ if command -v "$1" >/dev/null 2>&1; then
153
+ rv_emit "$rv_key" unknown "exit 127 but present in PATH: $rv_out"
154
+ else
155
+ rv_emit "$rv_key" missing "command not found: $1"
156
+ fi
157
+ return
158
+ fi
159
+ if [ "$rv_rc" -ne 0 ]; then rv_emit "$rv_key" unknown "exit $rv_rc: $rv_out"; return; fi
160
+ rv_line=$(printf '%s\\n' "$rv_out" | head -n 1)
161
+ if [ -z "$rv_line" ]; then rv_emit "$rv_key" unknown "exit 0 with no output"; return; fi
162
+ rv_emit "$rv_key" ok "$rv_line"
163
+ }
164
+ rv_helpers() {
165
+ if [ -z "$HOME" ]; then
166
+ rv_emit helpers unknown "HOME is not set, so the install root cannot be located"
167
+ return
168
+ fi
169
+ rv_root=${HELPER_ROOT}
170
+ if [ ! -e "$rv_root" ]; then
171
+ rv_emit helpers missing "no $rv_root (nothing has been pushed to this host)"
172
+ return
173
+ fi
174
+ if [ ! -d "$rv_root" ]; then
175
+ rv_emit helpers unknown "$rv_root exists but is not a directory"
176
+ return
177
+ fi
178
+ if [ ! -r "$rv_root" ] || [ ! -x "$rv_root" ]; then
179
+ rv_err=$(ls -a "$rv_root" 2>&1)
180
+ rv_emit helpers unknown "cannot read $rv_root: $rv_err"
181
+ return
182
+ fi
183
+ rv_list=''
184
+ rv_dirs=0
185
+ for rv_dir in "$rv_root"/*/; do
186
+ [ -d "$rv_dir" ] || continue
187
+ rv_dirs=$((rv_dirs + 1))
188
+ rv_manifest=$rv_dir/manifest.json
189
+ [ -f "$rv_manifest" ] || continue
190
+ rv_name=$(basename "$rv_dir")
191
+ rv_ver=$(grep -o '"version"[[:space:]]*:[[:space:]]*"[^"]*"' "$rv_manifest" | head -n 1 | cut -d'"' -f4)
192
+ if [ -z "$rv_ver" ]; then rv_list="$rv_list $rv_name=(version unparsed)"; else rv_list="$rv_list $rv_name=$rv_ver"; fi
193
+ done
194
+ if [ -n "$rv_list" ]; then rv_emit helpers ok "installed:$rv_list"; return; fi
195
+ if [ "$rv_dirs" -gt 0 ]; then
196
+ rv_emit helpers unknown "$rv_dirs helper dir(s) under $rv_root but no readable manifest.json"
197
+ return
198
+ fi
199
+ if [ -f "$rv_root/manifest.json" ]; then
200
+ rv_artifact=$(grep -o '"artifact"[[:space:]]*:[[:space:]]*"[^"]*"' "$rv_root/manifest.json" | head -n 1 | cut -d'"' -f4)
201
+ if [ -z "$rv_artifact" ]; then
202
+ rv_emit helpers ok "root manifest present (artifact unparsed)"
203
+ else
204
+ rv_emit helpers ok "root manifest: $rv_artifact"
205
+ fi
206
+ return
207
+ fi
208
+ rv_emit helpers missing "no manifest.json under $rv_root (nothing has been pushed to this host)"
209
+ }
210
+ rv_cmd os uname -sm
211
+ rv_cmd libc ldd --version
212
+ rv_cmd git git --version
213
+ rv_cmd rg rg --version
214
+ rv_cmd tar tar --version
215
+ rv_out=$(setsid --wait sh -c 'exit 7' 2>&1)
216
+ rv_rc=$?
217
+ if [ "$rv_rc" -eq 7 ]; then
218
+ rv_emit setsid ok "setsid --wait works (child exit 7 propagated)"
219
+ elif [ "$rv_rc" -eq 127 ]; then
220
+ if command -v setsid >/dev/null 2>&1; then
221
+ rv_emit setsid unknown "exit 127 but present in PATH: $rv_out"
222
+ else
223
+ rv_emit setsid missing "command not found: setsid"
224
+ fi
225
+ else
226
+ case "$rv_out" in
227
+ *nrecognized*|*llegal*|*nvalid*|*"not supported"*|*"unknown option"*)
228
+ rv_emit setsid missing "setsid rejects --wait: $rv_out" ;;
229
+ *)
230
+ rv_emit setsid unknown "exit $rv_rc: $rv_out" ;;
231
+ esac
232
+ fi
233
+ rv_out=$(df -h "$HOME" 2>&1)
234
+ rv_rc=$?
235
+ if [ "$rv_rc" -eq 127 ]; then
236
+ if command -v df >/dev/null 2>&1; then
237
+ rv_emit disk unknown "exit 127 but present in PATH: $rv_out"
238
+ else
239
+ rv_emit disk missing "command not found: df"
240
+ fi
241
+ elif [ "$rv_rc" -ne 0 ]; then
242
+ rv_emit disk unknown "exit $rv_rc: $rv_out"
243
+ else
244
+ rv_row=$(printf '%s\\n' "$rv_out" | grep -v '^Filesystem' | grep -v '^[[:space:]]*$' | tail -n 1)
245
+ if [ -z "$rv_row" ]; then rv_emit disk unknown "df printed no filesystem row: $rv_out"; else rv_emit disk ok "$rv_row"; fi
246
+ fi
247
+ rv_cmd nproc nproc
248
+ rv_out=$(free -m 2>&1)
249
+ rv_rc=$?
250
+ if [ "$rv_rc" -eq 127 ]; then
251
+ if command -v free >/dev/null 2>&1; then
252
+ rv_emit memory unknown "exit 127 but present in PATH: $rv_out"
253
+ else
254
+ rv_emit memory missing "command not found: free"
255
+ fi
256
+ elif [ "$rv_rc" -ne 0 ]; then
257
+ rv_emit memory unknown "exit $rv_rc: $rv_out"
258
+ else
259
+ rv_row=$(printf '%s\\n' "$rv_out" | grep '^Mem:' | head -n 1)
260
+ if [ -z "$rv_row" ]; then rv_emit memory unknown "free printed no Mem: row: $rv_out"; else rv_emit memory ok "$rv_row"; fi
261
+ fi
262
+ rv_helpers
263
+ rv_sshd_bin=''
264
+ for rv_cand in /usr/sbin/sshd /sbin/sshd; do
265
+ if [ -x "$rv_cand" ]; then rv_sshd_bin=$rv_cand; break; fi
266
+ done
267
+ if [ -z "$rv_sshd_bin" ]; then
268
+ rv_found=$(command -v sshd 2>&1)
269
+ if [ $? -eq 0 ] && [ -n "$rv_found" ]; then rv_sshd_bin=$rv_found; fi
270
+ fi
271
+ if [ -z "$rv_sshd_bin" ]; then
272
+ rv_emit sshd unknown "sshd not found in PATH, /usr/sbin/sshd or /sbin/sshd; MaxSessions is unknown"
273
+ else
274
+ rv_out=$("$rv_sshd_bin" -T 2>&1)
275
+ rv_rc=$?
276
+ if [ "$rv_rc" -ne 0 ]; then
277
+ rv_emit sshd unknown "exit $rv_rc: $rv_out"
278
+ else
279
+ rv_row=$(printf '%s\\n' "$rv_out" | grep -i '^maxsessions' | head -n 1)
280
+ if [ -z "$rv_row" ]; then rv_emit sshd unknown "sshd -T printed no MaxSessions line"; else rv_emit sshd ok "$rv_row"; fi
281
+ fi
282
+ fi
283
+ exit 0
284
+ `
285
+
286
+ /** The single remote command the panel runs through `api.exec`. */
287
+ export function doctorScript(): string {
288
+ return SCRIPT
289
+ }
290
+
291
+ const KNOWN = new Map(DOCTOR_PROBES.map(probe => [probe.key, probe]))
292
+
293
+ /** `@@RVS-DOC <key> <state> <detail…>` — anchored, so content cannot forge it. */
294
+ const MARKER = /^@@RVS-DOC ([a-z0-9-]+) (ok|missing|unknown)(?: (.*))?$/
295
+
296
+ /** Flatten whitespace and cap the length, so one detail stays one line. */
297
+ function oneLine(text: string, cap = 240): string {
298
+ const flat = text.replace(/\s+/g, ' ').trim()
299
+ return flat.length <= cap ? flat : `${flat.slice(0, cap - 1)}…`
300
+ }
301
+
302
+ function isCount(value: string): boolean {
303
+ return /^\d+$/.test(value)
304
+ }
305
+
306
+ /**
307
+ * `df -h` row → "avail 60G · use 40% · /dev/sda1 on /".
308
+ *
309
+ * Column positions are the same in GNU, busybox and BSD `df -h`
310
+ * (`filesystem size used avail use% mount`). A row that does not fit is not an
311
+ * error and not a "no space" verdict: it is unparseable, so the row stays
312
+ * `unknown` with the raw line as evidence.
313
+ */
314
+ function describeDisk(row: string): { state: DoctorState; detail: string } {
315
+ const cols = row.split(/\s+/).filter(col => col !== '')
316
+ if (cols.length < 6 || !/^\d+(?:[.,]\d+)?[KMGTPE]?i?$/.test(cols[3]) || !/^(?:\d+%|-)$/.test(cols[4])) {
317
+ return { state: 'unknown', detail: `unexpected df row: ${row}` }
318
+ }
319
+ return { state: 'ok', detail: `avail ${cols[3]} · use ${cols[4]} · ${cols[0]} on ${cols.slice(5).join(' ')}` }
320
+ }
321
+
322
+ /**
323
+ * `free -m` Mem row → "total 15884M · used 12000M · free 1000M".
324
+ *
325
+ * Only the first four columns are labelled: procps versions disagree about the
326
+ * tail (`shared buffers cached` in older ones, `available` in current ones), so
327
+ * naming column 7 would print "available 2484M" out of a host where it actually
328
+ * means `cached`. Three certain numbers beat four with one quietly wrong label.
329
+ */
330
+ function describeMemory(row: string): { state: DoctorState; detail: string } {
331
+ const cols = row.split(/\s+/).filter(col => col !== '')
332
+ if (cols.length < 4 || cols[0] !== 'Mem:' || !isCount(cols[1]) || !isCount(cols[2]) || !isCount(cols[3])) {
333
+ return { state: 'unknown', detail: `unexpected free row: ${row}` }
334
+ }
335
+ return { state: 'ok', detail: `total ${cols[1]}M · used ${cols[2]}M · free ${cols[3]}M` }
336
+ }
337
+
338
+ /** Per-key reinterpretation of a successful capture; undefined = keep as-is. */
339
+ function refine(key: string, detail: string): { state: DoctorState; detail: string } | undefined {
340
+ if (key === 'disk') return describeDisk(detail)
341
+ if (key === 'memory') return describeMemory(detail)
342
+ return undefined
343
+ }
344
+
345
+ function normalize(probe: DoctorProbe, state: DoctorState, rawDetail: string): DoctorItem {
346
+ // Longer than the default cap: a helper listing carries one entry per
347
+ // installed version and must not be cut in the middle for no reason.
348
+ const detail = oneLine(rawDetail, 600)
349
+ if (state === 'ok') {
350
+ // A "success" that produced no output proves nothing about the item.
351
+ if (detail === '') return { key: probe.key, label: probe.label, state: 'unknown', detail: 'the probe reported success but carried no output' }
352
+ const refined = refine(probe.key, detail)
353
+ if (refined !== undefined) return { key: probe.key, label: probe.label, state: refined.state, detail: refined.detail }
354
+ return { key: probe.key, label: probe.label, state: 'ok', detail }
355
+ }
356
+ if (state === 'missing') {
357
+ return { key: probe.key, label: probe.label, state: 'missing', detail: detail === '' ? 'reported not installed by the remote probe' : detail }
358
+ }
359
+ return { key: probe.key, label: probe.label, state: 'unknown', detail: detail === '' ? 'the probe could not decide' : detail }
360
+ }
361
+
362
+ function allUnknown(reason: string): DoctorItem[] {
363
+ const detail = oneLine(reason, 300)
364
+ return DOCTOR_PROBES.map(probe => ({ key: probe.key, label: probe.label, state: 'unknown' as DoctorState, detail }))
365
+ }
366
+
367
+ function wholeRunReason(stderr: string): string {
368
+ const err = oneLine(stderr, 200)
369
+ return err === ''
370
+ ? 'the remote command did not report an exit status (the link dropped or the time budget ran out)'
371
+ : `the remote command did not report an exit status; stderr: ${err}`
372
+ }
373
+
374
+ /**
375
+ * Parse the probe output into one row per known probe.
376
+ *
377
+ * @param exitCode - the remote exit status, or `null` when the channel died /
378
+ * the budget ran out. `null` invalidates the WHOLE run: partial stdout from a
379
+ * killed command is not evidence about the probes it never reached, so every
380
+ * row becomes `unknown` rather than some rows silently keeping stale states.
381
+ */
382
+ export function parseDoctor(stdout: string, stderr: string, exitCode: number | null): DoctorItem[] {
383
+ if (exitCode === null) return allUnknown(wholeRunReason(stderr))
384
+ const found = new Map<string, { state: DoctorState; detail: string }>()
385
+ for (const raw of stdout.split('\n')) {
386
+ const line = raw.endsWith('\r') ? raw.slice(0, -1) : raw
387
+ const match = MARKER.exec(line)
388
+ if (match === null) continue
389
+ const key = match[1]
390
+ // A marker for a probe this build does not know is ignored, never rendered.
391
+ if (!KNOWN.has(key) || found.has(key)) continue
392
+ const detail = (match[3] ?? '').trim()
393
+ // `-` is the script's "nothing to report" placeholder, not a detail.
394
+ found.set(key, { state: match[2] as DoctorState, detail: detail === '-' ? '' : detail })
395
+ }
396
+ return DOCTOR_PROBES.map((probe) => {
397
+ const hit = found.get(probe.key)
398
+ if (hit === undefined) {
399
+ // Absent evidence is NOT a negative answer. This is the line that keeps a
400
+ // truncated output from ever being reported as "not installed".
401
+ return {
402
+ key: probe.key,
403
+ label: probe.label,
404
+ state: 'unknown' as DoctorState,
405
+ detail: 'no marker line in the captured output (the probe did not answer, or the output was truncated)',
406
+ }
407
+ }
408
+ return normalize(probe, hit.state, hit.detail)
409
+ })
410
+ }
411
+
412
+ /**
413
+ * The all-unknown report for a run that never produced a result at all (exec
414
+ * rejected: dead link, timeout at the client, host refused the route). Kept
415
+ * separate so the panel cannot accidentally drop a partial list on the floor.
416
+ */
417
+ export function doctorFailure(reason: string): DoctorItem[] {
418
+ return allUnknown(reason)
419
+ }
420
+
421
+ /**
422
+ * Plain-text report for "copy all" — what the user pastes into a support
423
+ * thread. One line per probe, states spelled out (no color codes to decode),
424
+ * and every detail verbatim so the reply can be checked instead of trusted.
425
+ */
426
+ export function formatDoctorReport(
427
+ alias: string,
428
+ items: DoctorItem[],
429
+ t: (key: string) => string,
430
+ at: number = Date.now(),
431
+ ): string {
432
+ const lines = [
433
+ t('doctor.reportTitle').replace('{alias}', alias),
434
+ t('doctor.reportAt').replace('{at}', new Date(at).toISOString()),
435
+ '',
436
+ ]
437
+ for (const item of items) {
438
+ lines.push(`${t(DOCTOR_STATE_KEY[item.state])} ${t(item.label)}: ${item.detail}`)
439
+ }
440
+ return lines.join('\n')
441
+ }
@@ -17,7 +17,16 @@
17
17
  import { REMOTE_API, selectionDownloadName } from '../protocol.ts'
18
18
 
19
19
  /** What one download attempt ended as. */
20
- export type DownloadOutcome = 'saved' | 'downloaded'
20
+ export type DownloadOutcome =
21
+ /** Bytes went through the save picker into the user's chosen file. */
22
+ | 'saved-picker'
23
+ /** Bytes were fully received and then handed to the browser to save. */
24
+ | 'saved-browser'
25
+ /**
26
+ * The URL was handed to the browser, which now owns the transfer: its bytes,
27
+ * its failures and its cancel. The panel must NOT report completion.
28
+ */
29
+ | 'handedOff'
21
30
 
22
31
  /** One progress sample: `total` is absent for a streamed archive (chunked). */
23
32
  export interface DownloadProgress {
@@ -25,6 +34,28 @@ export interface DownloadProgress {
25
34
  total?: number
26
35
  }
27
36
 
37
+ /**
38
+ * Largest body the fallback path buffers before handing the URL to the browser.
39
+ *
40
+ * The save picker streams straight to disk, but a browser without the File
41
+ * System Access API can only be given a URL. Owning the transfer for small and
42
+ * medium files is what lets the panel see a Host error (a 502 JSON used to be
43
+ * saved as a file), report real progress and cancel; a 64 MiB ceiling keeps a
44
+ * multi-GB artifact from being assembled in the tab's memory.
45
+ */
46
+ export const FALLBACK_BUFFER_MAX_BYTES = 64 * 1024 * 1024
47
+
48
+ /**
49
+ * What the fallback should do with a body of `declaredTotal` bytes.
50
+ *
51
+ * `handoff` means the browser must own the transfer: too large to assemble in
52
+ * memory, and no failure/progress/cancel can be reported for it. Exported pure
53
+ * so the gate can pin the boundary without allocating 64 MiB.
54
+ */
55
+ export function fallbackPlan(declaredTotal: number | undefined): 'buffer' | 'handoff' {
56
+ return declaredTotal !== undefined && declaredTotal > FALLBACK_BUFFER_MAX_BYTES ? 'handoff' : 'buffer'
57
+ }
58
+
28
59
  /** Hooks the runner uses for the progress panel and its cancel button. */
29
60
  export interface SaveOptions {
30
61
  onProgress?: (progress: DownloadProgress) => void
@@ -108,6 +139,114 @@ function abortError(): Error {
108
139
  return error
109
140
  }
110
141
 
142
+ /** Hand a fully received body to the browser's own "save file" path. */
143
+ export function saveBytesViaBrowser(bytes: readonly Uint8Array[], fileName: string): void {
144
+ const blob = new Blob([...bytes] as unknown as BlobPart[])
145
+ const url = URL.createObjectURL(blob)
146
+ triggerDownload(url, fileName)
147
+ // The click has already started the read; revoking later keeps slower shells
148
+ // (and the Electron download hook) able to finish it.
149
+ const revoke = (): void => {
150
+ try {
151
+ URL.revokeObjectURL(url)
152
+ } catch {
153
+ // Already revoked.
154
+ }
155
+ }
156
+ const timer = setTimeout(revoke, 60_000)
157
+ timer.unref?.()
158
+ }
159
+
160
+ /**
161
+ * Fallback for browsers without the save picker (Firefox, some Electron shells).
162
+ *
163
+ * The old shape clicked an anchor and immediately reported COMPLETE, so the
164
+ * panel claimed a saved file before a byte had landed, a Host error response
165
+ * (502 JSON) was saved as a file, and the cancel button did nothing. This path
166
+ * owns the transfer whenever the body is small enough to buffer:
167
+ *
168
+ * - `fetch` first, so a non-2xx Host answer is a FAILED download, not a file;
169
+ * - the body is read chunk by chunk (progress + AbortSignal), capped at
170
+ * {@link FALLBACK_BUFFER_MAX_BYTES};
171
+ * - only a complete body is handed to the browser (`saved-browser`);
172
+ * - a body known to be larger (or an unknown-length archive that grows past the
173
+ * cap) is handed to the browser as a URL (`handedOff`) — the panel then says
174
+ * the browser owns it instead of claiming a completion it cannot verify.
175
+ */
176
+ async function saveViaFallback(href: string, fileName: string, options: SaveOptions): Promise<DownloadOutcome> {
177
+ const signal = options.signal
178
+ // Read through a closure: a direct signal?.aborted === true check above would
179
+ // narrow the optional chain and make every later comparison look impossible.
180
+ const cancelled = (): boolean => signal?.aborted === true
181
+ if (cancelled()) throw abortError()
182
+ const canFetch = typeof fetch === 'function'
183
+ const canSaveBytes = canFetch && typeof URL !== 'undefined'
184
+ && typeof URL.createObjectURL === 'function' && typeof Blob !== 'undefined'
185
+ if (!canSaveBytes) {
186
+ triggerDownload(href, fileName)
187
+ return 'handedOff'
188
+ }
189
+ let response: Response
190
+ try {
191
+ response = await fetch(href, signal === undefined ? undefined : { signal })
192
+ } catch (error) {
193
+ if (cancelled()) throw abortError()
194
+ throw error
195
+ }
196
+ if (!response.ok || response.body === null) {
197
+ const detail = await response.text().catch(() => '')
198
+ throw new Error(detail.trim() === '' ? `HTTP ${response.status}` : detail.trim())
199
+ }
200
+ const lengthHeader = response.headers.get('content-length')
201
+ const parsedLength = lengthHeader === null ? Number.NaN : Number(lengthHeader)
202
+ const declared = Number.isFinite(parsedLength) && parsedLength >= 0 ? parsedLength : undefined
203
+ if (fallbackPlan(declared) === 'handoff') {
204
+ // Too large to assemble in memory: the browser streams it to disk itself.
205
+ try {
206
+ await response.body.cancel()
207
+ } catch {
208
+ // Already gone.
209
+ }
210
+ triggerDownload(href, fileName)
211
+ return 'handedOff'
212
+ }
213
+ const chunks: Uint8Array[] = []
214
+ let loaded = 0
215
+ const reader = response.body.getReader()
216
+ try {
217
+ options.onProgress?.({ loaded, ...(declared === undefined ? {} : { total: declared }) })
218
+ for (;;) {
219
+ if (cancelled()) throw abortError()
220
+ const { done, value } = await reader.read()
221
+ if (done) break
222
+ loaded += value.byteLength
223
+ if (loaded > FALLBACK_BUFFER_MAX_BYTES) {
224
+ // Unknown-length body (a chunked tar archive) crossed the cap: abandon
225
+ // this read and hand the URL over — a fresh request, no partial file.
226
+ try {
227
+ await reader.cancel()
228
+ } catch {
229
+ // Already gone.
230
+ }
231
+ triggerDownload(href, fileName)
232
+ return 'handedOff'
233
+ }
234
+ chunks.push(value)
235
+ options.onProgress?.({ loaded, ...(declared === undefined ? {} : { total: declared }) })
236
+ }
237
+ } catch (error) {
238
+ try {
239
+ await reader.cancel()
240
+ } catch {
241
+ // Already gone.
242
+ }
243
+ if (cancelled()) throw abortError()
244
+ throw error
245
+ }
246
+ saveBytesViaBrowser(chunks, fileName)
247
+ return 'saved-browser'
248
+ }
249
+
111
250
  /** Delete the just-created target after a failed transfer (best effort). */
112
251
  async function discard(handle: SaveFileHandle): Promise<void> {
113
252
  try {
@@ -123,18 +262,17 @@ async function discard(handle: SaveFileHandle): Promise<void> {
123
262
  *
124
263
  * The picker runs while the click's transient activation is still valid, so it
125
264
  * 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.
265
+ * activation, policy) falls back to {@link saveViaFallback} instead of failing
266
+ * the download outright.
128
267
  *
129
- * @returns `'saved'` for the picked destination, `'downloaded'` for the
130
- * browser-default fallback.
268
+ * @returns `'saved-picker'` for the picked destination, `'saved-browser'` when
269
+ * the fallback received every byte and handed them to the browser, and
270
+ * `'handedOff'` when the browser owns an unverified transfer.
131
271
  */
132
272
  export async function saveRemoteUrl(href: string, fileName: string, options: SaveOptions = {}): Promise<DownloadOutcome> {
133
273
  const picker = (globalThis as unknown as SaveFilePickerApi).showSaveFilePicker
134
274
  if (typeof picker !== 'function') {
135
- if (options.signal?.aborted === true) throw abortError()
136
- triggerDownload(href, fileName)
137
- return 'downloaded'
275
+ return saveViaFallback(href, fileName, options)
138
276
  }
139
277
  let handle: SaveFileHandle
140
278
  try {
@@ -142,9 +280,7 @@ export async function saveRemoteUrl(href: string, fileName: string, options: Sav
142
280
  } catch (error) {
143
281
  if (error instanceof Error && error.name === 'AbortError') throw error
144
282
  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'
283
+ return saveViaFallback(href, fileName, options)
148
284
  }
149
285
  throw error
150
286
  }
@@ -192,7 +328,7 @@ export async function saveRemoteUrl(href: string, fileName: string, options: Sav
192
328
  await discard(handle)
193
329
  throw error
194
330
  }
195
- return 'saved'
331
+ return 'saved-picker'
196
332
  }
197
333
 
198
334
  /** Save one remote file (fresh name from its POSIX basename). */