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
@@ -48,7 +48,8 @@ import { effectiveEditorSurface, type EditorSurface } from './float-editor.ts'
48
48
  import { captureLiveEditorPosition, captureLiveEditorText, isLiveEditorDirty, isLiveEditorFor, markLiveEditorSaved } from './live-editor.ts'
49
49
  import { planWorkspaceFollow, selectionIsSessionBinding, type WorkspaceFollowDecision } from './remote-file-open-target.ts'
50
50
  import { revealViewTab } from './reveal.ts'
51
- import { isHtmlFile, isImageFile, isMarkdownFile, toast } from './vsc/kit.tsx'
51
+ import { connectionStateOf, isConnectionFailure } from './connection.ts'
52
+ import { confirmDialog, isHtmlFile, isImageFile, isMarkdownFile, toast } from './vsc/kit.tsx'
52
53
 
53
54
  /** One editor tab (code file, preview or diff). */
54
55
  export interface EditorTab {
@@ -72,6 +73,29 @@ export interface EditorTab {
72
73
  * guard silent) — the exact silent-loss path the handoff exists to avoid.
73
74
  */
74
75
  baseline?: string
76
+ /**
77
+ * The remote VERSION this buffer was loaded from / last saved to.
78
+ *
79
+ * Sent back on save as an optimistic lock: the Host refuses the write when the
80
+ * remote file has a different mtime (or size), because that means a person or
81
+ * an agent wrote it after this buffer was read and saving would destroy their
82
+ * work with a cheerful "saved". Kept here rather than in the editor because it
83
+ * must survive a surface handoff and a tab switch.
84
+ *
85
+ * `undefined` means NO baseline (a file created by this session, or a write
86
+ * whose post-save stat failed): the save then goes through unguarded, exactly
87
+ * as before this feature — the guard protects a known history, it must never
88
+ * invent one.
89
+ */
90
+ remoteMtime?: number
91
+ /** Size that belonged to `remoteMtime` (the second half of the same baseline). */
92
+ remoteSize?: number
93
+ /**
94
+ * Set when a save was REFUSED because the remote file moved on, carrying what
95
+ * is there now. The pane turns this into an offer — overwrite / reload / see
96
+ * the difference — instead of a red toast the user cannot act on.
97
+ */
98
+ conflict?: { mtime: number | null; size: number | null }
75
99
  dirty: boolean
76
100
  saving: boolean
77
101
  binary: boolean
@@ -87,6 +111,15 @@ export interface EditorTab {
87
111
  untracked: boolean
88
112
  /** Set for a commit drill-down: the diff compares `ref^` with `ref`. */
89
113
  ref?: string
114
+ /**
115
+ * 重命名差异的旧路径(commit diff 专用)。
116
+ *
117
+ * `openCommitFile` 的首次加载把它一起交给 `loadCommitFileDiff`(两个路径一起
118
+ * `git show -M` 才能把 rename 配对),但 `reloadTab` 是另一个调用点:不存进 tab,
119
+ * 重载(工具栏 ⟳ / 断线恢复的批量 reload)就只会拿新路径去问 git,rename 立刻
120
+ * 退化成「整篇新增」。
121
+ */
122
+ origPath?: string
90
123
  /** 1-based line to reveal after load (a content-search hit). */
91
124
  line?: number
92
125
  /**
@@ -229,6 +262,117 @@ const WS_KEY = 'dsh-remote-vs.files.ws'
229
262
  const VIEW_KEY = 'dsh-remote-vs.view'
230
263
  /** Per-workspace repository sub-directory, keyed by workspace id. */
231
264
  const REPO_SUBDIR_KEY = 'dsh-remote-vs.repo.subdir'
265
+ /**
266
+ * Per-workspace open file tabs, so a page reload does not lose the workbench.
267
+ *
268
+ * PATHS ONLY. The remote source itself never reaches browser storage — the
269
+ * README promises exactly that ("no cross-refresh content cache"), and a
270
+ * "restore the tabs" feature is the most tempting place to break it: keeping
271
+ * `text` here would put remote files on disk and would be one more copy to keep
272
+ * fresh. Paths are enough to reopen them, and a stale path fails harmlessly
273
+ * (the file open reports it and the tab is dropped).
274
+ */
275
+ const TABS_KEY = 'dsh-remote-vs.tabs'
276
+ /**
277
+ * How many tabs one reload reopens.
278
+ *
279
+ * Each restored tab costs one remote read, and a page reload happens on every
280
+ * plugin upgrade / `dsh web` restart — a workbench with thirty open files must
281
+ * not turn that into thirty concurrent reads against six channel slots.
282
+ */
283
+ const TAB_RESTORE_LIMIT = 12
284
+ /** Parallel reads while restoring (deliberately below the 6-channel budget). */
285
+ const TAB_RESTORE_CONCURRENCY = 2
286
+
287
+ /** One workspace's persisted workbench. */
288
+ interface StoredTabSet {
289
+ /** Absolute remote paths, in strip order. */
290
+ paths: string[]
291
+ /** The path of the active tab, when there was one. */
292
+ active?: string
293
+ }
294
+
295
+ /** Every workspace's persisted workbench, keyed by binding id. */
296
+ type StoredTabs = Record<string, StoredTabSet>
297
+
298
+ /**
299
+ * Read the stored tab sets.
300
+ *
301
+ * Strict on shape and lenient on junk: a half-written or hand-edited entry must
302
+ * degrade to "nothing to restore" instead of throwing on page load (module-level
303
+ * state that throws here would take the whole panel down before it renders).
304
+ */
305
+ function readStoredTabs(): StoredTabs {
306
+ try {
307
+ const raw = localStorage.getItem(TABS_KEY)
308
+ if (raw === null) return {}
309
+ const parsed: unknown = JSON.parse(raw)
310
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return {}
311
+ const out: StoredTabs = {}
312
+ for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) {
313
+ if (typeof value !== 'object' || value === null) continue
314
+ const entry = value as { paths?: unknown; active?: unknown }
315
+ if (!Array.isArray(entry.paths)) continue
316
+ const paths = entry.paths.filter((item): item is string => typeof item === 'string' && item !== '')
317
+ if (paths.length === 0) continue
318
+ out[key] = typeof entry.active === 'string' ? { paths, active: entry.active } : { paths }
319
+ }
320
+ return out
321
+ } catch {
322
+ return {}
323
+ }
324
+ }
325
+
326
+ /** The signature of what got persisted last, so publishes do not rewrite it. */
327
+ let persistedTabsSignature = ''
328
+ /** The restore happens at most once per page load. */
329
+ let tabsRestored = false
330
+ /**
331
+ * Persistence is armed only once the restore has finished (or decided there was
332
+ * nothing to restore).
333
+ *
334
+ * Before that, the strip is legitimately EMPTY: the bootstrap publishes
335
+ * (hosts/workspaces/git) run before any tab is reopened, and writing that empty
336
+ * set would delete the very list the restore is about to read. The guard is
337
+ * about that one window, not about "never store an empty workbench" — closing
338
+ * every tab afterwards DOES remove the entry, which is what keeps a deleted tab
339
+ * from coming back on the next reload.
340
+ */
341
+ let tabsPersistReady = false
342
+
343
+ /**
344
+ * Persist the current file tabs for the current workspace.
345
+ *
346
+ * Called from every publish (a tab opened / closed / switched re-renders the
347
+ * strip, and that is exactly when the persisted set changes). The signature
348
+ * keeps a keystroke-driven publish from touching localStorage, whose writes are
349
+ * synchronous and would otherwise land on the typing path.
350
+ *
351
+ * Only FILE tabs are stored: a diff / commit tab is a view of git state that is
352
+ * cheap to reopen from the SCM panel, and restoring one without its repository
353
+ * context would open a tab that cannot load.
354
+ */
355
+ function persistTabsIfChanged(): void {
356
+ const workspace = currentWorkspace()
357
+ if (workspace === undefined) return
358
+ const paths = state.tabs.filter(tab => tab.kind === 'file').map(tab => tab.fullPath)
359
+ const activeTab = state.tabs.find(tab => tab.id === state.activeTabId)
360
+ const active = activeTab?.kind === 'file' ? activeTab.fullPath : undefined
361
+ const signature = `${workspace.id}\u0000${active ?? ''}\u0000${paths.join('\u0000')}`
362
+ if (signature === persistedTabsSignature) return
363
+ // See `tabsPersistReady`: an empty strip before the restore has run is the
364
+ // bootstrap's transient state, not a user closing their last tab.
365
+ if (!tabsPersistReady && paths.length === 0) return
366
+ persistedTabsSignature = signature
367
+ try {
368
+ const all = readStoredTabs()
369
+ if (paths.length === 0) delete all[workspace.id]
370
+ else all[workspace.id] = active === undefined ? { paths } : { paths, active }
371
+ localStorage.setItem(TABS_KEY, JSON.stringify(all))
372
+ } catch {
373
+ // Private mode / quota: the workbench simply does not come back.
374
+ }
375
+ }
232
376
 
233
377
  function readWorkspaceId(): string {
234
378
  try {
@@ -508,7 +652,14 @@ export interface ExplorerValue {
508
652
  * @returns true only when the write really succeeded — the caller uses it to
509
653
  * advance the editor's dirty baseline (see `CodeEditorHandle.markSaved`).
510
654
  */
511
- saveTab: (id: string, content: string) => Promise<boolean>
655
+ saveTab: (id: string, content: string, options?: { force?: boolean }) => Promise<boolean>
656
+ /**
657
+ * Forget the pending save-conflict banner for one tab (the user dismissed it).
658
+ *
659
+ * The buffer and the dirty flag are untouched: dismissing only hides the
660
+ * offer, it never decides anything on the user's behalf.
661
+ */
662
+ dismissConflict: (id: string) => void
512
663
  reloadTab: (id: string) => Promise<void>
513
664
  info: (text: string) => void
514
665
  fail: (text: string) => void
@@ -620,6 +771,7 @@ function build(): ExplorerValue {
620
771
  markChangeStale,
621
772
  undoChange,
622
773
  saveTab,
774
+ dismissConflict,
623
775
  reloadTab,
624
776
  info,
625
777
  fail,
@@ -628,6 +780,10 @@ function build(): ExplorerValue {
628
780
 
629
781
  function publish(): void {
630
782
  snapshot = build()
783
+ // Every mutation ends here, and a tab opened / closed / activated is such a
784
+ // mutation — so this is the one place the stored workbench cannot fall behind
785
+ // (an explicit call at each of the dozen tab sites would eventually miss one).
786
+ persistTabsIfChanged()
631
787
  for (const listener of listeners) listener()
632
788
  }
633
789
 
@@ -829,6 +985,10 @@ export function refreshAll(): void {
829
985
  // other, and its cached slice is what keeps the panel from "Loading…".
830
986
  const resolved = activeBinding().key
831
987
  if (resolved !== key) adoptCachedGit(resolved)
988
+ // Bring the previous page's workbench back AFTER the workspace table is
989
+ // known: the stored sets are keyed by binding id, and a tab can only be
990
+ // reopened against the workspace that owns it.
991
+ restoreStoredTabs()
832
992
  void refreshGit('join')
833
993
  },
834
994
  (error: unknown) => {
@@ -837,6 +997,133 @@ export function refreshAll(): void {
837
997
  )
838
998
  }
839
999
 
1000
+ /** `file:` tab id for one path on one host (the one place that shape is built). */
1001
+ function tabIdOf(alias: string, fullPath: string): string {
1002
+ return `file:${alias}:${fullPath}`
1003
+ }
1004
+
1005
+ /**
1006
+ * Open one stored path and wait until the read settles.
1007
+ *
1008
+ * `openFile` is fire-and-forget by design (every caller is a click), but a
1009
+ * restore has to know whether it worked — that is what separates "restored 5"
1010
+ * from "3 files are gone" — and it must not put a dozen reads in flight at
1011
+ * once. Waiting for the tab to leave `loading` is the only signal available
1012
+ * without changing that public contract.
1013
+ *
1014
+ * THREE outcomes, and the distinction is the point: a slow read (a thin link, a
1015
+ * huge file, a cold cache) is NOT a missing file. Treating a short wait as
1016
+ * failure closed the tab and dropped its path from storage, so "slow" turned
1017
+ * into "gone" — the exact "encode the uncertain as a negative" failure this
1018
+ * project keeps paying for. Only a tab that finished WITH an error is missing;
1019
+ * one that is still loading when the wait ends is unknown and left untouched,
1020
+ * so the next reload tries again.
1021
+ */
1022
+ type StoredTabOutcome = 'restored' | 'missing' | 'unknown'
1023
+
1024
+ /** How long to watch one restoring read before calling its outcome unknown. */
1025
+ const TAB_RESTORE_WAIT_MS = 150_000
1026
+ /** Poll interval while watching a restoring read. */
1027
+ const TAB_RESTORE_POLL_MS = 50
1028
+
1029
+ async function openStoredTab(alias: string, fullPath: string): Promise<StoredTabOutcome> {
1030
+ openFile(fullPath)
1031
+ const id = tabIdOf(alias, fullPath)
1032
+ const attempts = Math.ceil(TAB_RESTORE_WAIT_MS / TAB_RESTORE_POLL_MS)
1033
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
1034
+ const tab = state.tabs.find(item => item.id === id)
1035
+ if (tab === undefined) return 'missing'
1036
+ if (!tab.loading) return tab.error === undefined ? 'restored' : 'missing'
1037
+ await new Promise(resolve => setTimeout(resolve, TAB_RESTORE_POLL_MS))
1038
+ }
1039
+ // Still loading: the read owns its own deadline, so this is "could not tell
1040
+ // within a generous window", not "does not exist".
1041
+ return 'unknown'
1042
+ }
1043
+
1044
+ /** Reopen `paths` two at a time, reporting what came back and dropping only the misses. */
1045
+ async function reopenTabs(
1046
+ alias: string,
1047
+ paths: readonly string[],
1048
+ ): Promise<{ restored: number; missing: number; unknown: number }> {
1049
+ const queue = [...paths]
1050
+ let restored = 0
1051
+ let missing = 0
1052
+ let unknown = 0
1053
+ const worker = async (): Promise<void> => {
1054
+ for (;;) {
1055
+ const next = queue.shift()
1056
+ if (next === undefined) return
1057
+ const outcome = await openStoredTab(alias, next)
1058
+ if (outcome === 'restored') {
1059
+ restored += 1
1060
+ continue
1061
+ }
1062
+ if (outcome === 'unknown') {
1063
+ // Leave both the tab and the stored path alone: it may still be loading,
1064
+ // and closing it would turn a slow read into "this file is gone".
1065
+ unknown += 1
1066
+ continue
1067
+ }
1068
+ missing += 1
1069
+ // Close the tab this restore created. The user did not open it this time,
1070
+ // so leaving a red error tab in the strip is noise they never asked for;
1071
+ // the toast counts it instead. (`closeTab` on an absent id is a no-op.)
1072
+ closeTab(tabIdOf(alias, next))
1073
+ }
1074
+ }
1075
+ await Promise.all(Array.from({ length: TAB_RESTORE_CONCURRENCY }, () => worker()))
1076
+ return { restored, missing, unknown }
1077
+ }
1078
+
1079
+ /**
1080
+ * Reopen the file tabs this browser had for the current workspace.
1081
+ *
1082
+ * Runs once per page load, for the CURRENT workspace only: switching workspaces
1083
+ * keeps its existing contract (the strip is cleared and the user is told so
1084
+ * first), and re-running this on every `refreshAll` would fight that clear
1085
+ * rather than complement it.
1086
+ *
1087
+ * A tab that no longer loads (deleted, renamed, no permission) is dropped and
1088
+ * COUNTED — silently restoring "6 of 9" would leave the user looking for three
1089
+ * tabs they think they had.
1090
+ *
1091
+ * Only PATHS are restored. Caret and scroll position are not persisted: the
1092
+ * README's privacy stance is "paths only, never content", and a caret stored
1093
+ * weeks ago would point into a file that has since changed.
1094
+ */
1095
+ export function restoreStoredTabs(): void {
1096
+ if (tabsRestored) return
1097
+ tabsRestored = true
1098
+ const workspace = currentWorkspace()
1099
+ const stored = workspace === undefined ? undefined : readStoredTabs()[workspace.id]
1100
+ if (workspace === undefined || stored === undefined || stored.paths.length === 0) {
1101
+ // Nothing to reopen: arm persistence now, or the first real tab would be
1102
+ // stored but a later "close all" could never remove it.
1103
+ tabsPersistReady = true
1104
+ return
1105
+ }
1106
+ const paths = stored.paths.slice(0, TAB_RESTORE_LIMIT)
1107
+ const activePath = stored.active
1108
+ void (async () => {
1109
+ try {
1110
+ const { restored, missing, unknown } = await reopenTabs(workspace.alias, paths)
1111
+ if (activePath !== undefined) {
1112
+ const id = tabIdOf(workspace.alias, activePath)
1113
+ if (state.tabs.some(tab => tab.id === id)) patch({ activeTabId: id })
1114
+ }
1115
+ if (restored > 0) toast(t('editor.tabsRestored').replace('{count}', String(restored)), false)
1116
+ if (missing > 0) toast(t('editor.tabsRestoreMissing').replace('{count}', String(missing)), true)
1117
+ // Slow is not missing: say so, and keep the tab for the next reload.
1118
+ if (unknown > 0) toast(t('editor.tabsRestoreUnknown').replace('{count}', String(unknown)), false)
1119
+ } finally {
1120
+ // From here on the strip is the user's, not the bootstrap's: an empty one
1121
+ // means they closed everything.
1122
+ tabsPersistReady = true
1123
+ }
1124
+ })()
1125
+ }
1126
+
840
1127
  /** Switch the sidebar panel (persisted across reloads). */
841
1128
  export function setView(view: RailView): void {
842
1129
  if (state.view === view) return
@@ -913,20 +1200,105 @@ export function openTerminalAt(dir: string): void {
913
1200
  * has not resolved yet from undoing it.
914
1201
  */
915
1202
  export function selectWorkspace(id: string): void {
916
- applyWorkspaceSelection(id, true)
1203
+ if (state.workspaceId === id) return
1204
+ /**
1205
+ * A workspace switch closes EVERY tab (`applyWorkspaceSelection` replaces the
1206
+ * list), so unsaved buffers must be confirmed first — the same rule the single
1207
+ * tab close already follows (`EditorPane.closeWithGuard`). Without this the
1208
+ * edits vanished with no prompt, from this plugin's own workspace dropdown.
1209
+ *
1210
+ * The CLEAN path stays fully synchronous on purpose: a switch that was read
1211
+ * before repaints its whole change list in the same frame (see the hydration
1212
+ * comment in `applyWorkspaceSelection`, and `check-git-cache` asserts it).
1213
+ * Only the dirty path awaits the dialog.
1214
+ */
1215
+ const dirty = state.tabs.filter(tab => tab.dirty)
1216
+ if (dirty.length === 0) {
1217
+ applyWorkspaceSelection(id, true)
1218
+ return
1219
+ }
1220
+ void (async () => {
1221
+ if (!(await confirmDiscardOnWorkspaceSwitch(dirty))) return
1222
+ applyWorkspaceSelection(id, true)
1223
+ })()
917
1224
  }
918
1225
 
919
1226
  /**
920
- * Select a binding on the PLUGIN's own initiative, claiming nothing.
1227
+ * Switch workspace on the PLUGIN's own initiative (session follow, opening a
1228
+ * file that belongs to another binding), claiming nothing.
921
1229
  *
922
1230
  * Two callers: opening a file that belongs to another binding (the change
923
1231
  * panel, the click interceptor) and the follow itself. Neither is a statement
924
1232
  * about where the user wants to browse — clicking a changed file is "show me
925
1233
  * this result", not "I moved my workspace" — so a pending follow stays free to
926
1234
  * put the selection back on the session's binding afterwards.
1235
+ *
1236
+ * Never discards unsaved edits: when any tab is dirty the switch is skipped and
1237
+ * the selection stays where the user left it (they can still switch by hand,
1238
+ * which goes through `selectWorkspace` and its confirmation).
1239
+ *
1240
+ * @returns whether the selection really is `id` afterwards. The auto callers
1241
+ * MUST check it: skipping the switch is not a no-op for them — a caller that
1242
+ * goes on to open a file would read that file with the OLD workspace's alias
1243
+ * (another host, or another file at the same path). See
1244
+ * `openRemoteFileInBinding`.
927
1245
  */
928
- function selectWorkspaceAuto(id: string): void {
1246
+ function selectWorkspaceAuto(id: string): boolean {
1247
+ if (state.workspaceId === id) return true
1248
+ if (state.tabs.some(tab => tab.dirty)) return false
929
1249
  applyWorkspaceSelection(id, false)
1250
+ return true
1251
+ }
1252
+
1253
+ /** Ask once before a workspace switch closes dirty editor tabs. */
1254
+ let switchGuardBusy = false
1255
+ /** Generation of the run that currently owns `switchGuardBusy` (see `finish`). */
1256
+ let switchGuardToken = 0
1257
+ /**
1258
+ * How long a dirty workspace switch waits for its confirmation.
1259
+ *
1260
+ * The guard is a module-level flag, so an answer that never arrives must not
1261
+ * hold it forever: the modal slot can be replaced, and the host can unmount the
1262
+ * dialog host while the question is up. Without a deadline the flag would stay
1263
+ * `true` for the rest of the session and every later dirty switch would do
1264
+ * nothing at all, with no message (only a reload recovers). Generous on
1265
+ * purpose — it exists for the pathological case, not to rush the user.
1266
+ */
1267
+ const SWITCH_GUARD_TIMEOUT_MS = 60_000
1268
+
1269
+ /**
1270
+ * Ask before a workspace switch closes dirty editor tabs.
1271
+ *
1272
+ * @returns true only when the user answered "discard and switch"; a dismiss, a
1273
+ * second pending switch and a TIMEOUT all answer false — the timeout also
1274
+ * releases the guard and says so, so the failure is never silent.
1275
+ */
1276
+ function confirmDiscardOnWorkspaceSwitch(dirty: readonly EditorTab[]): Promise<boolean> {
1277
+ if (switchGuardBusy) return Promise.resolve(false)
1278
+ switchGuardBusy = true
1279
+ const token = ++switchGuardToken
1280
+ return new Promise<boolean>((resolve) => {
1281
+ let done = false
1282
+ let timer: ReturnType<typeof setTimeout> | undefined
1283
+ const finish = (answer: boolean, timedOut = false): void => {
1284
+ // A late answer from a dialog that already timed out must neither resolve
1285
+ // this promise a second time nor unlock a NEWER guard run.
1286
+ if (done) return
1287
+ done = true
1288
+ if (timer !== undefined) clearTimeout(timer)
1289
+ if (switchGuardToken === token) switchGuardBusy = false
1290
+ resolve(answer)
1291
+ if (timedOut) toast(t('editor.switchTimeout'), true)
1292
+ }
1293
+ timer = setTimeout(() => finish(false, true), SWITCH_GUARD_TIMEOUT_MS)
1294
+ timer.unref?.()
1295
+ void confirmDialog({
1296
+ title: t('editor.switchDirty'),
1297
+ text: dirty.map(tab => tab.rel).join('、'),
1298
+ danger: true,
1299
+ okText: t('editor.discardSwitch'),
1300
+ }).then(answer => finish(answer), () => finish(false))
1301
+ })
930
1302
  }
931
1303
 
932
1304
  /** Move the selection; `byUser` decides whether it is remembered as a choice. */
@@ -1201,6 +1573,27 @@ export function selectedWorkspaceId(): string {
1201
1573
  return currentWorkspace()?.id ?? ''
1202
1574
  }
1203
1575
 
1576
+ /**
1577
+ * Snapshot of the editor tabs, for non-React callers (the local gates).
1578
+ *
1579
+ * Same shape as `selectedWorkspaceId` / `gitState`: a plain read so a script can
1580
+ * assert what the store actually holds without rendering a component.
1581
+ */
1582
+ export function editorTabs(): readonly EditorTab[] {
1583
+ return state.tabs
1584
+ }
1585
+
1586
+ /**
1587
+ * The active tab's id.
1588
+ *
1589
+ * A plain getter rather than a hook, for the same reason `editorTabs` is one:
1590
+ * the restore path lives outside React, and the gates that verify it need to see
1591
+ * what the strip would consider current without mounting a component.
1592
+ */
1593
+ export function activeEditorTabId(): string | undefined {
1594
+ return state.activeTabId
1595
+ }
1596
+
1204
1597
  /**
1205
1598
  * Point git at a directory inside the workspace. Repositories often live in a
1206
1599
  * sub-directory of the binding (`/srv/app` holding `/srv/app/web/.git`), and
@@ -1250,6 +1643,25 @@ export async function discoverRepos(): Promise<string[]> {
1250
1643
  export async function refreshGit(mode: 'join' | 'fresh' = 'fresh'): Promise<void> {
1251
1644
  const { workspace, key } = activeBinding()
1252
1645
  if (workspace === undefined) return
1646
+ /**
1647
+ * An AUTOMATIC read (`join`: bootstrap、切工作区) must not dial a link the Host
1648
+ * already reports as down — the directory tree gates the same way
1649
+ * (`loadDir`/`prefetchDir`), and so do save and undo (`EditorPane.saveActive`,
1650
+ * `undoChange`). An EXPLICIT read (`fresh`: ⟳、写后、重连) still tries: it is
1651
+ * also how a recovered link gets re-proven.
1652
+ *
1653
+ * `undefined` (no status answer yet) must NOT block: bootstrap runs before the
1654
+ * first `/status` poll, and treating "no evidence" as "down" would leave the
1655
+ * panel empty forever.
1656
+ */
1657
+ if (mode === 'join' && connectionStateOf(workspace.alias) === 'error') {
1658
+ // Nothing cached and nothing read yet: the SCM empty state would sit on
1659
+ // "Loading…" forever, so say WHY instead. A cached slice stays untouched —
1660
+ // the connection chip is the indicator, and the panel must not paint a
1661
+ // second, raw-socket error over a list it can still show.
1662
+ if (state.repoRoot === undefined && state.status === undefined) patch({ gitError: t('scm.offlineRead') })
1663
+ return
1664
+ }
1253
1665
  const subdir = state.repoSubdir
1254
1666
  const cacheKey = gitCacheKey(key, subdir)
1255
1667
  const settleMs = gitReadSettleMs()
@@ -1394,6 +1806,19 @@ export async function afterWrite(): Promise<void> {
1394
1806
  patch({ revision: state.revision + 1 })
1395
1807
  }
1396
1808
 
1809
+ /**
1810
+ * The connection came back: re-read everything a disconnect froze.
1811
+ *
1812
+ * `revision` is what makes the explorer re-list the root and every expanded
1813
+ * directory (the cached rows may predate the drop), and the git refresh updates
1814
+ * the status marks they are drawn with. Clean editor tabs are reloaded by the
1815
+ * caller (it owns the tab list); dirty ones must be left to the user.
1816
+ */
1817
+ export function refreshAfterReconnect(): void {
1818
+ void refreshGit()
1819
+ patch({ revision: state.revision + 1 })
1820
+ }
1821
+
1397
1822
  /** The repository the SCM panel is pointed at, or undefined when none. */
1398
1823
  export function scmTarget(): { alias: string; root: string } | undefined {
1399
1824
  const workspace = currentWorkspace()
@@ -1770,6 +2195,9 @@ export function openFile(fullPath: string, options: { line?: number } = {}): voi
1770
2195
  text: read.binary ? '' : (read.text ?? ''),
1771
2196
  // The disk side of the dirty comparison (see EditorTab.baseline).
1772
2197
  ...(read.binary ? {} : { baseline: read.text ?? '' }),
2198
+ // The version these bytes came from: the save guard's baseline.
2199
+ remoteMtime: read.mtime,
2200
+ remoteSize: read.size,
1773
2201
  })
1774
2202
  } catch (error) {
1775
2203
  patchTab(id, { loading: false, error: error instanceof Error ? error.message : String(error) })
@@ -1796,8 +2224,10 @@ export function remoteOpenBindings(): {
1796
2224
  * interceptor already resolved it), switching the explorer's selected
1797
2225
  * workspace when the on-screen one differs.
1798
2226
  *
1799
- * @returns true when the file was handed to the editor; false when the binding
1800
- * is unknown (the caller then keeps the native preview).
2227
+ * @returns true when the click was HANDLED — either the file went to the editor,
2228
+ * or it was deliberately refused with a message (see below); false only when
2229
+ * the binding is unknown, which is the caller's cue to keep the native
2230
+ * preview.
1801
2231
  */
1802
2232
  export function openRemoteFileInBinding(
1803
2233
  bindingId: string,
@@ -1808,7 +2238,19 @@ export function openRemoteFileInBinding(
1808
2238
  if (binding === undefined || remotePath === '') return false
1809
2239
  // AUTO, not a user choice: clicking a result that lives in another binding
1810
2240
  // must not cancel the session's pending follow (see `selectWorkspaceAuto`).
1811
- if (state.workspaceId !== binding.id) selectWorkspaceAuto(binding.id)
2241
+ if (state.workspaceId !== binding.id && !selectWorkspaceAuto(binding.id)) {
2242
+ /**
2243
+ * The auto switch is skipped while any tab has unsaved edits, and the
2244
+ * selection therefore still points at the OLD workspace. Opening the file
2245
+ * anyway would read it with that workspace's alias — a different host (the
2246
+ * read just fails) or, on the same host, whatever happens to live at the
2247
+ * same path — and it would mint a tab keyed by the wrong alias. Refuse, say
2248
+ * why, and still answer "handled" so the click interceptor does not fall
2249
+ * back to the native preview and repeat the same wrong resolution.
2250
+ */
2251
+ toast(t('files.openBlockedByDirty'), true)
2252
+ return true
2253
+ }
1812
2254
  openFile(remotePath, options)
1813
2255
  return true
1814
2256
  }
@@ -1836,10 +2278,11 @@ export function openDiff(rel: string, staged: boolean, untracked = false): void
1836
2278
  }
1837
2279
  const root = state.repoRoot
1838
2280
  const id = `diff:${workspace.alias}:${root}:${rel}:${staged ? 'staged' : 'worktree'}`
2281
+ const diffPath = `${root.replace(/\/+$/, '')}/${rel}`
1839
2282
  upsertTab({
1840
2283
  id,
1841
2284
  kind: 'diff',
1842
- fullPath: `${root.replace(/\/+$/, '')}/${rel}`,
2285
+ fullPath: diffPath,
1843
2286
  rel,
1844
2287
  loading: true,
1845
2288
  error: undefined,
@@ -1866,6 +2309,17 @@ export function openDiff(rel: string, staged: boolean, untracked = false): void
1866
2309
  diff: payload,
1867
2310
  model: payload.unsupported ? undefined : buildDiffModel(payload),
1868
2311
  binary: payload.unsupported,
2312
+ // The after pane is a prefix when the working-tree read hit the cap:
2313
+ // it must be read-only, or saving it would truncate the real file.
2314
+ truncated: payload.truncated === true,
2315
+ /**
2316
+ * The working-tree version this pane was read from — the save baseline,
2317
+ * taken from the SAME read rather than from a later stat (a second stat
2318
+ * could describe a version the user never saw, so the guard would accept
2319
+ * bytes read before that change). Absent for staged/commit diffs, which
2320
+ * are read-only.
2321
+ */
2322
+ ...(payload.mtime === undefined ? {} : { remoteMtime: payload.mtime, remoteSize: payload.size }),
1869
2323
  })
1870
2324
  } catch (error) {
1871
2325
  patchTab(id, { loading: false, error: error instanceof Error ? error.message : String(error) })
@@ -1873,6 +2327,12 @@ export function openDiff(rel: string, staged: boolean, untracked = false): void
1873
2327
  })()
1874
2328
  }
1875
2329
 
2330
+ /** Apply a diff payload's baseline (see `DiffPayload.mtime`). */
2331
+ function applyDiffBaseline(id: string, payload: { mtime?: number; size?: number }): void {
2332
+ if (payload.mtime === undefined) return
2333
+ patchTab(id, { remoteMtime: payload.mtime, remoteSize: payload.size })
2334
+ }
2335
+
1876
2336
  /**
1877
2337
  * Open (or focus) one file of one commit (`ref^` against `ref`).
1878
2338
  *
@@ -1905,6 +2365,7 @@ export function openCommitFile(hash: string, rel: string, origPath?: string): vo
1905
2365
  staged: true,
1906
2366
  untracked: false,
1907
2367
  ref: hash,
2368
+ ...(origPath === undefined ? {} : { origPath }),
1908
2369
  diff: undefined,
1909
2370
  model: undefined,
1910
2371
  view: 'split',
@@ -1947,11 +2408,91 @@ export function updateTab(id: string, next: Partial<EditorTab>): void {
1947
2408
  patchTab(id, next)
1948
2409
  }
1949
2410
 
1950
- /** Write one tab back to the remote host. @returns true when the write landed. */
1951
- export async function saveTab(id: string, content: string): Promise<boolean> {
2411
+ /**
2412
+ * One tab's save slot: at most one write in flight plus ONE pending content.
2413
+ *
2414
+ * Writes to the same remote path must never overlap. `RemoteFiles.write` is a
2415
+ * side file + `unlink` + `rename` (the atomic-save shape), so two writers race on
2416
+ * the RENAME: whichever lands last wins regardless of which the user pressed
2417
+ * last, and the store's baseline is then set by the other promise. The file can
2418
+ * end up holding the OLDER bytes while the UI says the newer ones were saved.
2419
+ *
2420
+ * Depth ONE on purpose: keyboard auto-repeat on Ctrl+S (holding it on a slow
2421
+ * link) would otherwise queue one full-document string per repeat (8 MiB files
2422
+ * make that an actual memory problem, not a theoretical one).
2423
+ */
2424
+ interface SaveSlot {
2425
+ running: boolean
2426
+ /** The newest content waiting; a later request REPLACES it (last press wins). */
2427
+ pending: SaveRequest | undefined
2428
+ /** Callers waiting for the pending write; they get ITS outcome. */
2429
+ waiters: ((ok: boolean) => void)[]
2430
+ }
2431
+
2432
+ /** One queued save: the bytes to write plus whether the user forced it. */
2433
+ interface SaveRequest {
2434
+ content: string
2435
+ /**
2436
+ * Explicit "overwrite the changed remote file" (answered a conflict prompt).
2437
+ *
2438
+ * A merged request is one burst of the SAME intent, so the newest request's
2439
+ * force flag wins with its content: a forced save that coalesces a later
2440
+ * unforced one is still the user's overwrite decision, and the reverse
2441
+ * (unforced replacing forced) means they went back to the guarded path.
2442
+ */
2443
+ force: boolean
2444
+ }
2445
+
2446
+ const saveSlots = new Map<string, SaveSlot>()
2447
+
2448
+ function saveSlotOf(id: string): SaveSlot {
2449
+ const existing = saveSlots.get(id)
2450
+ if (existing !== undefined) return existing
2451
+ const created: SaveSlot = { running: false, pending: undefined, waiters: [] }
2452
+ saveSlots.set(id, created)
2453
+ return created
2454
+ }
2455
+
2456
+ /** Drop a drained slot: the map is keyed by tab id and must not grow forever. */
2457
+ function releaseSaveSlot(id: string, slot: SaveSlot): void {
2458
+ if (slot.running || slot.pending !== undefined || slot.waiters.length > 0) return
2459
+ if (saveSlots.get(id) === slot) saveSlots.delete(id)
2460
+ }
2461
+
2462
+ /**
2463
+ * Where one tab's save would go, or undefined when it is not writable NOW.
2464
+ *
2465
+ * Re-derived at EXECUTION time as well as at request time: a queued save can
2466
+ * outlive a workspace switch (the tab is gone), a reload that turns the tab
2467
+ * `truncated`, or a tab closed mid-queue. A queued write must never land in a
2468
+ * workspace that no longer shows the tab.
2469
+ *
2470
+ * The rule itself is S1's: a file tab, or a WORKING-TREE diff's after pane
2471
+ * (`kind: 'diff'`, no `ref`, not the staged side). Commit diffs and the staged
2472
+ * side are history.
2473
+ */
2474
+ function saveTargetOf(id: string): { alias: string; fullPath: string; rel: string } | undefined {
1952
2475
  const workspace = currentWorkspace()
1953
2476
  const tab = state.tabs.find(item => item.id === id)
1954
- if (workspace === undefined || tab === undefined || tab.kind !== 'file' || tab.binary || tab.truncated) return false
2477
+ if (workspace === undefined || tab === undefined) return undefined
2478
+ const writable = tab.kind === 'file' || (tab.kind === 'diff' && tab.ref === undefined && !tab.staged)
2479
+ if (!writable || tab.binary || tab.truncated) return undefined
2480
+ return { alias: workspace.alias, fullPath: tab.fullPath, rel: tab.rel }
2481
+ }
2482
+
2483
+ /**
2484
+ * Write one tab back to the remote host. @returns true when the burst's LAST
2485
+ * write landed.
2486
+ *
2487
+ * Requests for the SAME tab are serialized (see `SaveSlot`); a request that
2488
+ * arrives while one is in flight becomes the single pending write, replacing any
2489
+ * earlier pending content. Every caller of that burst — the one that started it
2490
+ * and the coalesced-away ones — resolves with the outcome of the write that
2491
+ * finally lands: the bytes they asked for are part of the newer buffer the
2492
+ * editor held, so "your edit is on disk" stays true (and a burst whose last
2493
+ * write failed reports false to all of them).
2494
+ */
2495
+ export async function saveTab(id: string, content: string, options: { force?: boolean } = {}): Promise<boolean> {
1955
2496
  // Never fall back to the tab's loaded text. `tab.text` is only ever written
1956
2497
  // by a load/reload or by the surface handoff (`captureLiveBuffer`), never as
1957
2498
  // a fallback for a caller without a live buffer, so substituting it here
@@ -1960,12 +2501,83 @@ export async function saveTab(id: string, content: string): Promise<boolean> {
1960
2501
  // without a live buffer must refuse to save instead (see EditorPane.saveActive).
1961
2502
  if (typeof content !== 'string') {
1962
2503
  toast(t('editor.needSource'), true)
1963
- return false
2504
+ return Promise.resolve(false)
1964
2505
  }
1965
- const text = content
1966
- patchTab(id, { saving: true, text })
2506
+ // Cheap refusal at REQUEST time: a truncated / binary / history tab answers
2507
+ // "no" synchronously and issues no write at all (the gate depends on it).
2508
+ if (saveTargetOf(id) === undefined) return Promise.resolve(false)
2509
+ /**
2510
+ * `text` is the request-time snapshot the success path compares against
2511
+ * (`newer` below): it must be recorded when the user ASKED, not when the write
2512
+ * finally runs — a handoff written in between would otherwise look like a
2513
+ * regression and keep the dirty flag for no reason.
2514
+ */
2515
+ patchTab(id, { saving: true, text: content })
2516
+ const request: SaveRequest = { content, force: options.force === true }
2517
+ const slot = saveSlotOf(id)
2518
+ if (slot.running) {
2519
+ slot.pending = request
2520
+ return new Promise<boolean>(resolve => { slot.waiters.push(resolve) })
2521
+ }
2522
+ return runSaveSlot(id, slot, request)
2523
+ }
2524
+
2525
+ /** Drain one tab's queue: one write, then at most one pending, then settle all. */
2526
+ async function runSaveSlot(id: string, slot: SaveSlot, first: SaveRequest): Promise<boolean> {
2527
+ slot.running = true
2528
+ let ok = true
2529
+ let request: SaveRequest | undefined = first
2530
+ try {
2531
+ while (request !== undefined) {
2532
+ ok = await performSave(id, request.content, request.force)
2533
+ request = slot.pending
2534
+ slot.pending = undefined
2535
+ }
2536
+ } finally {
2537
+ // `saving` is a QUEUE flag: it must stay true across the two writes of one
2538
+ // burst, or the status chip flickers "unsaved → saved → unsaved".
2539
+ slot.running = false
2540
+ patchTab(id, { saving: false })
2541
+ const waiters = slot.waiters
2542
+ slot.waiters = []
2543
+ for (const resolve of waiters) resolve(ok)
2544
+ releaseSaveSlot(id, slot)
2545
+ }
2546
+ return ok
2547
+ }
2548
+
2549
+ /**
2550
+ * One queued write. Everything it needs is re-read when it actually runs.
2551
+ *
2552
+ * The write carries the remote VERSION this tab was based on, and the Host
2553
+ * refuses it when the file moved on since. That refusal is the whole point of
2554
+ * this function's guard: this project's normal way of working is a human and an
2555
+ * agent editing the same remote tree, and a save that silently overwrote an
2556
+ * agent's last write was the one data-loss path with no recovery (the changes
2557
+ * panel would only notice the file afterwards, with the other side already
2558
+ * gone).
2559
+ *
2560
+ * @param force - the user answered the conflict prompt with "overwrite": the
2561
+ * write then goes through unguarded. It is an explicit decision made on
2562
+ * screen, not a default.
2563
+ */
2564
+ async function performSave(id: string, text: string, force: boolean): Promise<boolean> {
2565
+ const target = saveTargetOf(id)
2566
+ if (target === undefined) return false
2567
+ const tab = state.tabs.find(item => item.id === id)
2568
+ /**
2569
+ * The lock, built from the version this buffer was loaded from or last saved
2570
+ * to. No baseline (`undefined`) means the guard cannot say anything truthful
2571
+ * about this file, so it stays silent instead of blocking a legitimate save.
2572
+ */
2573
+ const guard = !force && tab !== undefined && tab.remoteMtime !== undefined
2574
+ ? {
2575
+ expectMtime: tab.remoteMtime,
2576
+ ...(tab.remoteSize === undefined ? {} : { expectSize: tab.remoteSize }),
2577
+ }
2578
+ : undefined
1967
2579
  try {
1968
- await api.fileOp.write(workspace.alias, tab.fullPath, text)
2580
+ const written = await api.fileOp.write(target.alias, target.fullPath, text, guard)
1969
2581
  /**
1970
2582
  * The remote file now holds `text`, so that becomes the disk-side dirty
1971
2583
  * baseline (a later remount compares against it).
@@ -1979,7 +2591,9 @@ export async function saveTab(id: string, content: string): Promise<boolean> {
1979
2591
  * through `markLiveEditorSaved` below);
1980
2592
  * - the tab was switched away from mid-write: its stored `text` is then the
1981
2593
  * handoff copy of that newer buffer, so comparing it with what was
1982
- * written detects the difference without an editor.
2594
+ * written detects the difference without an editor. A LATER queued save
2595
+ * also lands here: its request-time `text` is newer than this write, so
2596
+ * the flag stays until that one lands.
1983
2597
  *
1984
2598
  * Only a tab whose stored text IS the written text, with no mounted editor,
1985
2599
  * has nothing newer — there the flag is cleared directly. (Clearing it
@@ -1989,18 +2603,54 @@ export async function saveTab(id: string, content: string): Promise<boolean> {
1989
2603
  const liveEditor = isLiveEditorFor(id)
1990
2604
  const current = state.tabs.find(item => item.id === id)
1991
2605
  const newer = current !== undefined && current.text !== text
1992
- patchTab(id, { saving: false, baseline: text, ...(liveEditor || newer ? {} : { dirty: false }) })
2606
+ patchTab(id, {
2607
+ baseline: text,
2608
+ // The version just written becomes the next save's baseline. A Host that
2609
+ // could not read it back answers null: the next save is then unguarded,
2610
+ // which is honest, rather than "conflicting" with a made-up timestamp.
2611
+ remoteMtime: written.mtime ?? undefined,
2612
+ remoteSize: written.size,
2613
+ // Whatever conflict was on screen is answered by this successful write.
2614
+ conflict: undefined,
2615
+ ...(liveEditor || newer ? {} : { dirty: false }),
2616
+ })
1993
2617
  markLiveEditorSaved(id, text)
1994
- toast(`${t('editor.saved')} · ${tab.rel}`, false)
2618
+ toast(`${t('editor.saved')} · ${target.rel}`, false)
1995
2619
  await afterWrite()
1996
2620
  return true
1997
2621
  } catch (error) {
1998
- patchTab(id, { saving: false })
2622
+ /**
2623
+ * A REFUSED save, not a failed one: the remote file moved on. Nothing was
2624
+ * written, so the buffer, its dirty flag and the baseline all stay exactly
2625
+ * as they were — the user is shown what is there now and decides.
2626
+ *
2627
+ * Deliberately NOT going through `afterWrite()`: re-listing the tree here
2628
+ * would repaint a panel behind the decision the user is about to make.
2629
+ */
2630
+ if (error instanceof RemoteApiError && error.conflict !== undefined) {
2631
+ patchTab(id, { conflict: error.conflict })
2632
+ toast(`${t('editor.conflictBlocked')} · ${target.rel}`, true)
2633
+ return false
2634
+ }
1999
2635
  toast(error instanceof Error ? error.message : String(error), true)
2000
2636
  return false
2001
2637
  }
2002
2638
  }
2003
2639
 
2640
+ /**
2641
+ * Drop the pending save-conflict banner for one tab.
2642
+ *
2643
+ * Hiding the offer is NOT a decision: the buffer stays dirty and the baseline
2644
+ * stays untouched, so the next save is guarded exactly as this one was. Only a
2645
+ * forced save or a reload can settle a conflict for real — anything else would
2646
+ * be deciding for the user which version of their file to keep.
2647
+ */
2648
+ export function dismissConflict(id: string): void {
2649
+ const tab = state.tabs.find(item => item.id === id)
2650
+ if (tab?.conflict === undefined) return
2651
+ patchTab(id, { conflict: undefined })
2652
+ }
2653
+
2004
2654
  /**
2005
2655
  * Re-read one tab (file content or diff payload).
2006
2656
  *
@@ -2034,6 +2684,13 @@ export async function reloadTab(id: string): Promise<void> {
2034
2684
  truncated: read.truncated,
2035
2685
  dirty: false,
2036
2686
  ...(read.binary ? {} : { baseline: read.text ?? '' }),
2687
+ // A reload REPLACES the version this tab was based on, so the next save
2688
+ // is guarded against the bytes the user actually saw. Leaving the old
2689
+ // mtime here would make the very next save conflict with itself.
2690
+ remoteMtime: read.mtime,
2691
+ remoteSize: read.size,
2692
+ // Whatever conflict was pending is answered by this reload.
2693
+ conflict: undefined,
2037
2694
  })
2038
2695
  // Only now: the new text must already be in the tab when the editor remounts.
2039
2696
  patchTab(id, { reloadNonce: (tab.reloadNonce ?? 0) + 1 })
@@ -2046,7 +2703,7 @@ export async function reloadTab(id: string): Promise<void> {
2046
2703
  if (root === undefined) return
2047
2704
  try {
2048
2705
  const payload = tab.ref !== undefined
2049
- ? await withDeadline(loadCommitFileDiff(workspace.alias, root, tab.ref, tab.rel), gitDeadlineMs(), t('editor.readTimeout'))
2706
+ ? await withDeadline(loadCommitFileDiff(workspace.alias, root, tab.ref, tab.rel, tab.origPath), gitDeadlineMs(), t('editor.readTimeout'))
2050
2707
  : await withDeadline(loadDiff(workspace.alias, root, tab.rel, tab.staged, tab.untracked), gitDeadlineMs(), t('editor.readTimeout'))
2051
2708
  patchTab(id, {
2052
2709
  loading: false,
@@ -2054,8 +2711,12 @@ export async function reloadTab(id: string): Promise<void> {
2054
2711
  diff: payload,
2055
2712
  binary: payload.unsupported,
2056
2713
  model: payload.unsupported ? undefined : buildDiffModel(payload),
2714
+ truncated: payload.truncated === true,
2057
2715
  dirty: false,
2058
2716
  })
2717
+ // The diff now shows the CURRENT working tree, so the save baseline has to
2718
+ // follow it — a stale one would make the next save conflict with itself.
2719
+ applyDiffBaseline(id, payload)
2059
2720
  } catch (error) {
2060
2721
  patchTab(id, { error: error instanceof Error ? error.message : String(error) })
2061
2722
  }
@@ -2276,6 +2937,18 @@ export async function undoChange(tabId: string, mark: ChangeMark): Promise<void>
2276
2937
  info(t('changes.undoNoContext'))
2277
2938
  return
2278
2939
  }
2940
+ /**
2941
+ * 撤销是一次远端写(`git apply -R`)。链路已经判定断开时,请求发出去也只有一个
2942
+ * 结果:让 socket 文案冒出来、再被 `catch` 误标成「撤销冲突」。这里按**请求所属的
2943
+ * alias** 预判(不是页面上可见的那个),与保存路径(`EditorPane.saveActive` 的
2944
+ * offline 分支)用同一句「操作未发送」;`undefined` = 没有证据,不拦。
2945
+ *
2946
+ * 顺序是承重的:dirty 门在前(用远端补丁盖掉未保存编辑是最糟的结果),离线门在后。
2947
+ */
2948
+ if (connectionStateOf(context.alias) === 'error') {
2949
+ info(t('connection.actionFailed'))
2950
+ return
2951
+ }
2279
2952
  const patch = tab.changeSet?.patches?.[mark.hunk ?? -1]
2280
2953
  if (patch === undefined || patch.trim() === '') {
2281
2954
  info(t('changes.undoMissing'))
@@ -2285,6 +2958,16 @@ export async function undoChange(tabId: string, mark: ChangeMark): Promise<void>
2285
2958
  // 'revert' = 远端 `git apply -R`;上下文不匹配它就抛错,这就是冲突护栏。
2286
2959
  await applyHunk(context.alias, context.root, patch, 'revert')
2287
2960
  } catch (error) {
2961
+ /**
2962
+ * 传输失败不是「补丁上下文变了」:报成冲突会让用户去改文件,而真正的原因是链路。
2963
+ * `applyHunk` 的补丁临时文件写失败会以 transport 错误原样抛出(`actions.ts` 的
2964
+ * write 在 try 之外),`api.call` 会给它打 `transport` 标记,所以这里的判据对
2965
+ * 「首次失败(原始 socket 文案)」和「重复失败(已本地化)」都成立。
2966
+ */
2967
+ if (isConnectionFailure(error)) {
2968
+ info(t('connection.actionFailed'))
2969
+ return
2970
+ }
2288
2971
  // 可把 git 的说法附在后面("patch does not apply" 之类),但**不动**标记与文件。
2289
2972
  const detail = error instanceof Error ? error.message.trim() : String(error).trim()
2290
2973
  info(detail === '' ? t('changes.undoConflict') : `${t('changes.undoConflict')} · ${detail}`)