dsh-remote-vs 0.24.0 → 0.26.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 (125) hide show
  1. package/README.en.md +50 -16
  2. package/README.md +40 -15
  3. package/THIRD-PARTY-NOTICES.md +188 -0
  4. package/lib/client.js +6512 -77887
  5. package/lib/index.js +1461 -1024
  6. package/lib/p2-router-fs.js +1 -1
  7. package/lib/types/client/CodeEditor.d.ts +25 -0
  8. package/lib/types/client/EditorPane.d.ts +16 -5
  9. package/lib/types/client/FloatingPlaceholder.d.ts +16 -5
  10. package/lib/types/client/RemoteEditorView.d.ts +13 -10
  11. package/lib/types/client/RemoteExplorer.d.ts +53 -0
  12. package/lib/types/client/RemoteRoot.d.ts +5 -5
  13. package/lib/types/client/TerminalSnippets.d.ts +36 -0
  14. package/lib/types/client/TerminalView.d.ts +1 -1
  15. package/lib/types/client/XTerm.d.ts +33 -0
  16. package/lib/types/client/api.d.ts +37 -2
  17. package/lib/types/client/changes/review-state.d.ts +19 -0
  18. package/lib/types/client/connection.d.ts +16 -0
  19. package/lib/types/client/editor-capability.d.ts +27 -0
  20. package/lib/types/client/i18n.d.ts +1 -1
  21. package/lib/types/client/request-gate.d.ts +110 -0
  22. package/lib/types/client/scm/DiffView.d.ts +45 -7
  23. package/lib/types/client/scm/actions.d.ts +31 -3
  24. package/lib/types/client/store.d.ts +112 -4
  25. package/lib/types/client/terminal-input.d.ts +23 -0
  26. package/lib/types/client/terminal-snippets.d.ts +86 -0
  27. package/lib/types/client/vsc/FindWidget.d.ts +6 -0
  28. package/lib/types/client/vsc/breadcrumb.d.ts +30 -0
  29. package/lib/types/client/vsc/change-marks.d.ts +16 -6
  30. package/lib/types/client/vsc/editor-caret.d.ts +32 -0
  31. package/lib/types/client/vsc/editor-keymap.d.ts +35 -1
  32. package/lib/types/client/vsc/editor-langs.d.ts +9 -0
  33. package/lib/types/client/vsc/editor-settings.d.ts +55 -0
  34. package/lib/types/client/vsc/image-preview.d.ts +36 -0
  35. package/lib/types/client/vsc/kit.d.ts +13 -0
  36. package/lib/types/client/vsc/save-shortcut.d.ts +21 -0
  37. package/lib/types/client/vsc/terminal-clipboard.d.ts +15 -0
  38. package/lib/types/client/vsc/terminal-line.d.ts +25 -0
  39. package/lib/types/client/vsc/terminal-links.d.ts +62 -0
  40. package/lib/types/client/vsc/terminal-theme.d.ts +48 -0
  41. package/lib/types/client/vsc/terminal-writer.d.ts +52 -0
  42. package/lib/types/forward.d.ts +12 -0
  43. package/lib/types/fs-ops.d.ts +42 -0
  44. package/lib/types/http.d.ts +2 -0
  45. package/lib/types/keygen.d.ts +9 -0
  46. package/lib/types/monitor.d.ts +8 -0
  47. package/lib/types/notices.d.ts +16 -1
  48. package/lib/types/p2/helper-rpc.d.ts +45 -0
  49. package/lib/types/pool.d.ts +25 -0
  50. package/lib/types/routes.d.ts +2 -0
  51. package/lib/types/store.d.ts +7 -0
  52. package/lib/types/terminal.d.ts +33 -1
  53. package/lib/types/view-settings.d.ts +5 -0
  54. package/lib/{worlds-B7gEDBzC.js → worlds-RG8K5eom.js} +113 -15
  55. package/package.json +2 -1
  56. package/src/client/CodeEditor.tsx +205 -10
  57. package/src/client/DirectoryFlow.tsx +16 -0
  58. package/src/client/DoctorPanel.tsx +70 -7
  59. package/src/client/EditorPane.tsx +545 -118
  60. package/src/client/FloatingPlaceholder.tsx +34 -5
  61. package/src/client/HostsView.tsx +12 -3
  62. package/src/client/RemoteDirectoryPicker.tsx +12 -0
  63. package/src/client/RemoteEditorView.tsx +14 -11
  64. package/src/client/RemoteExplorer.tsx +929 -40
  65. package/src/client/RemoteRoot.tsx +167 -147
  66. package/src/client/SearchView.tsx +8 -0
  67. package/src/client/TerminalSnippets.tsx +432 -0
  68. package/src/client/TerminalView.tsx +50 -1
  69. package/src/client/XTerm.tsx +228 -58
  70. package/src/client/api.ts +106 -13
  71. package/src/client/auto-open-remote.ts +11 -9
  72. package/src/client/changes/ChangesDock.tsx +188 -6
  73. package/src/client/changes/changes.css +10 -3
  74. package/src/client/changes/review-state.ts +34 -0
  75. package/src/client/connection.ts +29 -0
  76. package/src/client/downloads.ts +49 -4
  77. package/src/client/editor-capability.ts +42 -0
  78. package/src/client/i18n.ts +228 -12
  79. package/src/client/index.tsx +22 -6
  80. package/src/client/request-gate.ts +221 -0
  81. package/src/client/scm/CommitPane.tsx +20 -2
  82. package/src/client/scm/DiffView.tsx +343 -117
  83. package/src/client/scm/HistoryPanel.tsx +23 -2
  84. package/src/client/scm/RepoPicker.tsx +1 -1
  85. package/src/client/scm/ScmPanel.tsx +391 -87
  86. package/src/client/scm/actions.ts +95 -12
  87. package/src/client/store.tsx +537 -22
  88. package/src/client/terminal-input.ts +44 -0
  89. package/src/client/terminal-snippets.ts +216 -0
  90. package/src/client/ui.tsx +4 -0
  91. package/src/client/vsc/FindWidget.tsx +24 -9
  92. package/src/client/vsc/breadcrumb.tsx +339 -0
  93. package/src/client/vsc/change-marks.ts +93 -44
  94. package/src/client/vsc/editor-caret.ts +30 -0
  95. package/src/client/vsc/editor-keymap.ts +59 -1
  96. package/src/client/vsc/editor-langs.ts +20 -0
  97. package/src/client/vsc/editor-settings.ts +146 -0
  98. package/src/client/vsc/editor-theme.ts +4 -5
  99. package/src/client/vsc/file-icons.tsx +17 -3
  100. package/src/client/vsc/image-preview.tsx +110 -0
  101. package/src/client/vsc/kit.tsx +46 -10
  102. package/src/client/vsc/save-shortcut.ts +47 -1
  103. package/src/client/vsc/terminal-clipboard.ts +19 -0
  104. package/src/client/vsc/terminal-line.ts +101 -0
  105. package/src/client/vsc/terminal-links.ts +166 -0
  106. package/src/client/vsc/terminal-theme.ts +97 -0
  107. package/src/client/vsc/terminal-writer.ts +112 -0
  108. package/src/client/vsc/vsc.css +1078 -181
  109. package/src/forward.ts +47 -9
  110. package/src/fs-ops.ts +124 -4
  111. package/src/git-ops.ts +20 -3
  112. package/src/http.ts +35 -4
  113. package/src/keygen.ts +55 -4
  114. package/src/monitor.ts +13 -0
  115. package/src/notices.ts +23 -1
  116. package/src/p2/helper-rpc.ts +113 -7
  117. package/src/p2/worlds.ts +14 -1
  118. package/src/pool.ts +99 -27
  119. package/src/routes.ts +212 -43
  120. package/src/sftp.ts +51 -14
  121. package/src/store.ts +10 -0
  122. package/src/terminal.ts +225 -24
  123. package/src/view-settings.ts +50 -10
  124. package/lib/types/client/Dialog.d.ts +0 -14
  125. package/src/client/Dialog.tsx +0 -76
