dsh-remote-vs 0.21.0 → 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.
@@ -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(() => {
@@ -75,6 +75,14 @@ export interface RemovedChip {
75
75
  truncated: boolean
76
76
  /** 这个 chip 落在哪一行(1-based)。**省略 = 所属 mark 的 `from` 行**。 */
77
77
  line?: number
78
+ /**
79
+ * 这个 chip 代表的**被删行数**(省略或 1 = 单行/行内片段)。
80
+ *
81
+ * 一个整块删除(例如删掉 10 行)不能画成 10 个 chip 叠在同一列上 —— 那既读不出
82
+ * "删了 10 行",也读不出内容。此时 `count > 1`,`text` 改为携带**预览**(前若干
83
+ * 行的原文,供 tooltip),渲染成一个 `−N 行已删除` 的可读胶囊。
84
+ */
85
+ count?: number
78
86
  }
79
87
 
80
88
  /**
@@ -118,6 +126,15 @@ export interface ChangeSet {
118
126
  * 护栏,比在浏览器里重算一遍替换区间可靠。
119
127
  */
120
128
  patches?: string[]
129
+ /**
130
+ * 整文件的补丁(一个文件头 + 全部 hunk),用于"撤销该文件的全部改动"。
131
+ *
132
+ * 一次远端写而不是逐 hunk 循环:后者会让后面每个 hunk 的行号整体错位,撤到一半
133
+ * 报冲突,文件就停在半截状态。补丁由 Host 生成(浏览器一侧没有基线内容,自己拼
134
+ * 出来的补丁只会把别人的改动一起盖掉)。省略 = 这个文件没有可整体撤销的补丁
135
+ * (新建 / 二进制 / 字节被上限扣下)。
136
+ */
137
+ filePatch?: string
121
138
  }
122
139
 
123
140
  /** 换一份改动标记;`null` = 清空(有改动数据,但没有任何要画的东西)。 */
@@ -170,6 +187,9 @@ const WORD_ADD = Decoration.mark({ class: 'rvs-change-word-add' })
170
187
  /** 删除 chip 的悬浮说明。与 gutter 的 `LABEL` 一样,是编辑器侧的固定文案。 */
171
188
  const CHIP_TITLE = '已删除的内容'
172
189
 
190
+ /** 整块删除那种胶囊的悬浮说明(后面跟行数)。 */
191
+ const BLOCK_CHIP_TITLE = '已删除的整块内容'
192
+
173
193
  /**
174
194
  * 被删内容的零宽 widget。
175
195
  *
@@ -180,25 +200,37 @@ const CHIP_TITLE = '已删除的内容'
180
200
  class RemovedChipWidget extends WidgetType {
181
201
  private readonly text: string
182
202
  private readonly truncated: boolean
203
+ private readonly count: number
183
204
 
184
- constructor(text: string, truncated: boolean) {
205
+ constructor(text: string, truncated: boolean, count = 0) {
185
206
  super()
186
207
  this.text = text
187
208
  this.truncated = truncated
209
+ this.count = count
188
210
  }
189
211
 
190
212
  eq(other: WidgetType): boolean {
191
213
  return other instanceof RemovedChipWidget
192
214
  && other.text === this.text
193
215
  && other.truncated === this.truncated
216
+ && other.count === this.count
194
217
  }
195
218
 
196
219
  toDOM(): HTMLElement {
197
220
  const chip = document.createElement('span')
198
- chip.className = 'rvs-change-word-del'
199
- chip.textContent = this.truncated ? `${this.text}…` : this.text
200
- chip.title = CHIP_TITLE
201
- chip.setAttribute('aria-label', CHIP_TITLE)
221
+ /**
222
+ * 整块删除(`count > 1`)读成一枚胶囊,不是一行删除线文字。
223
+ *
224
+ * 行内删短(`const a = 1 + 2` → `const a = 1`)仍然是划掉的原文 —— 那里被删的
225
+ * 是一个片段,位置和内容都能直接读。多行整块没有这个性质:原文是一个段落,
226
+ * 划线堆在行首只会糊成一片,所以这里只报**行数**,原文进 tooltip(已在数据层
227
+ * 限过长度,见 `model.ts` 的 `deletedRunChip`)。
228
+ */
229
+ const block = this.count > 1
230
+ chip.className = block ? 'rvs-change-word-del rvs-change-block-del' : 'rvs-change-word-del'
231
+ chip.textContent = block ? `−${this.count} 行已删除` : (this.truncated ? `${this.text}…` : this.text)
232
+ chip.title = block ? `${BLOCK_CHIP_TITLE}(${this.count} 行)\n${this.text}` : CHIP_TITLE
233
+ chip.setAttribute('aria-label', chip.title)
202
234
  return chip
203
235
  }
