dsh-remote-vs 0.25.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 (85) hide show
  1. package/README.en.md +11 -7
  2. package/README.md +10 -7
  3. package/THIRD-PARTY-NOTICES.md +188 -0
  4. package/lib/client.js +6512 -79961
  5. package/lib/index.js +1283 -992
  6. package/lib/p2-router-fs.js +1 -1
  7. package/lib/types/client/CodeEditor.d.ts +8 -0
  8. package/lib/types/client/RemoteExplorer.d.ts +53 -0
  9. package/lib/types/client/api.d.ts +37 -2
  10. package/lib/types/client/changes/review-state.d.ts +19 -0
  11. package/lib/types/client/connection.d.ts +16 -0
  12. package/lib/types/client/request-gate.d.ts +110 -0
  13. package/lib/types/client/scm/DiffView.d.ts +45 -7
  14. package/lib/types/client/scm/actions.d.ts +31 -3
  15. package/lib/types/client/store.d.ts +53 -0
  16. package/lib/types/client/vsc/FindWidget.d.ts +6 -0
  17. package/lib/types/client/vsc/change-marks.d.ts +16 -6
  18. package/lib/types/client/vsc/editor-keymap.d.ts +35 -1
  19. package/lib/types/client/vsc/kit.d.ts +11 -0
  20. package/lib/types/client/vsc/save-shortcut.d.ts +21 -0
  21. package/lib/types/client/vsc/terminal-theme.d.ts +28 -2
  22. package/lib/types/forward.d.ts +12 -0
  23. package/lib/types/fs-ops.d.ts +42 -0
  24. package/lib/types/http.d.ts +2 -0
  25. package/lib/types/keygen.d.ts +9 -0
  26. package/lib/types/monitor.d.ts +8 -0
  27. package/lib/types/notices.d.ts +16 -1
  28. package/lib/types/p2/helper-rpc.d.ts +45 -0
  29. package/lib/types/routes.d.ts +2 -0
  30. package/lib/types/store.d.ts +7 -0
  31. package/lib/types/terminal.d.ts +8 -0
  32. package/lib/types/view-settings.d.ts +5 -0
  33. package/lib/{worlds-B7gEDBzC.js → worlds-RG8K5eom.js} +113 -15
  34. package/package.json +2 -1
  35. package/src/client/CodeEditor.tsx +151 -8
  36. package/src/client/DirectoryFlow.tsx +16 -0
  37. package/src/client/DoctorPanel.tsx +70 -7
  38. package/src/client/EditorPane.tsx +63 -14
  39. package/src/client/HostsView.tsx +12 -3
  40. package/src/client/RemoteDirectoryPicker.tsx +12 -0
  41. package/src/client/RemoteExplorer.tsx +929 -40
  42. package/src/client/RemoteRoot.tsx +147 -22
  43. package/src/client/SearchView.tsx +8 -0
  44. package/src/client/TerminalSnippets.tsx +83 -8
  45. package/src/client/api.ts +106 -13
  46. package/src/client/changes/ChangesDock.tsx +188 -6
  47. package/src/client/changes/changes.css +10 -3
  48. package/src/client/changes/review-state.ts +34 -0
  49. package/src/client/connection.ts +29 -0
  50. package/src/client/downloads.ts +49 -4
  51. package/src/client/i18n.ts +82 -8
  52. package/src/client/request-gate.ts +221 -0
  53. package/src/client/scm/CommitPane.tsx +20 -2
  54. package/src/client/scm/DiffView.tsx +343 -117
  55. package/src/client/scm/HistoryPanel.tsx +23 -2
  56. package/src/client/scm/RepoPicker.tsx +1 -1
  57. package/src/client/scm/ScmPanel.tsx +391 -87
  58. package/src/client/scm/actions.ts +95 -12
  59. package/src/client/store.tsx +372 -9
  60. package/src/client/ui.tsx +4 -0
  61. package/src/client/vsc/FindWidget.tsx +24 -9
  62. package/src/client/vsc/breadcrumb.tsx +91 -3
  63. package/src/client/vsc/change-marks.ts +93 -44
  64. package/src/client/vsc/editor-keymap.ts +59 -1
  65. package/src/client/vsc/file-icons.tsx +17 -3
  66. package/src/client/vsc/kit.tsx +26 -9
  67. package/src/client/vsc/save-shortcut.ts +47 -1
  68. package/src/client/vsc/terminal-theme.ts +44 -18
  69. package/src/client/vsc/vsc.css +411 -153
  70. package/src/forward.ts +47 -9
  71. package/src/fs-ops.ts +124 -4
  72. package/src/git-ops.ts +20 -3
  73. package/src/http.ts +35 -4
  74. package/src/keygen.ts +55 -4
  75. package/src/monitor.ts +13 -0
  76. package/src/notices.ts +23 -1
  77. package/src/p2/helper-rpc.ts +113 -7
  78. package/src/p2/worlds.ts +14 -1
  79. package/src/routes.ts +212 -43
  80. package/src/sftp.ts +51 -14
  81. package/src/store.ts +10 -0
  82. package/src/terminal.ts +73 -26
  83. package/src/view-settings.ts +50 -10
  84. package/lib/types/client/Dialog.d.ts +0 -14
  85. package/src/client/Dialog.tsx +0 -76