@@ -5,27 +5,41 @@
5
5
  */
6
6
  import '@xterm/xterm/css/xterm.css'
7
7
  import { useEffect, useRef, type ReactNode } from 'react'
8
- import { Terminal } from '@xterm/xterm'
9
- import type { ITheme } from '@xterm/xterm'
8
+ import { Terminal, type ILink, type ILinkProvider } from '@xterm/xterm'
10
9
  import { FitAddon } from '@xterm/addon-fit'
11
10
  import type { TerminalClientFrame, TerminalServerFrame } from '../protocol.ts'
12
11
  import { isDarkScheme, subscribeColorScheme } from './theme.ts'
13
12
  import { ContextMenu, useContextMenu, type MenuEntry } from './vsc/kit.tsx'
14
13
  import {
15
- clipboardChordFor,
16
14
  createPasteFallback,
17
15
  stripBracketedPasteMarkers,
16
+ terminalKeyCommand,
18
17
  terminalMenuState,
19
18
  } from './vsc/terminal-clipboard.ts'
19
+ import { terminalTheme } from './vsc/terminal-theme.ts'
20
+ import { findTerminalPathTokens } from './vsc/terminal-links.ts'
21
+ import { registerTerminalPaste } from './terminal-input.ts'
22
+ import { createTerminalWriter } from './vsc/terminal-writer.ts'
23
+ import { applyTerminalInput } from './vsc/terminal-line.ts'
20
24
 
21
- function send(ws: WebSocket, frame: TerminalClientFrame): void {
25
+ /**
26
+ * Send one frame; `false` means it was NOT handed to the socket.
27
+ *
28
+ * The caller that tracks "the PTY already knows this size" depends on that
29
+ * answer (see `pushSize`): recording a size that never left is how a terminal
30
+ * used to sit at the URL's 80x24 for the rest of its life.
31
+ */
32
+ function send(ws: WebSocket, frame: TerminalClientFrame): boolean {
22
33
  if (ws.readyState === WebSocket.OPEN) {
23
34
  try {
24
35
  ws.send(JSON.stringify(frame))
36
+ return true
25
37
  } catch {
26
38
  // Socket raced away.
39
+ return false
27
40
  }
28
41
  }
42
+ return false
29
43
  }
30
44
 
31
45
  /** Clipboard write with a legacy execCommand fallback (non-secure contexts). */
@@ -59,53 +73,6 @@ async function readClipboard(): Promise<string | undefined> {
59
73
  }
60
74
  }
61
75
 
