dsh-remote-vs 0.25.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.en.md +11 -7
  2. package/README.md +10 -7
  3. package/THIRD-PARTY-NOTICES.md +188 -0
  4. package/lib/client.js +6512 -79961
  5. package/lib/index.js +1283 -992
  6. package/lib/p2-router-fs.js +1 -1
  7. package/lib/types/client/CodeEditor.d.ts +8 -0
  8. package/lib/types/client/RemoteExplorer.d.ts +53 -0
  9. package/lib/types/client/api.d.ts +37 -2
  10. package/lib/types/client/changes/review-state.d.ts +19 -0
  11. package/lib/types/client/connection.d.ts +16 -0
  12. package/lib/types/client/request-gate.d.ts +110 -0
  13. package/lib/types/client/scm/DiffView.d.ts +45 -7
  14. package/lib/types/client/scm/actions.d.ts +31 -3
  15. package/lib/types/client/store.d.ts +53 -0
  16. package/lib/types/client/vsc/FindWidget.d.ts +6 -0
  17. package/lib/types/client/vsc/change-marks.d.ts +16 -6
  18. package/lib/types/client/vsc/editor-keymap.d.ts +35 -1
  19. package/lib/types/client/vsc/kit.d.ts +11 -0
  20. package/lib/types/client/vsc/save-shortcut.d.ts +21 -0
  21. package/lib/types/client/vsc/terminal-theme.d.ts +28 -2
  22. package/lib/types/forward.d.ts +12 -0
  23. package/lib/types/fs-ops.d.ts +42 -0
  24. package/lib/types/http.d.ts +2 -0
  25. package/lib/types/keygen.d.ts +9 -0
  26. package/lib/types/monitor.d.ts +8 -0
  27. package/lib/types/notices.d.ts +16 -1
  28. package/lib/types/p2/helper-rpc.d.ts +45 -0
  29. package/lib/types/routes.d.ts +2 -0
  30. package/lib/types/store.d.ts +7 -0
  31. package/lib/types/terminal.d.ts +8 -0
  32. package/lib/types/view-settings.d.ts +5 -0
  33. package/lib/{worlds-B7gEDBzC.js → worlds-RG8K5eom.js} +113 -15
  34. package/package.json +2 -1
  35. package/src/client/CodeEditor.tsx +151 -8
  36. package/src/client/DirectoryFlow.tsx +16 -0
  37. package/src/client/DoctorPanel.tsx +70 -7
  38. package/src/client/EditorPane.tsx +63 -14
  39. package/src/client/HostsView.tsx +12 -3
  40. package/src/client/RemoteDirectoryPicker.tsx +12 -0
  41. package/src/client/RemoteExplorer.tsx +929 -40
  42. package/src/client/RemoteRoot.tsx +147 -22
  43. package/src/client/SearchView.tsx +8 -0
  44. package/src/client/TerminalSnippets.tsx +83 -8
  45. package/src/client/api.ts +106 -13
  46. package/src/client/changes/ChangesDock.tsx +188 -6
  47. package/src/client/changes/changes.css +10 -3
  48. package/src/client/changes/review-state.ts +34 -0
  49. package/src/client/connection.ts +29 -0
  50. package/src/client/downloads.ts +49 -4
  51. package/src/client/i18n.ts +82 -8
  52. package/src/client/request-gate.ts +221 -0
  53. package/src/client/scm/CommitPane.tsx +20 -2
  54. package/src/client/scm/DiffView.tsx +343 -117
  55. package/src/client/scm/HistoryPanel.tsx +23 -2
  56. package/src/client/scm/RepoPicker.tsx +1 -1
  57. package/src/client/scm/ScmPanel.tsx +391 -87
  58. package/src/client/scm/actions.ts +95 -12
  59. package/src/client/store.tsx +372 -9
  60. package/src/client/ui.tsx +4 -0
  61. package/src/client/vsc/FindWidget.tsx +24 -9
  62. package/src/client/vsc/breadcrumb.tsx +91 -3
  63. package/src/client/vsc/change-marks.ts +93 -44
  64. package/src/client/vsc/editor-keymap.ts +59 -1
  65. package/src/client/vsc/file-icons.tsx +17 -3
  66. package/src/client/vsc/kit.tsx +26 -9
  67. package/src/client/vsc/save-shortcut.ts +47 -1
  68. package/src/client/vsc/terminal-theme.ts +44 -18
  69. package/src/client/vsc/vsc.css +411 -153
  70. package/src/forward.ts +47 -9
  71. package/src/fs-ops.ts +124 -4
  72. package/src/git-ops.ts +20 -3
  73. package/src/http.ts +35 -4
  74. package/src/keygen.ts +55 -4
  75. package/src/monitor.ts +13 -0
  76. package/src/notices.ts +23 -1
  77. package/src/p2/helper-rpc.ts +113 -7
  78. package/src/p2/worlds.ts +14 -1
  79. package/src/routes.ts +212 -43
  80. package/src/sftp.ts +51 -14
  81. package/src/store.ts +10 -0
  82. package/src/terminal.ts +73 -26
  83. package/src/view-settings.ts +50 -10
  84. package/lib/types/client/Dialog.d.ts +0 -14
  85. package/src/client/Dialog.tsx +0 -76