@@ -9,12 +9,12 @@
9
9
  * the OPTIONAL full-width seat the editor's own button switches to.
10
10
  */
11
11
  import type { Context } from '@deepseek-ai/cordis'
12
- import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react'
12
+ import { memo, useCallback, useEffect, useRef, useState, type ReactNode } from 'react'
13
13
  import { api } from './api.ts'
14
14
  import { ConnectionStatusChip } from './ConnectionStatus.tsx'
15
15
  import { applyConnectionStatuses, isConnectionRecovery, setActiveConnectionAlias, useConnectionStatus, type ConnectionTrace } from './connection.ts'
16
- import { EditorPane } from './EditorPane.tsx'
17
- import { FloatingEditorPlaceholder } from './FloatingPlaceholder.tsx'
16
+ import { EditorPane as EditorPaneView } from './EditorPane.tsx'
17
+ import { FloatingEditorPlaceholder as FloatingEditorPlaceholderView } from './FloatingPlaceholder.tsx'
18
18
  import { DownloadDock } from './DownloadDock.tsx'
19
19
  import { PortsView, IconPlug } from './PortsView.tsx'
20
20
  import { MonitorView, IconMonitor } from './MonitorView.tsx'
@@ -25,9 +25,20 @@ import { HistoryPanel } from './scm/HistoryPanel.tsx'
25
25
  import { ScmPanel } from './scm/ScmPanel.tsx'
26
26
  import { TerminalView } from './TerminalView.tsx'
27
27
  import { WorkspacesView } from './WorkspacesView.tsx'
28
- import { useBootstrap, useExplorer, followSessionWorkspace, refreshAfterReconnect, setFollowSession } from './store.tsx'
28
+ import {
29
+ followSessionWorkspace,
30
+ refreshAfterReconnect,
31
+ selectWorkspace,
32
+ setFollowSession,
33
+ setView,
34
+ shallowEqual,
35
+ useBootstrap,
36
+ useExplorerSelector,
37
+ type ExplorerValue,
38
+ } from './store.tsx'
29
39
  import { useRemoteChatTarget } from './use-remote-chat-target.ts'
30
40
  import { DialogHost } from './vsc/kit.tsx'
41
+ import { FOREIGN_TARGET, isModalLayerOpen } from './vsc/save-shortcut.ts'
31
42
  import {
32
43
  IconBranch,
33
44
  IconCode,
@@ -78,6 +89,81 @@ export function planRecoveryReload(
78
89
  }
79
90
  }
80
91
 