62
- /** Opaque high-readability palette (opaque: the contrast engine cannot reason about transparency). */
63
- function buildTheme(dark: boolean): ITheme {
64
- return dark
65
- ? {
66
- background: '#0e0e13',
67
- foreground: '#e8e8e8',
68
- cursor: '#e8e8e8',
69
- black: '#000000',
70
- red: '#cd3131',
71
- green: '#0dbc79',
72
- yellow: '#e5e910',
73
- blue: '#2472c8',
74
- magenta: '#bc3fbc',
75
- cyan: '#11a8cd',
76
- white: '#e5e5e5',
77
- brightBlack: '#7a7a7a',
78
- brightRed: '#f14c4c',
79
- brightGreen: '#23d18b',
80
- brightYellow: '#f5f543',
81
- brightBlue: '#3b8eea',
82
- brightMagenta: '#d670d6',
83
- brightCyan: '#29b8db',
84
- brightWhite: '#ffffff',
85
- }
86
- : {
87
- background: '#ffffff',
88
- foreground: '#1a1a1a',
89
- cursor: '#1a1a1a',
90
- black: '#000000',
91
- red: '#cd3131',
92
- green: '#00bc67',
93
- yellow: '#949800',
94
- blue: '#0451a5',
95
- magenta: '#bc05bc',
96
- cyan: '#0598bc',
97
- white: '#555555',
98
- brightBlack: '#666666',
99
- brightRed: '#f14c4c',
100
- brightGreen: '#23d18b',
101
- brightYellow: '#f5f543',
102
- brightBlue: '#3b8eea',
103
- brightMagenta: '#d670d6',
104
- brightCyan: '#29b8db',
105
- brightWhite: '#ffffff',
106
- }
107
- }
108
-
109
76
  export function XTerm(props: {
110
77
  wsUrl: string
111
78
  onReady: (id: string) => void
@@ -121,6 +88,33 @@ export function XTerm(props: {
121
88
  initialInput?: string
122
89
  /** Translator for the right-click menu (copy / paste / select all). */
123
90
  t: (key: string) => string
91
+ /** Tab identity, used by the snippet panel to target THIS terminal. */
92
+ tabId: string
93
+ /**
94
+ * Ctrl/Cmd+B inside the terminal: open the "add snippet" form.
95
+ *
96
+ * Receives a best-effort draft so the form can pre-fill its command: the
97
+ * current terminal SELECTION when there is one (the user picked exactly what
98
+ * they want), else the line reconstructed from this session's keystrokes.
99
+ *
100
+ * Absent → the keystroke stays the shell's (readline's backward-char), which
101
+ * is what a host that did not wire the panel should keep.
102
+ */
103
+ onQuickAddSnippet?: (draft: { selection?: string; line?: string }) => void
104
+ /**
105
+ * Remote home directory of this tab's host, when known.
106
+ *
107
+ * Used to resolve a `~/x` token printed by the shell. The SSH user's home is
108
+ * the only honest source — the terminal protocol carries no home directory.
109
+ */
110
+ home?: string
111
+ /**
112
+ * Ctrl/Cmd + click on a path printed in the terminal.
113
+ *
114
+ * Receives the path AS PRINTED plus the hints that make sense of a relative
115
+ * one: the shell's cwd when it reports it (OSC 7) and the remote home.
116
+ */
117
+ onPathClick?: (token: string, context: { cwd?: string; home?: string }) => void
124
118
  }): ReactNode {
125
119
  const hostRef = useRef<HTMLDivElement>(null)
126
120
  const propsRef = useRef(props)
@@ -148,12 +142,12 @@ export function XTerm(props: {
148
142
  fontSize: 13,
149
143
  fontFamily: propsRef.current.fontFamily ?? 'var(--ds-font-family-code, ui-monospace, monospace)',
150
144
  minimumContrastRatio: 7,
151
- theme: buildTheme(isDarkScheme()),
145
+ theme: terminalTheme(isDarkScheme()),
152
146
  })
153
147
  // Re-theme live when the user flips the DSH scheme.
154
148
  const unflip = subscribeColorScheme(() => {
155
149
  try {
156
- term.options.theme = buildTheme(isDarkScheme())
150
+ term.options.theme = terminalTheme(isDarkScheme())
157
151
  } catch {
158
152
  // Terminal gone.
159
153
  }
@@ -163,8 +157,105 @@ export function XTerm(props: {
163
157
  term.open(host)
164
158
  fit.fit()
165
159
 
160
+ /**
161
+ * The shell's working directory, when it reports it.
162
+ *
163
+ * OSC 7 (`ESC ] 7 ; file://host/path BEL`) is the standard, prompt-hook-driven
164
+ * way shells announce `pwd`; bash/zsh print it when their profile enables it.
165
+ * It is the only trustworthy anchor for a RELATIVE path printed by a command:
166
+ * without it the click falls back to the workspace roots (see
167
+ * `jumpToTerminalPath`). Silent when absent — nothing to report.
168
+ */
169
+ let cwd: string | undefined
170
+ const osc7 = term.parser.registerOscHandler(7, (data) => {
171
+ const match = /^file:\/\/[^/]*(\/.*)$/.exec(data)
172
+ if (match?.[1] !== undefined && match[1] !== '') {
173
+ try {
174
+ cwd = decodeURIComponent(match[1])
175
+ } catch {
176
+ // A malformed escape is not worth failing over; keep the raw bytes.
177
+ cwd = match[1]
178
+ }
179
+ }
180
+ return true
181
+ })
182
+
183
+ /**
184
+ * Ctrl/Cmd + click on a path printed in the terminal jumps to that folder in
185
+ * the directory tree (`jumpToTerminalPath` validates against the host first).
186
+ *
187
+ * Only paths the tokenizer accepts become links, and the modifier is checked
188
+ * in `activate`: plain clicks keep their normal text-selection behaviour.
189
+ */
190
+ const linkProvider: ILinkProvider = {
191
+ provideLinks: (lineNumber, callback) => {
192
+ if (propsRef.current.onPathClick === undefined) {
193
+ callback(undefined)
194
+ return
195
+ }
196
+ const line = term.buffer.active.getLine(lineNumber - 1)
197
+ if (line === undefined) {
198
+ callback(undefined)
199
+ return
200
+ }
201
+ // `trimRight` keeps the columns aligned with the buffer (a wrapped line's
202
+ // trailing blanks must not shift the token indexes).
203
+ const text = line.translateToString(true)
204
+ const tokens = findTerminalPathTokens(text)
205
+ if (tokens.length === 0) {
206
+ callback(undefined)
207
+ return
208
+ }
209
+ const links: ILink[] = tokens.map(token => ({
210
+ range: {
211
+ start: { x: token.start + 1, y: lineNumber },
212
+ end: { x: token.end + 1, y: lineNumber },
213
+ },
214
+ text: token.path,
215
+ activate: (event: MouseEvent, linkText: string) => {
216
+ // Ctrl (or Cmd on a Mac): a plain click stays a plain click, so
217
+ // selecting text near a path is not hijacked.
218
+ if (!event.ctrlKey && !event.metaKey) return
219
+ propsRef.current.onPathClick?.(linkText, {
220
+ ...(cwd === undefined ? {} : { cwd }),
221
+ ...(propsRef.current.home === undefined ? {} : { home: propsRef.current.home }),
222
+ })
223
+ },
224
+ }))
225
+ callback(links)
226
+ },
227
+ }
228
+ const linkRegistration = term.registerLinkProvider(linkProvider)
229
+ /**
230
+ * The snippet panel's handle on THIS terminal: insert a command at the prompt
231
+ * without pressing Enter (see `terminal-input.ts`).
232
+ *
233
+ * `term.paste` is the honest primitive — it goes through xterm's own bracketed
234
+ * paste handling and the normal input path, so the shell sees typed text and
235
+ * still decides when to run it.
236
+ */
237
+ const unregisterPaste = registerTerminalPaste(propsRef.current.tabId, (text: string) => {
238
+ try {
239
+ term.paste(text)
240
+ term.focus()
241
+ } catch {
242
+ // Terminal disposed mid-call.
243
+ }
244
+ })
245
+
166
246
  const ws = new WebSocket(propsRef.current.wsUrl)
167
247
  let opened = false
248
+ /**
249
+ * True once the HOST said `ready` for this socket.
250
+ *
251
+ * Frames sent before that are lost, not queued: the host only attaches its
252
+ * message listener after the shell exists (a cold dial takes seconds), so a
253
+ * `resize` sent on the WebSocket `open` event never reached the PTY — and
254
+ * because the client had already recorded the size, the later push (once the
255
+ * host was listening) was deduped away. The shell then stayed at the URL's
256
+ * 80x24 for its whole life. Sizes are only sent after `ready`.
257
+ */
258
+ let hostReady = false
168
259
  /** The seeded line is typed at most once per mount (a reconnect re-mounts). */
169
260
  let seeded = false
170
261
  let exitReported = false
@@ -174,6 +265,12 @@ export function XTerm(props: {
174
265
  propsRef.current.onExit(code, message)
175
266
  }
176
267
 
268
+ /**
269
+ * Size last pushed to the PTY (`0` = nothing sent yet, so the first push
270
+ * always goes). Declared BEFORE `pushSize` reads it: a `let` declared below
271
+ * would be in its temporal dead zone on the first call.
272
+ */
273
+ let lastSize = { cols: 0, rows: 0 }
177
274
  const pushSize = (): void => {
178
275
  if (host.clientWidth < 20 || host.clientHeight < 20) return
179
276
  try {
@@ -181,7 +278,19 @@ export function XTerm(props: {
181
278
  } catch {
182
279
  // Not laid out yet.
183
280
  }
184
- send(ws, { t: 'resize', cols: term.cols, rows: term.rows })
281
+ // Nothing may be sent before the host is listening (see `hostReady`); the
282
+ // `ready` handler pushes the measured size itself.
283
+ if (!hostReady) return
284
+ // Only a CHANGED size is news: the observer fires on every pixel of a
285
+ // window drag, and a resize frame per tick makes the remote shell re-run
286
+ // SIGWINCH handling (full-screen apps redraw) for nothing.
287
+ if (term.cols === lastSize.cols && term.rows === lastSize.rows) return
288
+ // Record the size only once it really left: the observer can fire before
289
+ // the socket is OPEN (and `send` then drops the frame), and remembering a
290
+ // size the PTY never received left the shell at the URL's 80x24 until the
291
+ // user dragged the window.
292
+ const sent = send(ws, { t: 'resize', cols: term.cols, rows: term.rows })
293
+ if (sent) lastSize = { cols: term.cols, rows: term.rows }
185
294
  }
186
295
  liveRef.current = {
187
296
  refit: () => {
@@ -203,9 +312,20 @@ export function XTerm(props: {
203
312
  * characters — far under that cap either way, and far above a keystroke.
204
313
  */
205
314
  const INPUT_CHUNK_CHARS = 64 * 1024
315
+ /**
316
+ * Best-effort reconstruction of the line the user is typing, for Ctrl+B.
317
+ *
318
+ * Fed from the SAME `onData` stream that goes to the PTY (see
319
+ * `vsc/terminal-line.ts`): printable text appends, backspace removes,
320
+ * Enter/Ctrl+C/Ctrl+U clear, escape sequences are ignored. Used only to
321
+ * pre-fill the snippet form, so an inexact line (history recall, cursor
322
+ * movement) costs nothing.
323
+ */
324
+ let inputLine = ''
206
325
  const sendInput = (rawData: string): void => {
207
326
  const data = stripBracketedPasteMarkers(rawData)
208
327
  if (data === '') return
328
+ inputLine = applyTerminalInput(inputLine, data)
209
329
  if (data.length <= INPUT_CHUNK_CHARS) {
210
330
  send(ws, { t: 'in', d: data })
211
331
  return
@@ -221,6 +341,21 @@ export function XTerm(props: {
221
341
  if (chunk !== '') send(ws, { t: 'in', d: chunk })
222
342
  }
223
343
  term.onData(sendInput)
344
+
345
+ /**
346
+ * Output writer (see `vsc/terminal-writer.ts` for the full reasoning).
347
+ *
348
+ * Frames are appended to ONE ordered buffer and handed to xterm on a timer,
349
+ * instead of one `term.write` per frame — and, importantly, NOT chained on
350
+ * the xterm write callback. That callback waits for parse+render, which a
351
+ * throttled/occluded window can delay indefinitely; the echo of what the user
352
+ * types then sat in this queue with no echo on screen until the callback
353
+ * finally fired. Nothing here waits for a write to finish.
354
+ */
355
+ const writer = createTerminalWriter({ write: (text) => { term.write(text) } })
356
+ const writeOut = (text: string): void => {
357
+ writer.push(text)
358
+ }
224
359
  ws.addEventListener('open', () => {
225
360
  opened = true
226
361
  pushSize()
@@ -233,6 +368,9 @@ export function XTerm(props: {
233
368
  return
234
369
  }
235
370
  if (frame.t === 'ready') {
371
+ hostReady = true
372
+ // The host is listening now: apply the size this client really has.
373
+ pushSize()
236
374
  propsRef.current.onReady(frame.id)
237
375
  // The shell exists now: type the seeded line (a menu entry's `cd`), as a
238
376
  // normal input line so the shell echoes it and redraws its prompt.
@@ -242,7 +380,7 @@ export function XTerm(props: {
242
380
  send(ws, { t: 'in', d: `${seed}\n` })
243
381
  }
244
382
  } else if (frame.t === 'out') {
245
- term.write(frame.d)
383
+ writeOut(frame.d)
246
384
  } else if (frame.t === 'exit') {
247
385
  reportExit(frame.code)
248
386
  try {
@@ -251,7 +389,7 @@ export function XTerm(props: {
251
389
  // Ignore.
252
390
  }
253
391
  } else if (frame.t === 'error') {
254
- term.write(`\r\n[dsh-remote] ${frame.message}\r\n`)
392
+ writeOut(`\r\n[dsh-remote] ${frame.message}\r\n`)
255
393
  reportExit(null, frame.message)
256
394
  }
257
395
  })
@@ -330,14 +468,43 @@ export function XTerm(props: {
330
468
  }
331
469
  host.addEventListener('paste', onPasteEvent, true)
332
470
  term.attachCustomKeyEventHandler((e) => {
333
- const chord = clipboardChordFor({
471
+ // `terminalKeyCommand` answers undefined for keyup/keypress: xterm invokes
472
+ // this hook for all three, and acting on keyup pasted twice.
473
+ const chord = terminalKeyCommand({
474
+ type: e.type,
334
475
  key: e.key,
335
476
  ctrl: e.ctrlKey,
336
477
  shift: e.shiftKey,
337
478
  alt: e.altKey,
338
479
  meta: e.metaKey,
339
480
  })
340
- if (chord === undefined) return true
481
+ if (chord === undefined) {
482
+ /**
483
+ * Ctrl/Cmd+B opens "add snippet".
484
+ *
485
+ * Note the trade-off: in a plain readline, ^B is backward-char. The
486
+ * shortcut is a user requirement, and it is only claimed while the panel
487
+ * is wired (`onQuickAddSnippet` present) — the terminal's own Ctrl+F etc.
488
+ * stay untouched because they go through xterm's keymap, not here.
489
+ */
490
+ if (
491
+ e.type === 'keydown'
492
+ && (e.ctrlKey || e.metaKey)
493
+ && !e.shiftKey
494
+ && !e.altKey
495
+ && (e.key === 'b' || e.key === 'B')
496
+ && propsRef.current.onQuickAddSnippet !== undefined
497
+ ) {
498
+ e.preventDefault()
499
+ const selection = term.getSelection()
500
+ propsRef.current.onQuickAddSnippet({
501
+ ...(selection !== '' ? { selection } : {}),
502
+ ...(inputLine !== '' ? { line: inputLine } : {}),
503
+ })
504
+ return false
505
+ }
506
+ return true
507
+ }
341
508
  if (chord === 'copy-interrupt') {
342
509
  // Ctrl+C: with a selection the convention is COPY (never SIGINT); without
343
510
  // one the key falls through so the remote shell interrupts as usual.
@@ -387,6 +554,9 @@ export function XTerm(props: {
387
554
  return () => {
388
555
  liveRef.current = undefined
389
556
  unflip()
557
+ unregisterPaste()
558
+ linkRegistration.dispose()
559
+ osc7.dispose()
390
560
  window.clearTimeout(timer)
391
561
  window.removeEventListener('resize', onWindowResize)
392
562
  host.removeEventListener('paste', onPasteEvent, true)
package/src/client/api.ts CHANGED
@@ -36,6 +36,7 @@ import { activeConnectionAlias, currentConnection, isConnectionFailure, noteConn
36
36
  import { detectLang, makeT } from './i18n.ts'
37
37
  import { dispatchHostNotices } from './notices.ts'
38
38
  import { parseSseFrame, takeSseFrames } from './exec-output.ts'
39
+ import { requestGate } from './request-gate.ts'
39
40
  import {
40
41
  branchesCommand,
41
42
  gitFailed,
@@ -77,6 +78,14 @@ export class RemoteApiError extends Error {
77
78
  * happened (the Host successfully protected the file).
78
79
  */
79
80
  conflict?: RemoteWriteConflict
81
+ /**
82
+ * The Host's own words, kept when the message was rewritten for the user.
83
+ *
84
+ * Today only the loopback fence's `403 forbidden: loopback-only` takes this
85
+ * path (see `loopbackFenceMessage`): the readable sentence explains what to do,
86
+ * while this keeps the exact server string for diagnostics and logs.
87
+ */
88
+ detail?: string
80
89
  constructor(
81
90
  readonly status: number,
82
91
  message: string,
@@ -85,6 +94,34 @@ export class RemoteApiError extends Error {
85
94
  }
86
95
  }
87
96
 
97
+ /**
98
+ * The readable form of the loopback fence's refusal (audit S-34).
99
+ *
100
+ * Every `/api/dsh-remote/*` route refuses a request that is not loopback +
101
+ * same-origin with `403 {error: 'forbidden: loopback-only'}`. That is the
102
+ * security model working, not a fault — but through a remote Web UI
103
+ * (`ds-harness-remote`, a tunnel) the whole plugin answers 403 and the raw
104
+ * phrase told the user nothing. The plugin cannot relax the fence (and must
105
+ * not), so it says what happened instead.
106
+ *
107
+ * Kept HERE rather than in `i18n.ts` only because that file was outside this
108
+ * round's write scope; the pair should move into the dictionaries the next time
109
+ * it is touched.
110
+ */
111
+ const REMOTE_ACCESS_DENIED: Record<'zh' | 'en', string> = {
112
+ zh: '插件 API 仅限本机访问:通过远程 Web UI(中继 / 隧道)打开 DSH 时该功能不可用,请在本机浏览器中打开 DSH。',
113
+ en: 'The plugin API is only reachable from this machine: it is unavailable when DSH is opened through a remote Web UI (relay / tunnel). Open DSH locally instead.',
114
+ }
115
+
116
+ /**
117
+ * Localize `403 forbidden: loopback-only`, or answer undefined for everything
118
+ * else (the caller then keeps the server's own text).
119
+ */
120
+ function loopbackFenceMessage(status: number, rawError: string | undefined): string | undefined {
121
+ if (status !== 403 || rawError !== 'forbidden: loopback-only') return undefined
122
+ return REMOTE_ACCESS_DENIED[detectLang()]
123
+ }
124
+
88
125
  /**
89
126
  * Validate a 409 payload before believing it is a save conflict.
90
127
  *
@@ -99,11 +136,42 @@ function isWriteConflict(value: unknown): value is RemoteWriteConflict {
99
136
  return measured(shape.mtime) && measured(shape.size)
100
137
  }
101
138
 
102
- async function call<T>(path: string, init?: RequestInit): Promise<T> {
103
- const res = await fetch(path, {
139
+ /**
140
+ * Per-request scheduling options (the channel lives in `request-gate.ts`).
141
+ *
142
+ * Every call site that does NOT pass them keeps the pre-gate behaviour: a
143
+ * foreground request that starts immediately and never waits.
144
+ */
145
+ export interface RequestOptions {
146
+ /**
147
+ * Run this request on the BACKGROUND channel.
148
+ *
149
+ * Only repository-wide git walks use it (see `scm/actions.ts`): they can take
150
+ * minutes on a large tree, and a workspace switch must not make the directory
151
+ * listing queue behind them for a connection. Background requests start only
152
+ * while no foreground request is in flight, one at a time.
153
+ */
154
+ background?: boolean
155
+ /**
156
+ * Cancels the request: a queued background entry leaves the queue, and a
157
+ * request that already started is aborted at the fetch.
158
+ */
159
+ signal?: AbortSignal
160
+ }
161
+
162
+ async function call<T>(path: string, init?: RequestInit, opts?: RequestOptions): Promise<T> {
163
+ // The signal both takes a queued background request out and cancels the fetch
164
+ // itself; an `init.signal` from the caller counts the same way when no
165
+ // explicit one is given.
166
+ const signal = opts?.signal ?? init?.signal ?? undefined
167
+ const send = (): Promise<Response> => fetch(path, {
104
168
  ...init,
169
+ ...(signal === undefined ? {} : { signal }),
105
170
  headers: { 'content-type': 'application/json', ...(init?.headers ?? {}) },
106
171
  })
172
+ const res = opts?.background === true
173
+ ? await requestGate.runBackground(send, signal)
174
+ : await requestGate.runForeground(send)
107
175
  let data: unknown = null
108
176
  try {
109
177
  data = await res.json()
@@ -114,8 +182,15 @@ async function call<T>(path: string, init?: RequestInit): Promise<T> {
114
182
  const body = typeof data === 'object' && data !== null
115
183
  ? data as { error?: unknown; code?: unknown; conflict?: unknown }
116
184
  : undefined
117
- const message = typeof body?.error === 'string' ? body.error : `request failed: HTTP ${res.status}`
185
+ const rawMessage = typeof body?.error === 'string' ? body.error : `request failed: HTTP ${res.status}`
186
+ // S-34: the one refusal that is the security fence, not a failure.
187
+ const fenced = loopbackFenceMessage(res.status, typeof body?.error === 'string' ? body.error : undefined)
188
+ const message = fenced ?? rawMessage
118
189
  const failure = new RemoteApiError(res.status, message)
190
+ if (fenced !== undefined) {
191
+ failure.detail = rawMessage
192
+ console.debug('[dsh-remote-vs] remote access refused by the loopback fence:', rawMessage)
193
+ }
119
194
  if (body?.code === 'deadline') failure.deadline = true
120
195
  // A refused save is not a link failure: keep its payload so the caller can
121
196
  // ask the user what to do with the current version.
@@ -150,8 +225,8 @@ async function call<T>(path: string, init?: RequestInit): Promise<T> {
150
225
  return data as T
151
226
  }
152
227
 
153
- function post<T>(path: string, body: unknown): Promise<T> {
154
- return call<T>(path, { method: 'POST', body: JSON.stringify(body ?? {}) })
228
+ function post<T>(path: string, body: unknown, opts?: RequestOptions): Promise<T> {
229
+ return call<T>(path, { method: 'POST', body: JSON.stringify(body ?? {}) }, opts)
155
230
  }
156
231
 
157
232
  /** Raise a friendly git error for a failed exec result. */
@@ -298,10 +373,17 @@ export function uploadFile(options: {
298
373
  resolve({ size })
299
374
  return
300
375
  }
301
- const message = typeof body === 'object' && body !== null && typeof (body as { error?: unknown }).error === 'string'
376
+ const rawError = typeof body === 'object' && body !== null && typeof (body as { error?: unknown }).error === 'string'
302
377
  ? (body as { error: string }).error
303
- : `upload failed: HTTP ${xhr.status}`
304
- reject(new RemoteApiError(xhr.status, message))
378
+ : undefined
379
+ // Same fence, same readable answer as the JSON path above (S-34).
380
+ const fenced = loopbackFenceMessage(xhr.status, rawError)
381
+ const failure = new RemoteApiError(xhr.status, fenced ?? (rawError ?? `upload failed: HTTP ${xhr.status}`))
382
+ if (fenced !== undefined) {
383
+ failure.detail = rawError
384
+ console.debug('[dsh-remote-vs] remote access refused by the loopback fence:', rawError)
385
+ }
386
+ reject(failure)
305
387
  }
306
388
  xhr.onerror = () => reject(new RemoteApiError(0, 'upload failed: connection error'))
307
389
  xhr.onabort = () => reject(new RemoteApiError(0, 'upload cancelled'))
@@ -417,7 +499,8 @@ export const api = {
417
499
  }).then(r => r.host),
418
500
  deleteHost: (alias: string) =>
419
501
  call<{ ok: boolean }>(`${REMOTE_API.hosts}?alias=${encodeURIComponent(alias)}`, { method: 'DELETE' }),
420
- testHost: (alias: string) => post<{ ok: boolean; error?: string; durationMs: number }>(REMOTE_API.test, { alias }),
502
+ testHost: (alias: string, opts?: RequestOptions) =>
503
+ post<{ ok: boolean; error?: string; durationMs: number }>(REMOTE_API.test, { alias }, opts),
421
504
  /** Per-alias SSH connection health (Host pool's view; this is a local poll). */
422
505
  connectionStatus: () => call<{ connections: RemoteConnectionStatus[] }>(REMOTE_API.status).then(r => r.connections),
423
506
  bootstrap: (alias: string) => post<{ alias: string; keyPath: string; flipped: boolean; detail: string }>(REMOTE_API.keygen, { alias }),
@@ -453,8 +536,13 @@ export const api = {
453
536
  post<{ ok: boolean }>(REMOTE_API.files, { op: 'rename', alias, from, to }).then(afterRemoteWrite),
454
537
  },
455
538
  // -- exec
456
- exec: (alias: string, command: string, timeoutMs?: number) =>
457
- post<RemoteExecResult>(REMOTE_API.exec, timeoutMs === undefined ? { alias, command } : { alias, command, timeoutMs })
539
+ /**
540
+ * One remote command (`/exec`), foreground unless `opts.background` asks for
541
+ * the git channel. Reads the SCM panel builds stay foreground; the
542
+ * repository-wide walks pass `{ background: true }` (see `scm/actions.ts`).
543
+ */
544
+ exec: (alias: string, command: string, timeoutMs?: number, opts?: RequestOptions) =>
545
+ post<RemoteExecResult>(REMOTE_API.exec, timeoutMs === undefined ? { alias, command } : { alias, command, timeoutMs }, opts)
458
546
  .then((result) => {
459
547
  // A worktree-changing git verb (discard / checkout / stash apply …) runs
460
548
  // through here rather than `fileOp`, so it is the one place an index
@@ -476,12 +564,17 @@ export const api = {
476
564
  timeoutMs: number,
477
565
  handlers: { onData?: (stream: 'out' | 'err', text: string) => void; signal?: AbortSignal },
478
566
  ): Promise<RemoteExecResult> => {
479
- const response = await fetch(REMOTE_API.execStream, {
567
+ // A USER-initiated verb (fetch/pull/push, its own live panel), so it is
568
+ // foreground — but only the RESPONSE ESTABLISHMENT is claimed: the SSE body
569
+ // streams for minutes, and holding the foreground counter for that long
570
+ // would starve every background git read (and make the panel's own refresh
571
+ // wait for itself).
572
+ const response = await requestGate.runForeground(() => fetch(REMOTE_API.execStream, {
480
573
  method: 'POST',
481
574
  headers: { 'content-type': 'application/json' },
482
575
  body: JSON.stringify({ alias, command, timeoutMs }),
483
576
  ...(handlers.signal === undefined ? {} : { signal: handlers.signal }),
484
- })
577
+ }))
485
578
  if (!response.ok || response.body === null) {
486
579
  let message = `request failed: HTTP ${response.status}`
487
580
  try {
@@ -172,10 +172,7 @@ export function installAutoOpenRemote(ctx: Context): () => void {
172
172
  // screen: the right column is shared with every other sidebar page (the
173
173
  // local workbench among them), and a width meant for the remote workspace
174
174
  // must not restyle a panel showing something else.
175
- if (handle !== null && ownTabActive(ctx)) {
176
- resizeRightbar(handle, ratio)
177
- return
178
- }
175
+ if (handle !== null && ownTabActive(ctx) && resizeRightbar(handle, ratio)) return
179
176
  frames -= 1
180
177
  // The panel renders its handle in the frame it becomes visible, so a poll
181
178
  // corrects a restored panel immediately instead of on a timer.
@@ -303,17 +300,17 @@ export function installAutoOpenRemote(ctx: Context): () => void {
303
300
  * exactly on `target` (DSH clamps the column itself, but the target is clamped
304
301
  * here too so a narrow window cannot ask for the impossible).
305
302
  */
306
- function resizeRightbar(handle: HTMLElement, ratio: number): void {
303
+ function resizeRightbar(handle: HTMLElement, ratio: number): boolean {
307
304
  const viewport = document.documentElement.clientWidth
308
- if (viewport <= 0) return
305
+ if (viewport <= 0) return false
309
306
  const target = Math.min(
310
307
  Math.max(Math.round(viewport * clampViewWidthRatio(ratio)), RIGHTBAR_MIN_WIDTH),
311
308
  Math.max(RIGHTBAR_MIN_WIDTH, Math.round(viewport * RIGHTBAR_MAX_RATIO)),
312
309
  )
313
310
  const current = currentRightbarWidth(handle, viewport)
314
- if (current === undefined) return
311
+ if (current === undefined) return false
315
312
  const dx = Math.round(current) - target
316
- if (Math.abs(dx) < 1) return
313
+ if (Math.abs(dx) < 1) return true
317
314
  const origin = Math.round(handle.getBoundingClientRect().left)
318
315
  withNeutralPointerCapture(handle, () => {
319
316
  withoutTrackTransition(handle, () => {
@@ -321,6 +318,7 @@ function resizeRightbar(handle: HTMLElement, ratio: number): void {
321
318
  dispatchPointer(handle, 'pointerup', origin + dx)
322
319
  })
323
320
  })
321
+ return true
324
322
  }
325
323
 
326
324
  /**
@@ -339,7 +337,11 @@ function currentRightbarWidth(handle: HTMLElement, viewport: number): number | u
339
337
  const positioned = Number.parseFloat(handle.style.left)
340
338
  if (Number.isFinite(positioned) && positioned >= 0 && positioned <= viewport) {
341
339
  const width = viewport - positioned
342
- if (width > 0) return width
340
+ // A reading below the plausible minimum means the column has not settled
341
+ // yet (a restored panel animating in). Treating it as the base turns the
342
+ // delta into a huge overshoot that lands on DSH's 70 % clamp — the panel
343
+ // then opens far wider than the configured share (2026-11-23 report).
344
+ if (width >= RIGHTBAR_MIN_WIDTH / 2) return width
343
345
  }
344
346
  const column = document.querySelector<HTMLElement>(RIGHTBAR_COLUMN)
345
347
  if (column !== null) {