dsh-remote-vs 0.26.0 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.en.md +112 -28
  2. package/README.md +84 -25
  3. package/THIRD-PARTY-NOTICES.md +7 -2
  4. package/lib/client.js +1237 -254
  5. package/lib/index.js +821 -17
  6. package/lib/types/changes/recorder.d.ts +119 -2
  7. package/lib/types/client/CodeEditor.d.ts +29 -0
  8. package/lib/types/client/OutlinePanel.d.ts +22 -0
  9. package/lib/types/client/ProcessesSection.d.ts +19 -0
  10. package/lib/types/client/api.d.ts +22 -2
  11. package/lib/types/client/blame-model.d.ts +77 -0
  12. package/lib/types/client/changes/apply-failure.d.ts +41 -0
  13. package/lib/types/client/changes/block-confirm.d.ts +97 -0
  14. package/lib/types/client/changes/diff-outcome.d.ts +56 -0
  15. package/lib/types/client/changes/freshness.d.ts +51 -0
  16. package/lib/types/client/changes/model.d.ts +19 -1
  17. package/lib/types/client/changes/session-diff.d.ts +100 -0
  18. package/lib/types/client/changes/staleness.d.ts +98 -0
  19. package/lib/types/client/changes/turn-reverted.d.ts +82 -0
  20. package/lib/types/client/changes/turn-view.d.ts +131 -0
  21. package/lib/types/client/changes/undo-affordance.d.ts +44 -10
  22. package/lib/types/client/changes/undo-target.d.ts +12 -0
  23. package/lib/types/client/i18n.d.ts +1 -1
  24. package/lib/types/client/outline-model.d.ts +59 -0
  25. package/lib/types/client/scm/actions.d.ts +12 -1
  26. package/lib/types/client/store.d.ts +109 -1
  27. package/lib/types/client/vsc/blame.d.ts +19 -0
  28. package/lib/types/client/vsc/change-marks.d.ts +21 -0
  29. package/lib/types/client/vsc/kit.d.ts +0 -2
  30. package/lib/types/client/vsc/preview-document.d.ts +46 -0
  31. package/lib/types/client/vsc/preview-model.d.ts +31 -0
  32. package/lib/types/client/vsc/preview-services.d.ts +24 -0
  33. package/lib/types/git-ops.d.ts +18 -0
  34. package/lib/types/processes.d.ts +43 -0
  35. package/lib/types/protocol.d.ts +133 -1
  36. package/package.json +2 -1
  37. package/src/changes/recorder.ts +851 -8
  38. package/src/client/CodeEditor.tsx +86 -4
  39. package/src/client/EditorPane.tsx +581 -41
  40. package/src/client/MonitorView.tsx +16 -5
  41. package/src/client/OutlinePanel.tsx +287 -0
  42. package/src/client/ProcessesSection.tsx +292 -0
  43. package/src/client/api.ts +38 -3
  44. package/src/client/blame-model.ts +242 -0
  45. package/src/client/changes/ChangesDock.tsx +539 -54
  46. package/src/client/changes/apply-failure.ts +73 -0
  47. package/src/client/changes/block-confirm.ts +180 -0
  48. package/src/client/changes/changes.css +45 -0
  49. package/src/client/changes/diff-outcome.ts +97 -0
  50. package/src/client/changes/freshness.ts +68 -0
  51. package/src/client/changes/model.ts +56 -1
  52. package/src/client/changes/session-diff.ts +187 -0
  53. package/src/client/changes/staleness.ts +148 -0
  54. package/src/client/changes/turn-reverted.ts +254 -0
  55. package/src/client/changes/turn-view.ts +195 -0
  56. package/src/client/changes/undo-affordance.ts +295 -63
  57. package/src/client/changes/undo-target.ts +12 -0
  58. package/src/client/i18n.ts +294 -2
  59. package/src/client/index.tsx +4 -0
  60. package/src/client/outline-model.ts +775 -0
  61. package/src/client/scm/DiffView.tsx +32 -13
  62. package/src/client/scm/HistoryPanel.tsx +38 -1
  63. package/src/client/scm/actions.ts +55 -2
  64. package/src/client/store.tsx +446 -21
  65. package/src/client/vsc/blame.ts +147 -0
  66. package/src/client/vsc/change-marks.ts +21 -0
  67. package/src/client/vsc/kit.tsx +3 -11
  68. package/src/client/vsc/preview-document.tsx +326 -0
  69. package/src/client/vsc/preview-model.ts +216 -0
  70. package/src/client/vsc/preview-services.ts +118 -0
  71. package/src/client/vsc/vsc.css +965 -39
  72. package/src/git-ops.ts +34 -0
  73. package/src/processes.ts +177 -0
  74. package/src/protocol.ts +138 -1
  75. package/src/routes.ts +138 -9