92
+ /**
93
+ * What the SHELL itself renders — and nothing else.
94
+ *
95
+ * The shell used to subscribe to the whole snapshot (`useExplorer()`), so every
96
+ * publish repainted it: a save (3-4 publishes), a git status refresh, a tab
97
+ * dirty flag. Each of those renders re-created the element for every KEPT-ALIVE
98
+ * panel (the wrapper is always mounted, see `panelFor`) and — because a function
99
+ * component re-renders whenever its parent does — rebuilt all ten panels,
100
+ * including the 4000-row SCM change list.
101
+ *
102
+ * This slice is exactly what the root chrome paints (rail badges and title,
103
+ * workspace picker, branch pill, busy spinner, banner) plus what its effects
104
+ * need (tabs for the recovery timer, workspaces/aliasPaths for the session
105
+ * follow, terminalRequest for the terminal page). `useExplorerSelector` +
106
+ * `shallowEqual` repaint the shell only when one of these changes; the panels
107
+ * are memoized below, so even when the shell DOES render they are skipped
108
+ * unless their own props changed.
109
+ *
110
+ * Module-level so its identity is stable: between publishes the hook's cache
111
+ * answers without running the selector.
112
+ */
113
+ const selectShellStore = (snapshot: ExplorerValue) => ({
114
+ t: snapshot.t,
115
+ ready: snapshot.ready,
116
+ view: snapshot.view,
117
+ hosts: snapshot.hosts,
118
+ workspaces: snapshot.workspaces,
119
+ routing: snapshot.routing,
120
+ workspace: snapshot.workspace,
121
+ aliasPaths: snapshot.aliasPaths,
122
+ error: snapshot.error,
123
+ repoRoot: snapshot.repoRoot,
124
+ head: snapshot.head,
125
+ gitBusy: snapshot.gitBusy,
126
+ editorSurface: snapshot.editorSurface,
127
+ floatOpen: snapshot.floatOpen,
128
+ terminalRequest: snapshot.terminalRequest,
129
+ tabs: snapshot.tabs,
130
+ activeTab: snapshot.activeTab,
131
+ buckets: snapshot.buckets,
132
+ selectWorkspace: snapshot.selectWorkspace,
133
+ refreshAll: snapshot.refreshAll,
134
+ reloadTab: snapshot.reloadTab,
135
+ info: snapshot.info,
136
+ })
137
+
138
+ /**
139
+ * The kept-alive panels, memoized.
140
+ *
141
+ * `React.memo` compares PROPS shallowly: none of these panels is re-rendered
142
+ * just because their parent was — only when their own props changed. That is
143
+ * what makes the selector migration pay off, and it also covers local shell
144
+ * state (the Ctrl+P modal, `showHidden`, the IntersectionObserver's `live` bit)
145
+ * that used to drag every panel into a render.
146
+ *
147
+ * The props must therefore be STABLE while nothing changes for the panel:
148
+ * - `go`/`openHistory`/`openWorkspaceFiles`/`toggleHidden` below are
149
+ * `useCallback`s over module-level store actions, so they keep one identity;
150
+ * - the other props are strings, booleans or store references, compared with
151
+ * `Object.is` (and the store hands out the same reference until that value
152
+ * changes — see `selectShellStore`).
153
+ *
154
+ * `EditorPane` and `FloatingEditorPlaceholder` keep their original JSX names
155
+ * (a gate pins those call sites), so they are wrapped under their own name.
156
+ */
157
+ const MemoSearchView = memo(SearchView)
158
+ const MemoScmPanel = memo(ScmPanel)
159
+ const MemoHistoryPanel = memo(HistoryPanel)
160
+ const MemoTerminalView = memo(TerminalView)
161
+ const MemoPortsView = memo(PortsView)
162
+ const MemoMonitorView = memo(MonitorView)
163
+ const MemoWorkspacesView = memo(WorkspacesView)
164
+ const EditorPane = memo(EditorPaneView)
165
+ const FloatingEditorPlaceholder = memo(FloatingEditorPlaceholderView)
166
+
81
167
  export function RemoteRoot(props: { ctx: Context; visible?: boolean }): ReactNode {
82
168
  useBootstrap(props.ctx)
83
169
  return (
@@ -89,7 +175,7 @@ export function RemoteRoot(props: { ctx: Context; visible?: boolean }): ReactNod
89
175
  }
90
176
 
91
177
  function Shell(props: { ctx: Context; visible: boolean }): ReactNode {
92
- const store = useExplorer()
178
+ const store = useExplorerSelector(selectShellStore, shallowEqual)
93
179
  const t = store.t
94
180
  // The active panel lives in the shared store so other surfaces (the tree's
95
181
  // "Find in Folder…", the SCM panel's history shortcut) can switch it.
@@ -171,16 +257,35 @@ function Shell(props: { ctx: Context; visible: boolean }): ReactNode {
171
257
  if (!(event.ctrlKey || event.metaKey)) return
172
258
  if (event.altKey || event.shiftKey) return
173
259
  if (event.key !== 'p' && event.key !== 'P') return
260
+ // Claimed even when the handler steps aside below: the browser's print
261
+ // dialog must never appear behind a layer that owns the keyboard.
174
262
  event.preventDefault()
175
263
  // Auto-repeat would flash the modal on a held key.
176
264
  if (event.repeat) return
177
- const focused = document.activeElement
178
- if (focused instanceof HTMLElement && focused.closest('.xterm') !== null) return
265
+ // While OUR modal is up, Ctrl+P is its documented "press again to leave",
266
+ // so the guards below (which belong to OPENING it) must not run.
267
+ if (!quickOpen) {
268
+ // A dialog or menu on screen owns the keyboard: opening QuickOpen over a
269
+ // host approval / the Settings dialog would steal the focus from the
270
+ // layer the user is answering (audit I-2).
271
+ if (isModalLayerOpen()) return
272
+ const focused = document.activeElement
273
+ if (focused instanceof HTMLElement && focused.closest('.xterm') !== null) return
274
+ // Every other text field keeps Ctrl+P too — the host's chat composer, a
275
+ // dialog input — i.e. the same FOREIGN_TARGET the save shortcut yields
276
+ // to, so both global shortcuts draw one line (audit I-11). Our own
277
+ // CodeMirror surface is the exception: editing is the state quick open is
278
+ // FOR, and CodeMirror marks its content `contenteditable`, which the
279
+ // shared list would otherwise turn into "Ctrl+P does nothing here".
280
+ if (focused instanceof HTMLElement
281
+ && focused.closest(FOREIGN_TARGET) !== null
282
+ && focused.closest('.cm-content') === null) return
283
+ }
179
284
  setQuickOpen(open => !open)
180
285
  }
181
286
  window.addEventListener('keydown', onQuickOpenKey)
182
287
  return () => window.removeEventListener('keydown', onQuickOpenKey)
183
- }, [live, storeReady])
288
+ }, [live, storeReady, quickOpen])
184
289
 
