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
package/src/importers.ts CHANGED
@@ -23,6 +23,19 @@ function expandHome(path: string): string {
23
23
  return path
24
24
  }
25
25
 
26
+ /**
27
+ * Parse one configured port (number, or a decimal string from older stores).
28
+ *
29
+ * `undefined` means absent (caller defaults to 22); `NaN`/out-of-range returns
30
+ * `undefined` too, and callers turn that into an explicit skip — silently
31
+ * importing an invalid port as 22 would connect to the wrong sshd (or none).
32
+ */
33
+ function validPort(value: string | number): number | undefined {
34
+ const port = typeof value === 'number' ? value : /^\d+$/.test(value) ? Number(value) : Number.NaN
35
+ if (!Number.isInteger(port) || port < 1 || port > 65535) return undefined
36
+ return port
37
+ }
38
+
26
39
  /** Parse OpenSSH client config text into host payloads. */
27
40
  export function parseSshConfig(text: string): ParsedImport {
28
41
  const payloads: HostPayload[] = []
@@ -46,31 +59,58 @@ export function parseSshConfig(text: string): ParsedImport {
46
59
  } else if (key === 'match') {
47
60
  current = undefined
48
61
  skipped.push({ alias: '(match)', reason: 'Match conditional blocks are not imported' })
62
+ } else if (key === 'include') {
63
+ // Not expanded: multi-file configs live in separate files, and a silent
64
+ // omission used to look like "the config only had a few hosts".
65
+ skipped.push({ alias: '(include)', reason: `Include ${value} is not expanded — import that file separately` })
49
66
  } else if (current !== undefined && !current.fields.has(key)) {
50
67
  current.fields.set(key, value)
51
68
  }
52
69
  }
53
70
  for (const block of blocks) {
54
- const alias = block.patterns[0] as string
55
- if (alias === undefined || alias.includes('*') || alias.includes('?') || alias.includes('!')) {
56
- skipped.push({ alias: block.patterns.join(' ') || '(empty)', reason: 'wildcard patterns are not imported' })
71
+ // A `Host a b` line declares TWO names with the same fields: import each
72
+ // concrete pattern instead of silently dropping everything after the first.
73
+ const concrete = block.patterns.filter(pattern => pattern !== '' && !/[*?!]/.test(pattern))
74
+ const special = block.patterns.filter(pattern => pattern !== '' && /[*?!]/.test(pattern))
75
+ if (special.length > 0) {
76
+ skipped.push({ alias: special.join(' '), reason: 'wildcard/negation patterns are not imported' })
77
+ }
78
+ if (concrete.length === 0) {
79
+ if (special.length === 0) skipped.push({ alias: '(empty)', reason: 'Host line has no pattern' })
57
80
  continue
58
81
  }
59
82
  if (block.fields.has('proxyjump') || block.fields.has('proxycommand')) {
60
- skipped.push({ alias, reason: 'proxyJump/proxyCommand needs P1 (direct hosts only in P0)' })
83
+ for (const alias of concrete) skipped.push({ alias, reason: 'proxyJump/proxyCommand needs P1 (direct hosts only in P0)' })
61
84
  continue
62
85
  }
86
+ const rawPort = block.fields.get('port')
87
+ const port = rawPort === undefined ? 22 : validPort(rawPort)
63
88
  const identityFile = block.fields.get('identityfile')?.split(/\s+/)[0]
64
- payloads.push({
65
- alias,
66
- host: block.fields.get('hostname') ?? alias,
67
- port: block.fields.get('port') !== undefined ? Number(block.fields.get('port')) : 22,
68
- user: block.fields.get('user') ?? '',
69
- auth: identityFile !== undefined
70
- ? { kind: 'key', keyPath: expandHome(identityFile) }
71
- : { kind: 'password', password: '' },
72
- tags: ['imported:ssh-config'],
73
- })
89
+ const user = block.fields.get('user') ?? ''
90
+ for (const alias of concrete) {
91
+ if (port === undefined) {
92
+ skipped.push({ alias, reason: `invalid Port '${rawPort ?? ''}' (expected 1-65535)` })
93
+ continue
94
+ }
95
+ if (user === '') {
96
+ skipped.push({ alias, reason: 'no User in ssh_config — set the login user after import' })
97
+ continue
98
+ }
99
+ if (identityFile === undefined) {
100
+ // The old code produced an empty-password payload, which the store then
101
+ // rejected with a misleading "auth.password must be non-empty".
102
+ skipped.push({ alias, reason: 'no IdentityFile in ssh_config — add the key or password after import' })
103
+ continue
104
+ }
105
+ payloads.push({
106
+ alias,
107
+ host: block.fields.get('hostname') ?? alias,
108
+ port,
109
+ user,
110
+ auth: { kind: 'key', keyPath: expandHome(identityFile) },
111
+ tags: ['imported:ssh-config'],
112
+ })
113
+ }
74
114
  }
75
115
  return { payloads, skipped }
76
116
  }