@@ -17,6 +17,8 @@ import type { Context } from '@deepseek-ai/cordis'
17
17
  import type {
18
18
  DiffModel,
19
19
  GitStatusDetail,
20
+ RemoteChangedFile,
21
+ RemoteChangesTurnView,
20
22
  RemoteHostSummary,
21
23
  RemoteRoutingStatus,
22
24
  RemoteWorkspaceBinding,
@@ -27,9 +29,13 @@ import { DEFAULT_GIT_TIMEOUT_MS, clientDeadlineFor } from '../timeouts.ts'
27
29
  import { normalizeRepoSubdir, repoSubdirOf, repoWorkdir } from '../git-ops.ts'
28
30
  import { buildDiffModel } from './scm/diff-model.ts'
29
31
  import type { ChangeMark, ChangeSet } from './vsc/change-marks.ts'
30
- import { changeSetFromHunks } from './changes/model.ts'
32
+ import { changeSetFromDiff, diffNoticeKey, noticeOfDiff, type DiffNotice } from './changes/diff-outcome.ts'
33
+ import { applyFailureText } from './changes/apply-failure.ts'
34
+ import { sessionDiffOutcome } from './changes/session-diff.ts'
35
+ import { tabsToMarkStale, turnMarksStale, type MarksTab } from './changes/staleness.ts'
36
+ import { hunkRevertClearsTurn, markTurnReverted } from './changes/turn-reverted.ts'
31
37
  import { undoContext, type UndoContext } from './changes/undo-context.ts'
32
- import { changeOriginForTab, resolveUndoTarget } from './changes/undo-target.ts'
38
+ import { changeOriginForTab, forgetChangeOrigin, rememberChangeOrigin, resolveUndoTarget } from './changes/undo-target.ts'
33
39
  import { applyStageOverrides, bucketStatus, buildTreeMarks, insertStagedEntry, optimisticStageDetail, type ChangeEntry, type StageOverride, type StatusBuckets, type TreeMarks } from './scm/status-map.ts'
34
40
  import { loadCommitFileDiff, findRepos, loadDiff, loadHead, loadStatusDetail, probeRepoRoot, probeStatusDir, probeStatusPaths, applyHunk, stagePaths, unstagePaths, type DiffPayload } from './scm/actions.ts'
35
41
  import { StageCoordinator } from './scm/stage-queue.ts'
@@ -53,7 +59,8 @@ import { planWorkspaceFollow, selectionIsSessionBinding, type WorkspaceFollowDec
53
59
  import { revealViewTab } from './reveal.ts'
54
60
  import { applyConnectionStatuses, connectionStateOf, isConnectionFailure, markConnectionProbeOk } from './connection.ts'
55
61
  import { isRequestAbort } from './request-gate.ts'
56
- import { confirmDialog, isHtmlFile, isImageFile, isMarkdownFile, toast } from './vsc/kit.tsx'
62
+ import { confirmDialog, isImageFile, toast } from './vsc/kit.tsx'
63
+ import { hasTextSource, isBytePreview, previewKindOf } from './vsc/preview-model.ts'
57
64
  import {
58
65
  isWithinRoot,
59
66
  normalizeRemotePath,
@@ -146,10 +153,32 @@ export interface EditorTab {
146
153
  activeHunk?: number
147
154
  /** 编辑器报告文档已与 `changeSet` 脱钩(用户敲过字),上层该重新拉数据。 */
148
155
  changeStale?: boolean
156
+ /**
157
+ * 这批改动标记的建立时刻(`Date.now()`,`applyChangeSet` 写入)。
158
+ *
159
+ * 面板的轮询用它和 `RemoteChangesSummary.at` 比先后:标记比列表新时(保存/撤销
160
+ * 刚重读过),那份更早的列表不能证明标记过期(见 `changes/staleness.ts`)。
161
+ */
162
+ changeSetAt?: number
149
163
  /** 改动点跳转目标行(1-based)。与 `line` 分开,两条跳转链路互不干扰。 */
150
164
  revealHunkLine?: number
151
165
  /** 改动点跳转的 nonce,语义同 `lineNonce`。 */
152
166
  revealHunkNonce?: number
167
+ /**
168
+ * 「会话改动」面板那一行的只读 diff(不是 git 工作区 diff)。
169
+ *
170
+ * 有它 = 这一页是账本轮次的比较:两栏都只读(改前是还原出来的基线、改后是远端
171
+ * 当前内容),没有 hunk 暂存/撤销,重新载入走账本而不是 `git diff`。`reloadTab`
172
+ * 与 `saveTargetOf` 都按它分流。
173
+ */
174
+ sessionDiff?: {
175
+ sessionId: string
176
+ alias: string
177
+ /** 会话账本的仓库根(`git apply -R` 的目标目录,也是仓库目录的答案)。 */
178
+ root: string
179
+ /** 面板显示路径(标签条与 diff 头用它,不参与任何写操作)。 */
180
+ display: string
181
+ }
153
182
  /**
154
183
  * 重读(`reloadTab`)成功后递增的 nonce。
155
184
  *
@@ -219,6 +248,8 @@ interface State {
219
248
  revealRequest: RevealRequest | undefined
220
249
  /** A pending "open a terminal in this folder" request (search-result menu). */
221
250
  terminalRequest: TerminalRequest | undefined
251
+ /** A pending "select this commit in the history rail" request. */
252
+ commitFocus: CommitFocusRequest | undefined
222
253
  /**
223
254
  * Expanded untracked DIRECTORY rows (`-u normal` collapses a directory into
224
255
  * one row, so the panel asks for its contents on demand — see
@@ -268,6 +299,13 @@ export interface TerminalRequest {
268
299
  dir: string
269
300
  }
270
301
 
302
+ /** One "show this commit in the history rail" request. */
303
+ export interface CommitFocusRequest {
304
+ /** Monotonic id so selecting the same commit twice still re-triggers. */
305
+ id: number
306
+ hash: string
307
+ }
308
+
271
309
  const WS_KEY = 'dsh-remote-vs.files.ws'
272
310
  const VIEW_KEY = 'dsh-remote-vs.view'
273
311
  /** Per-workspace repository sub-directory, keyed by workspace id. */
@@ -526,6 +564,7 @@ const state: State = {
526
564
  searchRequest: undefined,
527
565
  revealRequest: undefined,
528
566
  terminalRequest: undefined,
567
+ commitFocus: undefined,
529
568
  untrackedDirs: new Map(),
530
569
  }
531
570
 
@@ -577,6 +616,8 @@ export interface ExplorerValue {
577
616
  revealRequest: RevealRequest | undefined
578
617
  /** Pending "open a terminal here" request (consumed by the terminal panel). */
579
618
  terminalRequest: TerminalRequest | undefined
619
+ /** Pending "select this commit in the history rail" request. */
620
+ commitFocus: CommitFocusRequest | undefined
580
621
  setView: (view: RailView) => void
581
622
  /** Switch to the search panel (optionally scoped to a folder) — the tree's
582
623
  "find in folder" entry point. */
@@ -592,6 +633,8 @@ export interface ExplorerValue {
592
633
  * search results' "open in terminal" entry.
593
634
  */
594
635
  openTerminalAt: (dir: string) => void
636
+ /** Open the history rail with this commit selected (blame / file history). */
637
+ focusCommit: (hash: string) => void
595
638
  /**
596
639
  * The USER's pick — the workspace dropdowns and the wizard's "open files".
597
640
  *
@@ -770,10 +813,12 @@ function build(): ExplorerValue {
770
813
  searchRequest: state.searchRequest,
771
814
  revealRequest: state.revealRequest,
772
815
  terminalRequest: state.terminalRequest,
816
+ commitFocus: state.commitFocus,
773
817
  setView,
774
818
  requestSearch,
775
819
  revealInExplorer,
776
820
  openTerminalAt,
821
+ focusCommit,
777
822
  selectWorkspace,
778
823
  setRepoSubdir,
779
824
  discoverRepos,
@@ -1430,6 +1475,23 @@ export function openTerminalAt(dir: string): void {
1430
1475
  setView('terminal')
1431
1476
  }
1432
1477
 
1478
+ /** Monotonic ticket for "show this commit" requests from the editor. */
1479
+ let commitFocusSeq = 0
1480
+
1481
+ /**
1482
+ * Open the history rail and select one commit.
1483
+ *
1484
+ * Blame cells and the file-history menu only know a hash; the history panel owns
1485
+ * the list and the detail pane, so the selection travels as a request (the same
1486
+ * pattern as `revealInExplorer` / `openTerminalAt`).
1487
+ */
1488
+ export function focusCommit(hash: string): void {
1489
+ if (hash === '' || /^0+$/.test(hash)) return
1490
+ commitFocusSeq += 1
1491
+ patch({ commitFocus: { id: commitFocusSeq, hash } })
1492
+ setView('history')
1493
+ }
1494
+
1433
1495
  /**
1434
1496
  * Select the binding every view works against — the USER's choice.
1435
1497
  *
@@ -2620,6 +2682,7 @@ export function openFile(fullPath: string, options: { line?: number } = {}): voi
2620
2682
  const workspace = currentWorkspace()
2621
2683
  if (workspace === undefined || fullPath === '') return
2622
2684
  const id = `file:${workspace.alias}:${fullPath}`
2685
+ const previewKind = previewKindOf(fullPath)
2623
2686
  // Re-opening a tab that is already up only re-addresses the reveal line, so
2624
2687
  // a second search hit in the same file moves the cursor instead of reloading.
2625
2688
  // The nonce also re-triggers a jump to the SAME line (value alone would not).
@@ -2647,10 +2710,10 @@ export function openFile(fullPath: string, options: { line?: number } = {}): voi
2647
2710
  saving: false,
2648
2711
  binary: false,
2649
2712
  truncated: false,
2650
- image: isImageFile(fullPath),
2651
- markdown: isMarkdownFile(fullPath),
2652
- html: isHtmlFile(fullPath),
2653
- preview: isMarkdownFile(fullPath) || isHtmlFile(fullPath),
2713
+ image: previewKind === 'image',
2714
+ markdown: previewKind === 'markdown',
2715
+ html: previewKind === 'html',
2716
+ preview: hasTextSource(previewKind),
2654
2717
  staged: false,
2655
2718
  untracked: false,
2656
2719
  ...(options.line === undefined ? {} : { line: options.line, lineNonce: 1 }),
@@ -2658,6 +2721,13 @@ export function openFile(fullPath: string, options: { line?: number } = {}): voi
2658
2721
  model: undefined,
2659
2722
  view: 'split',
2660
2723
  })
2724
+ // PDF/Office/media have no editable text: reading them through fs.read would
2725
+ // only fetch a capped base64 window and land on the binary notice. The
2726
+ // preview component reads their bytes from the download route instead.
2727
+ if (isBytePreview(previewKind)) {
2728
+ patchTab(id, { loading: false })
2729
+ return
2730
+ }
2661
2731
  void (async () => {
2662
2732
  try {
2663
2733
  const read = await withDeadline(api.fileOp.read(workspace.alias, fullPath), fileReadDeadlineMs(), t('editor.readTimeout'))
@@ -2963,6 +3033,10 @@ function saveTargetOf(id: string): { alias: string; fullPath: string; rel: strin
2963
3033
  const workspace = currentWorkspace()
2964
3034
  const tab = state.tabs.find(item => item.id === id)
2965
3035
  if (workspace === undefined || tab === undefined) return undefined
3036
+ // A session diff is a comparison of the session's history, not an editable
3037
+ // working-tree copy: nothing in it may be written back (its "after" side is a
3038
+ // read of the file that a revert/agent may have moved on since).
3039
+ if (tab.sessionDiff !== undefined) return undefined
2966
3040
  const writable = tab.kind === 'file' || (tab.kind === 'diff' && tab.ref === undefined && !tab.staged)
2967
3041
  if (!writable || tab.binary || tab.truncated) return undefined
2968
3042
  return { alias: workspace.alias, fullPath: tab.fullPath, rel: tab.rel }
@@ -3182,10 +3256,51 @@ export function dismissConflict(id: string): void {
3182
3256
  * is fixing, only harder to see.
3183
3257
  */
3184
3258
  export async function reloadTab(id: string): Promise<void> {
3185
- const workspace = currentWorkspace()
3186
3259
  const tab = state.tabs.find(item => item.id === id)
3187
- if (workspace === undefined || tab === undefined) return
3260
+ if (tab === undefined) return
3261
+ /**
3262
+ * A session-diff tab re-reads the LEDGER, not the working tree: it has its own
3263
+ * alias/root on the tab (the sidebar may be pointing at another binding), and
3264
+ * `git diff` would show a different baseline. Handled before the workspace
3265
+ * lookup below, which a session diff does not need at all.
3266
+ */
3267
+ if (tab.sessionDiff !== undefined) {
3268
+ try {
3269
+ const loaded = await loadSessionDiffPayload({
3270
+ sessionId: tab.sessionDiff.sessionId,
3271
+ alias: tab.sessionDiff.alias,
3272
+ root: tab.sessionDiff.root,
3273
+ path: tab.fullPath,
3274
+ display: tab.sessionDiff.display,
3275
+ })
3276
+ if (loaded.payload === undefined) {
3277
+ // 重新载入时拿不到完整的两栏(内容被扣下 / 已无差异 / 读不到):说清是哪一种,
3278
+ // 而不是留一个错误字符串占位。标签页本身保留,用户可以再试或改看文件。
3279
+ const notice = loaded.notice ?? 'missing'
3280
+ patchTab(id, { loading: false, error: t(diffNoticeKey(notice)), diff: undefined, model: undefined })
3281
+ return
3282
+ }
3283
+ patchTab(id, {
3284
+ loading: false,
3285
+ error: undefined,
3286
+ diff: loaded.payload,
3287
+ model: buildDiffModel(loaded.payload),
3288
+ })
3289
+ } catch (error) {
3290
+ patchTab(id, { loading: false, error: error instanceof Error ? error.message : String(error) })
3291
+ }
3292
+ return
3293
+ }
3294
+ const workspace = currentWorkspace()
3295
+ if (workspace === undefined) return
3188
3296
  if (tab.kind === 'file') {
3297
+ // Byte previews have no text buffer: fs.read would fetch a capped base64
3298
+ // window and turn the tab into "binary", hiding the preview. A revision
3299
+ // bump is the whole reload for them.
3300
+ if (isBytePreview(previewKindOf(tab.fullPath))) {
3301
+ patchTab(id, { loading: false, error: undefined, reloadNonce: (tab.reloadNonce ?? 0) + 1 })
3302
+ return
3303
+ }
3189
3304
  try {
3190
3305
  const read = await withDeadline(api.fileOp.read(workspace.alias, tab.fullPath), fileReadDeadlineMs(), t('editor.readTimeout'))
3191
3306
  patchTab(id, {
@@ -3385,7 +3500,7 @@ export function dockFloatingEditor(): void {
3385
3500
  * `hunks[0]`),所以紧接着按"下一个"会走到第 2 处,不会把第 1 处跳过。
3386
3501
  */
3387
3502
  export function applyChangeSet(tabId: string, set: ChangeSet | null): void {
3388
- patchTab(tabId, { changeSet: set, activeHunk: 0, changeStale: false })
3503
+ patchTab(tabId, { changeSet: set, activeHunk: 0, changeStale: false, changeSetAt: Date.now() })
3389
3504
  }
3390
3505
 
3391
3506
  /**
@@ -3429,6 +3544,176 @@ export function markChangeStale(tabId: string): void {
3429
3544
  patchTab(tabId, { changeStale: true })
3430
3545
  }
3431
3546
 
3547
+ /**
3548
+ * 面板拿到新统计后,指出哪些已开标签页的改动标记已经过期。
3549
+ *
3550
+ * 标记的失效原来只由"本地输入"触发(`markChangeStale` 由编辑器报告),所以远端或
3551
+ * 会话继续改同一个文件时,屏幕上那份行号与补丁会一直画着、看起来仍然准确。面板每
3552
+ * 3 秒重读一次账本,那份列表就是"这批标记还算不算数"的唯一证据 —— 这里把它翻成
3553
+ * 既有那张「位置已过期」标记。
3554
+ *
3555
+ * 判据是纯函数(`changes/staleness.ts`),这里只负责选出**属于这个会话**的标签页:
3556
+ * 换会话后屏幕上可能还留着上一个会话的标记,拿本会话的列表去比对只会误报。
3557
+ * **不发起任何远端读**:重新计算是用户点该行时的事。
3558
+ *
3559
+ * @param sessionId - 面板当前会话。
3560
+ * @param files - 这一轮列表的行。
3561
+ * @param truncated - 列表自己被文件上限截断("找不到"不再算证据)。
3562
+ * @param listedAt - 这份列表的重算时刻(`RemoteChangesSummary.at`)。
3563
+ * @param turnView - 本轮视图;带本轮来源的标记要用它那一份行来判(见实现)。
3564
+ */
3565
+ export function syncChangeSetStaleness(
3566
+ sessionId: string,
3567
+ files: readonly RemoteChangedFile[],
3568
+ truncated = false,
3569
+ listedAt?: number,
3570
+ turnView?: RemoteChangesTurnView,
3571
+ ): void {
3572
+ const sessionRows: MarksTab[] = []
3573
+ const turnRows: MarksTab[] = []
3574
+ for (const tab of state.tabs) {
3575
+ const set = tab.changeSet
3576
+ if (set === undefined || set === null) continue
3577
+ const origin = changeOriginForTab(tab.id)
3578
+ // 没有 provenance 就没法证明这批标记是哪个会话画的:不猜。
3579
+ if (origin === undefined || origin.sessionId !== sessionId) continue
3580
+ const row: MarksTab = {
3581
+ id: tab.id,
3582
+ path: tab.fullPath,
3583
+ ...(set.added === undefined ? {} : { added: set.added }),
3584
+ ...(set.deleted === undefined ? {} : { deleted: set.deleted }),
3585
+ ...(set.status === undefined ? {} : { status: set.status }),
3586
+ ...(tab.changeStale === true ? { stale: true } : {}),
3587
+ ...(tab.changeSetAt === undefined ? {} : { at: tab.changeSetAt }),
3588
+ }
3589
+ // 行数是"哪条轴"的数字:同一文件的本轮 Δ 与会话累计按定义不同,所以每种
3590
+ // 标记只能拿它当初所在的那份列表来判,否则切一轮就会把好好的标记判成过期。
3591
+ if (origin.scope === 'turn') turnRows.push(row)
3592
+ else sessionRows.push(row)
3593
+ }
3594
+ for (const tabId of tabsToMarkStale(sessionRows, files, truncated, listedAt)) markChangeStale(tabId)
3595
+ // Remembered for later re-reads: see `latestTurns`.
3596
+ if (turnView !== undefined) rememberLatestTurn(sessionId, turnView.turn)
3597
+ /*
3598
+ * 本轮轴用 `turnMarksStale`,不是 `tabsToMarkStale`:
3599
+ * - 不传 `listedAt`(`turnView.at` 是关闭时刻、`changeSetAt` 是点击时刻,传了会
3600
+ * 让判据恒假 —— 审核 S1 的第一半);
3601
+ * - 轮次翻篇直接判过期(`origin.turn !== turnView.turn`),否则旧轮标记永久脱离
3602
+ * 校验(S1 的第二半)。
3603
+ */
3604
+ for (const row of turnRows) {
3605
+ if (row.stale === true) continue
3606
+ if (turnMarksStale(row, changeOriginForTab(row.id)?.turn, turnView)) markChangeStale(row.id)
3607
+ }
3608
+ }
3609
+
3610
+ /**
3611
+ * 「会话改动」面板那一行的 → 只读并排 diff(见 `changes/session-diff.ts`)。
3612
+ *
3613
+ * 与 `openFile`/`openDiff` 的区别是数据来源:这里读的是会话账本(会话起点为基线),
3614
+ * 而 `openDiff` 读的是 git 工作区(索引/HEAD 为基线)。两件事不能互相顶替 ——
3615
+ * 工作区里可能有会话开始之前就存在的未提交改动。
3616
+ *
3617
+ * 结果里的 `notice` 就是面板要显示的那句话(截断 / 二进制 / 读不到 / 已无差异),
3618
+ * 打开成功时为 `undefined`。调用方负责把它渲染出来,不要吞掉。
3619
+ */
3620
+ export interface ChangeDiffTarget {
3621
+ sessionId: string
3622
+ alias: string
3623
+ /** 会话账本的仓库根(与 `revertFileChanges` 的 `root` 同源)。 */
3624
+ root: string
3625
+ /** 远端绝对路径。 */
3626
+ path: string
3627
+ /** 面板显示路径(标签条用)。 */
3628
+ display: string
3629
+ /** 面板选定的仓库子目录(透传给账本的 `repoSubdir`,可省略)。 */
3630
+ repoSubdir?: string
3631
+ }
3632
+
3633
+ export interface ChangeDiffResult {
3634
+ opened: boolean
3635
+ /** 必须显示给用户的结论;`undefined` = 打开成功且没有任何要说明的。 */
3636
+ notice?: DiffNotice
3637
+ }
3638
+
3639
+ /** 读一次账本 diff 并拼成 DiffPayload;拿不到可显示内容时 `undefined`。 */
3640
+ async function loadSessionDiffPayload(target: ChangeDiffTarget): Promise<{
3641
+ payload: DiffPayload | undefined
3642
+ notice?: DiffNotice
3643
+ }> {
3644
+ const diff = await api.changes.diff(target.sessionId, target.path, target.repoSubdir)
3645
+ // 被字节上限扣下的 diff 不值得再读文件:结论已经确定(比较不完整、不能撤销)。
3646
+ if (diff === null || diff.kind !== 'text' || diff.truncated === true || diff.hunks.length === 0) {
3647
+ const outcome = sessionDiffOutcome(diff, { text: '' }, target.display)
3648
+ return { payload: undefined, ...(outcome.ok ? {} : { notice: outcome.notice }) }
3649
+ }
3650
+ /**
3651
+ * 改后一栏的读取结果要参与结论:撞上 8 MiB 上限的 `text` 只是前缀,拿去还原
3652
+ * 基线会让两栏整体错位;二进制读取也没有可比的文本(审核 S4)。
3653
+ */
3654
+ let read: { text: string; truncated?: true; binary?: true } = { text: '' }
3655
+ try {
3656
+ const answer = await api.fileOp.read(target.alias, target.path)
3657
+ read = {
3658
+ text: answer.binary ? '' : (answer.text ?? ''),
3659
+ ...(answer.truncated === true ? { truncated: true as const } : {}),
3660
+ ...(answer.binary === true ? { binary: true as const } : {}),
3661
+ }
3662
+ } catch {
3663
+ // 读不到"改后"(已删除 / 权限):改后一栏空着,改前仍可看。
3664
+ read = { text: '' }
3665
+ }
3666
+ const outcome = sessionDiffOutcome(diff, read, target.display)
3667
+ return { payload: outcome.ok ? outcome.payload : undefined, ...(outcome.ok ? {} : { notice: outcome.notice }) }
3668
+ }
3669
+
3670
+ /** 打开(或聚焦)一行的会话只读 diff。 */
3671
+ export async function openChangeDiff(target: ChangeDiffTarget): Promise<ChangeDiffResult> {
3672
+ const id = `changes-diff:${target.alias}:${target.path}`
3673
+ const loaded = await loadSessionDiffPayload(target)
3674
+ const notice = loaded.payload === undefined ? (loaded.notice ?? 'missing') : undefined
3675
+ const sessionDiff = {
3676
+ sessionId: target.sessionId,
3677
+ alias: target.alias,
3678
+ root: target.root,
3679
+ display: target.display,
3680
+ }
3681
+ const already = state.tabs.find(item => item.id === id)
3682
+ if (already !== undefined) {
3683
+ if (loaded.payload !== undefined) {
3684
+ patchTab(id, { diff: loaded.payload, model: buildDiffModel(loaded.payload), sessionDiff, loading: false, error: undefined })
3685
+ patch({ activeTabId: id })
3686
+ revealEditor()
3687
+ }
3688
+ return { opened: loaded.payload !== undefined, ...(notice === undefined ? {} : { notice }) }
3689
+ }
3690
+ if (loaded.payload === undefined) return { opened: false, ...(notice === undefined ? {} : { notice }) }
3691
+ upsertTab({
3692
+ id,
3693
+ kind: 'diff',
3694
+ fullPath: target.path,
3695
+ rel: target.display,
3696
+ loading: false,
3697
+ error: undefined,
3698
+ text: '',
3699
+ dirty: false,
3700
+ saving: false,
3701
+ binary: false,
3702
+ truncated: false,
3703
+ image: isImageFile(target.display),
3704
+ markdown: false,
3705
+ html: false,
3706
+ preview: false,
3707
+ staged: false,
3708
+ untracked: false,
3709
+ diff: loaded.payload,
3710
+ model: buildDiffModel(loaded.payload),
3711
+ view: 'split',
3712
+ sessionDiff,
3713
+ })
3714
+ return { opened: true, ...(notice === undefined ? {} : { notice }) }
3715
+ }
3716
+
3432
3717
  /**
3433
3718
  * 撤销「本会话在某个文件里的一处改动」(改动行上那个悬浮按钮点下去的动作)。
3434
3719
  *
@@ -3446,6 +3731,33 @@ export function markChangeStale(tabId: string): void {
3446
3731
  * 全部失效;重读让标签页的数字回到磁盘上的事实。
3447
3732
  * 5. 失败时**不清标记、不重读**:远端一个字节都没动,屏幕上那份标记仍然是事实。
3448
3733
  */
3734
+ /**
3735
+ * The newest turn each session has seen (`summary.turnView.turn`).
3736
+ *
3737
+ * Written by the panel's every poll (`syncChangeSetStaleness`) and read when a
3738
+ * save/revert re-reads a turn-scope tab: the host's `turnDiff` always answers for
3739
+ * the CURRENT turn, so the provenance's `turn` must move forward with it — pinned
3740
+ * to the turn of the click, the marks would be judged stale the instant a new
3741
+ * turn closed (review S1).
3742
+ */
3743
+ const latestTurns = new Map<string, number>()
3744
+ /** Ceiling on tracked sessions (a long-lived page must not grow this forever). */
3745
+ const LATEST_TURNS_CAP = 200
3746
+
3747
+ function latestTurnOf(sessionId: string): number | undefined {
3748
+ return latestTurns.get(sessionId)
3749
+ }
3750
+
3751
+ function rememberLatestTurn(sessionId: string, turn: number): void {
3752
+ if (turn <= 0) return
3753
+ latestTurns.delete(sessionId)
3754
+ if (latestTurns.size >= LATEST_TURNS_CAP) {
3755
+ const oldest = latestTurns.keys().next().value
3756
+ if (oldest !== undefined) latestTurns.delete(oldest)
3757
+ }
3758
+ latestTurns.set(sessionId, turn)
3759
+ }
3760
+
3449
3761
  /**
3450
3762
  * Re-read one file's change set from the host and hand it to the editor.
3451
3763
  *
@@ -3456,13 +3768,56 @@ export function markChangeStale(tabId: string): void {
3456
3768
  async function refreshChangeSet(tabId: string, context: UndoContext): Promise<void> {
3457
3769
  const tab = state.tabs.find(item => item.id === tabId)
3458
3770
  if (tab === undefined || tab.kind !== 'file') return
3771
+ const turnScope = context.scope === 'turn'
3459
3772
  try {
3460
- const diff = await api.changes.diff(context.sessionId, tab.fullPath)
3461
- if (diff === null || diff.kind !== 'text' || diff.hunks.length === 0) {
3773
+ /*
3774
+ * Re-read the SAME axis the marks came from. A turn-scope tab rebuilt from the
3775
+ * session baseline would change what "undo this change" means mid-review (its
3776
+ * hunks cover the whole session, not the turn), and its counts would then
3777
+ * disagree with the turn list on every poll.
3778
+ */
3779
+ const diff = turnScope
3780
+ ? await api.changes.turnDiff(context.sessionId, tab.fullPath)
3781
+ : await api.changes.diff(context.sessionId, tab.fullPath)
3782
+ if (turnScope && (diff === null || diff.kind === 'stale' || diff.kind === 'unavailable')) {
3783
+ // The turn's comparison no longer describes the disk (a write of ours just
3784
+ // moved the file, or the turn rolled over): drop the marks and SAY so. The
3785
+ // session view is the surface that still knows the file.
3462
3786
  applyChangeSet(tabId, null)
3787
+ forgetChangeOrigin(tabId)
3788
+ info(t('changes.turnMarksStale'))
3463
3789
  return
3464
3790
  }
3465
- applyChangeSet(tabId, changeSetFromHunks(diff.hunks, `${tab.fullPath}@${Date.now()}`, diff.patch))
3791
+ /**
3792
+ * 不能建标记的结局都要**说出来**(审核 NIT-4):被字节上限扣下、二进制、读不到、
3793
+ * 或者改动已经没了时,静默清空标记会让用户以为"改动消失了 / 工具坏了"。这里复用
3794
+ * 面板点行时那套结论文案(`changes/diff-outcome.ts`),一次 `info` 就够了 ——
3795
+ * 标记本身确实失效,不能继续画。
3796
+ */
3797
+ const notice = noticeOfDiff(diff)
3798
+ if (notice !== undefined) {
3799
+ applyChangeSet(tabId, null)
3800
+ info(t(diffNoticeKey(notice)))
3801
+ return
3802
+ }
3803
+ // 块级「确认保留」的身份用**远端绝对路径**(不是显示路径):它与面板打开时
3804
+ // 是同一个字符串,所以一次保存/撤销不会让已确认的块失配,也不会把另一个仓库
3805
+ // 里同号同显示路径的块认成同一块。
3806
+ const built = changeSetFromDiff(diff, `${tab.fullPath}@${turnScope ? 'turn' : 'session'}@${Date.now()}`, { path: tab.fullPath })
3807
+ applyChangeSet(tabId, built.set)
3808
+ /*
3809
+ * A turn-scope re-read fetches the CURRENT turn's comparison (the host only
3810
+ * ever holds one). Recording that turn on the provenance is what keeps the
3811
+ * marks from being instantly judged stale the moment a new turn has closed —
3812
+ * they now describe the current turn, not the one the click happened in
3813
+ * (review S1: `origin.turn` used to stay pinned to the old turn forever).
3814
+ */
3815
+ if (turnScope) {
3816
+ const current = latestTurnOf(context.sessionId)
3817
+ if (current !== undefined && current !== context.turn) {
3818
+ rememberChangeOrigin(tabId, { ...context, turn: current })
3819
+ }
3820
+ }
3466
3821
  } catch {
3467
3822
  // A read that fails leaves no marks rather than wrong ones.
3468
3823
  applyChangeSet(tabId, null)
@@ -3496,11 +3851,25 @@ export async function undoChange(tabId: string, mark: ChangeMark): Promise<void>
3496
3851
  info(t('connection.actionFailed'))
3497
3852
  return
3498
3853
  }
3499
- const patch = tab.changeSet?.patches?.[mark.hunk ?? -1]
3854
+ // Snapshot the set BEFORE the write: after a successful revert the marks are
3855
+ // re-read (`refreshChangeSet`), so "was this the file's only hunk" can only be
3856
+ // answered from the data the user actually clicked.
3857
+ const changeSet = tab.changeSet
3858
+ const patches = changeSet?.patches ?? []
3859
+ const patch = patches[mark.hunk ?? -1]
3500
3860
  if (patch === undefined || patch.trim() === '') {
3501
3861
  info(t('changes.undoMissing'))
3502
3862
  return
3503
3863
  }
3864
+ /**
3865
+ * Would this ONE undo leave the file with no change in this turn?
3866
+ *
3867
+ * Only then may the row be hidden from the turn list (see
3868
+ * `changes/turn-reverted.ts`): a multi-hunk file that is partially reverted still
3869
+ * has changes, and hiding it would hide them too — worse than the stale row this
3870
+ * task is fixing.
3871
+ */
3872
+ const clearsTurn = hunkRevertClearsTurn(context.scope, patches.length)
3504
3873
  try {
3505
3874
  // 'revert' = 远端 `git apply -R`;上下文不匹配它就抛错,这就是冲突护栏。
3506
3875
  await applyHunk(context.alias, context.root, patch, 'revert')
@@ -3516,10 +3885,23 @@ export async function undoChange(tabId: string, mark: ChangeMark): Promise<void>
3516
3885
  return
3517
3886
  }
3518
3887
  // 可把 git 的说法附在后面("patch does not apply" 之类),但**不动**标记与文件。
3888
+ // 先按 stderr 归类:上下文变了 / 文件不在了 / 不是仓库 / 权限,四种修法完全不同。
3519
3889
  const detail = error instanceof Error ? error.message.trim() : String(error).trim()
3520
- info(detail === '' ? t('changes.undoConflict') : `${t('changes.undoConflict')} · ${detail}`)
3890
+ info(applyFailureText(detail, t) ?? t('changes.undoConflict'))
3521
3891
  return
3522
3892
  }
3893
+ /**
3894
+ * The remote write succeeded. Record it on the CLIENT so the frozen turn list
3895
+ * stops showing the row (the host keeps its turn delta untouched — that snapshot
3896
+ * is what the whole turn view is built on).
3897
+ *
3898
+ * Fail-closed on a missing turn: hiding is a claim about "this turn", and with no
3899
+ * turn recorded the panel would have to guess which one to hide. Not hiding is
3900
+ * the safe answer (the row stays, exactly as before this feature).
3901
+ */
3902
+ if (clearsTurn && context.turn !== undefined) {
3903
+ markTurnReverted(context.sessionId, context.turn, tab.fullPath)
3904
+ }
3523
3905
  // Refresh the marks instead of dropping them, and put the caret back where the
3524
3906
  // revert happened.
3525
3907
  //
@@ -3565,6 +3947,25 @@ export interface RevertFileTarget {
3565
3947
  path: string
3566
3948
  display: string
3567
3949
  mode: 'patch' | 'delete'
3950
+ /**
3951
+ * Which comparison the patch must come from.
3952
+ *
3953
+ * `turn` = "undo what THIS turn did to this file" (restore the previous turn's
3954
+ * close); absent = the session baseline (unchanged default). The patch is
3955
+ * re-fetched from the host rather than taken from the panel's poll, so the
3956
+ * same argument decides WHICH host read to make.
3957
+ */
3958
+ scope?: 'session' | 'turn'
3959
+ /**
3960
+ * For `scope: 'turn'`: which turn the row came from.
3961
+ *
3962
+ * Used after a successful revert to hide that row from the turn list (the host's
3963
+ * frozen delta keeps listing it, by design). **Fail-closed**: when it is omitted
3964
+ * the row is NOT hidden — hiding is a claim about one specific turn, and guessing
3965
+ * it (e.g. from "the latest turn seen") could hide a row in a turn the user never
3966
+ * reverted. The only caller (the dock) always knows it.
3967
+ */
3968
+ turn?: number
3568
3969
  }
3569
3970
 
3570
3971
  /**
@@ -3609,6 +4010,8 @@ export async function revertFileChanges(target: RevertFileTarget): Promise<boole
3609
4010
  bindingId: target.bindingId,
3610
4011
  alias: target.alias,
3611
4012
  root: target.root,
4013
+ display: target.display,
4014
+ ...(target.scope === 'turn' ? { scope: 'turn' as const } : {}),
3612
4015
  }
3613
4016
  /**
3614
4017
  * The session check inside `resolveUndoTarget` is trivially true here (the panel
@@ -3632,7 +4035,16 @@ export async function revertFileChanges(target: RevertFileTarget): Promise<boole
3632
4035
  if (target.mode === 'patch') {
3633
4036
  // Fresh from the host: the panel's numbers may be a poll old, and the patch
3634
4037
  // must describe the file as it is NOW.
3635
- const diff = await api.changes.diff(target.sessionId, target.path)
4038
+ const diff = target.scope === 'turn'
4039
+ ? await api.changes.turnDiff(target.sessionId, target.path)
4040
+ : await api.changes.diff(target.sessionId, target.path)
4041
+ if (target.scope === 'turn' && diff !== null && (diff.kind === 'stale' || diff.kind === 'unavailable')) {
4042
+ // The turn's comparison is gone (the file moved on, or the host dropped
4043
+ // the hunks): nothing was written, and saying which is better than a
4044
+ // generic refusal the user cannot act on.
4045
+ info(t('changes.turnMarksStale'))
4046
+ return false
4047
+ }
3636
4048
  const patch = diff !== null && diff.kind === 'text' ? (diff.patch ?? '') : ''
3637
4049
  if (patch.trim() === '') {
3638
4050
  info(t('changes.undoMissing'))
@@ -3655,11 +4067,15 @@ export async function revertFileChanges(target: RevertFileTarget): Promise<boole
3655
4067
  return false
3656
4068
  }
3657
4069
  const detail = error instanceof Error ? error.message.trim() : String(error).trim()
3658
- // A refused reverse patch means "the surroundings moved" (that is the conflict
3659
- // guard); a failed delete has no such reading, so it gets its own wording
3660
- // instead of pretending the patch context drifted.
3661
- const label = target.mode === 'delete' ? t('changes.revertFailed') : t('changes.undoConflict')
3662
- info(detail === '' ? label : `${label} · ${detail}`)
4070
+ /**
4071
+ * A refused reverse patch means "the surroundings moved" — one of several
4072
+ * causes, each with a different fix, so the patch path classifies git's own
4073
+ * stderr (`changes/apply-failure.ts`). A failed delete has no such reading
4074
+ * (it is one `rm`), so it keeps its own wording instead of pretending the
4075
+ * patch context drifted.
4076
+ */
4077
+ const label = target.mode === 'delete' ? t('changes.revertFailed') : (applyFailureText(detail, t) ?? t('changes.undoConflict'))
4078
+ info(target.mode === 'delete' && detail !== '' ? `${label} · ${detail}` : label)
3663
4079
  return false
3664
4080
  }
3665
4081
  /**
@@ -3667,6 +4083,15 @@ export async function revertFileChanges(target: RevertFileTarget): Promise<boole
3667
4083
  * remote file has already changed. Refreshing the tab and the list is best
3668
4084
  * effort — a read that fails here leaves a stale panel, not a lost revert.
3669
4085
  */
4086
+ /*
4087
+ * Turn scope: the whole file's turn change is gone, so record it for the panel
4088
+ * to hide. The host is NOT told (its turn delta stays frozen — see
4089
+ * `changes/turn-reverted.ts`); the session-cumulative view is untouched.
4090
+ * Fail-closed like `undoChange`: no recorded turn ⇒ no hide, never a guess.
4091
+ */
4092
+ if (target.scope === 'turn' && target.turn !== undefined) {
4093
+ markTurnReverted(target.sessionId, target.turn, target.path)
4094
+ }
3670
4095
  try {
3671
4096
  // Re-read the tab: the write took a round trip, and it may have been closed
3672
4097
  // (or replaced) meanwhile.