dsh-remote-vs 0.21.1 → 0.22.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.
@@ -165,6 +165,54 @@ function chipAt(at: number, text: string): RemovedChip | undefined {
165
165
  return { at, text: truncated ? text.slice(0, MAX_CHIP_CHARS) : text, truncated }
166
166
  }
167
167
 
168
+ /**
169
+ * How many lines of a collapsed deletion block travel as the tooltip preview.
170
+ *
171
+ * The pill only shows the COUNT, so the text is not on screen; it is still worth
172
+ * carrying a bounded prefix for the hover — enough to recognize the block, never
173
+ * enough to build a thousand-line title from a thousand-line removal.
174
+ */
175
+ const MAX_BLOCK_PREVIEW_LINES = 20
176
+
177
+ /**
178
+ * One chip for a run of deleted lines.
179
+ *
180
+ * A block deletion used to emit one chip PER line, every one of them at column 0
181
+ * of the same anchor line: a ten-line removal became ten struck-through
182
+ * fragments printed on top of each other, which says neither "ten lines" nor
183
+ * what they were. A run longer than a single line now collapses into one chip
184
+ * carrying the count (rendered as `−N 行已删除`) with a bounded preview in its
185
+ * title; a one-line removal keeps the exact text at the cut, which is the case
186
+ * where the struck-through words are genuinely readable.
187
+ *
188
+ * @param deleted - the run's deleted texts, in order.
189
+ * @param line - the line the run belongs to.
190
+ * @param anchor - the mark's anchor line (see {@link chipOnLine}).
191
+ */
192
+ function deletedRunChip(deleted: readonly string[], line: number, anchor: number): RemovedChip | undefined {
193
+ const [only] = deleted
194
+ if (only === undefined) return undefined
195
+ if (deleted.length === 1) {
196
+ const chip = chipAt(0, only)
197
+ return chip === undefined ? undefined : chipOnLine(chip, line, anchor)
198
+ }
199
+ const preview = deleted
200
+ .slice(0, MAX_BLOCK_PREVIEW_LINES)
201
+ .map(text => (text.length > MAX_CHIP_CHARS ? text.slice(0, MAX_CHIP_CHARS) : text))
202
+ .join('\n')
203
+ return chipOnLine(
204
+ {
205
+ at: 0,
206
+ text: preview,
207
+ // The preview was cut either by the line cap or by the line count.
208
+ truncated: deleted.length > MAX_BLOCK_PREVIEW_LINES || deleted.some(text => text.length > MAX_CHIP_CHARS),
209
+ count: deleted.length,
210
+ },
211
+ line,
212
+ anchor,
213
+ )
214
+ }
215
+
168
216
  /**
169
217
  * Attach `line` only when the fragment is NOT on the mark's anchor line.
170
218
  *
@@ -196,24 +244,57 @@ function shortEnough(deleted: readonly string[], added: readonly AddedLine[]): b
196
244
  /**
197
245
  * Fill in `mark.inline` / `mark.removed` for one modified block.
198
246
  *
199
- * Pairing is positional: the i-th deleted line of the block goes with the i-th
200
- * added line (git puts every deletion of a block before its additions, and a
201
- * block with unequal counts leaves the extras as pure additions/removals).
247
+ * Pairing happens in two phases, and the first one is what keeps the highlight
248
+ * honest:
249
+ *
250
+ * 1. **Exact matches are consumed first, at any index.** A block that was merely
251
+ * REORDERED (`a`,`b` → `b`,`a`) has no character-level change in it, but
252
+ * positional pairing compares `a` against `b` and paints "these characters
253
+ * changed" on two lines that did not change at all. The same phase fixes the
254
+ * common "one line inserted inside an edited run" shape, where every line
255
+ * after the insertion used to be paired with the wrong neighbour. Lookup goes
256
+ * through a text → indices map, so the phase stays linear in the block rather
257
+ * than quadratic in its lines.
258
+ * 2. **What is left pairs by position** — the i-th edited deletion with the i-th
259
+ * remaining addition. git puts every deletion of a block before its
260
+ * additions, and a block with unequal counts leaves the extras as pure
261
+ * additions/removals.
202
262
  *
203
263
  * @param mark - the block's mark (mutated).
204
264
  * @param deleted - the block's deleted texts, in order.
205
265
  * @param added - the block's added lines, in order.
206
266
  */