@@ -98,29 +138,48 @@ export function migrateDshSsh(home: string = dshHome()): ParsedImport {
98
138
  const alias = typeof raw.alias === 'string' ? raw.alias : '(unknown)'
99
139
  const auth = (raw.auth ?? {}) as Record<string, unknown>
100
140
  const kind = auth.kind
101
- const proxyJump = (raw.proxyJump ?? []) as unknown[]
141
+ const proxyJump = raw.proxyJump
102
142
  const proxyCommand = raw.proxyCommand
143
+ const hasProxy = (Array.isArray(proxyJump) && proxyJump.length > 0)
144
+ || (typeof proxyJump === 'string' && proxyJump !== '')
145
+ || (typeof proxyCommand === 'string' && proxyCommand !== '')
103
146
  if (kind !== 'key' && kind !== 'password') {
104
147
  skipped.push({ alias, reason: `auth kind '${String(kind)}' needs P1 (key/password only in P0)` })
105
148
  continue
106
149
  }
107
- if (proxyJump.length > 0 || (typeof proxyCommand === 'string' && proxyCommand !== '')) {
150
+ if (hasProxy) {
108
151
  skipped.push({ alias, reason: 'proxyJump/proxyCommand needs P1 (direct hosts only in P0)' })
109
152
  continue
110
153
  }
111
- if (kind === 'key' && typeof auth.keyPath !== 'string') {
154
+ if (kind === 'key' && (typeof auth.keyPath !== 'string' || auth.keyPath.trim() === '')) {
112
155
  skipped.push({ alias, reason: 'key auth without keyPath' })
113
156
  continue
114
157
  }
115
- if (kind === 'password' && typeof auth.password !== 'string') {
158
+ if (kind === 'password' && (typeof auth.password !== 'string' || auth.password === '')) {
116
159
  skipped.push({ alias, reason: 'password auth without stored password (enter it manually)' })
117
160
  continue
118
161
  }
162
+ const host = typeof raw.host === 'string' ? raw.host : ''
163
+ const user = typeof raw.user === 'string' ? raw.user : ''
164
+ const rawPort = raw.port
165
+ const port = rawPort === undefined ? 22 : validPort(rawPort as string | number)
166
+ if (host === '') {
167
+ skipped.push({ alias, reason: 'no host address — enter it manually after import' })
168
+ continue
169
+ }
170
+ if (user === '') {
171
+ skipped.push({ alias, reason: 'no login user — enter it manually after import' })
172
+ continue
173
+ }
174
+ if (port === undefined) {
175
+ skipped.push({ alias, reason: `invalid port '${String(rawPort)}' (expected 1-65535)` })
176
+ continue
177
+ }
119
178
  payloads.push({
120
179
  alias,
121
- host: typeof raw.host === 'string' ? raw.host : '',
122
- port: typeof raw.port === 'number' ? raw.port : 22,
123
- user: typeof raw.user === 'string' ? raw.user : '',
180
+ host,
181
+ port,
182
+ user,
124
183
  auth: kind === 'key'
125
184
  ? {
126
185
  kind: 'key',
package/src/index.ts CHANGED
@@ -330,6 +330,25 @@ export function apply(ctx: Context, config?: ResolvedConfig): void {
330
330
  changes,
331
331
  })
332
332
 
333
+ /**
334
+ * PTY sessions own their own lifetime, separate from route registration.
335
+ *
336
+ * `sync()` rebuilds the route/tool registrations whenever a volatile config
337
+ * value changes (`loader/volatile-update` fires for every settings edit), and a
338
+ * cleanup that also closed terminals made "change one setting" kill every live
339
+ * remote shell. So the registry gets a fiber-scoped effect of its own: it is
340
+ * disposed exactly once — when the plugin is actually unloaded — and never by
341
+ * the route re-registration in `sync()`.
342
+ *
343
+ * Cleanup order is load-bearing: this effect is registered AFTER the pool
344
+ * effect but BEFORE the routes effect created in `sync()`, and cordis starts a
345
+ * fiber's effect cleanups in reverse registration order (these cleanups are
346
+ * synchronous) — so on unload the routes are unregistered first (no new shell
347
+ * can be opened), then the terminals close (a channel close still has a live
348
+ * pool), and the pool is disposed last.
349
+ */
350
+ ctx.effect(() => () => { terminalSessions.dispose() }, 'dsh-remote-vs: terminal sessions')
351
+
333
352
  let disposeRoutes: (() => void) | undefined
334
353
 
335
354
  const tools = [
@@ -372,10 +391,11 @@ export function apply(ctx: Context, config?: ResolvedConfig): void {
372
391
  () => {
373
392
  const disposers = routes.map(route => ctx.webServer.register(route))
374
393
  const upgradeDisposer = ctx.webServer.registerUpgrade(upgrade)
394
+ // Route registration only: live PTY sessions are disposed by their own
395
+ // effect (see above), so a volatile config edit cannot kill them.
375
396
  return () => {
376
397
  for (const dispose of disposers) dispose()
377
398
  upgradeDisposer()
378
- terminalSessions.dispose()
379
399
  }
380
400
  },
381
401
  'dsh-remote-vs: routes',
@@ -19,6 +19,7 @@ import type { FileSystem } from '@deepseek-ai/dsh-fs'
19
19
  import type { FileReferenceCandidate } from '@deepseek-ai/dsh-file-reference'
20
20
  import type {
21
21
  SubprocessHandle,
22
+ SubprocessOutcome,
22
23
  SubprocessSpawnSpec,
23
24
  } from '@deepseek-ai/dsh-subprocess'
24
25
 
@@ -36,6 +37,27 @@ export const REMOTE_FILE_SEARCH_EXCLUDED_DIRECTORIES: readonly string[] = [
36
37
  /** Byte ceiling for one rg listing transfer (50k lines worst case). */
37
38
  const RG_OUTPUT_MAX_BYTES = 16 * 1024 * 1024
38
39
 
40
+ /**
41
+ * How long the ended scan may take to actually close before we stop waiting.
42
+ *
43
+ * The cap above terminates `rg` ourselves, and a cap is a RESULT, not a failure —
44
+ * but the process may be slow to die (or its ssh channel may never report close
45
+ * at all). Waiting forever there would leave the shared `pending` promise
46
+ * unsettled for the life of the Host, so every later bare query would join it and
47
+ * never answer. Two minutes is far beyond a healthy 5-entry/16MiB listing and only
48
+ * ever bites a half-dead transport.
49
+ */
50
+ const DONE_TIMEOUT_MS = 120_000
51
+
52
+ /** Why the cached index is a bounded prefix instead of the whole tree. */
53
+ export type RemoteIndexCap = 'entries' | 'bytes' | 'timeout'
54
+
55
+ /** What one `done` wait observed (a rejection is unknown, not an exit fact). */
56
+ type DoneWait =
57
+ | { kind: 'outcome'; outcome: SubprocessOutcome | undefined }
58
+ | { kind: 'timeout' }
59
+ | { kind: 'failed'; error: unknown }
60
+
39
61
  export interface RemoteFileSearchDeps {
40
62
  /** Remote fs view (worlds.fsFor) for scoped live listings. */
41
63
  fs: FileSystem
@@ -45,10 +67,18 @@ export interface RemoteFileSearchDeps {
45
67
  remoteRoot: string
46
68
  /** Optional warn sink (router wires ctx.logger). */
47
69
  warn?: (message: string) => void
70
+ /** Override the post-cap close wait (tests only; production keeps the default). */
71
+ doneTimeoutMs?: number
48
72
  }
49
73
 
50
74
  export class RemoteFileSearch {
51
75
  private readonly excluded: ReadonlySet<string>
76
+ /**
77
+ * Explicit field assignment instead of a constructor parameter property: the
78
+ * local gates load this module through Node's type-stripping runner (same as
79
+ * `changes/recorder.ts`), which rejects parameter properties.
80
+ */
81
+ private readonly deps: RemoteFileSearchDeps
52
82
  private settled: FileReferenceCandidate[] | undefined
53
83
  private pending: Promise<FileReferenceCandidate[]> | undefined
54
84
  private pendingAbort: AbortController | undefined
@@ -57,11 +87,25 @@ export class RemoteFileSearch {
57
87
  private disposed = false
58
88
  /** Monotonic invalidation counter; a scan started below it is stale. */
59
89
  private invalidations = 0
90
+ /** Why the cached index is bounded, or undefined when it is complete. */
91
+ private cappedIndex: RemoteIndexCap | undefined
60
92
 
61
- constructor(private readonly deps: RemoteFileSearchDeps) {
93
+ constructor(deps: RemoteFileSearchDeps) {
94
+ this.deps = deps
62
95
  this.excluded = new Set(REMOTE_FILE_SEARCH_EXCLUDED_DIRECTORIES)
63
96
  }
64
97
 
98
+ /**
99
+ * Why the current index is a bounded prefix, or `undefined` for a complete one.
100
+ *
101
+ * The `@` surface itself returns candidates only (its contract is the stock
102
+ * local list), so this is the honest place to expose "you are looking at a
103
+ * prefix": host logs get the warning, and a future consumer can surface it.
104
+ */
105
+ get indexCap(): RemoteIndexCap | undefined {
106
+ return this.cappedIndex
107
+ }
108
+
65
109
  /**
66
110
  * Drop the cached index (tool activity); the next bare query rebuilds.
67
111
  *
@@ -79,6 +123,8 @@ export class RemoteFileSearch {
79
123
  invalidate(): void {
80
124
  this.invalidations += 1
81
125
  this.settled = undefined
126
+ // The cap verdict belongs to the index being dropped.
127
+ this.cappedIndex = undefined
82
128
  if (this.pendingAbort !== undefined) {
83
129
  try {
84
130
  this.pendingAbort.abort(new Error('file search index invalidated'))
@@ -195,13 +241,24 @@ export class RemoteFileSearch {
195
241
  })
196
242
  }
197
243
 
198
- /** One remote `rg --files` run, head-capped, sorted for determinism. */
244
+ /**
245
+ * One remote `rg --files` run, head-capped, sorted for determinism.
246
+ *
247
+ * A cap is a BOUNDED ANSWER, not a failure: whatever was read before the cap is
248
+ * still the prefix of the listing, and it used to be thrown away because the
249
+ * process's own SIGTERM (we killed it) looked like a non-zero exit. On a
250
+ * monorepo past 50k files that made the bare `@` query answer "nothing to
251
+ * reference" for a repo full of files. Now the prefix is served and
252
+ * {@link RemoteFileSearch.indexCap} / the warn sink say it is a prefix.
253
+ */
199
254
  private async buildIndex(signal: AbortSignal): Promise<FileReferenceCandidate[]> {
200
255
  const globs: string[] = []
201
256
  for (const name of this.excluded) {
202
257
  globs.push(`--glob=!**/${name}`, `--glob=!**/${name}/**`)
203
258
  }
204
259
  const argv = ['rg', '--no-config', '--files', '--no-ignore', '--hidden', ...globs, '--', '.']
260
+ // A fresh build decides the cap verdict from scratch.
261
+ this.cappedIndex = undefined
205
262
  let handle: SubprocessHandle
206
263
  try {
207
264
  handle = this.deps.spawn({
@@ -217,7 +274,7 @@ export class RemoteFileSearch {
217
274
  }
218
275
  const lines: string[] = []
219
276
  let bytes = 0
220
- let truncated = false
277
+ let cappedBy: RemoteIndexCap | undefined
221
278
  try {
222
279
  const stdout = handle.stdout
223
280
  if (stdout === undefined) {
@@ -241,15 +298,19 @@ export class RemoteFileSearch {
241
298
  const clean = line.endsWith('\r') ? line.slice(0, -1) : line
242
299
  if (clean === '') continue
243
300
  bytes += Buffer.byteLength(clean, 'utf8') + 1
244
- if (lines.length >= REMOTE_FILE_SEARCH_MAX_ENTRIES || bytes > RG_OUTPUT_MAX_BYTES) {
245
- truncated = true
301
+ if (lines.length >= REMOTE_FILE_SEARCH_MAX_ENTRIES) {
302
+ cappedBy = 'entries'
303
+ break
304
+ }
305
+ if (bytes > RG_OUTPUT_MAX_BYTES) {
306
+ cappedBy = 'bytes'
246
307
  break
247
308
  }
248
309
  lines.push(clean)
249
310
  }
250
- if (truncated) break
311
+ if (cappedBy !== undefined) break
251
312
  }
252
- if (!truncated && carry !== '') {
313
+ if (cappedBy === undefined && carry !== '') {
253
314
  if (lines.length < REMOTE_FILE_SEARCH_MAX_ENTRIES && bytes <= RG_OUTPUT_MAX_BYTES) {
254
315
  lines.push(carry.endsWith('\r') ? carry.slice(0, -1) : carry)
255
316
  }
@@ -257,12 +318,22 @@ export class RemoteFileSearch {
257
318
  } finally {
258
319
  signal.removeEventListener('abort', onAbort)
259
320
  }
321
+ // A real cancellation is still a rejection; the cap is decided below.
260
322
  signal.throwIfAborted()
261
323
  handle.terminate()
262
324
  }
263
- const outcome = await handle.done.catch(() => undefined)
264
- if (outcome !== undefined && outcome.exitCode !== 0 && outcome.exitCode !== 1) {
265
- this.warn(`remote file index rg exited ${outcome.exitCode ?? outcome.signal}`)
325
+ const waited = await this.waitForDone(handle)
326
+ if (waited.kind === 'timeout') {
327
+ // The channel never closed. The prefix is still the best answer there is.
328
+ cappedBy ??= 'timeout'
329
+ } else if (waited.kind === 'failed') {
330
+ if (cappedBy === undefined) {
331
+ this.warn(`remote file index failed: ${messageOf(waited.error)}`)
332
+ return []
333
+ }
334
+ } else if (cappedBy === undefined && waited.outcome !== undefined
335
+ && waited.outcome.exitCode !== 0 && waited.outcome.exitCode !== 1) {
336
+ this.warn(`remote file index rg exited ${waited.outcome.exitCode ?? waited.outcome.signal}`)
266
337
  return []
267
338
  }
268
339
  } catch (error) {
@@ -275,6 +346,10 @@ export class RemoteFileSearch {
275
346
  this.warn(`remote file index failed: ${messageOf(error)}`)
276
347
  return []
277
348
  }
349
+ if (cappedBy !== undefined) {
350
+ this.cappedIndex = cappedBy
351
+ this.warn(`remote file index capped by ${cappedBy}; serving the prefix read so far`)
352
+ }
278
353
  // Normalize to stock index shape: strip ./, drop excluded segments
279
354
  // (covers the root-inside-excluded glob edge), sort, derive dirs.
280
355
  const files = new Set<string>()
@@ -301,6 +376,33 @@ export class RemoteFileSearch {
301
376
  return indexed
302
377
  }
303
378
 
379
+ /**
380
+ * Wait for the ended scan to close, but never forever.
381
+ *
382
+ * `handle.done` settles from the transport's close event; a half-dead channel
383
+ * can withhold it for the life of the process. Every outcome is reported as a
384
+ * fact — a rejection stays a rejection so the caller can still treat it as a
385
+ * failure when nothing else explains the scan.
386
+ */
387
+ private async waitForDone(handle: SubprocessHandle): Promise<DoneWait> {
388
+ const ms = this.deps.doneTimeoutMs ?? DONE_TIMEOUT_MS
389
+ let timer: ReturnType<typeof setTimeout> | undefined
390
+ const settled = handle.done.then(
391
+ (outcome): DoneWait => ({ kind: 'outcome', outcome }),
392
+ (error: unknown): DoneWait => ({ kind: 'failed', error }),
393
+ )
394
+ try {
395
+ return await Promise.race([
396
+ settled,
397
+ new Promise<DoneWait>(resolve => {
398
+ timer = setTimeout(() => resolve({ kind: 'timeout' }), ms)
399
+ }),
400
+ ])
401
+ } finally {
402
+ if (timer !== undefined) clearTimeout(timer)
403
+ }
404
+ }
405
+
304
406
  private warn(message: string): void {
305
407
  try {
306
408
  this.deps.warn?.(`[remote-refs] ${message}`)
@@ -116,6 +116,31 @@ class HelperTimeoutError extends Error {
116
116
  }
117
117
  }
118
118
 
119
+ /**
120
+ * Close each resource, ignoring failures — and keeping going.
121
+ *
122
+ * Teardown runs while an error is already unwinding: one resource that throws on
123
+ * close must not stop the NEXT one from being released (that skipped socket is
124
+ * exactly the leak this exists to prevent). Exported so the gate can drive the
125
+ * real behaviour with fake resources; there is no transport to stub locally.
126
+ */
127
+ export function closeQuietly(
128
+ resources: ReadonlyArray<{ close?: () => void; end?: () => void }>,
129
+ ): void {
130
+ for (const resource of resources) {
131
+ try {
132
+ resource.close?.()
133
+ } catch {
134
+ // Ignore: teardown must reach every resource.
135
+ }
136
+ try {
137
+ resource.end?.()
138
+ } catch {
139
+ // Ignore.
140
+ }
141
+ }
142
+ }
143
+
119
144
  export class RpcConnection {
120
145
  private conn: Client | undefined
121
146
  private channel: ClientChannel | undefined
@@ -204,30 +229,17 @@ export class RpcConnection {
204
229
  */
205
230
  private async reconnect(): Promise<void> {
206
231
  if (this.disposed) throw new Error('helper RPC was disposed')
207
- try {
208
- this.peer?.close()
209
- } catch {
210
- // Ignore.
211
- }
212
- try {
213
- this.channel?.close()
214
- } catch {
215
- // Ignore.
216
- }
217
- try {
218
- this.conn?.end()
219
- } catch {
220
- // Ignore.
221
- }
222
- if (this.heartbeat !== undefined) clearTimeout(this.heartbeat)
223
- this.peer = undefined
224
- this.channel = undefined
225
- this.conn = undefined
232
+ // One teardown for every field: the old transport is fully gone before a new
233
+ // attempt starts (a half-closed one would keep the ssh session alive).
234
+ this.teardownTransport()
226
235
  this.dead = undefined
227
236
  this.readyPromise = this.open()
228
237
  try {
229
238
  await this.readyPromise
230
239
  } catch (error) {
240
+ // Belt and braces: `open()` already tears its own attempt down on failure,
241
+ // but the reconnect path must leave NO lingering transport either way.
242
+ this.teardownTransport()
231
243
  // Leave no poisoned promise behind: the next caller should be able to try.
232
244
  this.readyPromise = undefined
233
245
  throw error
@@ -237,22 +249,7 @@ export class RpcConnection {
237
249
  async dispose(): Promise<void> {
238
250
  if (this.disposed) return
239
251
  this.disposed = true
240
- if (this.heartbeat !== undefined) clearTimeout(this.heartbeat)
241
- try {
242
- this.peer?.close()
243
- } catch {
244
- // Ignore.
245
- }
246
- try {
247
- this.channel?.close()
248
- } catch {
249
- // Ignore.
250
- }
251
- try {
252
- this.conn?.end()
253
- } catch {
254
- // Ignore.
255
- }
252
+ this.teardownTransport()
256
253
  }
257
254
 
258
255
  private async peerReady(): Promise<SshRpcPeer> {
@@ -263,10 +260,50 @@ export class RpcConnection {
263
260
  return this.peer
264
261
  }
265
262
 
263
+ /**
264
+ * Release the current transport, whatever state it is in.
265
+ *
266
+ * Shared by `reconnect()`, a failed `open()` and `dispose()` because all three
267
+ * carry the same obligation: afterwards no ssh session, channel or heartbeat may
268
+ * survive. A half-open transport is a real leak — the socket lives until the
269
+ * remote's keepalive gives up, and the next attempt opens a SECOND session.
270
+ * `stderrTail` is cleared too: it describes the connection being torn down, and
271
+ * keeping it would attribute the NEXT failure to the previous transport's error
272
+ * output.
273
+ */
274
+ private teardownTransport(): void {
275
+ if (this.heartbeat !== undefined) {
276
+ clearTimeout(this.heartbeat)
277
+ this.heartbeat = undefined
278
+ }
279
+ const resources: Array<{ close?: () => void; end?: () => void }> = []
280
+ if (this.peer !== undefined) resources.push(this.peer)
281
+ if (this.channel !== undefined) resources.push(this.channel)
282
+ if (this.conn !== undefined) resources.push(this.conn)
283
+ closeQuietly(resources)
284
+ this.peer = undefined
285
+ this.channel = undefined
286
+ this.conn = undefined
287
+ this.stderrTail = ''
288
+ }
289
+
266
290
  private async open(): Promise<RpcHello> {
267
- const { entry } = this.opts
268
291
  const conn = new Client()
269
292
  this.conn = conn
293
+ try {
294
+ return await this.dialAndHello(conn)
295
+ } catch (error) {
296
+ // Anything that fails after the socket is up must not leave it behind: the
297
+ // caller only sees the reject, and the next attempt would open a second
298
+ // session while this one lingers until keepalive gives up.
299
+ this.teardownTransport()
300
+ throw error
301
+ }
302
+ }
303
+
304
+ /** The part of {@link open} that runs once the socket object exists. */
305
+ private async dialAndHello(conn: Client): Promise<RpcHello> {
306
+ const { entry } = this.opts
270
307
  await new Promise<void>((resolve, reject) => {
271
308
  let settled = false
272
309
  conn.on('ready', () => {