@@ -29,6 +29,7 @@ import {
29
29
  gitErrorHint,
30
30
  GIT_CAP,
31
31
  headMessageCommand,
32
+ initCommand,
32
33
  mergeCommand,
33
34
  parseAllBranches,
34
35
  parseCommitFiles,
@@ -61,7 +62,8 @@ import {
61
62
  statusPathsCommand,
62
63
  unstageCommand,
63
64
  } from '../../git-ops.ts'
64
- import { api, gitTimeoutMs } from '../api.ts'
65
+ import { api, gitTimeoutMs, type RequestOptions } from '../api.ts'
66
+ import { isRequestAbort } from '../request-gate.ts'
65
67
  import { appendExecOutput, networkBudgetMs, networkCommands, type PushTarget } from '../exec-output.ts'
66
68
  import { timeoutSeconds } from '../../timeouts.ts'
67
69
 
@@ -101,19 +103,61 @@ function failureOf(result: RemoteExecResult, timeoutMs: number): GitOpError {
101
103
  return new GitOpError(hint ?? detail ?? result.error ?? `git failed [exit code: ${result.exitCode ?? '?'}]`)
102
104
  }
103
105
 
106
+ /**
107
+ * Per-command options for {@link run} / {@link tryRun}.
108
+ *
109
+ * `background` puts the command on the request gate's git channel: it waits
110
+ * while a foreground request is in flight and only one such command runs at a
111
+ * time. ONLY the repository-wide READ paths use it (`probeRepoRoot`,
112
+ * `loadStatusDetail`, `loadHead`), because those are the walks a workspace
113
+ * switch starts and the ones that must never make the directory listing queue
114
+ * behind them. Every verb the user is waiting on (stage, commit, push, the
115
+ * bounded probes, the search) stays foreground and is unaffected.
116
+ *
117
+ * `signal` cancels the command: the HTTP request is aborted (and, while still
118
+ * queued, is taken out of the queue) — the store's `readGit` uses it to release
119
+ * the connections of a workspace the user just left.
120
+ */
121
+ export interface RunOptions {
122
+ background?: boolean
123
+ signal?: AbortSignal
124
+ }
125
+
126
+ /** Map {@link RunOptions} onto the HTTP layer's {@link RequestOptions}. */
127
+ function requestOptionsOf(options: RunOptions): RequestOptions {
128
+ return {
129
+ ...(options.background === true ? { background: true } : {}),
130
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
131
+ }
132
+ }
133
+
104
134
  /** Run one command, raising a readable error on a non-zero exit. */
105
- async function run(alias: string, command: string, timeoutMs = normalTimeoutMs()): Promise<RemoteExecResult> {
106
- const result = await api.exec(alias, command, timeoutMs)
135
+ async function run(
136
+ alias: string,
137
+ command: string,
138
+ timeoutMs = normalTimeoutMs(),
139
+ options: RunOptions = {},
140
+ ): Promise<RemoteExecResult> {
141
+ const result = await api.exec(alias, command, timeoutMs, requestOptionsOf(options))
107
142
  if (result.success) return result
108
143
  throw failureOf(result, timeoutMs)
109
144
  }
110
145
 
111
146
  /** Run one command tolerating failure (returns '' instead). */
112
- async function tryRun(alias: string, command: string, timeoutMs = normalTimeoutMs()): Promise<string> {
147
+ async function tryRun(
148
+ alias: string,
149
+ command: string,
150
+ timeoutMs = normalTimeoutMs(),
151
+ options: RunOptions = {},
152
+ ): Promise<string> {
113
153
  try {
114
- const result = await api.exec(alias, command, timeoutMs)
154
+ const result = await api.exec(alias, command, timeoutMs, requestOptionsOf(options))
115
155
  return result.success ? result.stdout : ''
116
- } catch {
156
+ } catch (error) {
157
+ // A cancelled command is not "no answer": swallowing it would let the
158
+ // sibling half of a `Promise.all` land with a placeholder value (an aborted
159
+ // HEAD write once cached `detached: true`).
160
+ if (isRequestAbort(error)) throw error
117
161
  return ''
118
162
  }
119
163
  }
@@ -146,11 +190,22 @@ export type RepoRootProbe =
146
190
  | { kind: 'failed'; error: string }
147
191
 
148
192
  /** The repository root, or WHY the probe could not answer. */
149
- export async function probeRepoRoot(alias: string, workspaceRoot: string): Promise<RepoRootProbe> {
193
+ export async function probeRepoRoot(
194
+ alias: string,
195
+ workspaceRoot: string,
196
+ signal?: AbortSignal,
197
+ ): Promise<RepoRootProbe> {
150
198
  let result: RemoteExecResult
151
199
  try {
152
- result = await api.exec(alias, repoProbeDetailCommand(workspaceRoot), normalTimeoutMs())
200
+ result = await api.exec(alias, repoProbeDetailCommand(workspaceRoot), normalTimeoutMs(), {
201
+ // The probe is the FIRST step of a workspace switch's background walk: on
202
+ // a large tree it is a full `rev-parse` + `cd` over SSH, and it must yield
203
+ // to the listing the user is waiting on.
204
+ background: true,
205
+ ...(signal === undefined ? {} : { signal }),
206
+ })
153
207
  } catch (error) {
208
+ if (isRequestAbort(error)) throw error
154
209
  // The transport/route failed before any git exit code existed.
155
210
  return { kind: 'failed', error: error instanceof Error ? error.message : String(error) }
156
211
  }
@@ -171,8 +226,13 @@ export async function findRepos(alias: string, workspaceRoot: string): Promise<s
171
226
  }
172
227
 
173
228
  /** Every changed path plus the ignored half. */
174
- export async function loadStatusDetail(alias: string, root: string): Promise<GitStatusDetail> {
175
- const out = await run(alias, statusDetailCommand(root))
229
+ export async function loadStatusDetail(alias: string, root: string, signal?: AbortSignal): Promise<GitStatusDetail> {
230
+ // The walk itself: the expensive half of a switch (8–9 s on the reported AOSP
231
+ // trees), so it runs on the git channel and yields to every foreground read.
232
+ const out = await run(alias, statusDetailCommand(root), normalTimeoutMs(), {
233
+ background: true,
234
+ ...(signal === undefined ? {} : { signal }),
235
+ })
176
236
  return parseStatusDetail(out.stdout)
177
237
  }
178
238
 
@@ -212,9 +272,20 @@ export async function probeStatusDir(alias: string, root: string, dir: string):
212
272
  }
213
273
 
214
274
  /** Current branch with its ahead/behind counters (detached HEAD tolerated). */
215
- export async function loadHead(alias: string, root: string): Promise<{ branch: string; detached: boolean; ahead: number; behind: number }> {
216
- const out = await tryRun(alias, branchHeaderCommand(root), 60_000)
275
+ export async function loadHead(
276
+ alias: string,
277
+ root: string,
278
+ signal?: AbortSignal,
279
+ ): Promise<{ branch: string; detached: boolean; ahead: number; behind: number }> {
280
+ const out = await tryRun(alias, branchHeaderCommand(root), 60_000, {
281
+ background: true,
282
+ ...(signal === undefined ? {} : { signal }),
283
+ })
217
284
  const first = (out.split('\0')[0] ?? out.split('\n')[0] ?? '').replace(/^## /, '').trim()
285
+ // An empty repository reports `## No commits yet on <branch>`: the branch name
286
+ // lives AFTER the words, and the generic pattern below would read "No".
287
+ const unborn = /^No commits yet on (\S+)$/.exec(first)
288
+ if (unborn !== null) return { branch: unborn[1] as string, detached: false, ahead: 0, behind: 0 }
218
289
  if (first === '' || first.startsWith('HEAD (no branch')) return { branch: 'HEAD', detached: true, ahead: 0, behind: 0 }
219
290
  const match = /^([^\s.]+(?:\.\.\.[^\s[]+)?)(?: \[(?:ahead (\d+))?(?:, )?(?:behind (\d+))?\])?/.exec(first)
220
291
  if (match === null) return { branch: first, detached: false, ahead: 0, behind: 0 }
@@ -374,6 +445,18 @@ export async function loadStashes(alias: string, root: string): Promise<GitStash
374
445
 
375
446
  // ------------------------------------------------------------ write paths
376
447
 
448
+ /**
449
+ * Initialize a repository in place (`git init`).
450
+ *
451
+ * The panel's "not a repository" state used to be a dead end (the only offer
452
+ * was "browse somewhere else") while the command builder had no caller at all.
453
+ * The caller refreshes the status afterwards — that read re-probes the
454
+ * directory, so the panel moves to the normal view without another discovery.
455
+ */
456
+ export async function initRepo(alias: string, root: string): Promise<string> {
457
+ return (await run(alias, initCommand(root), 60_000)).stdout
458
+ }
459
+
377
460
  /** Stage paths (additions, edits, deletions, renames). */
378
461
  export async function stagePaths(alias: string, root: string, paths: readonly string[]): Promise<void> {
379
462
  if (paths.length === 0) return
@@ -12,7 +12,7 @@
12
12
  * Remote work stays lazy: a directory is listed once per expansion, a diff
13
13
  * loads both revisions on demand, and git status is one NUL-separated call.
14
14
  */
15
- import { useEffect, useSyncExternalStore } from 'react'
15
+ import { useCallback, useEffect, useRef, useSyncExternalStore } from 'react'
16
16
  import type { Context } from '@deepseek-ai/cordis'
17
17
  import type {
18
18
  DiffModel,
@@ -51,7 +51,8 @@ import { captureLiveEditorPosition, captureLiveEditorText, isLiveEditorDirty, is
51
51
  import { editorSeatCount } from './editor-capability.ts'
52
52
  import { planWorkspaceFollow, selectionIsSessionBinding, type WorkspaceFollowDecision } from './remote-file-open-target.ts'
53
53
  import { revealViewTab } from './reveal.ts'
54
- import { connectionStateOf, isConnectionFailure } from './connection.ts'
54
+ import { applyConnectionStatuses, connectionStateOf, isConnectionFailure, markConnectionProbeOk } from './connection.ts'
55
+ import { isRequestAbort } from './request-gate.ts'
55
56
  import { confirmDialog, isHtmlFile, isImageFile, isMarkdownFile, toast } from './vsc/kit.tsx'
56
57
  import {
57
58
  isWithinRoot,
@@ -834,6 +835,128 @@ export function useExplorer(): ExplorerValue {
834
835
  )
835
836
  }
836
837
 
838
+ /**
839
+ * The store's subscription, extracted so `useExplorerSelector` passes React a
840
+ * STABLE function: a fresh arrow per render makes `useSyncExternalStore`
841
+ * unsubscribe/resubscribe on every paint.
842
+ */
843
+ function subscribeStore(listener: () => void): () => void {
844
+ listeners.add(listener)
845
+ return () => {
846
+ listeners.delete(listener)
847
+ }
848
+ }
849
+
850
+ /**
851
+ * Shallow equality for selector results — one level deep, `Object.is` per field.
852
+ *
853
+ * Selectors naturally build a fresh `{ repoRoot, head, … }` object out of the
854
+ * snapshot, and a plain `Object.is` would then see a new reference on every
855
+ * publish and repaint the panel anyway (defeating the whole point). Passing this
856
+ * as `equal` compares the FIELDS, so "the snapshot was rebuilt but none of the
857
+ * fields I read changed" answers `true` and the previous value (and render) is
858
+ * kept. Arrays are compared as objects, i.e. by index.
859
+ *
860
+ * Shallow is deliberate: every selected field is either a primitive or a
861
+ * REFERENCE the store already owns (`status`, `buckets`, `tabs`, `untrackedDirs`
862
+ * …). Comparing those by reference is a real value check — the store only
863
+ * replaces them when they actually change.
864
+ */
865
+ export function shallowEqual(a: unknown, b: unknown): boolean {
866
+ if (Object.is(a, b)) return true
867
+ if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) return false
868
+ if (Array.isArray(a) !== Array.isArray(b)) return false
869
+ const left = a as Record<string, unknown>
870
+ const right = b as Record<string, unknown>
871
+ const keys = Object.keys(left)
872
+ if (keys.length !== Object.keys(right).length) return false
873
+ for (const key of keys) {
874
+ // `hasOwnProperty` first: `Object.is(undefined, undefined)` must still pass
875
+ // only for a field that EXISTS on both sides (a shorter object is a change).
876
+ if (!Object.prototype.hasOwnProperty.call(right, key)) return false
877
+ if (!Object.is(left[key], right[key])) return false
878
+ }
879
+ return true
880
+ }
881
+
882
+ /**
883
+ * Subscribe to ONE slice of the explorer store.
884
+ *
885
+ * Why this exists: `useExplorer()` hands out the whole `ExplorerValue`, and
886
+ * every `publish()` builds a NEW snapshot object — so every subscriber repaints
887
+ * on every mutation, including mutations its panel does not read (a save bumps
888
+ * the tab array, a git refresh replaces `status`, a rail switch changes `view`).
889
+ * With the panels kept MOUNTED, one publish therefore repainted every panel,
890
+ * and the SCM panel's change list (up to 4000 rows) was rebuilt for a change in
891
+ * an unrelated field.
892
+ *
893
+ * This hook re-renders its component ONLY when the selected value changes:
894
+ * - `publish()` still notifies every listener (that is how the store stays a
895
+ * single source of truth), but React asks this hook for a fresh value and
896
+ * `Object.is`-compares it with the last rendered one; equal means no render;
897
+ * - the selector runs at most once per (snapshot, selector) pair, and its
898
+ * result is kept in a per-hook cache, so an equal result keeps the PREVIOUS
899
+ * reference (downstream `useMemo`s keyed on it stay valid).
900
+ *
901
+ * Constraints, all from `useSyncExternalStore`:
902
+ * - the value returned for an UNCHANGED snapshot must be stable. This hook
903
+ * guarantees it (cache keyed on the snapshot identity), which is also why a
904
+ * selector may safely return a fresh object — with `shallowEqual` it is
905
+ * compared and the old reference is kept, and without `equal` it is cached
906
+ * and only recomputed when the snapshot itself changes;
907
+ * - `selector` must be PURE and should read only the snapshot. It may be an
908
+ * inline arrow (the hook tracks its identity, so a selector that closes over
909
+ * props is recomputed when it changes), but a module-level selector is
910
+ * cheaper: its identity is stable, so between publishes the cache answers
911
+ * without running it at all;
912
+ * - `selector` must not mutate the snapshot.
913
+ *
914
+ * @param selector - pure read of the fields this component needs.
915
+ * @param equal - comparison used to decide whether the new selection is the
916
+ * same value; defaults to `Object.is`. Pass `shallowEqual` for object slices.
917
+ */
918
+ export function useExplorerSelector<T>(
919
+ selector: (snapshot: ExplorerValue) => T,
920
+ equal: (a: T, b: T) => boolean = Object.is,
921
+ ): T {
922
+ /**
923
+ * Last (snapshot, selector) → value. A `useRef`, not module state: two
924
+ * components selecting different fields must not evict each other.
925
+ */
926
+ const cache = useRef<{ source: ExplorerValue; selector: (snapshot: ExplorerValue) => T; value: T } | undefined>(undefined)
927
+ /**
928
+ * Latest selector/equal, kept in refs so `getSelection` can stay stable
929
+ * (one `useCallback([])`) while still calling the CURRENT functions. A
930
+ * selector that closes over props changes identity every render; comparing it
931
+ * with the cached one is what makes such a selector recompute (and see the new
932
+ * props) instead of returning the previous, now stale, value.
933
+ */
934
+ const selectorRef = useRef(selector)
935
+ selectorRef.current = selector
936
+ const equalRef = useRef(equal)
937
+ equalRef.current = equal
938
+ const getSelection = useCallback((): T => {
939
+ const source = snapshot
940
+ const current = cache.current
941
+ if (current !== undefined && current.source === source && current.selector === selectorRef.current) {
942
+ // Same snapshot, same selector: the cached value is the answer. This is
943
+ // what `useSyncExternalStore` requires (a changing value here would loop),
944
+ // and what keeps two consecutive reads of one snapshot identical.
945
+ return current.value
946
+ }
947
+ const next = selectorRef.current(source)
948
+ if (current !== undefined && equalRef.current(current.value, next)) {
949
+ // The snapshot moved but this slice did not: keep the OLD reference so
950
+ // React sees no change (no render) and downstream memo keys stay stable.
951
+ cache.current = { source, selector: selectorRef.current, value: current.value }
952
+ return current.value
953
+ }
954
+ cache.current = { source, selector: selectorRef.current, value: next }
955
+ return next
956
+ }, [])
957
+ return useSyncExternalStore(subscribeStore, getSelection)
958
+ }
959
+
837
960
  /** The repo-relative path of an absolute remote path ('' when outside). */
838
961
  export function repoRelative(repoRoot: string | undefined, fullPath: string): string {
839
962
  if (repoRoot === undefined) return ''
@@ -887,6 +1010,23 @@ const gitReads = new ReadQueue(refreshGitBusy)
887
1010
  const latestGitRead = new Map<string, number>()
888
1011
  let gitReadTicket = 0
889
1012
 
1013
+ /**
1014
+ * Cancellation handle for the git read in flight per binding.
1015
+ *
1016
+ * A workspace switch must take the OLD workspace's repository walk out of the
1017
+ * browser's connection pool. The browser gives one origin six connections and
1018
+ * the walk (probe + status + branch header) is the largest thing the plugin
1019
+ * sends; measured on the reported P710/Z700 trees, the walk took 8–9 s and a
1020
+ * purely in-memory `/status` route took 2.7–4.6 s during it — that is queueing,
1021
+ * not a slow host. Aborting the HTTP request frees the connection immediately;
1022
+ * the answer of an aborted read is dropped on purpose (a newer read of that
1023
+ * binding, or of the workspace now on screen, is the one that matters).
1024
+ *
1025
+ * One controller per binding, so a repo-picker move (same binding, another
1026
+ * directory) also retires the read it supersedes.
1027
+ */
1028
+ const gitReadAborts = new Map<string, AbortController>()
1029
+
890
1030
  /** True when `bindingId`'s read `ticket` may paint the on-screen slice. */
891
1031
  function gitReadIsCurrent(bindingId: string, ticket: number): boolean {
892
1032
  return latestGitRead.get(bindingId) === ticket && activeBinding().key === bindingId
@@ -1400,10 +1540,77 @@ function confirmDiscardOnWorkspaceSwitch(dirty: readonly EditorTab[]): Promise<b
1400
1540
  })
1401
1541
  }
1402
1542
 
1543
+ /**
1544
+ * The in-flight switch probe, so a newer switch cancels an older dial.
1545
+ *
1546
+ * A test dial is a real SSH connection attempt: against a host that is down it
1547
+ * runs for the connection timeout (tens of seconds), and it is a FOREGROUND
1548
+ * request (the tree is waiting on its answer), so it would hold the background
1549
+ * git channel shut behind it. Switching again makes that dial pointless, hence
1550
+ * the abort.
1551
+ */
1552
+ let switchProbe: { alias: string; controller: AbortController } | undefined
1553
+
1554
+ /**
1555
+ * Re-prove one alias' link when the user selects a workspace on it.
1556
+ *
1557
+ * The connection chip polls (and an explicit retry is exactly this pair of
1558
+ * calls), but the tree gates on the same evidence: `loadDir`/`prefetchDir`
1559
+ * refuse an alias known down. A switch made inside the poll interval therefore
1560
+ * used to leave the tree empty until the next tick — the user had to retry by
1561
+ * hand. One dial here answers the question the switch just raised; a failed
1562
+ * probe changes nothing (the chip owns the failure, and the alias stays down).
1563
+ */
1564
+ function probeConnectionOnSwitch(alias: string): void {
1565
+ if (alias === '') return
1566
+ switchProbe?.controller.abort()
1567
+ const controller = new AbortController()
1568
+ switchProbe = { alias, controller }
1569
+ void (async () => {
1570
+ try {
1571
+ // Background on purpose: a dead host's dial runs for the connection
1572
+ // timeout (45 s + guard). As a FOREGROUND request it would hold the
1573
+ // foreground counter up for that whole window and starve every background
1574
+ // git read; as a background one it only contends with the git channel,
1575
+ // while the tree keeps showing its cached/empty state.
1576
+ const answer = await api.testHost(alias, { background: true, signal: controller.signal })
1577
+ if (controller.signal.aborted || !answer.ok) return
1578
+ // The same two steps as the chip's retry: record the success (so a stale
1579
+ // poll cannot paint it red again) and refresh the pooled status.
1580
+ markConnectionProbeOk(alias)
1581
+ const statuses = await api.connectionStatus()
1582
+ if (controller.signal.aborted) return
1583
+ applyConnectionStatuses(statuses)
1584
+ } catch {
1585
+ // A failed probe is not news: the alias keeps the state the chip shows.
1586
+ } finally {
1587
+ if (switchProbe?.controller === controller) switchProbe = undefined
1588
+ }
1589
+ })()
1590
+ }
1591
+
1403
1592
  /** Move the selection; `byUser` decides whether it is remembered as a choice. */
1404
1593
  function applyWorkspaceSelection(id: string, byUser: boolean): void {
1405
1594
  if (state.workspaceId === id) return
1406
1595
  if (byUser) noteManualPick()
1596
+ const target = state.workspaces.find(item => item.id === id)
1597
+ // A connection probe started for the workspace being left is a real SSH dial
1598
+ // (up to the connection timeout on a dead host) and it is a FOREGROUND
1599
+ // request: left running, it would keep the background git channel of the NEW
1600
+ // workspace shut. Cancel it whether or not the new alias needs its own probe.
1601
+ if (switchProbe !== undefined && switchProbe.alias !== target?.alias) {
1602
+ switchProbe.controller.abort()
1603
+ switchProbe = undefined
1604
+ }
1605
+ // The workspace being left may have a full `git status` walk in flight. It is
1606
+ // no longer what the screen shows, and its connections are exactly what the
1607
+ // new workspace's directory list needs — cancel it here (the read drops its
1608
+ // answer; the cache it may already have written stays).
1609
+ for (const [readId, controller] of [...gitReadAborts]) {
1610
+ if (readId === id) continue
1611
+ controller.abort()
1612
+ gitReadAborts.delete(readId)
1613
+ }
1407
1614
  // Local stage results are repository-relative: another binding's paths must
1408
1615
  // never be re-applied to this one. The expanded untracked directories are
1409
1616
  // repository-relative too.
@@ -1430,6 +1637,9 @@ function applyWorkspaceSelection(id: string, byUser: boolean): void {
1430
1637
  // flag must reflect that before anything is published again.
1431
1638
  refreshGitBusy()
1432
1639
  if (stale) void refreshGit('join')
1640
+ // Selected onto an alias whose last known state was `error`: ask once, so the
1641
+ // tree is not gated offline by evidence from before the switch.
1642
+ if (target !== undefined && connectionStateOf(target.alias) === 'error') probeConnectionOnSwitch(target.alias)
1433
1643
  }
1434
1644
 
1435
1645
  let searchSeq = 0
@@ -1479,6 +1689,9 @@ let manualPickSession: string | undefined
1479
1689
  */
1480
1690
  function noteManualPick(): void {
1481
1691
  if (followSessionId !== undefined) manualPickSession = followSessionId
1692
+ // An explicit choice settles the follow for good: no fast retry may move the
1693
+ // selection out from under it afterwards.
1694
+ clearFollowRetry()
1482
1695
  }
1483
1696
 
1484
1697
  /**
@@ -1506,11 +1719,118 @@ export function setFollowSession(sessionId: string | undefined): void {
1506
1719
  // A new seat re-follows: the previous session's manual pick was about that
1507
1720
  // session's workspace, not this one's.
1508
1721
  manualPickSession = undefined
1722
+ // …and its pending retry was about the previous session too.
1723
+ clearFollowRetry()
1724
+ // A different seat gets its own fast-retry budget.
1725
+ followFastRetrySpent = undefined
1509
1726
  }
1510
1727
 
1511
1728
  /** One resolution in flight, so the same session is never probed twice at once. */
1512
1729
  let followFlight: { sessionId: string; promise: Promise<string | undefined> } | undefined
1513
1730
 
1731
+ /**
1732
+ * Fast retries for a session whose workspace has not resolved yet.
1733
+ *
1734
+ * Opening a conversation right after a page load (or before the change panel's
1735
+ * first scan) used to leave the selector on the previous workspace until the
1736
+ * panel's slow fallback came around: the workspace visibly switched by itself a
1737
+ * quarter of a minute later, which reads as a slow/glitchy app. Three quick
1738
+ * attempts cover that window; the SLOW fallback stays in the panel, so this is a
1739
+ * latency fix, not a second poll. Only an UNRESOLVED follow retries: an answer
1740
+ * that landed, a manual pick and a session change all stop the chain.
1741
+ *
1742
+ * Module-level state for the same reason the follow itself is: it must outlive
1743
+ * any one surface's render, and there is exactly one follow per page.
1744
+ */
1745
+ const FOLLOW_FAST_RETRY_MS = [300, 1_000, 3_000] as const
1746
+
1747
+ /** The pending fast-retry chain (one session at a time). */
1748
+ let followRetry: { sessionId: string; attempt: number; timer: ReturnType<typeof setTimeout> } | undefined
1749
+
1750
+ /**
1751
+ * Session whose fast-retry budget has been spent.
1752
+ *
1753
+ * The slow panel tick keeps calling the follow every 15 s; without this, each
1754
+ * unresolved answer would arm a NEW three-attempt chain and a session with no
1755
+ * resolvable workspace would cost four cwd probes per tick instead of one.
1756
+ * Cleared when the session changes (a new seat gets its own budget).
1757
+ */
1758
+ let followFastRetrySpent: string | undefined
1759
+
1760
+ /** > 0 while a retry-driven `followSessionWorkspace` call is in flight. */
1761
+ let followRetryDrive = 0
1762
+
1763
+ /** Drop the pending retry (a resolution landed, the session changed, or the user picked). */
1764
+ function clearFollowRetry(): void {
1765
+ if (followRetry === undefined) return
1766
+ clearTimeout(followRetry.timer)
1767
+ followRetry = undefined
1768
+ }
1769
+
1770
+ /** Is the retry chain still about the session on screen, and still wanted? */
1771
+ function followRetryWanted(sessionId: string): boolean {
1772
+ return followSessionId === sessionId
1773
+ && followedSession !== sessionId
1774
+ && manualPickSession !== sessionId
1775
+ }
1776
+
1777
+ /**
1778
+ * Arm one attempt of the chain.
1779
+ *
1780
+ * The timer calls the follow again; a resolution that still has not landed
1781
+ * schedules the next attempt, and the chain stops after
1782
+ * {@link FOLLOW_FAST_RETRY_MS}'s last entry. "Still not landed" includes a cwd
1783
+ * probe that failed (resolved as "nothing resolved", not thrown); only a
1784
+ * rejection of the whole follow call — a bug, not a host answer — stops the
1785
+ * chain outright.
1786
+ */
1787
+ function startFollowRetry(sessionId: string, attempt: number): void {
1788
+ clearFollowRetry()
1789
+ if (!followRetryWanted(sessionId)) return
1790
+ if (attempt >= FOLLOW_FAST_RETRY_MS.length) {
1791
+ followFastRetrySpent = sessionId
1792
+ return
1793
+ }
1794
+ const timer = setTimeout(() => {
1795
+ followRetry = undefined
1796
+ if (!followRetryWanted(sessionId)) return
1797
+ followRetryDrive += 1
1798
+ void followSessionWorkspace({}).then(
1799
+ (resolved) => {
1800
+ followRetryDrive -= 1
1801
+ if (resolved !== undefined || !followRetryWanted(sessionId)) {
1802
+ clearFollowRetry()
1803
+ return
1804
+ }
1805
+ startFollowRetry(sessionId, attempt + 1)
1806
+ },
1807
+ () => {
1808
+ followRetryDrive -= 1
1809
+ clearFollowRetry()
1810
+ },
1811
+ )
1812
+ }, FOLLOW_FAST_RETRY_MS[attempt] as number)
1813
+ // Never keep a Node gate (or a closing page) alive just for a retry.
1814
+ timer.unref?.()
1815
+ followRetry = { sessionId, attempt, timer }
1816
+ }
1817
+
1818
+ /**
1819
+ * Note that one resolution came back unresolved and arm the fast retry.
1820
+ *
1821
+ * A no-op while the chain already runs for this session (the chain owns its next
1822
+ * attempt — scheduling from here would restart the delays) and while a
1823
+ * retry-driven call is in flight. A chain belonging to ANOTHER session is stale
1824
+ * and is replaced.
1825
+ */
1826
+ function noteFollowUnresolved(sessionId: string): void {
1827
+ // The fast budget is once per session: the slow tick must not refill it.
1828
+ if (followFastRetrySpent === sessionId) return
1829
+ if (followRetry !== undefined && followRetry.sessionId !== sessionId) clearFollowRetry()
1830
+ if (followRetryDrive > 0 || followRetry !== undefined) return
1831
+ startFollowRetry(sessionId, 0)
1832
+ }
1833
+
1514
1834
  /**
1515
1835
  * Point the workspace selector (and with it the tree, the editor's dropdown and
1516
1836
  * the git panel) at the binding the registered session works in.
@@ -1569,8 +1889,14 @@ export function followSessionWorkspace(options: {
1569
1889
  // re-deciding what was already decided. A manual pick made BEFORE anything
1570
1890
  // resolved (see `manualPickSession`) is the same promise, kept even though
1571
1891
  // there is no follow to remember.
1572
- if (followedSession === sessionId) return Promise.resolve(followedBindingId)
1573
- if (manualPickSession === sessionId) return Promise.resolve(undefined)
1892
+ if (followedSession === sessionId) {
1893
+ clearFollowRetry()
1894
+ return Promise.resolve(followedBindingId)
1895
+ }
1896
+ if (manualPickSession === sessionId) {
1897
+ clearFollowRetry()
1898
+ return Promise.resolve(undefined)
1899
+ }
1574
1900
  const inFlight = followFlight
1575
1901
  if (inFlight !== undefined && inFlight.sessionId === sessionId) return inFlight.promise
1576
1902
  const promise = resolveSessionWorkspace(sessionId, options).finally(() => {
@@ -1611,6 +1937,9 @@ async function resolveSessionWorkspace(
1611
1937
  cwd = answer.cwd
1612
1938
  } catch {
1613
1939
  // A failed probe resolves nothing: the selection stands, nothing is sent.
1940
+ // Still unresolved, so the fast retry gets its chance (the panel's slow
1941
+ // fallback would otherwise be the only way out).
1942
+ noteFollowUnresolved(sessionId)
1614
1943
  return undefined
1615
1944
  }
1616
1945
  // The session may have changed while the host was answering; its evidence
@@ -1618,12 +1947,23 @@ async function resolveSessionWorkspace(
1618
1947
  if (followSessionId !== sessionId) return undefined
1619
1948
  if (cwd !== undefined && cwd !== '') decision = plan(cwd)
1620
1949
  }
1621
- if (decision.action === 'keep') return undefined
1950
+ if (decision.action === 'keep') {
1951
+ // Nothing resolved (the host knows no usable cwd for this session, or the
1952
+ // evidence names no binding): arm the fast retry instead of waiting for the
1953
+ // panel's slow one.
1954
+ noteFollowUnresolved(sessionId)
1955
+ return undefined
1956
+ }
1622
1957
  // The user may have chosen a workspace WHILE this resolution was in flight:
1623
1958
  // a choice beats a late answer.
1624
- if (followSessionId !== sessionId || manualPickSession === sessionId) return undefined
1959
+ if (followSessionId !== sessionId || manualPickSession === sessionId) {
1960
+ clearFollowRetry()
1961
+ return undefined
1962
+ }
1625
1963
  followedSession = decision.followedSession
1626
1964
  followedBindingId = decision.bindingId
1965
+ // An answer landed: the chain has nothing left to do.
1966
+ clearFollowRetry()
1627
1967
  if (state.workspaceId !== decision.bindingId) selectWorkspaceAuto(decision.bindingId)
1628
1968
  return decision.bindingId
1629
1969
  }
@@ -1767,6 +2107,9 @@ export async function refreshGit(mode: 'join' | 'fresh' = 'fresh'): Promise<void
1767
2107
  try {
1768
2108
  await gitReads.run(cacheKey, () => readGit(key, subdir, cacheKey), mode, settleMs)
1769
2109
  } catch (error) {
2110
+ // A cancelled read (a workspace switch retired it) is not a failure: the
2111
+ // selection moved on and there is nothing to report for the old key.
2112
+ if (isRequestAbort(error)) return
1770
2113
  // Only the settle deadline (or a throw before the read's own try) lands
1771
2114
  // here: `readGit` handles read failures itself. The failure belongs to the
1772
2115
  // key this read STARTED with — the repo picker may have moved the panel to
@@ -1789,6 +2132,14 @@ async function readGit(bindingId: string, subdir: string, cacheKey: string): Pro
1789
2132
  // The binding can disappear from the table while this read waits in the queue.
1790
2133
  const workspace = state.workspaces.find(item => item.id === bindingId)
1791
2134
  if (workspace === undefined) return
2135
+ // A read of the SAME binding is starting: the one already running describes a
2136
+ // slice that is about to be replaced (another repository directory, or a
2137
+ // refresh that started later), so it must release its connection instead of
2138
+ // walking the tree to an answer nobody will use.
2139
+ gitReadAborts.get(bindingId)?.abort()
2140
+ const controller = new AbortController()
2141
+ gitReadAborts.set(bindingId, controller)
2142
+ const signal = controller.signal
1792
2143
  const ticket = ++gitReadTicket
1793
2144
  latestGitRead.set(bindingId, ticket)
1794
2145
  // A local stage/unstage that happens while this read is in flight cannot be in
@@ -1802,7 +2153,7 @@ async function readGit(bindingId: string, subdir: string, cacheKey: string): Pro
1802
2153
  // hint, which is the very blank state the cache exists to prevent.
1803
2154
  // `withDeadline` covers the host that never answers at all; the probe itself
1804
2155
  // reports transport failures.
1805
- const probe = await withDeadline(probeRepoRoot(workspace.alias, workdir), gitDeadlineMs(), t('editor.readTimeout'))
2156
+ const probe = await withDeadline(probeRepoRoot(workspace.alias, workdir, signal), gitDeadlineMs(), t('editor.readTimeout'))
1806
2157
  if (probe.kind === 'failed') throw new Error(probe.error)
1807
2158
  if (probe.kind === 'none') {
1808
2159
  const snapshot: GitSnapshot = {
@@ -1820,9 +2171,12 @@ async function readGit(bindingId: string, subdir: string, cacheKey: string): Pro
1820
2171
  }
1821
2172
  const root = probe.root
1822
2173
  const [detail, head] = await Promise.all([
1823
- withDeadline(loadStatusDetail(workspace.alias, root), gitDeadlineMs(), t('editor.readTimeout')),
1824
- withDeadline(loadHead(workspace.alias, root), gitDeadlineMs(), t('editor.readTimeout')),
2174
+ withDeadline(loadStatusDetail(workspace.alias, root, signal), gitDeadlineMs(), t('editor.readTimeout')),
2175
+ withDeadline(loadHead(workspace.alias, root, signal), gitDeadlineMs(), t('editor.readTimeout')),
1825
2176
  ])
2177
+ // One half may have been aborted while the other answered; a half-finished
2178
+ // pair must never be cached (an aborted HEAD once landed as "detached").
2179
+ if (signal.aborted) return
1826
2180
  // A directory INSIDE a repository settles on that repository's root, so the
1827
2181
  // stored choice is what git actually uses (and what the picker shows). Only
1828
2182
  // the binding's LATEST read may rewrite that persisted choice: a read
@@ -1866,6 +2220,11 @@ async function readGit(bindingId: string, subdir: string, cacheKey: string): Pro
1866
2220
  if (settled !== subdir) writeGitSnapshot(gitCacheKey(bindingId, settled), snapshot)
1867
2221
  paintGit(bindingId, ticket, snapshot)
1868
2222
  } catch (error) {
2223
+ // An ABORTED read is not a failure. The switch (or the newer read that
2224
+ // superseded this one) cancelled it on purpose, so there is nothing to
2225
+ // report: `gitError` would blame the user's new workspace for a walk they
2226
+ // left, and the cached slice they already have stays the truth.
2227
+ if (signal.aborted || isRequestAbort(error)) return
1869
2228
  if (!gitReadIsCurrent(bindingId, ticket)) return
1870
2229
  // A failed read discards nothing that was already known: the panel keeps the
1871
2230
  // last good (or cached) slice and prints the message above it, so a transient
@@ -1875,6 +2234,10 @@ async function readGit(bindingId: string, subdir: string, cacheKey: string): Pro
1875
2234
  gitError: error instanceof Error ? error.message : String(error),
1876
2235
  gitCached: state.repoRoot !== undefined,
1877
2236
  })
2237
+ } finally {
2238
+ // Only the read that still owns the slot may clear it: a newer read has
2239
+ // already replaced the map entry and must stay abortable.
2240
+ if (gitReadAborts.get(bindingId) === controller) gitReadAborts.delete(bindingId)
1878
2241
  }
1879
2242
  }
1880
2243