185
290
  /**
186
291
  * Leaving the panel closes the modal.
@@ -193,9 +298,28 @@ function Shell(props: { ctx: Context; visible: boolean }): ReactNode {
193
298
  if (!live) setQuickOpen(false)
194
299
  }, [live])
195
300
 
301
+ /**
302
+ * Stable identities for the panel props below: a `useCallback` over a
303
+ * MODULE-level store action (`setView`/`selectWorkspace`), not over the slice
304
+ * object — the slice changes whenever any chrome field does, which would make
305
+ * every prop refresh and defeat `React.memo` on the panels.
306
+ */
196
307
  const go = useCallback((next: RailView): void => {
197
- store.setView(next)
198
- }, [store])
308
+ setView(next)
309
+ }, [])
310
+ /** The SCM panel's "history →" shortcut (stable, see above). */
311
+ const openHistory = useCallback((): void => {
312
+ setView('history')
313
+ }, [])
314
+ /** The workspace wizard's "open files" (stable, see above). */
315
+ const openWorkspaceFiles = useCallback((value: string): void => {
316
+ selectWorkspace(value)
317
+ setView('explorer')
318
+ }, [])
319
+ /** Arrow for `RemoteExplorer`'s "show hidden" toggle (stable, see above). */
320
+ const toggleHidden = useCallback((): void => {
321
+ setShowHidden(v => !v)
322
+ }, [])
199
323
 
