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/client/api.ts CHANGED
@@ -12,6 +12,7 @@ import {
12
12
  type ImportReport,
13
13
  type RemoteChangesDiff,
14
14
  type RemoteChangesSummary,
15
+ type RemoteConnectionStatus,
15
16
  type RemoteDeployState,
16
17
  type RemoteExecResult,
17
18
  type RemoteFileEntry,
@@ -22,8 +23,12 @@ import {
22
23
  type RemoteRoutingStatus,
23
24
  type RemoteTimeouts,
24
25
  type RemoteWorkspaceBinding,
26
+ type RemoteWriteConflict,
27
+ type RemoteWriteResult,
25
28
  } from '../protocol.ts'
26
29
  import { DEFAULT_TIMEOUTS, normalizeTimeouts, timeoutSeconds } from '../timeouts.ts'
30
+ import { activeConnectionAlias, currentConnection, isConnectionFailure, noteConnectionFailure } from './connection.ts'
31
+ import { detectLang, makeT } from './i18n.ts'
27
32
  import { parseSseFrame, takeSseFrames } from './exec-output.ts'
28
33
  import {
29
34
  branchesCommand,
@@ -39,6 +44,33 @@ import {
39
44
  } from '../git-format.ts'
40
45
 
41
46
  export class RemoteApiError extends Error {
47
+ /**
48
+ * The request failed because the SSH link did, not because the remote said no.
49
+ *
50
+ * Carried as a flag because the message can be REWRITTEN to a localized
51
+ * sentence for repeat failures; classification must survive that rewrite so
52
+ * callers (toast quieting, offline banners) keep treating it as transport.
53
+ */
54
+ transport?: boolean
55
+ /**
56
+ * The operation ran out of its budget; the link itself was not proven bad.
57
+ *
58
+ * Set from the Host's `code: 'deadline'`. It keeps classification honest: one
59
+ * slow request (a huge directory, an 8 MiB read on a thin link) must not flip
60
+ * the chip to "connection error" or downgrade the editor to read-only, while
61
+ * the operation still fails for the user with its readable reason.
62
+ */
63
+ deadline?: boolean
64
+ /**
65
+ * The remote file moved on since the version this buffer was based on.
66
+ *
67
+ * Carried as DATA, not prose: the editor has to offer overwrite / reload /
68
+ * see-the-difference, and that needs what is there now (`mtime`, `size`)
69
+ * without another round trip. The status is 409 for exactly this case — a
70
+ * plain 502 would read as "the host failed", which is the opposite of what
71
+ * happened (the Host successfully protected the file).
72
+ */
73
+ conflict?: RemoteWriteConflict
42
74
  constructor(
43
75
  readonly status: number,
44
76
  message: string,
@@ -47,6 +79,20 @@ export class RemoteApiError extends Error {
47
79
  }
48
80
  }
49
81
 
82
+ /**
83
+ * Validate a 409 payload before believing it is a save conflict.
84
+ *
85
+ * A conflict the client cannot read (an older Host, a proxy that rewrote the
86
+ * body) must fall back to the generic error path rather than produce a
87
+ * half-populated prompt.
88
+ */
89
+ function isWriteConflict(value: unknown): value is RemoteWriteConflict {
90
+ if (typeof value !== 'object' || value === null) return false
91
+ const shape = value as { mtime?: unknown; size?: unknown }
92
+ const measured = (field: unknown): boolean => field === null || (typeof field === 'number' && Number.isFinite(field))
93
+ return measured(shape.mtime) && measured(shape.size)
94
+ }
95
+
50
96
  async function call<T>(path: string, init?: RequestInit): Promise<T> {
51
97
  const res = await fetch(path, {
52
98
  ...init,
@@ -59,10 +105,37 @@ async function call<T>(path: string, init?: RequestInit): Promise<T> {
59
105
  // Fall through to the status check with a generic message.
60
106
  }
61
107
  if (!res.ok) {
62
- const message = typeof data === 'object' && data !== null && 'error' in data && typeof (data as { error: unknown }).error === 'string'
63
- ? (data as { error: string }).error
64
- : `request failed: HTTP ${res.status}`
65
- throw new RemoteApiError(res.status, message)
108
+ const body = typeof data === 'object' && data !== null
109
+ ? data as { error?: unknown; code?: unknown; conflict?: unknown }
110
+ : undefined
111
+ const message = typeof body?.error === 'string' ? body.error : `request failed: HTTP ${res.status}`
112
+ const failure = new RemoteApiError(res.status, message)
113
+ if (body?.code === 'deadline') failure.deadline = true
114
+ // A refused save is not a link failure: keep its payload so the caller can
115
+ // ask the user what to do with the current version.
116
+ if (body?.code === 'conflict' && isWriteConflict(body.conflict)) failure.conflict = body.conflict
117
+ // Classify the ERROR (not its text): the deadline flag has to be seen here,
118
+ // or a slow request is mistaken for a dead link.
119
+ if (isConnectionFailure(failure)) {
120
+ failure.transport = true
121
+ // Was the link already known to be down? The FIRST failure keeps its raw
122
+ // diagnostic (that is how the user learns WHY); every later failure is a
123
+ // repeat — the chip already explains it, so surfaces get one short
124
+ // sentence instead of another ssh2 string. The raw text stays on the
125
+ // console for anyone debugging the host.
126
+ const repeat = currentConnection()?.state === 'error'
127
+ noteConnectionFailure(activeConnectionAlias(), failure)
128
+ if (repeat) {
129
+ console.debug('[dsh-remote-vs] transport error:', message)
130
+ // Translated at throw time (not module load): the message follows the
131
+ // language the page is in when the failure happens.
132
+ const localized = new RemoteApiError(res.status, makeT(detectLang())('connection.actionFailed'))
133
+ localized.transport = true
134
+ throw localized
135
+ }
136
+ throw failure
137
+ }
138
+ throw failure
66
139
  }
67
140
  return data as T
68
141
  }
@@ -75,7 +148,11 @@ function post<T>(path: string, body: unknown): Promise<T> {
75
148
  function throwIfGitFailed(r: RemoteExecResult, timeoutMs: number): void {
76
149
  if (r.success) return
77
150
  if (r.timedOut) {
78
- throw new RemoteApiError(502, `git timed out after ${timeoutSeconds(timeoutMs)} (big/slow repo — retry, it may be warm now; raise gitTimeoutMs in the plugin settings)`)
151
+ const timedOut = new RemoteApiError(502, `git timed out after ${timeoutSeconds(timeoutMs)} (big/slow repo — retry, it may be warm now; raise gitTimeoutMs in the plugin settings)`)
152
+ // A command budget, not a link failure (the exec route reports a timeout as
153
+ // a result, never as a transport error).
154
+ timedOut.deadline = true
155
+ throw timedOut
79
156
  }
80
157
  const friendly = gitFailed(r.stderr)
81
158
  throw new RemoteApiError(502, friendly ?? (r.stderr.trim() || r.error || `git failed [exit code: ${r.exitCode}]`))
@@ -203,6 +280,8 @@ export function uploadFile(options: {
203
280
  // Keep the status-based message below.
204
281
  }
205
282
  if (xhr.status >= 200 && xhr.status < 300) {
283
+ // The bytes are on the remote host now: the quick-open index is stale.
284
+ noteRemoteWrite()
206
285
  const size = typeof body === 'object' && body !== null && typeof (body as { size?: unknown }).size === 'number'
207
286
  ? (body as { size: number }).size
208
287
  : options.blob.size
@@ -237,6 +316,85 @@ export interface PushReportView {
237
316
  detail: string
238
317
  }
239
318
 
319
+ /**
320
+ * How many remote WRITES this client session has issued.
321
+ *
322
+ * The quick-open file index is memory-only, so it has no filesystem watcher to
323
+ * tell it the tree changed; a write is the only signal there is. A counter is
324
+ * the smallest possible coupling: the writer does not know who caches, and a
325
+ * reader compares the number it saw when it built (see `quickopen-model.ts`) — a
326
+ * mismatch means rebuild.
327
+ *
328
+ * Bumped when the write actually LANDED (a rejected or conflicted write changed
329
+ * nothing and must not cost a rebuild), which is why the call sites sit on the
330
+ * success path.
331
+ *
332
+ * What bumps it:
333
+ * - the panel's own file writes: `fileOp.write/mkdir/rm/rename` and uploads;
334
+ * - the SCM verbs that change the WORKING TREE, detected in {@link execChangesWorktree}
335
+ * because those commands are built and issued outside this module
336
+ * (`scm/actions.ts`): discard (`restore` / `clean -fd`, which deletes untracked
337
+ * files), branch switches (`checkout` / `switch`), `reset`, `stash apply|pop`,
338
+ * patch/merge verbs and `pull`.
339
+ *
340
+ * Known boundary (deliberate, not an oversight): writes that do not come through
341
+ * either of those paths — a command typed in the remote terminal, or one the
342
+ * model runs through its own tooling — are invisible here. They are picked up on
343
+ * the next panel write, the next SCM worktree verb, or a page reload.
344
+ */
345
+ let remoteWriteSeq = 0
346
+
347
+ /** Record one landed remote write (see {@link remoteWriteSequence}). */
348
+ export function noteRemoteWrite(): void {
349
+ remoteWriteSeq += 1
350
+ }
351
+
352
+ /** The counter a cached listing must match to still be considered fresh. */
353
+ export function remoteWriteSequence(): number {
354
+ return remoteWriteSeq
355
+ }
356
+
357
+ /**
358
+ * Git verbs that change the WORKING TREE, so a file index built before them may
359
+ * list paths that no longer exist (or miss ones that now do).
360
+ *
361
+ * Deliberately narrow, and it reads the INDEX-ONLY variants out on purpose:
362
+ * - `restore --staged` (unstage) and `apply --cached` (stage a hunk) touch the
363
+ * index only, so the file set is unchanged — invalidating on those would
364
+ * rebuild the index after every stage click;
365
+ * - `stash drop` and `git branch -d` leave the worktree alone;
366
+ * - read verbs (`status`, `log`, `diff`, `show`, `rev-parse`, `stash list`,
367
+ * `ls-files`, …) run constantly.
368
+ * What DOES invalidate: discards (`restore`/`clean -fd`, which deletes untracked
369
+ * files), branch switches (`checkout`/`switch`), `reset`, `stash` apply/pop and
370
+ * `stash push`/`save`, patch/merge verbs (`apply` without `--cached`, `am`,
371
+ * `merge`, `rebase`, `cherry-pick`, `revert`) and `pull`.
372
+ */
373
+ const WORKTREE_WRITE_COMMAND =
374
+ /\bgit\b[^\n]*?\s(?:restore(?!\s+--staged)|clean|checkout|switch|reset|merge|rebase|cherry-pick|revert|pull|am|apply(?!\s+--(?:cached|index))|stash\s+(?:apply|pop|push|save))\b/
375
+
376
+ /**
377
+ * Does this remote command change the working tree?
378
+ *
379
+ * Exported so the gate can drive it directly: the SCM verbs do not pass through
380
+ * `api.fileOp`, so this predicate is the only thing that makes discard/checkout/
381
+ * stash invalidate the quick-open index at all.
382
+ */
383
+ export function execChangesWorktree(command: string): boolean {
384
+ return WORKTREE_WRITE_COMMAND.test(command)
385
+ }
386
+
387
+ /** Bump the counter for one landed command that changed the working tree. */
388
+ function afterRemoteCommand(command: string): void {
389
+ if (execChangesWorktree(command)) noteRemoteWrite()
390
+ }
391
+
392
+ /** Promise helper: bump the counter when a write request resolved. */
393
+ function afterRemoteWrite<T>(value: T): T {
394
+ noteRemoteWrite()
395
+ return value
396
+ }
397
+
240
398
  export const api = {
241
399
  // -- hosts
242
400
  getHosts: () => call<{ hosts: RemoteHostSummary[] }>(REMOTE_API.hosts).then(r => r.hosts),
@@ -250,6 +408,8 @@ export const api = {
250
408
  deleteHost: (alias: string) =>
251
409
  call<{ ok: boolean }>(`${REMOTE_API.hosts}?alias=${encodeURIComponent(alias)}`, { method: 'DELETE' }),
252
410
  testHost: (alias: string) => post<{ ok: boolean; error?: string; durationMs: number }>(REMOTE_API.test, { alias }),
411
+ /** Per-alias SSH connection health (Host pool's view; this is a local poll). */
412
+ connectionStatus: () => call<{ connections: RemoteConnectionStatus[] }>(REMOTE_API.status).then(r => r.connections),
253
413
  bootstrap: (alias: string) => post<{ alias: string; keyPath: string; flipped: boolean; detail: string }>(REMOTE_API.keygen, { alias }),
254
414
  // -- files
255
415
  fileOp: {
@@ -258,17 +418,40 @@ export const api = {
258
418
  stat: (alias: string, path: string) =>
259
419
  post<{ entry: RemoteFileEntry }>(REMOTE_API.files, { op: 'stat', alias, path }).then(r => r.entry),
260
420
  read: (alias: string, path: string) => post<RemoteRead>(REMOTE_API.files, { op: 'read', alias, path }),
261
- write: (alias: string, path: string, content: string) =>
262
- post<{ size: number }>(REMOTE_API.files, { op: 'write', alias, path, content, encoding: 'utf8' }),
263
- mkdir: (alias: string, path: string) => post<{ ok: boolean }>(REMOTE_API.files, { op: 'mkdir', alias, path }),
421
+ /**
422
+ * Write one file, optionally guarded by the version it was based on.
423
+ *
424
+ * `guard` is the save-conflict lock: the Host refuses (409, `code:
425
+ * 'conflict'`) when the remote file no longer matches, and the caller gets a
426
+ * `RemoteApiError` carrying `conflict`. Omitting it keeps the old
427
+ * unconditional write, which is what every programmatic caller wants.
428
+ */
429
+ write: (alias: string, path: string, content: string, guard?: { expectMtime?: number; expectSize?: number }) =>
430
+ post<RemoteWriteResult>(REMOTE_API.files, {
431
+ op: 'write',
432
+ alias,
433
+ path,
434
+ content,
435
+ encoding: 'utf8',
436
+ ...(guard ?? {}),
437
+ }).then(afterRemoteWrite),
438
+ mkdir: (alias: string, path: string) =>
439
+ post<{ ok: boolean }>(REMOTE_API.files, { op: 'mkdir', alias, path }).then(afterRemoteWrite),
264
440
  rm: (alias: string, path: string, recursive: boolean) =>
265
- post<{ ok: boolean }>(REMOTE_API.files, { op: 'rm', alias, path, recursive }),
441
+ post<{ ok: boolean }>(REMOTE_API.files, { op: 'rm', alias, path, recursive }).then(afterRemoteWrite),
266
442
  rename: (alias: string, from: string, to: string) =>
267
- post<{ ok: boolean }>(REMOTE_API.files, { op: 'rename', alias, from, to }),
443
+ post<{ ok: boolean }>(REMOTE_API.files, { op: 'rename', alias, from, to }).then(afterRemoteWrite),
268
444
  },
269
445
  // -- exec
270
446
  exec: (alias: string, command: string, timeoutMs?: number) =>
271
- post<RemoteExecResult>(REMOTE_API.exec, timeoutMs === undefined ? { alias, command } : { alias, command, timeoutMs }),
447
+ post<RemoteExecResult>(REMOTE_API.exec, timeoutMs === undefined ? { alias, command } : { alias, command, timeoutMs })
448
+ .then((result) => {
449
+ // A worktree-changing git verb (discard / checkout / stash apply …) runs
450
+ // through here rather than `fileOp`, so it is the one place an index
451
+ // cache can learn about it (see `execChangesWorktree`).
452
+ if (result.success) afterRemoteCommand(command)
453
+ return result
454
+ }),
272
455
  /**
273
456
  * Streaming exec: the network verbs' live log.
274
457
  *
@@ -318,6 +501,9 @@ export const api = {
318
501
  }
319
502
  }
320
503
  if (exit === undefined) throw new RemoteApiError(502, 'stream ended without an exit frame')
504
+ // The streaming path carries `pull`/`sync`, which merge into the worktree:
505
+ // same invalidation as the unary path above.
506
+ if (exit.success) afterRemoteCommand(command)
321
507
  return {
322
508
  success: exit.success,
323
509
  exitCode: exit.exitCode,
@@ -35,6 +35,7 @@ import { useRemoteChatTarget } from '../use-remote-chat-target.ts'
35
35
  import type { RemoteChangedFile, RemoteChangesSummary } from '../../protocol.ts'
36
36
  import { EMPTY_CHANGE_SET, changeSetFromHunks, type ChangeSet } from './model.ts'
37
37
  import { setUndoContext } from './undo-context.ts'
38
+ import { forgetChangeOrigin, publishableUndoOrigin, rememberChangeOrigin } from './undo-target.ts'
38
39
  import { FileIcon } from '../vsc/kit.tsx'
39
40
  import './changes.css'
40
41
 
@@ -149,14 +150,29 @@ export function ChangesDock(props: ChangesDockProps): React.ReactNode {
149
150
  }
150
151
  }, [load])
151
152
 
152
- // Keep the revert affordance pointed at the workspace this panel lists. It is
153
- // written on every summary so a rebound workspace cannot leave a stale root
154
- // behind, and cleared on unmount so an affordance in another session's editor
155
- // can never act on this one.
153
+ /**
154
+ * Publish the revert coordinates for the tab the user is LOOKING AT.
155
+ *
156
+ * The marks belong to one tab and one binding; the revert is the only user
157
+ * action that writes to the remote, so the slot must never be "whatever this
158
+ * panel last saw". `publishableUndoOrigin` re-checks the marks' session against
159
+ * this panel's session, the binding identity (alias alone is not one: two
160
+ * bindings can share a host alias) and the path against the recorded ledger
161
+ * root, and answers `undefined` when anything fails — the store's undo path
162
+ * then refuses instead of guessing.
163
+ *
164
+ * Runs on every store snapshot (tabs included) and on active-tab changes, so a
165
+ * tab switch republishes before a click can reach the button.
166
+ */
156
167
  useEffect(() => {
157
- if (sessionId === undefined || summary === null || summary.root === '') return
158
- setUndoContext({ sessionId, alias: summary.alias, root: summary.root })
159
- }, [sessionId, summary])
168
+ const tab = explorer.tabs.find(candidate => candidate.id === explorer.activeTabId)
169
+ setUndoContext(publishableUndoOrigin({
170
+ tabId: explorer.activeTabId,
171
+ tabPath: tab?.fullPath,
172
+ panelSessionId: sessionId,
173
+ bindings: remoteOpenBindings().bindings,
174
+ }))
175
+ }, [sessionId, explorer.activeTabId, explorer.tabs, explorer.workspaces])
160
176
 
161
177
  useEffect(() => () => { setUndoContext(undefined) }, [])
162
178
 
@@ -251,7 +267,18 @@ export function ChangesDock(props: ChangesDockProps): React.ReactNode {
251
267
  openRemoteFileInBinding(binding.id, file.path, set.hunks[0] === undefined ? {} : { line: set.hunks[0] })
252
268
  // The tab id is deterministic (store.openFile builds it the same way), so
253
269
  // the marks can be attached without waiting for the file read to settle.
254
- applyChangeSet(`file:${binding.alias}:${file.path}`, set)
270
+ const tabId = `file:${binding.alias}:${file.path}`
271
+ applyChangeSet(tabId, set)
272
+ // Remember WHERE these marks came from, once: the revert coordinates are
273
+ // read back from here (`publishableUndoOrigin`) instead of from the last
274
+ // summary this panel happened to render. No real hunk = no revert target,
275
+ // so a binary/failed diff forgets the previous provenance instead of
276
+ // leaving an older one around.
277
+ if (diff !== null && diff.kind === 'text' && diff.hunks.length > 0) {
278
+ rememberChangeOrigin(tabId, { sessionId, bindingId: binding.id, alias: binding.alias, root: summary.root })
279
+ } else {
280
+ forgetChangeOrigin(tabId)
281
+ }
255
282
  } catch (problem) {
256
283
  if (alive.current) explorer.info(`${t('changes.diffFailed')}: ${problem instanceof Error ? problem.message : String(problem)}`)
257
284
  } finally {
@@ -89,6 +89,21 @@ function markAtLine(state: EditorState, line: number): ChangeMark | undefined {
89
89
  return anchor
90
90
  }
91
91
 
92
+ /**
93
+ * 只读编辑器里不提供撤销(断线降级 / 超上限截断)。
94
+ *
95
+ * 撤销按钮点下去是一次远端写(`git apply -R`),所以只读时它必须消失:否则屏幕上
96
+ * 「只读(不能保存)」与「可写的撤销」并存,且请求只会在远端失败。判据读编辑器自己的
97
+ * `readOnly` facet —— 与 `CodeEditor` 的 readOnly Compartment 是同一个事实,不需要再传
98
+ * 一个 prop(第二个真相源迟早会漂)。
99
+ *
100
+ * 导出是为了让门禁能钉住这个判定(渲染 CodeMirror 的 DOM 级证明成本高,而这里的
101
+ * 语义只有"只读 ⇒ 不提供"一句话)。
102
+ */
103
+ export function undoBlockedByReadOnly(view: { state: { readOnly: boolean } }): boolean {
104
+ return view.state.readOnly
105
+ }
106
+
92
107
  /** 指针所在的 `.cm-line`(不属于编辑器内容时为 null)。 */
93
108
  function lineElementAt(view: EditorView, event: MouseEvent): Element | null {
94
109
  const node = event.target instanceof Node ? event.target : null
@@ -190,6 +205,16 @@ class UndoAffordanceView {
190
205
  /** 鼠标在编辑器内容里移动:命中一处改动就(重新)开始悬停计时。 */
191
206
  handleMove(event: MouseEvent): void {
192
207
  this.cancelLeave()
208
+ /**
209
+ * 只读的编辑器没有可执行的撤销:断线降级(`connection.state === error`)与超上限
210
+ * 截断都通过 CodeMirror 的 `readOnly` 生效,而这条动作是一次**远端写**
211
+ * (`git apply -R`)。判据直接读编辑器自己的 state,与只读 Compartment 是同一个
212
+ * 事实,不需要再传一个 prop(第二个真相源迟早会漂)。顺带覆盖将来任何只读面。
213
+ */
214
+ if (undoBlockedByReadOnly(this.view)) {
215
+ this.reset()
216
+ return
217
+ }
193
218
  // 拖着选区走过改动行不算悬停:那时用户在做选择,不该冒出按钮抢点击。
194
219
  if (event.buttons !== 0) {
195
220
  this.reset()
@@ -230,6 +255,14 @@ class UndoAffordanceView {
230
255
  this.timer = undefined
231
256
  const hover = this.hovered
232
257
  if (hover === undefined) return
258
+ /**
259
+ * 悬停计时这段时间里链路可能已经断了(只读 Compartment 被 reconfigure):
260
+ * 到点再确认一次,否则按钮会出现在一个已经不能写的编辑器里。
261
+ */
262
+ if (undoBlockedByReadOnly(this.view)) {
263
+ this.reset()
264
+ return
265
+ }
233
266
  if (markAtLine(this.view.state, hover.line) !== hover.mark) {
234
267
  this.reset()
235
268
  return
@@ -1,29 +1,25 @@
1
1
  /**
2
- * Where "revert this change" points.
2
+ * The coordinates the editor's "revert this change" action uses.
3
3
  *
4
- * The revert itself needs only `(alias, root, patch)`: `git apply -R` runs on the
5
- * host against the repository that owns the file, and its context check IS the
6
- * conflict guard — a hunk whose surroundings moved since the snapshot is
7
- * refused instead of overwriting whatever replaced it. Nothing about the
8
- * session is needed for that.
4
+ * This module is the SLOT the store reads (`undoContext()`); it no longer decides
5
+ * anything. The value is written by the change panel from the provenance of the
6
+ * marks on screen — see `undo-target.ts`, which validates that the marks' session,
7
+ * binding and root still describe the tab the user is looking at. When validation
8
+ * fails the slot holds `undefined`, and the store's undo path refuses
9
+ * (`changes.undoNoContext`) instead of guessing a repository.
9
10
  *
10
- * A small module-level record is the honest shape here: the affordance is
11
- * rendered by the editor (which knows a buffer, not a workspace), while the
12
- * coordinates come from the change panel (which knows the session). One value at
13
- * a time is enough because the panel only ever lists changes of the session on
14
- * screen.
11
+ * Historically the slot was "the last summary this panel saw", which could point
12
+ * a revert at another conversation's — or a sibling binding's — repository. The
13
+ * revert writes to the remote, so the coordinates now travel with the marks.
15
14
  */
15
+ import type { ChangeOrigin } from './undo-target.ts'
16
16
 
17
- /** Coordinates one revert needs, plus the session they were read for. */
18
- export interface UndoContext {
19
- sessionId: string
20
- alias: string
21
- root: string
22
- }
17
+ /** Coordinates one revert needs. Kept as the store's contract name. */
18
+ export type UndoContext = ChangeOrigin
23
19
 
24
20
  let current: UndoContext | undefined
25
21
 
26
- /** Point the affordance at one session's remote workspace. */
22
+ /** Publish the validated provenance for the tab currently on screen (or nothing). */
27
23
  export function setUndoContext(context: UndoContext | undefined): void {
28
24
  current = context
29
25
  }
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Undo provenance: which repository a set of change marks belongs to.
3
+ *
4
+ * The revert (`git apply -R`, see `client/scm/actions.ts`) is the only user
5
+ * action in this plugin that WRITES to the remote, so its coordinates must come
6
+ * from the marks themselves — not from "whichever change panel updated last".
7
+ * The panel therefore records one {@link ChangeOrigin} per tab when it attaches
8
+ * the marks, and publishes it (validated) only while that tab is the one on
9
+ * screen. The store's undo path keeps calling `undoContext()` unchanged; it now
10
+ * receives proven provenance or nothing.
11
+ *
12
+ * Three failure modes this closes:
13
+ * - **cross-session**: the panel's session and the marks' session must agree, so
14
+ * switching conversations cannot leave session A's patch aimed at session B's
15
+ * coordinates;
16
+ * - **cross-binding (same alias)**: two bindings can share one host alias — one
17
+ * machine may hold two checkouts of the same tree. The alias is not an
18
+ * identity; the `bindingId` is, and the file path must sit under the recorded
19
+ * ledger root — otherwise a revert computed for one checkout can land in an
20
+ * identical sibling one, where git's context check would happily accept it;
21
+ * - **stale binding**: a binding edited or moved keeps its id but changes its
22
+ * alias/root; the recorded snapshot no longer matches, so the revert refuses
23
+ * instead of guessing.
24
+ *
25
+ * Pure functions + a bounded registry here (no React, no cordis), so
26
+ * `scripts/check-undo-target.mjs` drives the real decisions.
27
+ */
28
+ import type { RemoteOpenBinding } from '../remote-file-open-target.ts'
29
+
30
+ /** Where one tab's change marks came from. */
31
+ export interface ChangeOrigin {
32
+ /** Session whose ledger produced the hunks. */
33
+ sessionId: string
34
+ /** Binding identity at attach time (the ONE unique key; alias is not). */
35
+ bindingId: string
36
+ /** Host alias snapshot, for the binding-changed check. */
37
+ alias: string
38
+ /** Ledger root the patch paths are relative to (`git apply -R` runs here). */
39
+ root: string
40
+ }
41
+
42
+ /** Why a revert must be refused. */
43
+ export type UndoRefusal =
44
+ | 'no-origin'
45
+ | 'session-mismatch'
46
+ | 'binding-gone'
47
+ | 'binding-changed'
48
+ | 'path-outside'
49
+
50
+ export type UndoTargetResult =
51
+ | { ok: true; origin: ChangeOrigin }
52
+ | { ok: false; reason: UndoRefusal }
53
+
54
+ /** True when `child` is at/inside `parent` (POSIX, trailing-slash tolerant). */
55
+ function underRoot(parent: string, child: string): boolean {
56
+ const root = parent.length > 1 && parent.endsWith('/') ? parent.replace(/\/+$/, '') : parent
57
+ if (root === '/') return child.startsWith('/')
58
+ return child === root || child.startsWith(`${root}/`)
59
+ }
60
+
61
+ /**
62
+ * Decide whether a revert may run, and with which coordinates.
63
+ *
64
+ * @param input.origin - provenance recorded when the marks were attached.
65
+ * @param input.tabPath - the tab's absolute remote path (the file the patch names).
66
+ * @param input.panelSessionId - the session whose panel is on screen right now.
67
+ * @param input.bindings - the live binding table (`remoteOpenBindings()`).
68
+ */
69
+ export function resolveUndoTarget(input: {
70
+ origin: ChangeOrigin | undefined
71
+ tabPath: string
72
+ panelSessionId: string | undefined
73
+ bindings: readonly RemoteOpenBinding[]
74
+ }): UndoTargetResult {
75
+ const { origin, tabPath, panelSessionId, bindings } = input
76
+ if (origin === undefined) return { ok: false, reason: 'no-origin' }
77
+ // The marks on screen and the panel on screen must describe the same session.
78
+ // Without this, a mark left over from another conversation could be reverted
79
+ // with THIS conversation's repository coordinates.
80
+ if (panelSessionId === undefined || panelSessionId === '' || origin.sessionId !== panelSessionId) {
81
+ return { ok: false, reason: 'session-mismatch' }
82
+ }
83
+ const binding = bindings.find(candidate => candidate.id === origin.bindingId)
84
+ if (binding === undefined) return { ok: false, reason: 'binding-gone' }
85
+ // Same id but different coordinates = the binding was edited/moved; the patch
86
+ // was computed against the old tree.
87
+ if (binding.alias !== origin.alias) return { ok: false, reason: 'binding-changed' }
88
+ if (!underRoot(binding.remotePath, origin.root)) return { ok: false, reason: 'binding-changed' }
89
+ if (tabPath === '' || !underRoot(origin.root, tabPath)) return { ok: false, reason: 'path-outside' }
90
+ return { ok: true, origin }
91
+ }
92
+
93
+ /** Ceiling on tracked tabs (a long-lived page must not grow this map forever). */
94
+ const ORIGIN_CAP = 500
95
+
96
+ /** tabId -> provenance, written when marks are attached, read when publishing. */
97
+ const origins = new Map<string, ChangeOrigin>()
98
+
99
+ /** Record where one tab's marks came from (called by the change panel). */
100
+ export function rememberChangeOrigin(tabId: string, origin: ChangeOrigin): void {
101
+ if (tabId === '') return
102
+ origins.delete(tabId)
103
+ if (origins.size >= ORIGIN_CAP) {
104
+ const oldest = origins.keys().next().value
105
+ if (oldest !== undefined) origins.delete(oldest)
106
+ }
107
+ origins.set(tabId, origin)
108
+ }
109
+
110
+ /** Drop one tab's provenance (marks cleared, file closed, diff failed). */
111
+ export function forgetChangeOrigin(tabId: string): void {
112
+ origins.delete(tabId)
113
+ }
114
+
115
+ /** Provenance recorded for one tab, if any. */
116
+ export function changeOriginForTab(tabId: string | undefined): ChangeOrigin | undefined {
117
+ return tabId === undefined ? undefined : origins.get(tabId)
118
+ }
119
+
120
+ /**
121
+ * The value the undo slot should hold for the tab currently on screen: the tab's
122
+ * own validated provenance, or `undefined` (which makes undo refuse, never guess).
123
+ */
124
+ export function publishableUndoOrigin(input: {
125
+ tabId: string | undefined
126
+ tabPath: string | undefined
127
+ panelSessionId: string | undefined
128
+ bindings: readonly RemoteOpenBinding[]
129
+ }): ChangeOrigin | undefined {
130
+ const origin = changeOriginForTab(input.tabId)
131
+ if (origin === undefined || input.tabPath === undefined) return undefined
132
+ const resolved = resolveUndoTarget({
133
+ origin,
134
+ tabPath: input.tabPath,
135
+ panelSessionId: input.panelSessionId,
136
+ bindings: input.bindings,
137
+ })
138
+ return resolved.ok ? resolved.origin : undefined
139
+ }