204
236
  }
@@ -209,7 +241,7 @@ class RemovedChipWidget extends WidgetType {
209
241
  * `-2e8`、chip `-1e8`、字符区间 `-1`)。
210
242
  */
211
243
  function chipDecoration(chip: RemovedChip): Decoration {
212
- return Decoration.widget({ widget: new RemovedChipWidget(chip.text, chip.truncated), side: -1 })
244
+ return Decoration.widget({ widget: new RemovedChipWidget(chip.text, chip.truncated, chip.count ?? 0), side: -1 })
213
245
  }
214
246
 
215
247
  /** 一行的行内片段:新增字符区间 + 删除 chip。 */
@@ -251,6 +283,7 @@ function inlineIndexOf(set: ChangeSet | null, doc: Text): Map<number, LineInline
251
283
  at: Math.max(0, Math.round(chip.at)),
252
284
  text: chip.text,
253
285
  truncated: chip.truncated === true,
286
+ ...(chip.count === undefined ? {} : { count: chip.count }),
254
287
  })
255
288
  }
256
289
  }
@@ -783,6 +783,15 @@ export function ContextMenu(props: {
783
783
  y: number
784
784
  entries: MenuEntry[]
785
785
  onClose: () => void
786
+ /**
787
+ * Extra class on the menu box, for a surface that lives OUTSIDE `.rvs-root`.
788
+ *
789
+ * The menu is portalled to `document.body`, so the `--rvs-*` variables defined
790
+ * on the root never reach it: an outside surface (the change panel above the
791
+ * composer) supplies its own palette through this hook instead of forking the
792
+ * component.
793
+ */
794
+ className?: string
786
795
  }): ReactNode {
787
796
  const boxRef = useRef<HTMLDivElement>(null)
788
797
  const [pos, setPos] = useState({ left: props.x, top: props.y })
@@ -896,7 +905,13 @@ export function ContextMenu(props: {
896
905
  if (typeof document === 'undefined') return null
897
906
  return createPortal(
898
907
  <div className="rvs-portal">
899
- <div ref={boxRef} className="rvs-menu" role="menu" style={{ left: pos.left, top: pos.top }} onKeyDown={onMenuKeyDown}>
908
+ <div
909
+ ref={boxRef}
910
+ className={props.className === undefined ? 'rvs-menu' : `rvs-menu ${props.className}`}
911
+ role="menu"
912
+ style={{ left: pos.left, top: pos.top }}
913
+ onKeyDown={onMenuKeyDown}
914
+ >
900
915
  {props.entries.map((entry, index) => (
901
916
  <div key={`${entry.label}-${index}`}>
902
917
  {entry.separated === true && index > 0 && <div className="rvs-menu-sep" />}
@@ -0,0 +1,170 @@
1
+ /**
2
+ * Terminal clipboard chords and the paste fallback, as testable logic.
3
+ *
4
+ * Why this module exists
5
+ * ----------------------
6
+ * The terminal's copy/paste handling used to be an inline `attachCustomKeyEventHandler`
7
+ * with three problems the UI tests could not see:
8
+ *
9
+ * 1. **Double paste on Ctrl+Shift+V.** The handler pasted through
10
+ * `navigator.clipboard.readText()` and returned `false`, but returning false only
11
+ * stops xterm's own handling — the browser still performed its default paste
12
+ * (Chrome maps Ctrl+Shift+V to "paste as plain text"), so both paths inserted the
13
+ * text. Handled chords must call `preventDefault()` themselves.
14
+ * 2. **Ctrl+V depended entirely on the browser's native paste.** When the host page
15
+ * or a wrapper swallows the paste event (desktop shells, non-standard clipboard
16
+ * permissions), the terminal silently received nothing. It now falls back to the
17
+ * Clipboard API only when no paste event arrived shortly after the key press.
18
+ * 3. **Right-click copied/pasted immediately with no visible affordance.** It is now
19
+ * a small menu (copy / paste / select all) so the action is discoverable and the
20
+ * copy item can be disabled when nothing is selected.
21
+ *
22
+ * The chord table and the fallback watcher are pure so a gate can pin all of it.
23
+ */
24
+
25
+ /** What one key press asks the terminal to do. */
26
+ export type TerminalClipboardChord =
27
+ /** Copy the current selection, then clear it (menu action). */
28
+ | 'copy'
29
+ /** Paste immediately through the Clipboard API. */
30
+ | 'paste'
31
+ /** Let the browser's native paste run; fall back to the Clipboard API when no paste event arrives. */
32
+ | 'paste-native'
33
+ /** Plain Ctrl+C: copy when a selection exists, otherwise stay SIGINT. */
34
+ | 'copy-interrupt'
35
+
36
+ /** The keyboard state the chord table reads. */
37
+ export interface TerminalChordInput {
38
+ key: string
39
+ ctrl: boolean
40
+ shift: boolean
41
+ alt: boolean
42
+ meta: boolean
43
+ }
44
+
45
+ /** True when the key is the letter (layout-aware `code` is not required: xterm gives `key`). */
46
+ function isLetter(input: TerminalChordInput, letter: string): boolean {
47
+ return input.key.toLowerCase() === letter
48
+ }
49
+
50
+ /**
51
+ * Map one keydown to a clipboard chord.
52
+ *
53
+ * Conventions: Ctrl+Shift+C / Ctrl+Insert / Cmd+C copy, Ctrl+Shift+V / Cmd+V /
54
+ * Shift+Insert paste. Plain Ctrl+V is left to the browser first (`paste-native`),
55
+ * and plain Ctrl+C always stays SIGINT.
56
+ */
57
+ export function clipboardChordFor(input: TerminalChordInput): TerminalClipboardChord | undefined {
58
+ const ctrl = input.ctrl,
59
+ shift = input.shift,
60
+ meta = input.meta,
61
+ alt = input.alt
62
+ if (alt) return undefined
63
+ if (!meta && ctrl && shift && isLetter(input, 'c')) return 'copy'
64
+ if (!meta && ctrl && !shift && input.key === 'Insert') return 'copy'
65
+ if (meta && !ctrl && !shift && isLetter(input, 'c')) return 'copy'
66
+ if (!meta && ctrl && shift && isLetter(input, 'v')) return 'paste'
67
+ if (!meta && !ctrl && shift && input.key === 'Insert') return 'paste'
68
+ if (meta && !ctrl && !shift && isLetter(input, 'v')) return 'paste'
69
+ if (!meta && ctrl && !shift && isLetter(input, 'v')) return 'paste-native'
70
+ // Plain Ctrl+C only means COPY when there is a selection; without one it must
71
+ // stay SIGINT. The chord therefore only says "look at the selection".
72
+ if (!meta && ctrl && !shift && isLetter(input, 'c')) return 'copy-interrupt'
73
+ return undefined
74
+ }
75
+
76
+ /** Copy and paste chords take the key over; the native-paste chord must not. */
77
+ export function chordTakesKey(chord: TerminalClipboardChord): boolean {
78
+ return chord !== 'paste-native'
79
+ }
80
+
81
+ /** Dependencies of {@link createPasteFallback}. */
82
+ export interface PasteFallbackDeps {
83
+ /** Clipboard read; `undefined` when the browser denies it. */
84
+ read: () => Promise<string | undefined>
85
+ /** Insert text into the terminal. */
86
+ paste: (text: string) => void
87
+ /** Report a denied clipboard read (shown in the terminal). */
88
+ onDenied: () => void
89
+ /** Timer injection (tests use a fake clock). */
90
+ schedule?: (run: () => void, ms: number) => unknown
91
+ }
92
+
93
+ /** How long to wait for a native paste event before falling back to the API. */
94
+ export const PASTE_FALLBACK_MS = 180
95
+
96
+ /**
97
+ * Watches one Ctrl+V press: the browser's native paste wins when its event arrives,
98
+ * otherwise the Clipboard API inserts the text after {@link PASTE_FALLBACK_MS}.
99
+ *
100
+ * The watcher is a single slot: arming again (a held/repeated key) replaces the
101
+ * pending window instead of stacking pastes.
102
+ */
103
+ export function createPasteFallback(deps: PasteFallbackDeps): {
104
+ arm: () => void
105
+ /** The terminal saw a native paste for this window: cancel the fallback. */
106
+ observed: () => void
107
+ } {
108
+ const schedule = deps.schedule
109
+ ?? ((run, ms) => {
110
+ const timer = setTimeout(run, ms)
111
+ // Never keep a Host-alike or a page alive for a clipboard probe.
112
+ ;(timer as unknown as { unref?: () => void }).unref?.()
113
+ return timer
114
+ })
115
+ let pending: { cancelled: boolean } | undefined
116
+ return {
117
+ arm: () => {
118
+ if (pending !== undefined) pending.cancelled = true
119
+ const token = { cancelled: false }
120
+ pending = token
121
+ schedule(() => {
122
+ if (token.cancelled) return
123
+ token.cancelled = true
124
+ if (pending === token) pending = undefined
125
+ void deps.read().then((text) => {
126
+ if (text === undefined) {
127
+ deps.onDenied()
128
+ return
129
+ }
130
+ deps.paste(text)
131
+ })
132
+ }, PASTE_FALLBACK_MS)
133
+ },
134
+ observed: () => {
135
+ if (pending !== undefined) pending.cancelled = true
136
+ pending = undefined
137
+ },
138
+ }
139
+ }
140
+
141
+ /** Menu entry state for the right-click menu. */
142
+ export function terminalMenuState(input: { hasSelection: boolean }): {
143
+ copyDisabled: boolean
144
+ } {
145
+ return { copyDisabled: !input.hasSelection }
146
+ }
147
+
148
+ // ------------------------------------------------- bracketed-paste sanitising
149
+
150
+ /** Start/end markers a terminal wraps around a bracketed paste. */
151
+ const PASTE_START = '\u001b[200~'
152
+ const PASTE_END = '\u001b[201~'
153
+
154
+ /**
155
+ * Remove ONE bracketed-paste wrapper from an input chunk.
156
+ *
157
+ * xterm wraps `Terminal.paste()`/native pastes while the remote application has
158
+ * bracketed paste enabled. When that mode is stale (an app that enabled it was
159
+ * killed, or the shell never enabled it) the wrapper is displayed literally as
160
+ * `^[[200~...^[[201~` and the text is not executed — a field screenshot showed
161
+ * exactly that. The host-side input path strips one wrapper before forwarding,
162
+ * so the PTY only ever receives the user's text. Apps that expect the wrapper
163
+ * still accept raw text, like a classic terminal.
164
+ */
165
+ export function stripBracketedPasteMarkers(data: string): string {
166
+ if (data.length < PASTE_START.length) return data
167
+ if (!data.startsWith(PASTE_START)) return data
168
+ if (!data.endsWith(PASTE_END)) return data
169
+ return data.slice(PASTE_START.length, data.length - PASTE_END.length)
170
+ }
@@ -1836,6 +1836,29 @@ body:not([data-ds-dark-theme]) .rvs-edge .rvs-change-word-del {
1836
1836
  background-color: rgba(207, 34, 46, .14);
1837
1837
  }
1838
1838
 
1839
+ /**
1840
+ * 整块删除:一枚带行数的胶囊,不是一行划掉的文字。
1841
+ *
1842
+ * 多行删除的原文是一个段落,划线堆在锚点行首只会糊成一片(数据层因此把 `count > 1`
1843
+ * 的 chip 压成一枚,见 `change-marks.ts` 的 `RemovedChipWidget`)。这里只做外形:
1844
+ * 去掉继承来的删除线(胶囊不是"被划掉的字符串"),字号与计数对齐,别把行高撑开。
1845
+ */
1846
+ .rvs-edge .rvs-change-block-del {
1847
+ padding: 0 4px;
1848
+ margin: 0 1px;
1849
+ border-radius: 3px;
1850
+ background-color: rgba(248, 81, 73, .18);
1851
+ font-size: 11px;
1852
+ font-variant-numeric: tabular-nums;
1853
+ text-decoration: none;
1854
+ opacity: 1;
1855
+ white-space: nowrap;
1856
+ }
1857
+
1858
+ body:not([data-ds-dark-theme]) .rvs-edge .rvs-change-block-del {
1859
+ background-color: rgba(207, 34, 46, .14);
1860
+ }
1861
+
1839
1862
  /**
1840
1863
  * 改动跳转按钮:浮在编辑器右上角。
1841
1864
  *
package/src/protocol.ts CHANGED
@@ -471,6 +471,18 @@ export interface RemoteChangedFile {
471
471
  oversized?: true
472
472
  /** Change kind from --name-status; undefined when git gave none. */
473
473
  status?: 'A' | 'M' | 'D' | 'R' | 'C' | 'T' | 'U'
474
+ /**
475
+ * What "undo this file" may do, decided by the HOST (the client never guesses).
476
+ *
477
+ * - `patch`: a real reverse patch exists — reverting restores the session
478
+ * baseline in one `git apply -R`.
479
+ * - `delete`: the file is a whole-file CREATION git has a copy of (a tracked
480
+ * addition), so the only reverse is deleting it. Recoverable from the index,
481
+ * but still a destructive write, so the client must confirm it.
482
+ * - absent: nothing can be undone — an UNTRACKED creation (git holds no copy),
483
+ * a binary, or a file whose bytes were withheld by the size caps.
484
+ */
485
+ revert?: 'patch' | 'delete'
474
486
  }
475
487
 
476
488
  /**
@@ -493,8 +505,23 @@ export interface RemoteChangesSummary {
493
505
  deleted: number
494
506
  /** Wall-clock ms when this summary was last recomputed. */
495
507
  at: number
496
- /** More files than the cap: `files` is truncated but the totals are whole. */
508
+ /**
509
+ * More files than the cap: `files` is truncated and so are `added` / `deleted`.
510
+ *
511
+ * The totals are summed from the rows that made it into `files` (the cost of
512
+ * counting the rest is a read per path), which is why the panel says "N files
513
+ * changed" about a subset and must not present the counts as whole-tree
514
+ * totals.
515
+ */
497
516
  truncated?: true
517
+ /**
518
+ * Directory names the new-file scan was told to skip (build output, caches).
519
+ *
520
+ * Present only when the exclusion ran, and listed rather than merely applied:
521
+ * a file the user expected to see must never be missing without a reason. The
522
+ * SCM panel stays the surface that shows every path.
523
+ */
524
+ excludedDirs?: string[]
498
525
  /** A scan is running right now (the slow one counts); the list will refresh. */
499
526
  pending: boolean
500
527
  /** Why this session has no ledger (local session, no git, timeout, …). */
@@ -509,6 +536,15 @@ export interface RemoteChangesDiff {
509
536
  display: string
510
537
  /** Text hunks (empty for binary/missing). */
511
538
  hunks: UnifiedHunk[]
539
+ /**
540
+ * The WHOLE file as one reverse-applicable patch (`git apply -R`).
541
+ *
542
+ * One write instead of one per hunk, which is what "revert everything this
543
+ * session did to this file" needs. Empty when the reverse is not expressible
544
+ * as a patch (see `RemoteChangedFile.revert`), which is the fail-closed answer
545
+ * the client must not try to build itself.
546
+ */
547
+ patch?: string
512
548
  /** File status at turn end (A/M/D/…), when git reported one. */
513
549
  status?: 'A' | 'M' | 'D' | 'R' | 'C' | 'T' | 'U'
514
550
  /** The diff was cut at the byte cap: `hunks` is a prefix. */