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,778 @@
1
+ /**
2
+ * Ctrl+P quick open: the remote file index and its fuzzy matcher.
3
+ *
4
+ * Pure logic on purpose (no React, no store, no `api` import): the pixels live
5
+ * in `QuickOpen.tsx`, and everything that has to be provable in Node lives
6
+ * here — scoring, ranking, the index lifecycle, the remote command and its
7
+ * parser. The only I/O this module performs is the injected `exec`, so a gate
8
+ * can drive it with a stub and never touch a real host.
9
+ *
10
+ * The incident-index rules that shape every decision below:
11
+ *
12
+ * - **A failed listing is not an empty listing.** {@link buildFileIndex}
13
+ * REJECTS a run that did not produce a trustworthy listing: a timed-out or
14
+ * transport-broken command, a command that never entered the workspace root,
15
+ * and a listing TOOL that exited non-zero without listing anything. Returning
16
+ * `[]` there would make "the host failed" look exactly like "this tree has no
17
+ * files".
18
+ * - **A capped listing is a bounded PREFIX, never a complete index.** THREE
19
+ * separate caps are enforced on the remote and reported as three separate
20
+ * facts: entries, bytes, and the walk depth of the no-ripgrep fallback. A
21
+ * listing that was cut anywhere says so in the result; nothing is silently
22
+ * dropped and called complete. A tool that listed SOME files and then exited
23
+ * non-zero is a fourth, separate fact (`toolStatus`) — its prefix is still
24
+ * useful, so it is kept but marked incomplete instead of being thrown away.
25
+ * - **A late answer must not overwrite a newer screen.** The index records which
26
+ * workspace it is for; a result (or failure) that lands after the user
27
+ * switched workspaces is discarded, because its relative paths would be
28
+ * resolved against the wrong root (see {@link applyIndexResult}).
29
+ *
30
+ * Privacy: the index is memory-only. Nothing here stores file content, and
31
+ * nothing is written to IndexedDB. The single persisted item is the recent-file
32
+ * list — absolute paths only — under a `dsh-remote-vs.` key, the same
33
+ * trade-off the panel-layout prefs already make.
34
+ */
35
+
36
+ /** Cap on one listing's entries; precedent: `src/p2/file-refs.ts` (same 50k). */
37
+ export const QUICKOPEN_MAX_ENTRIES = 50_000
38
+
39
+ /**
40
+ * Byte ceiling for one listing.
41
+ *
42
+ * Deliberately BELOW the Host's per-stream exec cap (2 MiB, `src/pool.ts`):
43
+ * when the transport truncates it appends its own marker line, which would
44
+ * arrive as a half-written path and be indistinguishable from a real one.
45
+ * Staying under it means every truncation is OURS and is reported as one.
46
+ */
47
+ export const QUICKOPEN_MAX_BYTES = 1_200_000
48
+
49
+ /**
50
+ * One listing command's budget. A cold `find` walk over a very large tree is
51
+ * the slow path (a few seconds with `rg`, minutes without it), and giving up
52
+ * too early turns "slow host" into "broken index".
53
+ */
54
+ export const QUICKOPEN_INDEX_TIMEOUT_MS = 120_000
55
+
56
+ /** Rows rendered in the result list. */
57
+ export const QUICKOPEN_RESULT_LIMIT = 50
58
+
59
+ /** Recent files remembered per host — paths only, never content. */
60
+ export const QUICKOPEN_RECENT_LIMIT = 20
61
+
62
+ /** localStorage key: `{ [alias]: string[] }`. Prefix kept for the panel's own data. */
63
+ export const QUICKOPEN_RECENT_KEY = 'dsh-remote-vs.recentFiles'
64
+
65
+ /**
66
+ * Sentinel the remote listing prints after its last path.
67
+ *
68
+ * It is what makes truncation OBSERVABLE without measuring bytes: the caps sit
69
+ * between the listing and this line, so the sentinel survives only when nothing
70
+ * was cut. Absent sentinel = the prefix ended at a cap (or the transport cut
71
+ * it), never "the tree is just that small".
72
+ */
73
+ const LIST_SENTINEL = 'RV-QO-END'
74
+
75
+ /**
76
+ * Depth-cap marker, printed by the `find` fallback only.
77
+ *
78
+ * `find` needs a depth bound on a huge tree, and a depth bound silently hides
79
+ * deep files — the exact "capped but reported complete" failure this feature
80
+ * exists to avoid. An uncapped `find` is not an option (it never finishes on a
81
+ * multi-million-file tree), so the cap is declared in-band instead: this line
82
+ * makes the normal depth bound a REPORTED fact rather than a lie of omission.
83
+ * It is deliberately conservative — it is printed even when the tree happens to
84
+ * be shallower than the bound, because proving "nothing is deeper" costs a
85
+ * second full walk.
86
+ */
87
+ const DEPTH_CAP_PREFIX = 'RV-QO-CAP '
88
+
89
+ /**
90
+ * Tool-status marker, printed to STDERR (so the stdout caps cannot eat it).
91
+ *
92
+ * The stdout pipeline's exit status is the last `head`'s, which means a listing
93
+ * tool that failed would otherwise be invisible: the index would look complete
94
+ * (or, worse, an empty index would look like an empty tree). The group captures
95
+ * the tool's own status and reports it out-of-band; {@link buildFileIndex} then
96
+ * decides between "reject" (nothing listed) and "keep, but incomplete".
97
+ */
98
+ const TOOL_STATUS_PREFIX = 'RV-QO-STATUS tool='
99
+
100
+ /** The Host's own exec-cap marker; should never appear, but never trust that. */
101
+ const HOST_CAP_MARKER = '[... truncated: output exceeded'
102
+
103
+ /**
104
+ * Directories a quick-open index never walks.
105
+ *
106
+ * The same evidence-based set the name search prunes (`src/client/scm/actions.ts`):
107
+ * build output and dependency caches are noise in a filename jump list and, on a
108
+ * large tree, most of the walk. Merged with the stock `@file` exclusions so both
109
+ * index surfaces agree on what a "file" is.
110
+ */
111
+ const EXCLUDED_DIRECTORIES: readonly string[] = [
112
+ '.git', 'node_modules', 'dist', 'build', 'out', 'coverage', 'target',
113
+ '.next', '.nuxt', '.turbo', '.venv', '__pycache__', '.pytest_cache',
114
+ '.mypy_cache', '.gradle',
115
+ ]
116
+
117
+ /**
118
+ * How deep the `find` fallback walks. `rg --files` has no depth limit and is
119
+ * the preferred path; this only bounds the no-ripgrep case, where an uncapped
120
+ * walk on a multi-million-file tree never finishes. 40 is far past any sane
121
+ * source layout (the name search needed 12 to see a deep file, and its cap was
122
+ * raised for exactly that reason).
123
+ *
124
+ * The bound is DECLARED in the listing stream ({@link DEPTH_CAP_PREFIX}), so an
125
+ * index built without ripgrep is never presented as complete.
126
+ */
127
+ export const QUICKOPEN_FALLBACK_MAX_DEPTH = 40
128
+
129
+ /** Characters that start a new "word" in a path, for the boundary bonus. */
130
+ const BOUNDARY_CHARACTERS = '/_-. '
131
+
132
+ const SCORE_PER_CHARACTER = 1
133
+ /**
134
+ * A consecutive run must outweigh the word-boundary bonus of the same
135
+ * characters spread over `a_b_c`: "the letters are adjacent" is by far the
136
+ * strongest signal that this is the name the user remembers. (Measured: with a
137
+ * lower value, `x/a_b_c.ts` outscored `x/abc.ts`.)
138
+ */
139
+ const SCORE_CONSECUTIVE = 12
140
+ const SCORE_BOUNDARY = 10
141
+ const SCORE_BASENAME = 6
142
+ /** Leading matched characters cost a little, capped so a deep hit is not doomed. */
143
+ const SCORE_LEADING_PENALTY_CAP = 10
144
+
145
+ /**
146
+ * Score one path against one query, or `undefined` when it does not match.
147
+ *
148
+ * Greedy left-to-right subsequence matching (not optimal alignment): it is what
149
+ * every editor's quick open does, it is O(path length), and — most importantly
150
+ * here — it is DETERMINISTIC, so equal scores can be tie-broken by path and the
151
+ * list never reshuffles between identical inputs.
152
+ *
153
+ * Weighting, in the order it matters for a filename jump list:
154
+ * - each matched character scores 1;
155
+ * - a run of consecutive characters beats the same characters spread out;
156
+ * - a match inside the LAST path segment (the file name) scores higher than one
157
+ * inside directories — the query is almost always "the name I remember";
158
+ * - a match at a word boundary (`/`, `_`, `-`, `.`, camel hump) beats one in the
159
+ * middle of a word.
160
+ *
161
+ * Case-insensitive in both directions; an empty query scores 0 (it matches
162
+ * everything, which is how "recent files" reuses this path).
163
+ */
164
+ export function fuzzyScore(query: string, path: string): number | undefined {
165
+ const needle = query.toLowerCase()
166
+ if (needle === '') return 0
167
+ if (needle.length > path.length) return undefined
168
+ const haystack = path.toLowerCase()
169
+ const lastSeparator = path.lastIndexOf('/')
170
+ let score = 0
171
+ let matched = 0
172
+ let previous = -2
173
+ let firstMatch = -1
174
+ for (let index = 0; index < haystack.length && matched < needle.length; index += 1) {
175
+ if (haystack[index] !== needle[matched]) continue
176
+ if (firstMatch < 0) firstMatch = index
177
+ score += SCORE_PER_CHARACTER
178
+ if (index === previous + 1) score += SCORE_CONSECUTIVE
179
+ if (index > lastSeparator) score += SCORE_BASENAME
180
+ if (isBoundaryAt(path, index)) score += SCORE_BOUNDARY
181
+ previous = index
182
+ matched += 1
183
+ }
184
+ if (matched < needle.length) return undefined
185
+ return score - Math.min(firstMatch, SCORE_LEADING_PENALTY_CAP)
186
+ }
187
+
188
+ /** Does a word start at `index` in `path`? */
189
+ function isBoundaryAt(path: string, index: number): boolean {
190
+ if (index === 0) return true
191
+ const previous = path[index - 1]
192
+ // Indices come from the lowercased copy, and a lowercase mapping can change
193
+ // the length for a handful of Unicode characters; never index past the end.
194
+ if (previous === undefined) return false
195
+ if (BOUNDARY_CHARACTERS.includes(previous)) return true
196
+ const current = path[index]
197
+ if (current === undefined) return false
198
+ // camelCase hump: "fooBar" lets "fb" match at the hump too.
199
+ return previous === previous.toLowerCase() && current !== current.toLowerCase()
200
+ }
201
+
202
+ /**
203
+ * Rank `paths` for one query.
204
+ *
205
+ * - Empty query: the caller's ORDER is the answer (that is what makes "recent
206
+ * files first" work without a second code path); the list is merely capped.
207
+ * - Otherwise: score descending, then path ascending. The path tie-break is not
208
+ * cosmetic — without it, equal-scoring matches would come out in whatever
209
+ * order the (remote-driven) input happened to have, and the list would jump
210
+ * around between two identical keystrokes.
211
+ *
212
+ * `truncated` here means "more matches than fit", which is a different fact
213
+ * from the index being truncated ({@link FileIndex.truncated}) — both are
214
+ * reported, and neither is swallowed.
215
+ */
216
+ export function rankFiles(
217
+ query: string,
218
+ paths: readonly string[],
219
+ limit: number,
220
+ ): { hits: string[]; truncated: boolean } {
221
+ const cap = Math.max(0, Math.floor(limit))
222
+ const needle = query.trim()
223
+ if (needle === '') {
224
+ return { hits: paths.slice(0, cap), truncated: paths.length > cap }
225
+ }
226
+ const scored: { path: string; score: number }[] = []
227
+ for (const path of paths) {
228
+ const score = fuzzyScore(needle, path)
229
+ if (score !== undefined) scored.push({ path, score })
230
+ }
231
+ scored.sort((left, right) => (right.score - left.score) || comparePaths(left.path, right.path))
232
+ return { hits: scored.slice(0, cap).map(item => item.path), truncated: scored.length > cap }
233
+ }
234
+
235
+ /** Byte-ish, locale-independent path order (stable across machines). */
236
+ function comparePaths(left: string, right: string): number {
237
+ if (left === right) return 0
238
+ return left < right ? -1 : 1
239
+ }
240
+
241
+ /**
242
+ * Character offsets matched by `query` inside `text`, for highlighting.
243
+ *
244
+ * Only a match that fits ENTIRELY inside the file name produces offsets: a hit
245
+ * whose characters are split between a directory and the name would otherwise
246
+ * highlight a misleading subset of the name. Returns `[]` when the query does
247
+ * not fully match, so the caller can render the name plain.
248
+ */
249
+ export function matchPositions(query: string, text: string): number[] {
250
+ const needle = query.trim().toLowerCase()
251
+ const haystack = text.toLowerCase()
252
+ const positions: number[] = []
253
+ if (needle === '') return positions
254
+ // Offsets index the ORIGINAL text, so a case mapping that changes the string
255
+ // length would misplace every highlight. Refusing to highlight is the honest
256
+ // degradation (the row still renders; it just has no marks).
257
+ if (haystack.length !== text.length) return positions
258
+ let at = 0
259
+ for (let index = 0; index < haystack.length && at < needle.length; index += 1) {
260
+ if (haystack[index] !== needle[at]) continue
261
+ positions.push(index)
262
+ at += 1
263
+ }
264
+ return at < needle.length ? [] : positions
265
+ }
266
+
267
+ /** Split a relative path into its directory part (trailing slash kept) and name. */
268
+ export function splitPath(path: string): { dir: string; name: string } {
269
+ const cut = path.lastIndexOf('/')
270
+ return cut < 0 ? { dir: '', name: path } : { dir: path.slice(0, cut + 1), name: path.slice(cut + 1) }
271
+ }
272
+
273
+ /** Absolute remote path for a workspace-relative one. */
274
+ export function absoluteFromRoot(root: string, relative: string): string {
275
+ const base = root.replace(/\/+$/, '')
276
+ const clean = relative.replace(/^\.\//, '').replace(/^\/+/, '')
277
+ return clean === '' ? base : `${base}/${clean}`
278
+ }
279
+
280
+ /**
281
+ * Workspace-relative form of an absolute path, or `undefined` when it is not
282
+ * inside this workspace.
283
+ *
284
+ * Used for the recent list: an entry from ANOTHER workspace must not be shown
285
+ * as if it were reachable here — opening it would act on a path whose binding
286
+ * the user is no longer looking at (the "opened in the wrong host" class of
287
+ * incident).
288
+ */
289
+ export function relativeToRoot(root: string, absolute: string): string | undefined {
290
+ const base = root.replace(/\/+$/, '')
291
+ if (base === '') return undefined
292
+ if (absolute === base) return undefined
293
+ if (!absolute.startsWith(`${base}/`)) return undefined
294
+ return absolute.slice(base.length + 1)
295
+ }
296
+
297
+ /** Render one thrown value as a readable reason. */
298
+ export function errorText(error: unknown): string {
299
+ return error instanceof Error ? error.message : String(error)
300
+ }
301
+
302
+ // ------------------------------------------------------------------ recents
303
+
304
+ interface RecentTable {
305
+ [alias: string]: string[]
306
+ }
307
+
308
+ function readRecentTable(): RecentTable {
309
+ try {
310
+ if (typeof localStorage === 'undefined') return {}
311
+ const raw = localStorage.getItem(QUICKOPEN_RECENT_KEY)
312
+ if (raw === null) return {}
313
+ const parsed: unknown = JSON.parse(raw)
314
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return {}
315
+ return parsed as RecentTable
316
+ } catch {
317
+ // Private mode / quota / corrupted value: an empty history is a valid state,
318
+ // and it must never break opening the panel.
319
+ return {}
320
+ }
321
+ }
322
+
323
+ /** Recently opened absolute paths for one host, newest first. */
324
+ export function loadRecentFiles(alias: string): string[] {
325
+ if (alias === '') return []
326
+ const list = readRecentTable()[alias]
327
+ if (!Array.isArray(list)) return []
328
+ return list
329
+ .filter((item): item is string => typeof item === 'string' && item.startsWith('/'))
330
+ .slice(0, QUICKOPEN_RECENT_LIMIT)
331
+ }
332
+
333
+ /**
334
+ * Record one opened file and return the new list.
335
+ *
336
+ * Paths only — this is the one thing quick open persists, so the promise in the
337
+ * README ("remote source never lands on this device") stays literally true:
338
+ * what is stored is a location, not content.
339
+ */
340
+ export function rememberRecentFile(alias: string, absolutePath: string): string[] {
341
+ if (alias === '' || !absolutePath.startsWith('/')) return []
342
+ const table = readRecentTable()
343
+ const current = Array.isArray(table[alias]) ? table[alias].filter(item => typeof item === 'string') : []
344
+ const next = [absolutePath, ...current.filter(item => item !== absolutePath)].slice(0, QUICKOPEN_RECENT_LIMIT)
345
+ try {
346
+ if (typeof localStorage !== 'undefined') {
347
+ localStorage.setItem(QUICKOPEN_RECENT_KEY, JSON.stringify({ ...table, [alias]: next }))
348
+ }
349
+ } catch {
350
+ // Best-effort: losing the history costs one extra search, not a failure.
351
+ }
352
+ return next
353
+ }
354
+
355
+ // ------------------------------------------------------------ index lifecycle
356
+
357
+ export type IndexPhase = 'idle' | 'loading' | 'ready' | 'error'
358
+
359
+ /** One built listing. Immutable; replaced wholesale, never mutated in place. */
360
+ export interface FileIndex {
361
+ alias: string
362
+ root: string
363
+ /** Remote-write counter observed when the listing was requested. */
364
+ writeSeq: number
365
+ /** Workspace-relative paths, sorted (deterministic order for equal scores). */
366
+ paths: readonly string[]
367
+ /** This is a bounded PREFIX in the entry/byte dimension: more files exist. */
368
+ truncated: boolean
369
+ /**
370
+ * The no-ripgrep fallback only walked this deep, so deeper files may be
371
+ * missing. `undefined` means the listing had no depth bound (ripgrep).
372
+ */
373
+ depthCapped: number | undefined
374
+ /**
375
+ * Exit status of the listing tool when it complained. The prefix is kept (a
376
+ * partial list is still useful) but it is NOT a complete index.
377
+ */
378
+ toolStatus: number | undefined
379
+ /** Human-readable reasons the index is incomplete (tool status, stderr). */
380
+ warning: string | undefined
381
+ }
382
+
383
+ /** Which workspace an index state is about. */
384
+ export interface IndexTarget {
385
+ alias: string
386
+ root: string
387
+ }
388
+
389
+ export interface IndexState {
390
+ phase: IndexPhase
391
+ /**
392
+ * The workspace this state belongs to — for `loading`, the build in flight.
393
+ *
394
+ * Carried explicitly because "loading" alone was a lie: a build for workspace
395
+ * A that was still in flight when the user switched to B made
396
+ * `indexNeedsRebuild` answer "nothing to do" for B, and A's listing then
397
+ * landed as if it were B's — Enter would join B's root with A's relative
398
+ * paths (a file that is not there, or, worse, a same-named one that is not
399
+ * what the list showed).
400
+ */
401
+ target: IndexTarget | undefined
402
+ index: FileIndex | undefined
403
+ error: string | undefined
404
+ }
405
+
406
+ export function createIndexState(): IndexState {
407
+ return { phase: 'idle', target: undefined, index: undefined, error: undefined }
408
+ }
409
+
410
+ /** Cache identity: an index is only valid for the alias + root it came from. */
411
+ export function indexTargetKey(alias: string, root: string): string {
412
+ return `${alias}\u0000${root.replace(/\/+$/, '')}`
413
+ }
414
+
415
+ /** Is `left` the same workspace as `right`? A trailing slash is not another tree. */
416
+ export function isSameIndexTarget(left: IndexTarget | undefined, right: IndexTarget): boolean {
417
+ if (left === undefined) return false
418
+ return indexTargetKey(left.alias, left.root) === indexTargetKey(right.alias, right.root)
419
+ }
420
+
421
+ /**
422
+ * Does the cached state still answer for this target?
423
+ *
424
+ * Three independent invalidations, all cheap:
425
+ * - this state is about a DIFFERENT workspace — including a build still in
426
+ * flight for one. Switching is a rebuild, and the foreign answer is dropped
427
+ * when it arrives (see {@link applyIndexResult});
428
+ * - no index yet, or the last attempt FAILED (a transient failure deserves a
429
+ * retry on the next open, and an error state must never be reused as if it
430
+ * were a complete answer);
431
+ * - a remote WRITE happened since the build (see `api.ts`), which is exactly
432
+ * when the path set can change.
433
+ */
434
+ export function indexNeedsRebuild(state: IndexState, alias: string, root: string, writeSeq: number): boolean {
435
+ if (!isSameIndexTarget(state.target, { alias, root })) return true
436
+ if (state.phase === 'loading') return false
437
+ if (state.phase === 'error') return true
438
+ const index = state.index
439
+ if (index === undefined) return true
440
+ return index.writeSeq !== writeSeq
441
+ }
442
+
443
+ /**
444
+ * Enter the loading phase for `alias` + `root`.
445
+ *
446
+ * An index for the SAME target is kept while it is being replaced, so the list
447
+ * keeps answering (from a snapshot that may be one write old) instead of
448
+ * blanking on every reopen. A different target's index is dropped: its paths
449
+ * are wrong for the new workspace.
450
+ */
451
+ export function beginIndexBuild(state: IndexState, alias: string, root: string): IndexState {
452
+ const target = { alias, root }
453
+ const keep = isSameIndexTarget(state.target, target) ? state.index : undefined
454
+ return { phase: 'loading', target, index: keep, error: undefined }
455
+ }
456
+
457
+ /**
458
+ * Publish one finished build — but only for the workspace that is current NOW.
459
+ *
460
+ * A build can outlive its workspace: 50k paths over a thin link takes seconds,
461
+ * and switching while it runs is normal use. Publishing that answer would put
462
+ * workspace A's relative paths in front of workspace B, so a foreign result is
463
+ * DISCARDED: whatever state is current stays exactly as it is (the current
464
+ * workspace's own build, or its error).
465
+ */
466
+ export function applyIndexResult(state: IndexState, index: FileIndex): IndexState {
467
+ if (!isSameIndexTarget(state.target, index)) return state
468
+ return { phase: 'ready', target: { alias: index.alias, root: index.root }, index, error: undefined }
469
+ }
470
+
471
+ /**
472
+ * Record a FAILED build for `target`, with the same foreign-result guard.
473
+ *
474
+ * `phase` stays `error` — never `ready` with zero paths. That distinction is the
475
+ * whole point: the modal prints the reason and does not claim "no matching
476
+ * file". Any previously built index for the same target is preserved so the
477
+ * list keeps showing something usable while the reason sits in the footer.
478
+ */
479
+ export function applyIndexFailure(state: IndexState, reason: string, target: IndexTarget): IndexState {
480
+ if (!isSameIndexTarget(state.target, target)) return state
481
+ return { phase: 'error', target, index: state.index, error: reason }
482
+ }
483
+
484
+ /**
485
+ * An immediately-known LOCAL failure (nothing remote ran, so there is no target
486
+ * to guard and no build to drop): e.g. no workspace is selected.
487
+ */
488
+ export function failIndexNow(reason: string): IndexState {
489
+ return { phase: 'error', target: undefined, index: undefined, error: reason }
490
+ }
491
+
492
+ /**
493
+ * The single in-memory index cache.
494
+ *
495
+ * ONE slot: an index is only valid for the exact alias + root it was built for,
496
+ * so there is nowhere for a foreign path list to hide (a switch invalidates by
497
+ * construction). Memory only — nothing here exists after a page reload, which
498
+ * is the published privacy trade-off.
499
+ *
500
+ * The modal subscribes to it (`useSyncExternalStore`) instead of keeping its own
501
+ * copy: a build outlives the modal that started it, so a copy would show
502
+ * "building…" forever when the user closes and reopens before the listing
503
+ * lands — the cache updates, the unmounted component's copy never does.
504
+ */
505
+ let cachedIndex: IndexState = createIndexState()
506
+ const indexListeners = new Set<() => void>()
507
+
508
+ export function quickOpenIndexState(): IndexState {
509
+ return cachedIndex
510
+ }
511
+
512
+ /** Subscribe to cache changes (the modal's view of the index). */
513
+ export function subscribeQuickOpenIndex(listener: () => void): () => void {
514
+ indexListeners.add(listener)
515
+ return () => { indexListeners.delete(listener) }
516
+ }
517
+
518
+ /** Replace the cached state and notify every subscriber. */
519
+ export function replaceQuickOpenIndexState(next: IndexState): void {
520
+ cachedIndex = next
521
+ for (const listener of [...indexListeners]) listener()
522
+ }
523
+
524
+ // -------------------------------------------------------- remote listing I/O
525
+
526
+ /** The slice of one remote command result this feature needs. */
527
+ export interface IndexExecResult {
528
+ success: boolean
529
+ exitCode: number | null
530
+ timedOut: boolean
531
+ stdout: string
532
+ stderr: string
533
+ error?: string | undefined
534
+ }
535
+
536
+ /** Injected I/O, so a gate can drive the whole build without a host. */
537
+ export interface FileIndexDeps {
538
+ exec: (alias: string, command: string, timeoutMs: number) => Promise<IndexExecResult>
539
+ /** Monotonic remote-write counter (see `api.ts` `remoteWriteSequence`). */
540
+ writeSequence: () => number
541
+ }
542
+
543
+ /** One POSIX shell word, quoted. */
544
+ export function shellQuote(value: string): string {
545
+ return `'${value.replace(/'/g, `'\\''`)}'`
546
+ }
547
+
548
+ /**
549
+ * The remote listing command.
550
+ *
551
+ * Shape decisions, and what each one prevents:
552
+ * - `cd` instead of passing the root to the tools: both paths are printed
553
+ * relative to the working directory, which is what the index wants.
554
+ * - a failed `cd` exits 3 WITH a message on stderr. Listing nothing would turn
555
+ * "the workspace root is gone" into "this tree has no files".
556
+ * - `rg` when the host has it, `find` otherwise, decided ON THE HOST in one
557
+ * command: no probe round trip and no per-alias cache to invalidate.
558
+ * - `--no-ignore --hidden` keeps ignored and dotted files searchable (what the
559
+ * name search does); the exclusion globs only prune noise directories.
560
+ * - both caps are applied remotely (`head -n cap+1`, then `head -c bytes`), so a
561
+ * million-line tree never crosses the wire just to be cut on this side.
562
+ * - the sentinel after the listing is what makes a capped prefix observable
563
+ * (see {@link parseFileIndexOutput}).
564
+ * - `LC_ALL=C`: byte-wise ordering from the tools, so the parser sees one
565
+ * canonical form no matter the host locale.
566
+ */
567
+ export function fileIndexCommand(
568
+ root: string,
569
+ caps: { entries?: number; bytes?: number } = {},
570
+ ): string {
571
+ const maxEntries = Math.max(1, Math.floor(caps.entries ?? QUICKOPEN_MAX_ENTRIES))
572
+ const maxBytes = Math.max(1024, Math.floor(caps.bytes ?? QUICKOPEN_MAX_BYTES))
573
+ const directories = shellQuote(root)
574
+ const rgGlobs = EXCLUDED_DIRECTORIES
575
+ .map(name => `--glob ${shellQuote(`!**/${name}`)} --glob ${shellQuote(`!**/${name}/**`)}`)
576
+ .join(' ')
577
+ const findPrune = EXCLUDED_DIRECTORIES.map(name => `-name ${shellQuote(name)}`).join(' -o ')
578
+ return [
579
+ `cd ${directories} || { echo ${shellQuote('quick-open: cannot enter the remote workspace root')} >&2; exit 3; }`,
580
+ 'export LC_ALL=C',
581
+ // The braces matter for two reasons: the caps must apply to the WHOLE
582
+ // either/or listing, and the sentinel must go THROUGH the caps — that is
583
+ // what makes "the stream ended at a cap" observable. Printing it after the
584
+ // pipeline instead would put it on every listing and the parser could no
585
+ // longer tell a truncated index from a complete one.
586
+ '{',
587
+ 'rv_status=0',
588
+ 'if command -v rg >/dev/null 2>&1; then',
589
+ // `|| rv_status=$?` is what stops the pipeline's own status (the last
590
+ // `head`'s, always 0) from hiding a tool that failed.
591
+ ` rg --no-config --files --no-ignore --hidden ${rgGlobs} -- . || rv_status=$?`,
592
+ // rg exits 1 for "no file matched" — an empty listing, not a failure.
593
+ ' [ "$rv_status" -eq 1 ] && rv_status=0',
594
+ 'else',
595
+ ` find . -maxdepth ${QUICKOPEN_FALLBACK_MAX_DEPTH} \\( ${findPrune} \\) -prune -o -type f -print || rv_status=$?`,
596
+ // The depth bound is DECLARED, not silent (see DEPTH_CAP_PREFIX).
597
+ ` printf '%s\\n' ${shellQuote(`${DEPTH_CAP_PREFIX}depth=${QUICKOPEN_FALLBACK_MAX_DEPTH}`)}`,
598
+ 'fi',
599
+ // Our own caps make the tool die of SIGPIPE (>=128) once `head` has enough;
600
+ // that is the truncation doing its job, not a tool failure.
601
+ 'if [ "$rv_status" -ge 128 ]; then rv_status=0; fi',
602
+ `printf '%s\\n' ${shellQuote(LIST_SENTINEL)}`,
603
+ // Out-of-band, on stderr: the stdout caps cannot eat it, so a failing tool
604
+ // is still visible on a truncated listing.
605
+ 'if [ "$rv_status" -ne 0 ]; then printf "RV-QO-STATUS tool=%s\\n" "$rv_status" >&2; fi',
606
+ `} | head -n ${maxEntries + 1} | head -c ${maxBytes}`,
607
+ ].join('\n')
608
+ }
609
+
610
+ export interface FileIndexListing {
611
+ paths: string[]
612
+ truncated: boolean
613
+ /** The find fallback declared a depth bound (deeper files may be missing). */
614
+ depthCapped: number | undefined
615
+ }
616
+
617
+ /**
618
+ * Turn one listing's stdout into sorted workspace-relative paths.
619
+ *
620
+ * Truncation is DERIVED, never assumed:
621
+ * - the sentinel is missing → the prefix ended at a cap (or the transport cut
622
+ * it) → `truncated: true`, and the final line is dropped because it may be a
623
+ * half-written path;
624
+ * - more than `maxEntries` lines survived → `truncated: true`, keep the prefix;
625
+ * - the find fallback's depth marker survived → `depthCapped` (a THIRD, separate
626
+ * bound: more levels exist than were walked).
627
+ *
628
+ * The caller-visible promise is that a bounded listing NEVER looks complete:
629
+ * every cap is its own reported fact.
630
+ */
631
+ export function parseFileIndexOutput(
632
+ stdout: string,
633
+ options: { root: string; maxEntries?: number } = { root: '' },
634
+ ): FileIndexListing {
635
+ const maxEntries = Math.max(1, Math.floor(options.maxEntries ?? QUICKOPEN_MAX_ENTRIES))
636
+ let text = stdout
637
+ let truncated = false
638
+ let depthCapped: number | undefined
639
+ const hostCut = text.indexOf(HOST_CAP_MARKER)
640
+ if (hostCut >= 0) {
641
+ // Our own byte cap should have prevented this; if the transport cut it
642
+ // anyway, the tail after the marker is not a path.
643
+ truncated = true
644
+ text = text.slice(0, hostCut)
645
+ }
646
+ const lines = text.split('\n').map(line => (line.endsWith('\r') ? line.slice(0, -1) : line))
647
+ /** Whether the stream ended on a line boundary (so its last line is complete). */
648
+ const closedLine = text.endsWith('\n')
649
+ if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop()
650
+ if (lines.length > 0 && lines[lines.length - 1] === LIST_SENTINEL) {
651
+ lines.pop()
652
+ } else {
653
+ truncated = true
654
+ // A stream that did NOT end on a line boundary was cut mid-path: that last
655
+ // fragment is not a file name and must not become one.
656
+ if (!closedLine && lines.length > 0) lines.pop()
657
+ }
658
+ const base = options.root.replace(/\/+$/, '')
659
+ const absolutePrefix = base === '' ? undefined : `${base}/`
660
+ const seen = new Set<string>()
661
+ for (const raw of lines) {
662
+ // Deliberately NOT `trim()`: a file name may legally end with a space, and
663
+ // trimming it would index (and open) a different path than the one listed.
664
+ // Only the line terminator is stripped, above.
665
+ if (raw === '') continue
666
+ if (raw === LIST_SENTINEL) continue
667
+ if (raw.startsWith(DEPTH_CAP_PREFIX)) {
668
+ const depth = Number.parseInt(raw.slice(DEPTH_CAP_PREFIX.length).replace(/^depth=/, ''), 10)
669
+ if (Number.isFinite(depth) && depth > 0) depthCapped = depth
670
+ continue
671
+ }
672
+ let path = raw
673
+ if (path.startsWith('./')) path = path.slice(2)
674
+ if (absolutePrefix !== undefined && path.startsWith(absolutePrefix)) path = path.slice(absolutePrefix.length)
675
+ path = path.replace(/^\/+/, '')
676
+ if (path === '') continue
677
+ seen.add(path)
678
+ }
679
+ const paths = Array.from(seen).sort(comparePaths)
680
+ if (paths.length > maxEntries) {
681
+ return { paths: paths.slice(0, maxEntries), truncated: true, depthCapped }
682
+ }
683
+ return { paths, truncated, depthCapped }
684
+ }
685
+
686
+ /** Exit status the listing tool reported, from its stderr marker (if any). */
687
+ function toolStatusOf(stderr: string): number | undefined {
688
+ for (const line of stderr.split('\n')) {
689
+ const clean = line.endsWith('\r') ? line.slice(0, -1) : line
690
+ if (!clean.startsWith(TOOL_STATUS_PREFIX)) continue
691
+ const status = Number.parseInt(clean.slice(TOOL_STATUS_PREFIX.length), 10)
692
+ // 128+ means killed by a signal — our own caps cause SIGPIPE, so a
693
+ // signal status is the truncation working, not the tool failing.
694
+ if (!Number.isFinite(status) || status <= 0 || status >= 128) continue
695
+ return status
696
+ }
697
+ return undefined
698
+ }
699
+
700
+ /**
701
+ * First non-marker line of remote stderr: the human detail behind "incomplete".
702
+ *
703
+ * The tool-status marker is stripped (it is protocol, not prose) and the result
704
+ * is capped so a wall of warnings cannot displace the list.
705
+ */
706
+ function warningOf(stderr: string, toolStatus: number | undefined): string | undefined {
707
+ const detail = stderr
708
+ .split('\n')
709
+ .map(item => (item.endsWith('\r') ? item.slice(0, -1) : item))
710
+ .map(item => item.trim())
711
+ .find(item => item !== '' && !item.startsWith(TOOL_STATUS_PREFIX))
712
+ const trimmed = detail === undefined
713
+ ? undefined
714
+ : (detail.length > 160 ? `${detail.slice(0, 157)}…` : detail)
715
+ if (toolStatus === undefined) return trimmed
716
+ // The exit code alone is the important part: it says the tool gave up, so the
717
+ // listing is not complete even when it looks complete.
718
+ const head = `listing tool exited ${toolStatus}`
719
+ return trimmed === undefined ? head : `${head}: ${trimmed}`
720
+ }
721
+
722
+ /**
723
+ * Fetch and parse one listing.
724
+ *
725
+ * Rejects — loudly — whenever the run did not produce a trustworthy listing:
726
+ * timed out, transport-broken, never entered the workspace root (exit 3), or the
727
+ * listing tool failed AND listed nothing. A successful run with zero paths is a
728
+ * legitimate empty index (a brand new repository) and resolves with `paths: []`;
729
+ * a run whose tool listed some files and then reported errors resolves with the
730
+ * usable prefix plus `toolStatus`/`warning` saying it is incomplete.
731
+ *
732
+ * The write counter is read BEFORE the command starts: a write that lands while
733
+ * the listing is in flight must leave the index stale (its `writeSeq` is older),
734
+ * otherwise the modal could show — and open — a path that no longer exists.
735
+ */
736
+ export async function buildFileIndex(
737
+ deps: FileIndexDeps,
738
+ target: { alias: string; root: string },
739
+ options: { entries?: number; bytes?: number; timeoutMs?: number } = {},
740
+ ): Promise<FileIndex> {
741
+ const alias = target.alias
742
+ const root = target.root.replace(/\/+$/, '')
743
+ const entries = options.entries ?? QUICKOPEN_MAX_ENTRIES
744
+ const bytes = options.bytes ?? QUICKOPEN_MAX_BYTES
745
+ const timeoutMs = options.timeoutMs ?? QUICKOPEN_INDEX_TIMEOUT_MS
746
+ const writeSeq = deps.writeSequence()
747
+ const command = fileIndexCommand(root, { entries, bytes })
748
+ const result = await deps.exec(alias, command, timeoutMs)
749
+ if (result.timedOut) {
750
+ throw new Error(`the remote listing did not finish within ${timeoutMs} ms`)
751
+ }
752
+ if (result.error !== undefined && result.error !== '') {
753
+ throw new Error(result.error)
754
+ }
755
+ const toolStatus = toolStatusOf(result.stderr)
756
+ if (!result.success) {
757
+ const detail = warningOf(result.stderr, undefined)
758
+ const exit = result.exitCode === null ? 'no exit status' : `exit ${result.exitCode}`
759
+ throw new Error(detail === undefined ? `the remote listing failed (${exit})` : `${detail} (${exit})`)
760
+ }
761
+ const listing = parseFileIndexOutput(result.stdout, { root, maxEntries: entries })
762
+ if (toolStatus !== undefined && listing.paths.length === 0 && !listing.truncated) {
763
+ // The tool failed and produced nothing: an empty answer from a broken tool is
764
+ // not evidence of an empty tree. Reject, exactly like a transport failure.
765
+ const detail = warningOf(result.stderr, toolStatus)
766
+ throw new Error(detail ?? `the remote listing failed (tool exit ${toolStatus})`)
767
+ }
768
+ return {
769
+ alias,
770
+ root,
771
+ writeSeq,
772
+ paths: listing.paths,
773
+ truncated: listing.truncated,
774
+ depthCapped: listing.depthCapped,
775
+ toolStatus,
776
+ warning: warningOf(result.stderr, toolStatus),
777
+ }
778
+ }