200
324
  /**
201
325
  * Connection status: point the client view at the workspace's host and poll
@@ -241,8 +365,9 @@ function Shell(props: { ctx: Context; visible: boolean }): ReactNode {
241
365
  * user's edits away) and the user is told so. Read-only DIFF tabs have no
242
366
  * unsaved edits, so they are reloaded like clean file tabs.
243
367
  *
244
- * Deps are intentionally just the state: `store` identity changes on every
245
- * publish, and re-running this on any publish would re-fire the refresh loop.
368
+ * Deps are intentionally just the connection state: the store slice changes
369
+ * whenever any chrome field does, and re-running this on those changes would
370
+ * re-fire the refresh loop.
246
371
  */
247
372
  const lastConnection = useRef<ConnectionTrace | undefined>(undefined)
248
373
  // Live mirrors for the settle timer below (it fires long after the effect ran).
@@ -352,32 +477,32 @@ function Shell(props: { ctx: Context; visible: boolean }): ReactNode {
352
477
  */
353
478
  const panelFor = (id: RailView): ReactNode => {
354
479
  switch (id) {
355
- case 'search': return <SearchView />
356
- case 'scm': return <ScmPanel onOpenHistory={() => go('history')} visible={panelLive('scm')} />
357
- case 'history': return <HistoryPanel />
480
+ case 'search': return <MemoSearchView />
481
+ case 'scm': return <MemoScmPanel onOpenHistory={openHistory} visible={panelLive('scm')} />
482
+ case 'history': return <MemoHistoryPanel />
358
483
  case 'terminal':
359
484
  // The terminal draws its own header + tab strip, so it takes the whole
360
485
  // slot (no extra padding wrapper).
361
- return <TerminalView t={t} hosts={store.hosts} visible={panelLive('terminal')} request={store.terminalRequest} />
486
+ return <MemoTerminalView t={t} hosts={store.hosts} visible={panelLive('terminal')} request={store.terminalRequest} />
362
487
  case 'ports':
363
488
  // Same shape as the terminal: its own header (host picker + refresh) and
364
489
  // its own scroller, so no viewpad wrapper either.
365
- return <PortsView t={t} hosts={store.hosts} visible={panelLive('ports')} />
490
+ return <MemoPortsView t={t} hosts={store.hosts} visible={panelLive('ports')} />
366
491
  case 'monitor':
367
492
  // Live host metrics: own header (scope picker + refresh/pause) and its
368
493
  // own scroller. Cross-host by design, so it reads `store.hosts` rather
369
494
  // than the current binding.
370
- return <MonitorView t={t} hosts={store.hosts} visible={panelLive('monitor')} />
495
+ return <MemoMonitorView t={t} hosts={store.hosts} visible={panelLive('monitor')} />
371
496
  case 'workspaces':
372
497
  return (
373
498
  <div className="rvs-viewpad" style={{ height: '100%' }}>
374
- <WorkspacesView
499
+ <MemoWorkspacesView
375
500
  t={t}
376
501
  hosts={store.hosts}
377
502
  workspaces={store.workspaces}
378
503
  routing={store.routing}
379
504
  onChanged={store.refreshAll}
380
- onOpenFiles={(value) => { store.selectWorkspace(value); go('explorer') }}
505
+ onOpenFiles={openWorkspaceFiles}
381
506
  />
382
507
  </div>
383
508
  )
@@ -397,7 +522,7 @@ function Shell(props: { ctx: Context; visible: boolean }): ReactNode {
397
522
  return (
398
523
  <RemoteExplorer
399
524
  showHidden={showHidden}
400
- onToggleHidden={() => setShowHidden(v => !v)}
525
+ onToggleHidden={toggleHidden}
401
526
  visible={panelLive('explorer')}
402
527
  />
403
528
  )
@@ -475,7 +600,7 @@ function Shell(props: { ctx: Context; visible: boolean }): ReactNode {
475
600
  )}
476
601
  {store.gitBusy && <MiniSpinner />}
477
602
  </div>
478
- {store.error !== undefined && <div className="rvs-banner error">{store.error}</div>}
603
+ {store.error !== undefined && <div className="rvs-banner error" role="status">{store.error}</div>}
479
604
  <div className="rvs-pane" style={{ flex: 1, minHeight: 0 }}>
480
605
  {panel}
481
606
  </div>
@@ -507,6 +507,14 @@ export function SearchView(): ReactNode {
507
507
  spellCheck={false}
508
508
  onChange={(e) => setQuery(e.target.value)}
509
509
  onKeyDown={(e) => {
510
+ // An IME candidate window uses Enter to pick a character and Escape
511
+ // to drop it. Searching then would submit a half-composed query,
512
+ // and clearing the field would wipe the composing text; skipping
513
+ // preventDefault keeps the candidate commit alive. `isComposing` is
514
+ // the platform-agnostic signal; `keyCode === 229` is the fallback
515
+ // for engines that dispatch compositionend before this keydown
516
+ // (Chrome), so that one Enter cannot run twice.
517
+ if (e.nativeEvent.isComposing === true || e.keyCode === 229) return
510
518
  if (e.key === 'Enter') {
511
519
  e.preventDefault()
512
520
  void run(query, mode, effectiveScope, options)
@@ -11,7 +11,16 @@
11
11
  * Snapshot + subscribe come from `terminal-snippets.ts` (one list shared with the
12
12
  * Ctrl+B quick-add shortcut, which `XTerm` reports as a counter prop).
13
13
  */
14
- import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from 'react'
14
+ import {
15
+ useCallback,
16
+ useEffect,
17
+ useMemo,
18
+ useRef,
19
+ useState,
20
+ useSyncExternalStore,
21
+ type KeyboardEvent as ReactKeyboardEvent,
22
+ type ReactNode,
23
+ } from 'react'
15
24
  import { createPortal } from 'react-dom'
16
25
  import {
17
26
  addSnippet,
@@ -23,7 +32,7 @@ import {
23
32
  updateSnippets,
24
33
  type TerminalSnippet,
25
34
  } from './terminal-snippets.ts'
26
- import { confirmDialog } from './vsc/kit.tsx'
35
+ import { confirmDialog, focusables } from './vsc/kit.tsx'
27
36
 
28
37
  /** Props of the panel (plus the button that opens it). */
29
38
  export interface TerminalSnippetsProps {
@@ -87,6 +96,57 @@ export function TerminalSnippets(props: TerminalSnippetsProps): ReactNode {
87
96
  setDropIndex(undefined)
88
97
  }, [])
89
98
 
99
+ /**
100
+ * The open panel owns the keyboard.
101
+ *
102
+ * It is portaled to the END of `<body>`, so a keyboard user who opened it from
103
+ * the ⚡ button otherwise had to Tab through the whole page to reach the first
104
+ * row. The first command is where the user wants to be; an empty library
105
+ * starts on the add button. Closing hands focus back to the trigger — but only
106
+ * when the user did not already put it somewhere else (closing by clicking the
107
+ * terminal must not steal the caret back).
108
+ */
109
+ useEffect(() => {
110
+ if (anchor === undefined) return
111
+ const panel = panelRef.current
112
+ if (panel === null) return
113
+ const first = panel.querySelector<HTMLElement>('.rvs-snips-insert') ?? focusables(panel)[0]
114
+ first?.focus()
115
+ return () => {
116
+ const active = document.activeElement
117
+ if (active === null || active === document.body || panelRef.current?.contains(active) === true) {
118
+ buttonRef.current?.focus()
119
+ }
120
+ }
121
+ }, [anchor])
122
+
123
+ /**
124
+ * List navigation inside the panel (audit I-9): ↑/↓ walk the command rows,
125
+ * Enter is the focused row's native button activation (so it inserts), and Esc
126
+ * is handled HERE, not on `document`: it used to be document-wide, so pressing
127
+ * Esc in the terminal closed the panel while the shell received the same ESC.
128
+ */
129
+ const onPanelKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>): void => {
130
+ if (event.nativeEvent.isComposing) return
131
+ if (event.key === 'Escape') {
132
+ event.preventDefault()
133
+ event.stopPropagation()
134
+ closePanel()
135
+ return
136
+ }
137
+ // Alt+↑/↓ is the grip's reorder chord; leave it to the row.
138
+ if (event.altKey) return
139
+ if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return
140
+ const panel = panelRef.current
141
+ if (panel === null) return
142
+ const rows = Array.from(panel.querySelectorAll<HTMLElement>('.rvs-snips-insert'))
143
+ if (rows.length === 0) return
144
+ event.preventDefault()
145
+ const at = rows.indexOf(document.activeElement as HTMLElement)
146
+ const next = event.key === 'ArrowDown' ? (at + 1) % rows.length : (at <= 0 ? rows.length - 1 : at - 1)
147
+ rows[next]?.focus()
148
+ }
149
+
90
150
  // Ctrl+B from the terminal: open the ADD form (and the panel behind it) with
91
151
  // the draft the terminal handed over — selection first, else the typed line.
92
152
  useEffect(() => {
@@ -96,9 +156,11 @@ export function TerminalSnippets(props: TerminalSnippetsProps): ReactNode {
96
156
  setForm({ mode: 'add', content: props.addContent })
97
157
  }, [props.addRequest, props.addContent, openPanel])
98
158
 
99
- // Close on outside click / Esc / window resize (a fixed popover would be left
159
+ // Close on outside click / window resize (a fixed popover would be left
100
160
  // pointing at nothing). Capture phase so xterm's own mousedown cannot refocus
101
- // the terminal first, which would make the panel look unclosable.
161
+ // the terminal first, which would make the panel look unclosable. Esc lives on
162
+ // the panel itself (see `onPanelKeyDown`): the keystroke must not be taken from
163
+ // the shell.
102
164
  useEffect(() => {
103
165
  if (anchor === undefined) return
104
166
  const onMouseDown = (event: MouseEvent): void => {
@@ -108,11 +170,23 @@ export function TerminalSnippets(props: TerminalSnippetsProps): ReactNode {
108
170
  if (buttonRef.current?.contains(target) === true) return
109
171
  closePanel()
110
172
  }
173
+ const onResize = (): void => closePanel()
174
+ /**
175
+ * Esc while the focus is anywhere EXCEPT the panel.
176
+ *
177
+ * The panel handles its own Esc when it has focus (`onPanelKeyDown`), but it
178
+ * can be visibly open while the focus sits elsewhere (clicking its title or
179
+ * scrolling it leaves the activeElement outside) — the old document-level
180
+ * handler closed it from anywhere. Restore that, but never steal Esc from
181
+ * the shell: a focus inside `.xterm` means the key belongs to the terminal.
182
+ */
111
183
  const onKeyDown = (event: KeyboardEvent): void => {
112
- if (event.isComposing) return
113
- if (event.key === 'Escape' && form === undefined) closePanel()
184
+ if (event.key !== 'Escape') return
185
+ const active = document.activeElement
186
+ if (active instanceof Node && panelRef.current?.contains(active) === true) return
187
+ if (active instanceof Element && active.closest('.xterm') !== null) return
188
+ closePanel()
114
189
  }
115
- const onResize = (): void => closePanel()
116
190
  document.addEventListener('mousedown', onMouseDown, true)
117
191
  document.addEventListener('keydown', onKeyDown, true)
118
192
  window.addEventListener('resize', onResize)
@@ -121,7 +195,7 @@ export function TerminalSnippets(props: TerminalSnippetsProps): ReactNode {
121
195
  document.removeEventListener('keydown', onKeyDown, true)
122
196
  window.removeEventListener('resize', onResize)
123
197
  }
124
- }, [anchor, form, closePanel])
198
+ }, [anchor, closePanel])
125
199
 
126
200
  /** Paste one command and get out of the way. */
127
201
  const insert = (snippet: TerminalSnippet): void => {
@@ -158,6 +232,7 @@ export function TerminalSnippets(props: TerminalSnippetsProps): ReactNode {
158
232
  className="rvs-portal rvs-snips-panel"
159
233
  role="dialog"
160
234
  aria-label={t('term.snippets')}
235
+ onKeyDown={onPanelKeyDown}
161
236
  style={{ left: `${anchor.left}px`, top: `${anchor.top}px`, width: `${anchor.width}px` }}
162
237
  >
163
238
  <div className="rvs-snips-head">
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 {