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
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Inline image preview for the editor body.
3
+ *
4
+ * A remote image has no text to edit, so the editor shows the picture instead
5
+ * of the "binary file" notice. Presentation only: the base64 payload comes from
6
+ * the tab's read (the same SFTP read every other preview uses), and this
7
+ * component owns nothing but the fit / actual-size toggle and the load-failure
8
+ * state.
9
+ *
10
+ * Why an `<img>` with a `data:` URL and not an object URL: the payload already
11
+ * arrived base64 from the file route, so there is nothing extra to fetch — and
12
+ * nothing to revoke when the tab closes.
13
+ */
14
+ import { useState, type ReactNode } from 'react'
15
+
16
+ /** Props of {@link ImagePreview}. */
17
+ export interface ImagePreviewProps {
18
+ /** `data:` URL built from the tab's base64 payload. */
19
+ src: string
20
+ /** Absolute remote path (tooltip / aria label). */
21
+ path: string
22
+ /** File size in bytes (shown next to the dimensions). */
23
+ size: number
24
+ /** Set when the read was capped: a partial image cannot decode. */
25
+ truncated?: boolean
26
+ /** i18n lookup (falls back to the inline English when the key is missing). */
27
+ t?: (key: string) => string
28
+ }
29
+
30
+ /** Human size for the meta line. */
31
+ export function imageSizeText(bytes: number): string {
32
+ if (!Number.isFinite(bytes) || bytes <= 0) return '0 B'
33
+ if (bytes < 1024) return `${bytes} B`
34
+ if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`
35
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
36
+ }
37
+
38
+ /** Translate one key, falling back to the inline copy when the dictionary lacks it. */
39
+ function tr(t: ((key: string) => string) | undefined, key: string, fallback: string): string {
40
+ const value = t?.(key)
41
+ return value === undefined || value === '' || value === key ? fallback : value
42
+ }
43
+
44
+ /**
45
+ * The preview body: the image, a click-to-toggle zoom, and a meta line.
46
+ *
47
+ * `fit` scales the picture down to the pane (the common case: look at it);
48
+ * `actual` shows it at natural size inside a scrollable pane (inspect pixels).
49
+ */
50
+ export function ImagePreview(props: ImagePreviewProps): ReactNode {
51
+ const [actual, setActual] = useState(false)
52
+ const [failed, setFailed] = useState(false)
53
+ const [natural, setNatural] = useState<{ width: number; height: number } | undefined>(undefined)
54
+ const hint = tr(props.t, 'editor.imageHint', '点击切换适应窗口 / 原始大小')
55
+ const meta = [
56
+ imageSizeText(props.size),
57
+ natural === undefined ? '' : `${natural.width} × ${natural.height}`,
58
+ ].filter((part) => part !== '').join(' · ')
59
+ if (props.truncated === true) {
60
+ return (
61
+ <div className="rvs-editor-notice">
62
+ <div className="rvs-editor-notice-title">{tr(props.t, 'editor.imageTooLargeTitle', '图片过大')}</div>
63
+ <div>{props.path}</div>
64
+ <div>
65
+ {tr(props.t, 'editor.imageTooLargeHint', '大小 {size} KiB,超出读取上限,不提供预览。')
66
+ .replace('{size}', String(Math.max(1, Math.round(props.size / 1024))))}
67
+ </div>
68
+ </div>
69
+ )
70
+ }
71
+ if (failed) {
72
+ return (
73
+ <div className="rvs-image-preview rvs-image-preview-failed">
74
+ <div className="rvs-editor-notice-title">{tr(props.t, 'editor.imageFailed', '图片读取失败。')}</div>
75
+ <div>{props.path}</div>
76
+ <div>{tr(props.t, 'editor.imageFailedHint', '文件可能已损坏,或不是受支持的图片格式。')}</div>
77
+ </div>
78
+ )
79
+ }
80
+ return (
81
+ <div
82
+ className={`rvs-image-preview${actual ? ' rvs-image-actual' : ''}`}
83
+ title={`${props.path}\n${hint}`}
84
+ role="img"
85
+ aria-label={props.path}
86
+ onClick={() => setActual((value) => !value)}
87
+ >
88
+ <img
89
+ className="rvs-image-preview-img"
90
+ src={props.src}
91
+ alt={props.path}
92
+ draggable={false}
93
+ onDragStart={(event) => event.preventDefault()}
94
+ onLoad={(event) => {
95
+ setNatural({
96
+ width: event.currentTarget.naturalWidth,
97
+ height: event.currentTarget.naturalHeight,
98
+ })
99
+ }}
100
+ onError={() => setFailed(true)}
101
+ />
102
+ <div className="rvs-image-preview-meta">
103
+ <span>{meta}</span>
104
+ <span className="rvs-image-preview-hint">{actual
105
+ ? tr(props.t, 'editor.imageFitHint', '点击适应窗口')
106
+ : hint}</span>
107
+ </div>
108
+ </div>
109
+ )
110
+ }
@@ -279,6 +279,16 @@ export function IconDiff(props: IconProps): ReactNode {
279
279
  return svg(props.size ?? 14, <path d="M2.6 3.6h10.8M5.4 8h8M5.4 12.4h8M2.6 8h.01M2.6 12.4h.01" />, props.className)
280
280
  }
281
281
 
282
+ /** Float / pop-out: a small frame with an arrow leaving its top-right corner. */
283
+ export function IconFloat(props: IconProps): ReactNode {
284
+ return svg(props.size ?? 13, (
285
+ <>
286
+ <path d="M9.4 2.6h4v4M13.4 2.6 8.4 7.6" />
287
+ <path d="M12.6 9.4v3.2a.8.8 0 0 1-.8.8H3a.8.8 0 0 1-.8-.8V4a.8.8 0 0 1 .8-.8h3.4" />
288
+ </>
289
+ ), props.className)
290
+ }
291
+
282
292
  export function IconImage(props: IconProps): ReactNode {
283
293
  return svg(props.size ?? 14, <path d="M2.4 3.4h11.2v9.2H2.4zM5.4 6.6h.01M9.6 12.6 6.8 9.4l-2 2.4M9.6 12.6l2.4-3.2 1.6 1.8" />, props.className)
284
294
  }
@@ -362,7 +372,16 @@ export function ExplorerFolderIcon(props: { path: string; open: boolean; size?:
362
372
 
363
373
  // ------------------------------------------------------------- file kinds
364
374
 
365
- const IMAGE_EXTS = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg', 'bmp', 'ico', 'avif'])
375
+ /**
376
+ * Raster formats the editor previews as pictures.
377
+ *
378
+ * SVG is deliberately NOT here: it is UTF-8 markup, editing it as text is
379
+ * genuinely useful, and the host only ships base64 for files it classified as
380
+ * binary — an SVG would arrive as text with no payload, so an "image" tab could
381
+ * neither render it nor edit it (reported by review 2026-11-23). `mimeFor` keeps
382
+ * the `image/svg+xml` entry for callers that only need a MIME type.
383
+ */
384
+ const IMAGE_EXTS = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico', 'avif'])
366
385
  const MIME: Record<string, string> = {
367
386
  png: 'image/png',
368
387
  jpg: 'image/jpeg',
@@ -635,13 +654,22 @@ export function DialogHost(): ReactNode {
635
654
  return createPortal(
636
655
  <>
637
656
  {request !== undefined && <ModalCard key={request.id} request={request} />}
638
- {items.length > 0 && (
639
- <div className="rvs-toasts">
640
- {items.map(item => (
641
- <div key={item.id} className={item.error ? 'rvs-toast error' : 'rvs-toast'}>{item.text}</div>
642
- ))}
643
- </div>
644
- )}
657
+ {/* Toast is the plugin's only report channel for "已上传 / 删除失败 / 已推送":
658
+ without a live region a screen reader never heard any of it (WCAG 4.1.3).
659
+ The stack is mounted even while empty so the region EXISTS before the
660
+ message arrives — a `role=status` region inserted together with its text
661
+ is announced by some screen readers and missed by others. It stays
662
+ polite; an error item asserts on its own, so a failure interrupts and a
663
+ success does not. (An empty stack is a zero-sized fixed box: no paint.) */}
664
+ <div className="rvs-toasts" role="status" aria-live="polite">
665
+ {items.map(item => (
666
+ <div
667
+ key={item.id}
668
+ className={item.error ? 'rvs-toast error' : 'rvs-toast'}
669
+ role={item.error ? 'alert' : undefined}
670
+ >{item.text}</div>
671
+ ))}
672
+ </div>
645
673
  </>,
646
674
  document.body,
647
675
  )
@@ -651,9 +679,13 @@ export function DialogHost(): ReactNode {
651
679
  * Focusable elements inside one dialog, in DOM order.
652
680
  *
653
681
  * The modal is portaled to the END of `<body>`, so without a Tab trap a
654
- * keyboard user tabs through the whole page to reach its buttons.
682
+ * keyboard user tabs through the whole page to reach its buttons. Exported for
683
+ * the other portaled layers that need the same walk (the terminal snippet
684
+ * popover); `DoctorPanel` keeps its own copy because it deliberately does not
685
+ * import this module (its copy path must not use the silently-failing
686
+ * `copyText`, which `check-doctor.mjs` pins).
655
687
  */
656
- function focusables(root: HTMLElement | null): HTMLElement[] {
688
+ export function focusables(root: HTMLElement | null): HTMLElement[] {
657
689
  if (root === null) return []
658
690
  return Array.from(root.querySelectorAll<HTMLElement>(
659
691
  'button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',
@@ -689,6 +721,10 @@ function ModalCard(props: { request: ModalRequest }): ReactNode {
689
721
 
690
722
  useEffect(() => {
691
723
  const onKey = (e: KeyboardEvent): void => {
724
+ // An IME candidate window owns Enter/Escape while composing: acting here
725
+ // would resolve the prompt with a half-composed value (or cancel it while
726
+ // the candidate list is open).
727
+ if (e.isComposing === true || e.keyCode === 229) return
692
728
  if (e.key === 'Escape') {
693
729
  e.preventDefault()
694
730
  request.resolve(request.kind === 'prompt' ? undefined : false)
@@ -40,8 +40,12 @@ export interface SaveShortcutEvent {
40
40
  * A terminal (xterm) forwards keys to the remote shell and a themed dialog's
41
41
  * input is mid-edit; hijacking the key there would be a surprise, and for the
42
42
  * shell it would also steal a control character (`^S`).
43
+ *
44
+ * Exported so the plugin's OTHER window-level shortcut (Ctrl+P in `RemoteRoot`)
45
+ * draws the same line instead of re-inventing a narrower one — it used to
46
+ * exclude only `.xterm` and hijacked the host's chat composer.
43
47
  */
44
- const FOREIGN_TARGET = '.xterm, textarea, input, [contenteditable="true"]'
48
+ export const FOREIGN_TARGET = '.xterm, textarea, input, [contenteditable="true"]'
45
49
 
46
50
  /**
47
51
  * Is this the save shortcut this module should act on?
@@ -86,8 +90,50 @@ const resolvers = new Set<SaveShortcutResolver>()
86
90
  /** True while the single window listener is installed. */
87
91
  let listening = false
88
92
 
93
+ /**
94
+ * The layers that own the keyboard while they are open.
95
+ *
96
+ * Mirrors the modal selector the host's own shortcut dispatcher trims commands
97
+ * with (`[role="dialog"][aria-modal="true"], [role="menu"]` in
98
+ * `@deepseek-ai/dsh-client-shortcuts`). These window listeners register nothing
99
+ * with `ctx.shortcuts`, so no host mechanism keeps them from firing THROUGH a
100
+ * dialog. Blanket on purpose: our own `.rvs-modal-mask`, QuickOpen and the
101
+ * context menus are modal too, and a global shortcut must not pierce those
102
+ * either. A caller that owns a layer and wants a toggle inside it (Ctrl+P
103
+ * closes QuickOpen) skips this check while its own layer is up.
104
+ *
105
+ * `role="menu"` is the one exception to the blanket: it is what the host's
106
+ * dispatcher treats as modal, but a NON-modal picker floats over the editor
107
+ * while the editor is still the surface in use, so swallowing Ctrl+S there was
108
+ * a real regression (audit NIT-5). Such a menu opts out with
109
+ * `[data-rvs-nonmodal]` — the breadcrumb dropdown (`vsc/breadcrumb.tsx`) carries
110
+ * it now, so no class-name bridge is needed.
111
+ * RESIDUAL, deliberately conservative: any future non-modal menu that carries
112
+ * neither marker still swallows Ctrl+S, and a modal layer that lacks
113
+ * `aria-modal="true"` is not caught by the dialog branch. Failing safe matters
114
+ * more here than a missed save: the alternative is writing a remote file
115
+ * underneath a layer the user is answering.
116
+ */
117
+ const MODAL_LAYER = '[role="dialog"][aria-modal="true"], '
118
+ + '[role="menu"]:not([data-rvs-nonmodal])'
119
+
120
+ /**
121
+ * Is a modal layer (host approval / settings, our own dialog, an open menu) on
122
+ * screen right now?
123
+ *
124
+ * Called from the DOM listener entry points only: `isSaveShortcut` stays a pure
125
+ * predicate on the event. Without it Ctrl+S silently saved the remote file
126
+ * underneath a pending host approval dialog — a write the user never confirmed.
127
+ */
128
+ export function isModalLayerOpen(): boolean {
129
+ if (typeof document === 'undefined') return false
130
+ return document.querySelector(MODAL_LAYER) !== null
131
+ }
132
+
89
133
  function onKeyDown(event: KeyboardEvent): void {
90
134
  if (!isSaveShortcut(event)) return
135
+ // A dialog or menu on screen owns the keyboard (see `isModalLayerOpen`).
136
+ if (isModalLayerOpen()) return
91
137
  for (const resolve of [...resolvers].reverse()) {
92
138
  const save = resolve()
93
139
  if (save === undefined) continue
@@ -78,6 +78,25 @@ export function chordTakesKey(chord: TerminalClipboardChord): boolean {
78
78
  return chord !== 'paste-native'
79
79
  }
80
80
 
81
+ /**
82
+ * Map ONE keyboard event to a terminal clipboard command.
83
+ *
84
+ * xterm calls its custom key handler for keydown, keyup AND keypress. Only the
85
+ * keydown PRESS is a command: handling keyup too ran every chord twice, which is
86
+ * what made Shift+Insert paste the clipboard twice (reported 2026-11-23) — two
87
+ * Clipboard-API reads and two input frames for one gesture, with no native paste
88
+ * event involved.
89
+ *
90
+ * Pure, so the gate can pin the "keyup is not a command" rule directly instead
91
+ * of matching source text.
92
+ */
93
+ export function terminalKeyCommand(
94
+ input: TerminalChordInput & { type: string },
95
+ ): TerminalClipboardChord | undefined {
96
+ if (input.type !== 'keydown') return undefined
97
+ return clipboardChordFor(input)
98
+ }
99
+
81
100
  /** Dependencies of {@link createPasteFallback}. */
82
101
  export interface PasteFallbackDeps {
83
102
  /** Clipboard read; `undefined` when the browser denies it. */
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Track what the user has typed on the CURRENT terminal line (pure).
3
+ *
4
+ * Why this exists: `Ctrl+B` should save the command the user is about to run as
5
+ * a snippet, pre-filled. The PTY protocol has no "current line" query, and asking
6
+ * the shell would mean typing into it — so the client reconstructs the line from
7
+ * the same `onData` stream it forwards: printable characters append, backspace
8
+ * removes, Enter/Ctrl+C/Ctrl+U clear, escape sequences (arrows, F-keys, history
9
+ * recall) are ignored.
10
+ *
11
+ * The result is a BEST-EFFORT draft, not a shell parser: after cursor movement or
12
+ * history recall it can differ from the real line. That is acceptable because it
13
+ * only pre-fills an editable form — nothing is executed, and the user can fix it.
14
+ */
15
+
16
+ /** Longest line worth remembering (a snippet's command is capped separately). */
17
+ export const TERMINAL_LINE_MAX = 4000
18
+
19
+ /**
20
+ * Apply one chunk of terminal INPUT to the current line.
21
+ *
22
+ * @param line - the line reconstructed so far.
23
+ * @param data - the chunk as handed to the PTY (bracketed-paste markers already
24
+ * stripped by the caller).
25
+ * @returns the new line.
26
+ */
27
+ export function applyTerminalInput(line: string, data: string): string {
28
+ if (data === '') return line
29
+ let next = line
30
+ /**
31
+ * Escape-sequence state: xterm hands whole control sequences (arrows, F-keys,
32
+ * history, mouse reports), and none of their bytes may become text.
33
+ *
34
+ * - `esc` just saw ESC: look at the introducer;
35
+ * - `csi` ESC `[` — consume until a final byte (0x40..0x7e);
36
+ * - `ss3` ESC `O` — consume exactly one more byte;
37
+ * - `osc` ESC `]` — consume until BEL or ESC `\`.
38
+ */
39
+ let escape: 'none' | 'esc' | 'csi' | 'ss3' | 'osc' | 'osc-esc' = 'none'
40
+ for (const character of data) {
41
+ const code = character.codePointAt(0) ?? 0
42
+ if (escape !== 'none') {
43
+ if (escape === 'esc') {
44
+ if (character === '[') escape = 'csi'
45
+ else if (character === 'O') escape = 'ss3'
46
+ else if (character === ']') escape = 'osc'
47
+ else escape = 'none'
48
+ continue
49
+ }
50
+ if (escape === 'csi') {
51
+ if (code >= 0x40 && code <= 0x7e) escape = 'none'
52
+ continue
53
+ }
54
+ if (escape === 'ss3') {
55
+ escape = 'none'
56
+ continue
57
+ }
58
+ // OSC: BEL ends it, ESC may start the ST terminator.
59
+ if (escape === 'osc') {
60
+ if (code === 0x07) escape = 'none'
61
+ else if (character === '\x1b') escape = 'osc-esc'
62
+ continue
63
+ }
64
+ // `osc-esc`: ESC `\` closes the OSC; anything else resumes the payload.
65
+ escape = character === '\\' ? 'none' : 'osc'
66
+ continue
67
+ }
68
+ if (character === '\r' || character === '\n') {
69
+ // The command was submitted (or a blank line was accepted).
70
+ next = ''
71
+ continue
72
+ }
73
+ if (character === '\x7f' || character === '\b') {
74
+ // Backspace deletes one CODE POINT (not one UTF-16 unit).
75
+ next = next.slice(0, next.length - Math.min(next.length, codePointLengthAtEnd(next)))
76
+ continue
77
+ }
78
+ // Ctrl+C / Ctrl+U / Ctrl+W abandon whatever was typed.
79
+ if (character === '\x03' || character === '\x15' || character === '\x17') {
80
+ next = ''
81
+ continue
82
+ }
83
+ if (character === '\x1b') {
84
+ escape = 'esc'
85
+ continue
86
+ }
87
+ // Other control characters (Ctrl+A/E/B/F/L, Tab completion, …) do not add
88
+ // text; they also do not erase what is there.
89
+ if (code < 0x20) continue
90
+ next += character
91
+ if (next.length > TERMINAL_LINE_MAX) next = next.slice(next.length - TERMINAL_LINE_MAX)
92
+ }
93
+ return next
94
+ }
95
+
96
+ /** UTF-16 length of the last code point in `value` (1 or 2). */
97
+ function codePointLengthAtEnd(value: string): number {
98
+ const last = value.charCodeAt(value.length - 1)
99
+ // A low surrogate means the last code point is a surrogate pair.
100
+ return last >= 0xdc00 && last <= 0xdfff ? 2 : 1
101
+ }
@@ -0,0 +1,166 @@
1
+ /**
2
+ * Terminal path links: find path-like tokens in a terminal line and turn them
3
+ * into absolute remote paths (pure, no xterm/DOM).
4
+ *
5
+ * The terminal prints paths constantly (compiler errors, `ls`, `grep`, logs) and
6
+ * the tree already knows how to reveal a folder over SFTP, so the missing piece
7
+ * is only "which text is a path, and what absolute path does it mean". Both
8
+ * questions are decided here; the xterm link provider and the store action are
9
+ * thin wiring on top.
10
+ *
11
+ * Scope decisions (kept deliberately conservative — a wrong jump is worse than a
12
+ * missing one):
13
+ * - absolute (`/opt/src/a.c`), home-relative (`~/build.log`) and relative
14
+ * tokens that contain a `/` (`v_sys/system/core.c`) are offered;
15
+ * - a `:line` / `:line:col` suffix is stripped (`src/a.ts:12:5` → `src/a.ts`);
16
+ * - URLs, flags (`--opt/x`) and pure numbers are not links;
17
+ * - resolution never guesses silently: it returns a CANDIDATE list, and the
18
+ * caller validates each candidate against the host before acting.
19
+ */
20
+
21
+ /** One path-looking range inside a terminal line. */
22
+ export interface TerminalPathToken {
23
+ /** 0-based index of the first character. */
24
+ start: number
25
+ /** 0-based index of the LAST character (inclusive). */
26
+ end: number
27
+ /** The path itself, with any `:line(:col)` suffix removed. */
28
+ path: string
29
+ }
30
+
31
+ /** Everything {@link resolutionCandidates} may use to anchor a relative token. */
32
+ export interface PathResolutionContext {
33
+ /** Remote home directory, when knowable (derived from the SSH user). */
34
+ home?: string
35
+ /** Shell working directory, when the shell reports it (OSC 7). */
36
+ cwd?: string
37
+ /** Remote workspace roots on this host, most specific first. */
38
+ roots?: readonly string[]
39
+ }
40
+
41
+ /**
42
+ * A run that may be a path: either an explicitly rooted form (`/`, `~/`, `./`,
43
+ * `../`) or a relative one that contains a `/` with a non-empty first segment.
44
+ */
45
+ const PATH_RUN = /(?:~\/|\/|\.{1,2}\/|[A-Za-z0-9_.@%+-]+\/)[A-Za-z0-9_.%+/@~-]*/g
46
+
47
+ /** Characters that end a path when they are the LAST character (sentence/quote noise). */
48
+ const TRAILING_NOISE = new Set(['.', ',', ':', ';', '!', '?', ')', ']', '}', '>', '"', "'", '`'])
49
+
50
+ /** `file.ts:12` / `file.ts:12:5` — the part editors and compilers append. */
51
+ const LOCATION_SUFFIX = /^(.*?):(\d+)(?::(\d+))?$/
52
+
53
+ /** Lower-case file extension-ish tail that a sentence dot must not eat. */
54
+ function stripLocationSuffix(raw: string): string {
55
+ const match = LOCATION_SUFFIX.exec(raw)
56
+ if (match === null) return raw
57
+ const base = match[1] ?? ''
58
+ // `10:30` is a time, not a path: a location suffix needs a path-shaped base
59
+ // (absolute or with a directory separator).
60
+ if (base === '' || !base.includes('/')) return raw
61
+ return base
62
+ }
63
+
64
+ /** Collapse `//`, resolve `.`/`..` and drop a trailing slash (POSIX semantics). */
65
+ export function normalizeRemotePath(path: string): string {
66
+ const absolute = path.startsWith('/')
67
+ const parts: string[] = []
68
+ for (const part of path.split('/')) {
69
+ if (part === '' || part === '.') continue
70
+ if (part === '..') {
71
+ if (parts.length > 0 && parts[parts.length - 1] !== '..') parts.pop()
72
+ else if (!absolute) parts.push('..')
73
+ continue
74
+ }
75
+ parts.push(part)
76
+ }
77
+ const joined = parts.join('/')
78
+ if (absolute) return parts.length === 0 ? '/' : `/${joined}`
79
+ return joined === '' ? '.' : joined
80
+ }
81
+
82
+ /** Join a base directory and a relative token (POSIX, no trailing slash). */
83
+ export function joinRemotePath(base: string, token: string): string {
84
+ return normalizeRemotePath(`${base.replace(/\/+$/, '')}/${token}`)
85
+ }
86
+
87
+ /** The parent directory of an absolute path (`/a/b/c` → `/a/b`; `/a` → `/`). */
88
+ export function parentDirectoryOf(path: string): string {
89
+ const normalized = normalizeRemotePath(path)
90
+ if (normalized === '/') return '/'
91
+ const cut = normalized.lastIndexOf('/')
92
+ return cut <= 0 ? '/' : normalized.slice(0, cut)
93
+ }
94
+
95
+ /** Whether `path` is `root` itself or lives under it. */
96
+ export function isWithinRoot(path: string, root: string): boolean {
97
+ const normalizedPath = normalizeRemotePath(path)
98
+ const normalizedRoot = normalizeRemotePath(root)
99
+ return normalizedPath === normalizedRoot || normalizedPath.startsWith(`${normalizedRoot.replace(/\/+$/, '')}/`)
100
+ }
101
+
102
+ /**
103
+ * Every path-looking token of one terminal line, in order.
104
+ *
105
+ * Trailing sentence punctuation is trimmed rather than excluded beforehand, so
106
+ * `see /opt/src/a.c.` links `a.c`; a location suffix is removed before that trim
107
+ * so `a.c:12` links `a.c` (not `a.c:12`).
108
+ */
109
+ export function findTerminalPathTokens(text: string): TerminalPathToken[] {
110
+ const tokens: TerminalPathToken[] = []
111
+ if (text === '') return tokens
112
+ PATH_RUN.lastIndex = 0
113
+ for (let match = PATH_RUN.exec(text); match !== null; match = PATH_RUN.exec(text)) {
114
+ const matchStart = match.index
115
+ // A match inside a URL (`https://example.com/a`) is a host fragment, not a
116
+ // remote path: the run starts after the `//`, so look at what precedes it.
117
+ if (matchStart > 0 && /:\/\/[^\s]*$/.test(text.slice(0, matchStart))) continue
118
+ let raw = match[0]
119
+ if (raw.includes('://')) continue
120
+ // The `//host/...` half of a URL, or a UNC-ish double slash: not a path the
121
+ // remote tree can reveal (`//` has implementation-defined meaning in POSIX).
122
+ if (raw.startsWith('//')) continue
123
+ if (raw.startsWith('-')) continue
124
+ raw = stripLocationSuffix(raw)
125
+ // Location stripping may leave noise (`a.c:12.` → `a.c:12` → `a.c`).
126
+ while (raw.length > 1 && TRAILING_NOISE.has(raw[raw.length - 1] as string)) raw = raw.slice(0, -1)
127
+ if (raw.length < 2) continue
128
+ // A bare `/` or `~/` is a directory symbol, not a jump target.
129
+ if (raw === '/' || raw === '~/' || raw === './' || raw === '../') continue
130
+ // `1/2` and `a/b` are legitimate; `2024/11/23` is a date, so require either a
131
+ // rooted form or a token with letters.
132
+ if (!raw.startsWith('/') && !raw.startsWith('~') && !/[A-Za-z_]/.test(raw)) continue
133
+ tokens.push({ start: matchStart, end: matchStart + raw.length - 1, path: raw })
134
+ }
135
+ return tokens
136
+ }
137
+
138
+ /**
139
+ * Absolute candidates for one token, in the order they should be validated.
140
+ *
141
+ * The caller stats each in turn (bounded) and acts on the first hit, which is
142
+ * why the order matters: the shell's reported cwd beats a workspace-root guess,
143
+ * and the home directory is the last resort (most relative paths a shell prints
144
+ * are relative to where the user is).
145
+ */
146
+ export function resolutionCandidates(token: string, ctx: PathResolutionContext = {}): string[] {
147
+ const out: string[] = []
148
+ const push = (candidate: string | undefined): void => {
149
+ if (candidate === undefined || candidate === '') return
150
+ const normalized = normalizeRemotePath(candidate)
151
+ if (!normalized.startsWith('/')) return
152
+ if (!out.includes(normalized)) out.push(normalized)
153
+ }
154
+ if (token.startsWith('/')) {
155
+ push(token)
156
+ return out
157
+ }
158
+ if (token.startsWith('~/')) {
159
+ if (ctx.home !== undefined && ctx.home !== '') push(joinRemotePath(ctx.home, token.slice(2)))
160
+ return out
161
+ }
162
+ if (ctx.cwd !== undefined && ctx.cwd !== '') push(joinRemotePath(ctx.cwd, token))
163
+ for (const root of ctx.roots ?? []) push(joinRemotePath(root, token))
164
+ if (ctx.home !== undefined && ctx.home !== '') push(joinRemotePath(ctx.home, token))
165
+ return out
166
+ }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * xterm colour theme, kept free of React/DOM so a gate can assert it.
3
+ *
4
+ * The palette is OPAQUE on purpose: xterm's contrast engine cannot reason about
5
+ * translucent colours, and a terminal over a wallpaper needs a definite surface.
6
+ *
7
+ * Selection colours are explicit per scheme. xterm's defaults assume a dark
8
+ * background, so in the light theme a selected block rendered white-on-white —
9
+ * copy worked while "selecting" looked like it did nothing (reported
10
+ * 2026-11-23). These are the VS Code selection colours, with a dimmer variant
11
+ * for an unfocused window.
12
+ *
13
+ * Only a TYPE import from xterm here: the module must stay loadable in Node for
14
+ * the gate (`@xterm/xterm`'s entry pulls CSS/UMD code).
15
+ */
16
+ import type { ITheme } from '@xterm/xterm'
17
+
18
+ /**
19
+ * The dark scheme palette.
20
+ *
21
+ * Contrast is measured against `background` (#0e0e13): the VS Code Dark+ ANSI
22
+ * set, with red / blue / magenta / brightBlack lifted just past 4.5:1 (`black`
23
+ * is left at #000000 on purpose — ANSI black is a background-fill colour by
24
+ * convention and is not read as text; 1.09:1). `brightCyan` is lifted off the
25
+ * plain cyan (#29b8db sat only ΔE76 6.0 from #11a8cd — the pair read as one
26
+ * colour) to #4dd0e1: ΔE76 18.5, 10.5:1 on the terminal surface.
27
+ */
28
+ export const DARK_TERMINAL_THEME: ITheme = {
29
+ background: '#0e0e13',
30
+ foreground: '#e8e8e8',
31
+ cursor: '#e8e8e8',
32
+ selectionBackground: '#264f78',
33
+ selectionInactiveBackground: '#333c48',
34
+ black: '#000000',
35
+ red: '#d54f4f',
36
+ green: '#0dbc79',
37
+ yellow: '#e5e910',
38
+ blue: '#2f7fd6',
39
+ magenta: '#cc55cc',
40
+ cyan: '#11a8cd',
41
+ white: '#e5e5e5',
42
+ brightBlack: '#858585',
43
+ brightRed: '#f14c4c',
44
+ brightGreen: '#23d18b',
45
+ brightYellow: '#f5f543',
46
+ brightBlue: '#3b8eea',
47
+ brightMagenta: '#d670d6',
48
+ brightCyan: '#4dd0e1',
49
+ brightWhite: '#ffffff',
50
+ }
51
+
52
+ /**
53
+ * The light scheme palette.
54
+ *
55
+ * Re-taken for a WHITE background (2026-11-23): the Dark+ ANSI set this used to
56
+ * copy measured 1.0–3.6:1 on #ffffff (brightWhite was white-on-white = 1.00,
57
+ * brightYellow 1.17). Text here is targeted at ≥4.5:1, and every colour is.
58
+ *
59
+ * "Bright" cannot mean "lighter" on white, so the bright group is the more
60
+ * saturated sibling of its hue rather than a lighter one; where a hue had to be
61
+ * re-picked the normal/bright pair keeps a visible difference. `brightWhite` is
62
+ * the one colour that has no readable white-ish form: it is #767676, the
63
+ * lightest neutral of the ramp, which keeps "bright white" distinguishable from
64
+ * `white`/`brightBlack` while reaching 4.54:1 (VS Code Light+ ships #e5e5e5,
65
+ * 1.05:1 — unreadable). `black` stays #000000 (ANSI background-fill convention).
66
+ * `brightCyan` moves to the teal step #0f766e: the previous #0e7490 sat ΔE76
67
+ * 4.0 from `cyan` (#0b6d84) and read as the same colour; the new value is ΔE76
68
+ * 20.5 away at 5.47:1.
69
+ */
70
+ export const LIGHT_TERMINAL_THEME: ITheme = {
71
+ background: '#ffffff',
72
+ foreground: '#1a1a1a',
73
+ cursor: '#1a1a1a',
74
+ selectionBackground: '#add6ff',
75
+ selectionInactiveBackground: '#d7e7f5',
76
+ black: '#000000',
77
+ red: '#b02a2a',
78
+ green: '#0b6b0b',
79
+ yellow: '#6f5f00',
80
+ blue: '#0451a5',
81
+ magenta: '#bc05bc',
82
+ cyan: '#0b6d84',
83
+ white: '#555555',
84
+ brightBlack: '#666666',
85
+ brightRed: '#cd3131',
86
+ brightGreen: '#107c10',
87
+ brightYellow: '#8a6d00',
88
+ brightBlue: '#1a6fc4',
89
+ brightMagenta: '#bd31bd',
90
+ brightCyan: '#0f766e',
91
+ brightWhite: '#767676',
92
+ }
93
+
94
+ /** The palette for one scheme. */
95
+ export function terminalTheme(dark: boolean): ITheme {
96
+ return dark ? DARK_TERMINAL_THEME : LIGHT_TERMINAL_THEME
97
+ }