207
267
  function attachInline(mark: ChangeMark, deleted: readonly string[], added: readonly AddedLine[]): void {
208
- const pairs = Math.min(deleted.length, added.length)
268
+ // Phase 1 — consume lines that did not change, only moved.
269
+ const pending = new Map<string, number[]>()
270
+ added.forEach((item, index) => {
271
+ const list = pending.get(item.text)
272
+ if (list === undefined) pending.set(item.text, [index])
273
+ else list.push(index)
274
+ })
275
+ const edited: string[] = []
276
+ const used = new Array<boolean>(added.length).fill(false)
277
+ for (const text of deleted) {
278
+ const list = pending.get(text)
279
+ if (list === undefined || list.length === 0) {
280
+ edited.push(text)
281
+ continue
282
+ }
283
+ const index = list.shift()
284
+ if (index !== undefined) used[index] = true
285
+ }
286
+ const fresh = added.filter((_item, index) => !used[index])
287
+
288
+ // Phase 2 — positional pairing over the survivors.
289
+ const pairs = Math.min(edited.length, fresh.length)
209
290
  const inline: InlineRange[] = []
210
291
  const removed: RemovedChip[] = []
211
292
  for (let index = 0; index < pairs; index += 1) {
212
- const before = deleted[index]
213
- const after = added[index].text
214
- const line = added[index].line
215
- // A pair that came out identical (the block was reordered, not rewritten).
216
- if (before === after) continue
293
+ const before = edited[index]
294
+ const item = fresh[index]
295
+ if (before === undefined || item === undefined) continue
296
+ const after = item.text
297
+ const line = item.line
217
298
  const { head, oldMid, newMid } = splitCommon(before, after)
218
299
  if (newMid.length === 0) {
219
300
  // The line was only shortened: there is no new character to paint, so the
@@ -231,11 +312,10 @@ function attachInline(mark: ChangeMark, deleted: readonly string[], added: reado
231
312
  for (const range of refineRanges(oldMid, newMid, head)) inline.push(rangeOnLine(range, line, mark.from))
232
313
  }
233
314
  // Deleted lines with no added counterpart: their text no longer exists in the
234
- // new file, so it hangs on the anchor line's first column as a chip.
235
- for (let index = pairs; index < deleted.length; index += 1) {
236
- const chip = chipAt(0, deleted[index])
237
- if (chip !== undefined) removed.push(chip)
238
- }
315
+ // new file, so it hangs on the anchor line's first column — as one collapsed
316
+ // chip when the run is longer than a line (see `deletedRunChip`).
317
+ const tailChip = deletedRunChip(edited.slice(pairs), mark.from, mark.from)
318
+ if (tailChip !== undefined) removed.push(tailChip)
239
319
  if (inline.length > 0) mark.inline = inline
240
320
  if (removed.length > 0) mark.removed = removed
241
321
  }
@@ -280,13 +360,14 @@ function collectHunk(hunk: UnifiedHunk, marks: ChangeMark[], index: number): num
280
360
  } else if (deleted.length > 0) {
281
361
  const anchor = Math.max(1, line)
282
362
  const mark: ChangeMark = { from: anchor, to: anchor, kind: 'del', hunk: index }
283
- if (inlineAllowed && deleted.every(text => text.length <= MAX_INLINE_LINE)) {
284
- const chips: RemovedChip[] = []
285
- for (const text of deleted) {
286
- const chip = chipAt(0, text)
287
- if (chip !== undefined) chips.push(chip)
288
- }
289
- if (chips.length > 0) mark.removed = chips
363
+ // A collapsed block pill carries a bounded preview only, so the per-line
364
+ // length cap (which exists to keep character-level work bounded) does not
365
+ // apply to it; a single deleted line still has to fit before its text is
366
+ // put on screen.
367
+ const printable = deleted.length > 1 || deleted.every(text => text.length <= MAX_INLINE_LINE)
368
+ if (inlineAllowed && printable) {
369
+ const chip = deletedRunChip(deleted, anchor, anchor)
370
+ if (chip !== undefined) mark.removed = [chip]
290
371
  }
291
372
  marks.push(mark)
292
373
  first ??= anchor
@@ -319,9 +400,11 @@ function collectHunk(hunk: UnifiedHunk, marks: ChangeMark[], index: number): num
319
400
  *
320
401
  * @param hunks - served hunks for the whole session.
321
402
  * @param stamp - identity of the comparison (file + baseline + turn).
403
+ * @param filePatch - the host's whole-file reverse patch, when it served one
404
+ * (see `ChangeSet.filePatch`); '' / missing = nothing to revert as a whole.
322
405
  * @returns the mark set the editor paints, or {@link EMPTY_CHANGE_SET}.
323
406
  */
324
- export function changeSetFromHunks(hunks: readonly UnifiedHunk[], stamp: string): ChangeSet {
407
+ export function changeSetFromHunks(hunks: readonly UnifiedHunk[], stamp: string, filePatch?: string): ChangeSet {
325
408
  if (hunks.length === 0) return { marks: [], hunks: [], stamp, patches: [] }
326
409
  const marks: ChangeMark[] = []
327
410
  // `hunks[i]` / `patches[i]` must stay in step with the mark's `hunk` index, so
@@ -343,5 +426,6 @@ export function changeSetFromHunks(hunks: readonly UnifiedHunk[], stamp: string)
343
426
  hunks: [...new Set(order.map(anchor => anchor.line))],
344
427
  stamp,
345
428
  patches,
429
+ ...(filePatch === undefined || filePatch === '' ? {} : { filePatch }),
346
430
  }
347
431
  }
@@ -0,0 +1,133 @@
1
+ /**
2
+ * 「这个文件我看过了」的本地标记。
3
+ *
4
+ * 会话改动面板原本只能看、不能收敛:一次三十个文件的重构,没有任何地方记得"这个我
5
+ * 已经审过",列表和游标每次都从头上开始。这里补的是**纯客户端**的审阅状态 —— 它不
6
+ * 写远端、不进账本、不影响任何一次 `git` 调用,因此是这条路线上唯一零风险的收敛手段
7
+ * ("接受改动"的另一半语义是真正的 `git apply --cached`,那要求基线等于索引,属于另一
8
+ * 个决定,**不在本模块**里)。
9
+ *
10
+ * ## 为什么键里带计数
11
+ *
12
+ * 键 = 路径 + 增删行数 + 状态。会话又改了同一批行(行数随之变化)时,旧标记自然失效,
13
+ * 文件重新变成"未审阅"——这正是想要的效果,而且不需要监听任何事件。行数完全没变的
14
+ * 二次编辑仍会被当成"已审阅",这是这套方案的已知盲点:它与"审阅的是哪一版"这个事实
15
+ * 相比,代价远小于为每个文件拉一次 diff 去算指纹。
16
+ *
17
+ * 纯函数 + 一个带上限的表,`scripts/check-review-state.mjs` 直接驱动真实的判定。
18
+ */
19
+
20
+ /** 面板能给的一行(`RemoteChangedFile` 的投影)。 */
21
+ export interface ReviewSubject {
22
+ /** 远端绝对路径(唯一标识)。 */
23
+ path: string
24
+ added: number
25
+ deleted: number
26
+ status?: string
27
+ }
28
+
29
+ /** 已审阅集合:键 → 1(用对象是为了能直接 JSON 往返)。 */
30
+ export type ReviewedMap = Readonly<Record<string, 1>>
31
+
32
+ /** 一个会话最多记住这么多条(长命页面不能无限长)。 */
33
+ export const REVIEW_CAP = 1000
34
+
35
+ /**
36
+ * 一行的审阅键。
37
+ *
38
+ * 计数进键里是刻意的:见文件头。`status` 也进键,因为"删掉了又加回来"和"一直在改"
39
+ * 是两件不同的事,标签变了就该重新看一遍。
40
+ *
41
+ * @param file - 面板的一行。
42
+ * @returns 稳定的键(路径里可能有任意字符,用 NUL 分隔不会与计数撞)。
43
+ */
44
+ export function reviewKeyOf(file: ReviewSubject): string {
45
+ return `${file.path}\u0000${file.added}\u0000${file.deleted}\u0000${file.status ?? ''}`
46
+ }
47
+
48
+ /** 这一行是否已被标为审阅。 */
49
+ export function isReviewed(file: ReviewSubject, reviewed: ReviewedMap): boolean {
50
+ return reviewed[reviewKeyOf(file)] === 1
51
+ }
52
+
53
+ /** 已审阅的行数(只数当前列表里的,所以它永远 ≤ 列表长度)。 */
54
+ export function reviewedCount(files: readonly ReviewSubject[], reviewed: ReviewedMap): number {
55
+ let count = 0
56
+ for (const file of files) if (isReviewed(file, reviewed)) count += 1
57
+ return count
58
+ }
59
+
60
+ /** 切换一行的标记,返回新表(输入不被修改)。 */
61
+ export function toggleReviewed(files: readonly ReviewSubject[], reviewed: ReviewedMap, file: ReviewSubject): Record<string, 1> {
62
+ const key = reviewKeyOf(file)
63
+ const next: Record<string, 1> = {}
64
+ for (const [candidate, value] of Object.entries(reviewed)) next[candidate] = value
65
+ if (next[key] === 1) delete next[key]
66
+ else next[key] = 1
67
+ return pruneReviewed(files, next)
68
+ }
69
+
70
+ /** 全标或全清。 */
71
+ export function setAllReviewed(files: readonly ReviewSubject[], on: boolean): Record<string, 1> {
72
+ if (!on) return {}
73
+ const next: Record<string, 1> = {}
74
+ for (const file of files) {
75
+ if (next[reviewKeyOf(file)] === 1) continue
76
+ next[reviewKeyOf(file)] = 1
77
+ if (Object.keys(next).length >= REVIEW_CAP) break
78
+ }
79
+ return next
80
+ }
81
+
82
+ /**
83
+ * 丢掉不属于当前列表的键。
84
+ *
85
+ * 列表每 3 秒重建一次,一条被删掉(或计数变了)的键如果留着,下次同一路径回到列表
86
+ * 时会被当成"已审阅"——那是凭空出现的勾。清理放在每次写入与每次加载后都做,代价是
87
+ * O(列表长度)。
88
+ */
89
+ export function pruneReviewed(files: readonly ReviewSubject[], reviewed: ReviewedMap): Record<string, 1> {
90
+ const live = new Set(files.map(file => reviewKeyOf(file)))
91
+ const next: Record<string, 1> = {}
92
+ let kept = 0
93
+ for (const [key, value] of Object.entries(reviewed)) {
94
+ if (value !== 1 || !live.has(key)) continue
95
+ next[key] = 1
96
+ kept += 1
97
+ if (kept >= REVIEW_CAP) break
98
+ }
99
+ return next
100
+ }
101
+
102
+ /**
103
+ * 解析持久化的一串 JSON。
104
+ *
105
+ * 任何畸形输入都给空表而不是抛错:这份状态是"看过没看过",读不出来最多重看一遍,
106
+ * 不值得让面板崩掉。键必须是字符串、值必须是 1,且受 {@link REVIEW_CAP} 限制。
107
+ *
108
+ * @param raw - `localStorage` 里存着的那串文本(可能为 null)。
109
+ */
110
+ export function parseReviewed(raw: string | null | undefined): Record<string, 1> {
111
+ if (typeof raw !== 'string' || raw === '') return {}
112
+ let parsed: unknown
113
+ try {
114
+ parsed = JSON.parse(raw)
115
+ } catch {
116
+ return {}
117
+ }
118
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return {}
119
+ const next: Record<string, 1> = {}
120
+ let kept = 0
121
+ for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) {
122
+ if (value !== 1 || key === '') continue
123
+ next[key] = 1
124
+ kept += 1
125
+ if (kept >= REVIEW_CAP) break
126
+ }
127
+ return next
128
+ }
129
+
130
+ /** 序列化(键数量已受上限约束,所以这串不会无限长)。 */
131
+ export function serializeReviewed(reviewed: ReviewedMap): string {
132
+ return JSON.stringify(reviewed)
133
+ }
@@ -207,9 +207,9 @@ const zh: Record<string, string> = {
207
207
  'term.new': '新建终端',
208
208
  'term.empty': '还没有终端 —— 选好主机后点右上角 + 新建一个。',
209
209
  'term.close': '关闭终端',
210
- 'term.closeTitle': '关闭这个终端',
211
- 'term.copy': '复制',
212
- 'term.paste': '粘贴',
210
+ 'term.closeTitle': '关闭这个终端',
211
+ 'term.copy': '复制',
212
+ 'term.paste': '粘贴',
213
213
  'term.selectAll': '全选',
214
214
  'term.noHosts': '还没有主机,请先去「设置 → 远程主机」配置。',
215
215
  'tab.git': 'Git',
@@ -574,7 +574,26 @@ const zh: Record<string, string> = {
574
574
  'changes.statusDeleted': '删除',
575
575
  'changes.statusModified': '修改',
576
576
  'changes.statusRenamed': '重命名',
577
- 'changes.truncated': '文件过多,只列出前 500 个(统计数字仍为全部)。',
577
+ 'changes.truncated': '文件过多,只列出前 500 个(统计数字也只算这 500 个)。',
578
+ 'changes.excluded': '未统计构建产物目录:{dirs}',
579
+ 'changes.markReviewed': '标记为已审阅',
580
+ 'changes.unmarkReviewed': '取消审阅标记',
581
+ 'changes.reviewCount': '已审阅 {done}/{total}',
582
+ 'changes.reviewMenu': '审阅标记选项',
583
+ 'changes.reviewAll': '全部标为已审阅',
584
+ 'changes.reviewNone': '清除审阅标记',
585
+ 'changes.menuOpen': '打开',
586
+ 'changes.openInScm': '在 SCM 中查看',
587
+ 'changes.copyPath': '复制远端路径',
588
+ 'changes.revertFile': '撤销该文件的全部改动',
589
+ 'changes.revertNotPossible': '无法撤销(新建、二进制或过大)',
590
+ 'changes.revertCreation': '撤销新建(删除该文件)',
591
+ 'changes.revertCreationOk': '删除该文件',
592
+ 'changes.revertCreationTitle': '撤回这个新建文件?',
593
+ 'changes.revertCreationText': '会删除 {path}。git 索引里还留着内容,可以用 git checkout 恢复。',
594
+ 'changes.revertedFile': '已撤销该文件的改动',
595
+ 'changes.revertFailed': '撤销失败',
596
+ 'changes.deletedCreation': '已删除新建文件',
578
597
  'changes.prev': '上一个修改点',
579
598
  'changes.next': '下一个修改点',
580
599
  'changes.navLabel': '改动跳转',
@@ -825,9 +844,9 @@ const en: Record<string, string> = {
825
844
  'term.new': 'New terminal',
826
845
  'term.empty': 'No terminal yet — pick a host, then press + to open one.',
827
846
  'term.close': 'Close terminal',
828
- 'term.closeTitle': 'Close this terminal',
829
- 'term.copy': 'Copy',
830
- 'term.paste': 'Paste',
847
+ 'term.closeTitle': 'Close this terminal',
848
+ 'term.copy': 'Copy',
849
+ 'term.paste': 'Paste',
831
850
  'term.selectAll': 'Select all',
832
851
  'term.noHosts': 'No hosts yet. Configure one in Settings → Remote Hosts first.',
833
852
  'tab.git': 'Git',
@@ -1192,7 +1211,26 @@ const en: Record<string, string> = {
1192
1211
  'changes.statusDeleted': 'deleted',
1193
1212
  'changes.statusModified': 'modified',
1194
1213
  'changes.statusRenamed': 'renamed',
1195
- 'changes.truncated': 'Too many files: the first 500 are listed (totals cover all of them).',
1214
+ 'changes.truncated': 'Too many files: the first 500 are listed (the counts cover only those).',
1215
+ 'changes.excluded': 'Build output directories not counted: {dirs}',
1216
+ 'changes.markReviewed': 'Mark as reviewed',
1217
+ 'changes.unmarkReviewed': 'Clear the review mark',
1218
+ 'changes.reviewCount': '{done}/{total} reviewed',
1219
+ 'changes.reviewMenu': 'Review mark options',
1220
+ 'changes.reviewAll': 'Mark all as reviewed',
1221
+ 'changes.reviewNone': 'Clear all review marks',
1222
+ 'changes.menuOpen': 'Open',
1223
+ 'changes.openInScm': 'Show in Source Control',
1224
+ 'changes.copyPath': 'Copy remote path',
1225
+ 'changes.revertFile': 'Revert all changes in this file',
1226
+ 'changes.revertNotPossible': 'Cannot be reverted (new file, binary or too large)',
1227
+ 'changes.revertCreation': 'Undo the new file (delete it)',
1228
+ 'changes.revertCreationOk': 'Delete the file',
1229
+ 'changes.revertCreationTitle': 'Undo this new file?',
1230
+ 'changes.revertCreationText': 'It deletes {path}. git keeps the bytes in its index, so git checkout can bring it back.',
1231
+ 'changes.revertedFile': 'Reverted this file',
1232
+ 'changes.revertFailed': 'Revert failed',
1233
+ 'changes.deletedCreation': 'Deleted the new file',
1196
1234
  'changes.prev': 'Previous change',
1197
1235
  'changes.next': 'Next change',
1198
1236
  'changes.navLabel': 'Change navigation',
@@ -28,6 +28,7 @@ import { buildDiffModel } from './scm/diff-model.ts'
28
28
  import type { ChangeMark, ChangeSet } from './vsc/change-marks.ts'
29
29
  import { changeSetFromHunks } from './changes/model.ts'
30
30
  import { undoContext, type UndoContext } from './changes/undo-context.ts'
31
+ import { changeOriginForTab, resolveUndoTarget } from './changes/undo-target.ts'
31
32
  import { applyStageOverrides, bucketStatus, buildTreeMarks, insertStagedEntry, optimisticStageDetail, type ChangeEntry, type StageOverride, type StatusBuckets, type TreeMarks } from './scm/status-map.ts'
32
33
  import { loadCommitFileDiff, findRepos, loadDiff, loadHead, loadStatusDetail, probeRepoRoot, probeStatusDir, probeStatusPaths, applyHunk, stagePaths, unstagePaths, type DiffPayload } from './scm/actions.ts'
33
34
  import { StageCoordinator } from './scm/stage-queue.ts'
@@ -647,6 +648,12 @@ export interface ExplorerValue {
647
648
  * `changeSet.marks`,`hunk` 是 `patches` 的下标)。
648
649
  */
649
650
  undoChange: (tabId: string, mark: ChangeMark) => Promise<void>
651
+ /**
652
+ * 撤销本会话对某个文件的**全部**改动(改动面板那一行的动作)。
653
+ *
654
+ * @returns 远端是否真的写了(`false` = 被某道门拒了,文件未变)。
655
+ */
656
+ revertFileChanges: (target: RevertFileTarget) => Promise<boolean>
650
657
  /**
651
658
  * Write one file tab back to the remote host.
652
659
  * @returns true only when the write really succeeded — the caller uses it to
@@ -770,6 +777,7 @@ function build(): ExplorerValue {
770
777
  gotoChange,
771
778
  markChangeStale,
772
779
  undoChange,
780
+ revertFileChanges,
773
781
  saveTab,
774
782
  dismissConflict,
775
783
  reloadTab,
@@ -2616,7 +2624,31 @@ async function performSave(id: string, text: string, force: boolean): Promise<bo
2616
2624
  })
2617
2625
  markLiveEditorSaved(id, text)
2618
2626
  toast(`${t('editor.saved')} · ${target.rel}`, false)
2619
- await afterWrite()
2627
+ /**
2628
+ * The write is DONE, and the save result must not include a remote git read.
2629
+ *
2630
+ * `afterWrite()` re-reads `git status` and only then re-lists the tree. On a
2631
+ * monorepo that read is the expensive half (the SCM panel shows the same cost:
2632
+ * seconds, and minutes when the tree is cold), and awaiting it here made the
2633
+ * editor's "saving…" last exactly that long — which is what "saving is slow,
2634
+ * it refreshes git first" looks like from the outside. Nothing the save
2635
+ * REPORTS depends on it: the baseline advances from the write's own answer
2636
+ * above, and the dirty flag is re-derived synchronously.
2637
+ *
2638
+ * So it runs in the background. It still runs — the status marks and the tree
2639
+ * revision catch up when it lands — and the read queue collapses a burst of
2640
+ * saves into at most one follow-up walk (`ReadQueue.run(..., 'fresh')`).
2641
+ */
2642
+ void afterWrite()
2643
+ /**
2644
+ * The save just changed what this file looks like against the session
2645
+ * baseline, so the marks painted from the PREVIOUS bytes are gone (typing
2646
+ * invalidates them by design) — and nothing used to bring them back until the
2647
+ * user clicked the row in the change panel again. Re-fetch them from the tab's
2648
+ * own recorded provenance, which needs no panel interaction. Also background:
2649
+ * it is one more remote read that must not stand between the user and "saved".
2650
+ */
2651
+ refreshChangeSetForTab(id)
2620
2652
  return true
2621
2653
  } catch (error) {
2622
2654
  /**
@@ -2915,7 +2947,7 @@ async function refreshChangeSet(tabId: string, context: UndoContext): Promise<vo
2915
2947
  applyChangeSet(tabId, null)
2916
2948
  return
2917
2949
  }
2918
- applyChangeSet(tabId, changeSetFromHunks(diff.hunks, `${tab.fullPath}@${Date.now()}`))
2950
+ applyChangeSet(tabId, changeSetFromHunks(diff.hunks, `${tab.fullPath}@${Date.now()}`, diff.patch))
2919
2951
  } catch {
2920
2952
  // A read that fails leaves no marks rather than wrong ones.
2921
2953
  applyChangeSet(tabId, null)
@@ -3002,6 +3034,158 @@ export async function undoChange(tabId: string, mark: ChangeMark): Promise<void>
3002
3034
  void api.changes.list(context.sessionId, true).catch(() => undefined)
3003
3035
  }
3004
3036
 
3037
+ /**
3038
+ * Coordinates for "undo everything this session did to this file".
3039
+ *
3040
+ * Handed over by the change panel, which is the only surface that knows both the
3041
+ * file and the session it belongs to. `mode` comes from the HOST
3042
+ * (`RemoteChangedFile.revert`), never from the client: only git can say whether a
3043
+ * creation has a copy to fall back on.
3044
+ */
3045
+ export interface RevertFileTarget {
3046
+ sessionId: string
3047
+ bindingId: string
3048
+ alias: string
3049
+ root: string
3050
+ path: string
3051
+ display: string
3052
+ mode: 'patch' | 'delete'
3053
+ }
3054
+
3055
+ /**
3056
+ * Revert one file's WHOLE session change set (the panel row's action).
3057
+ *
3058
+ * Three things make this a separate path from `undoChange`, and each one is
3059
+ * load-bearing:
3060
+ *
3061
+ * 1. **It works without an open tab.** The panel lists files nobody opened, so
3062
+ * the coordinates cannot come from `undoContext()` (which describes the tab on
3063
+ * screen). They arrive with the call and are validated by the SAME rules
3064
+ * (`resolveUndoTarget`: session agreement, binding identity, path under the
3065
+ * ledger root) — a row from another conversation, or from a sibling binding
3066
+ * that happens to share the alias, is refused rather than guessed.
3067
+ * 2. **It is ONE remote write.** The host serves the file as a single patch, which
3068
+ * is exactly what `git apply -R` needs to restore the session baseline; a loop
3069
+ * of per-hunk applies would shift every later hunk and report a conflict
3070
+ * halfway through, leaving the file half reverted.
3071
+ * 3. **A creation is not a patch.** `mode: 'delete'` (a tracked addition, where
3072
+ * git still holds the bytes) deletes the file behind an explicit confirmation;
3073
+ * an untracked creation never reaches here, because the host offers no mode
3074
+ * for it.
3075
+ *
3076
+ * The order of the gates is the one `undoChange` established: an unsaved buffer
3077
+ * refuses first (a remote write must never overwrite what the user has not
3078
+ * saved), then the offline check, then the coordinates, then the patch.
3079
+ *
3080
+ * @returns whether the remote was actually written.
3081
+ */
3082
+ export async function revertFileChanges(target: RevertFileTarget): Promise<boolean> {
3083
+ const tab = state.tabs.find(item => item.kind === 'file' && item.fullPath === target.path)
3084
+ if (tab?.dirty === true) {
3085
+ info(t('changes.undoDirty'))
3086
+ return false
3087
+ }
3088
+ if (connectionStateOf(target.alias) === 'error') {
3089
+ info(t('connection.actionFailed'))
3090
+ return false
3091
+ }
3092
+ const origin = {
3093
+ sessionId: target.sessionId,
3094
+ bindingId: target.bindingId,
3095
+ alias: target.alias,
3096
+ root: target.root,
3097
+ }
3098
+ /**
3099
+ * The session check inside `resolveUndoTarget` is trivially true here (the panel
3100
+ * passed both ids), and that is fine: the panel can only hand over a row from the
3101
+ * summary it fetched FOR this session (`data.id === sessionId`). What this call
3102
+ * really answers is the part the panel cannot know: is that binding still the
3103
+ * same one (id + alias), and does this path still sit under the ledger root the
3104
+ * patch was computed against?
3105
+ */
3106
+ const resolved = resolveUndoTarget({
3107
+ origin,
3108
+ tabPath: target.path,
3109
+ panelSessionId: target.sessionId,
3110
+ bindings: remoteOpenBindings().bindings,
3111
+ })
3112
+ if (!resolved.ok) {
3113
+ info(t('changes.undoNoContext'))
3114
+ return false
3115
+ }
3116
+ try {
3117
+ if (target.mode === 'patch') {
3118
+ // Fresh from the host: the panel's numbers may be a poll old, and the patch
3119
+ // must describe the file as it is NOW.
3120
+ const diff = await api.changes.diff(target.sessionId, target.path)
3121
+ const patch = diff !== null && diff.kind === 'text' ? (diff.patch ?? '') : ''
3122
+ if (patch.trim() === '') {
3123
+ info(t('changes.undoMissing'))
3124
+ return false
3125
+ }
3126
+ await applyHunk(target.alias, target.root, patch, 'revert')
3127
+ } else {
3128
+ const ok = await confirmDialog({
3129
+ title: t('changes.revertCreationTitle'),
3130
+ text: t('changes.revertCreationText').replace('{path}', target.display),
3131
+ danger: true,
3132
+ okText: t('changes.revertCreationOk'),
3133
+ })
3134
+ if (!ok) return false
3135
+ await api.fileOp.rm(target.alias, target.path, false)
3136
+ }
3137
+ } catch (error) {
3138
+ if (isConnectionFailure(error)) {
3139
+ info(t('connection.actionFailed'))
3140
+ return false
3141
+ }
3142
+ const detail = error instanceof Error ? error.message.trim() : String(error).trim()
3143
+ // A refused reverse patch means "the surroundings moved" (that is the conflict
3144
+ // guard); a failed delete has no such reading, so it gets its own wording
3145
+ // instead of pretending the patch context drifted.
3146
+ const label = target.mode === 'delete' ? t('changes.revertFailed') : t('changes.undoConflict')
3147
+ info(detail === '' ? label : `${label} · ${detail}`)
3148
+ return false
3149
+ }
3150
+ /**
3151
+ * The write SUCCEEDED, so nothing below may be reported as a failure: the
3152
+ * remote file has already changed. Refreshing the tab and the list is best
3153
+ * effort — a read that fails here leaves a stale panel, not a lost revert.
3154
+ */
3155
+ try {
3156
+ // Re-read the tab: the write took a round trip, and it may have been closed
3157
+ // (or replaced) meanwhile.
3158
+ const live = state.tabs.find(item => item.id === (tab?.id ?? ''))
3159
+ if (target.mode === 'delete') {
3160
+ // The file is gone; a tab showing it would keep a buffer that cannot be
3161
+ // saved anywhere sensible.
3162
+ if (live !== undefined) closeTab(live.id)
3163
+ } else if (live !== undefined) {
3164
+ await reloadTab(live.id)
3165
+ await refreshChangeSet(live.id, resolved.origin)
3166
+ }
3167
+ } catch {
3168
+ // Deliberately swallowed: see above.
3169
+ }
3170
+ void api.changes.list(target.sessionId, true).catch(() => undefined)
3171
+ info(target.mode === 'delete' ? t('changes.deletedCreation') : t('changes.revertedFile'))
3172
+ return true
3173
+ }
3174
+
3175
+ /**
3176
+ * Re-read one tab's change marks from the provenance recorded for it.
3177
+ *
3178
+ * Used after a successful save: typing invalidates the painted marks by design
3179
+ * (see `change-marks.ts`), and without this the file would keep its "positions
3180
+ * stale" badge until the user clicked the row again. A tab nobody attached marks
3181
+ * to has no provenance, so this is a no-op for every file opened from the tree.
3182
+ */
3183
+ function refreshChangeSetForTab(tabId: string): void {
3184
+ const origin = changeOriginForTab(tabId)
3185
+ if (origin === undefined) return
3186
+ void refreshChangeSet(tabId, origin)
3187
+ }
3188
+
3005
3189
  /** Mount-time hook: boot the store for a given ctx. */
3006
3190
  export function useBootstrap(ctx: Context): void {
3007
3191
  useEffect(() => {