dsh-remote-vs 0.23.0 → 0.25.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 (81) hide show
  1. package/README.en.md +49 -15
  2. package/README.md +40 -14
  3. package/lib/client.js +45978 -43338
  4. package/lib/index.js +388 -90
  5. package/lib/p2-router-fs.js +1 -1
  6. package/lib/types/client/CodeEditor.d.ts +17 -0
  7. package/lib/types/client/EditorPane.d.ts +16 -5
  8. package/lib/types/client/FloatingPlaceholder.d.ts +16 -5
  9. package/lib/types/client/RemoteEditorView.d.ts +13 -10
  10. package/lib/types/client/RemoteRoot.d.ts +5 -5
  11. package/lib/types/client/SettingsHosts.d.ts +3 -0
  12. package/lib/types/client/TerminalSnippets.d.ts +36 -0
  13. package/lib/types/client/TerminalView.d.ts +1 -1
  14. package/lib/types/client/XTerm.d.ts +33 -0
  15. package/lib/types/client/api.d.ts +4 -1
  16. package/lib/types/client/auto-open-remote.d.ts +41 -0
  17. package/lib/types/client/editor-capability.d.ts +27 -0
  18. package/lib/types/client/i18n.d.ts +1 -1
  19. package/lib/types/client/store.d.ts +59 -4
  20. package/lib/types/client/terminal-input.d.ts +23 -0
  21. package/lib/types/client/terminal-snippets.d.ts +86 -0
  22. package/lib/types/client/use-remote-chat-target.d.ts +2 -0
  23. package/lib/types/client/view-settings.d.ts +40 -0
  24. package/lib/types/client/vsc/breadcrumb.d.ts +30 -0
  25. package/lib/types/client/vsc/editor-caret.d.ts +32 -0
  26. package/lib/types/client/vsc/editor-langs.d.ts +9 -0
  27. package/lib/types/client/vsc/editor-settings.d.ts +55 -0
  28. package/lib/types/client/vsc/image-preview.d.ts +36 -0
  29. package/lib/types/client/vsc/kit.d.ts +2 -0
  30. package/lib/types/client/vsc/terminal-clipboard.d.ts +15 -0
  31. package/lib/types/client/vsc/terminal-line.d.ts +25 -0
  32. package/lib/types/client/vsc/terminal-links.d.ts +62 -0
  33. package/lib/types/client/vsc/terminal-theme.d.ts +22 -0
  34. package/lib/types/client/vsc/terminal-writer.d.ts +52 -0
  35. package/lib/types/paths.d.ts +9 -0
  36. package/lib/types/pool.d.ts +25 -0
  37. package/lib/types/protocol.d.ts +35 -0
  38. package/lib/types/routes.d.ts +7 -0
  39. package/lib/types/terminal.d.ts +25 -1
  40. package/lib/types/view-settings.d.ts +26 -0
  41. package/lib/{worlds-DXdP4SMn.js → worlds-B7gEDBzC.js} +13 -1
  42. package/package.json +36 -36
  43. package/src/client/CodeEditor.tsx +54 -2
  44. package/src/client/EditorPane.tsx +485 -107
  45. package/src/client/FloatingPlaceholder.tsx +34 -5
  46. package/src/client/RemoteEditorView.tsx +14 -11
  47. package/src/client/RemoteRoot.tsx +20 -125
  48. package/src/client/SettingsHosts.tsx +81 -3
  49. package/src/client/TerminalSnippets.tsx +357 -0
  50. package/src/client/TerminalView.tsx +50 -1
  51. package/src/client/XTerm.tsx +228 -58
  52. package/src/client/api.ts +7 -0
  53. package/src/client/auto-open-remote.ts +439 -0
  54. package/src/client/editor-capability.ts +42 -0
  55. package/src/client/i18n.ts +158 -6
  56. package/src/client/index.tsx +30 -6
  57. package/src/client/store.tsx +165 -13
  58. package/src/client/terminal-input.ts +44 -0
  59. package/src/client/terminal-snippets.ts +216 -0
  60. package/src/client/use-remote-chat-target.ts +1 -1
  61. package/src/client/view-settings.ts +99 -0
  62. package/src/client/vsc/breadcrumb.tsx +251 -0
  63. package/src/client/vsc/editor-caret.ts +30 -0
  64. package/src/client/vsc/editor-langs.ts +20 -0
  65. package/src/client/vsc/editor-settings.ts +146 -0
  66. package/src/client/vsc/editor-theme.ts +4 -5
  67. package/src/client/vsc/image-preview.tsx +110 -0
  68. package/src/client/vsc/kit.tsx +20 -1
  69. package/src/client/vsc/terminal-clipboard.ts +19 -0
  70. package/src/client/vsc/terminal-line.ts +101 -0
  71. package/src/client/vsc/terminal-links.ts +166 -0
  72. package/src/client/vsc/terminal-theme.ts +71 -0
  73. package/src/client/vsc/terminal-writer.ts +112 -0
  74. package/src/client/vsc/vsc.css +687 -48
  75. package/src/index.ts +6 -0
  76. package/src/paths.ts +13 -0
  77. package/src/pool.ts +99 -27
  78. package/src/protocol.ts +45 -0
  79. package/src/routes.ts +47 -0
  80. package/src/terminal.ts +160 -6
  81. package/src/view-settings.ts +133 -0
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Editor view preferences (word wrap + font size), shared by every surface that
3
+ * shows the editor (the sidebar pane, the conversation-view tab, the floating
4
+ * window).
5
+ *
6
+ * Module-level, React/DOM-free on purpose: those three surfaces are three
7
+ * different React trees, so React state cannot carry "I made the font bigger in
8
+ * the floating window, dock it and the sidebar must show the same size" — which
9
+ * is the whole point (it is ONE editor, only its mount changes).
10
+ *
11
+ * The pure parse/serialize half is exported because the self-check harness
12
+ * imports this module in Node: it must not read localStorage at module load
13
+ * (private mode throws on `getItem`).
14
+ */
15
+
16
+ /** One shared view preference set. */
17
+ export interface EditorSettings {
18
+ /** Soft wrap the long lines. */
19
+ wrap: boolean
20
+ /** Editor type size in px (0.5 px steps are legal). */
21
+ fontSize: number
22
+ }
23
+
24
+ /** localStorage key: ONE JSON object, so the two fields cannot drift apart. */
25
+ export const EDITOR_SETTINGS_KEY = 'dsh-remote-vs.editor.settings'
26
+
27
+ /** Legal font-size range, shared with the floating window's Ctrl+wheel zoom. */
28
+ export const FONT_MIN = 9
29
+ export const FONT_MAX = 28
30
+ export const FONT_STEP = 1
31
+
32
+ /** Defaults used before anything was stored (matches the theme's 13px fallback). */
33
+ export const DEFAULT_EDITOR_SETTINGS: EditorSettings = { wrap: false, fontSize: 13 }
34
+
35
+ /** Clamp any input to a legal font size; non-numbers answer undefined. */
36
+ export function parseFontSize(value: unknown): number | undefined {
37
+ const numeric = typeof value === 'number'
38
+ ? value
39
+ : typeof value === 'string' && value.trim() !== ''
40
+ ? Number(value)
41
+ : Number.NaN
42
+ if (!Number.isFinite(numeric)) return undefined
43
+ // Half-pixel steps are legal (historically 12.5px); 13.3333 noise snaps to the grid.
44
+ const snapped = Math.round(numeric * 2) / 2
45
+ return Math.min(FONT_MAX, Math.max(FONT_MIN, snapped))
46
+ }
47
+
48
+ /** One zoom step (-1 = smaller, +1 = bigger), already clamped. */
49
+ export function stepFontSize(size: number, direction: -1 | 1): number {
50
+ const current = parseFontSize(size) ?? DEFAULT_EDITOR_SETTINGS.fontSize
51
+ return parseFontSize(current + direction * FONT_STEP) ?? current
52
+ }
53
+
54
+ /**
55
+ * Parse the persisted JSON.
56
+ *
57
+ * Anything damaged (not JSON, not an object, wrong field types) falls back to
58
+ * the defaults: this data only affects presentation, and a dirty localStorage
59
+ * entry must never keep the page from starting.
60
+ */
61
+ export function parseEditorSettings(raw: string | null | undefined): EditorSettings {
62
+ if (typeof raw !== 'string' || raw === '') return DEFAULT_EDITOR_SETTINGS
63
+ let parsed: unknown
64
+ try {
65
+ parsed = JSON.parse(raw) as unknown
66
+ } catch {
67
+ return DEFAULT_EDITOR_SETTINGS
68
+ }
69
+ if (typeof parsed !== 'object' || parsed === null) return DEFAULT_EDITOR_SETTINGS
70
+ const record = parsed as Record<string, unknown>
71
+ const fontSize = parseFontSize(record.fontSize) ?? DEFAULT_EDITOR_SETTINGS.fontSize
72
+ const wrap = typeof record.wrap === 'boolean' ? record.wrap : DEFAULT_EDITOR_SETTINGS.wrap
73
+ return { wrap, fontSize }
74
+ }
75
+
76
+ /** Serialize only the known fields (never whatever else the caller passed). */
77
+ export function serializeEditorSettings(settings: EditorSettings): string {
78
+ return JSON.stringify({ wrap: settings.wrap, fontSize: settings.fontSize })
79
+ }
80
+
81
+ // ------------------------------------------------------------------ store
82
+
83
+ const listeners = new Set<() => void>()
84
+ /** Lazy current value; undefined = localStorage not read yet. */
85
+ let current: EditorSettings | undefined
86
+
87
+ function readFromStorage(): EditorSettings {
88
+ try {
89
+ return parseEditorSettings(localStorage.getItem(EDITOR_SETTINGS_KEY))
90
+ } catch {
91
+ // Private mode / storage disabled: the defaults still work this session.
92
+ return DEFAULT_EDITOR_SETTINGS
93
+ }
94
+ }
95
+
96
+ function persist(settings: EditorSettings): void {
97
+ try {
98
+ localStorage.setItem(EDITOR_SETTINGS_KEY, serializeEditorSettings(settings))
99
+ } catch {
100
+ // Same as above: failing to persist does not affect this session.
101
+ }
102
+ }
103
+
104
+ function emit(): void {
105
+ for (const listener of [...listeners]) {
106
+ try {
107
+ listener()
108
+ } catch {
109
+ // One broken surface must not starve the others.
110
+ }
111
+ }
112
+ }
113
+
114
+ /** Current snapshot (identity-stable while unchanged, safe for useSyncExternalStore). */
115
+ export function editorSettingsSnapshot(): EditorSettings {
116
+ if (current === undefined) current = readFromStorage()
117
+ return current
118
+ }
119
+
120
+ /** Subscribe to preference changes; returns the unsubscribe. */
121
+ export function subscribeEditorSettings(listener: () => void): () => void {
122
+ listeners.add(listener)
123
+ return () => {
124
+ listeners.delete(listener)
125
+ }
126
+ }
127
+
128
+ /**
129
+ * Change one preference and persist it.
130
+ *
131
+ * Illegal values (out-of-range size) are clamped BEFORE the "did it change"
132
+ * comparison: without that, every click on a "+" already at the cap would
133
+ * re-render all three surfaces for nothing.
134
+ */
135
+ export function updateEditorSettings(patch: Partial<EditorSettings>): void {
136
+ const before = editorSettingsSnapshot()
137
+ const fontSize = patch.fontSize === undefined
138
+ ? before.fontSize
139
+ : parseFontSize(patch.fontSize) ?? before.fontSize
140
+ const wrap = patch.wrap === undefined ? before.wrap : patch.wrap
141
+ if (fontSize === before.fontSize && wrap === before.wrap) return
142
+ const next: EditorSettings = { wrap, fontSize }
143
+ current = next
144
+ persist(next)
145
+ emit()
146
+ }
@@ -29,11 +29,10 @@ function chrome(p: Palette, dark: boolean): Extension {
29
29
  '&': {
30
30
  backgroundColor: p.bg,
31
31
  color: p.fg,
32
- // The floating window changes ONLY its own editor's type size (Ctrl+wheel,
33
- // see FloatingEditorWindow); the variable is unset everywhere else, so the
34
- // normal editor keeps 13px. A plain literal here would freeze the size and
35
- // make the zoom silently do nothing. The zoom is a property of the window,
36
- // so a docked editor always renders at the default size.
32
+ // Type size comes from a CSS variable: the docked pane and the
33
+ // conversation tab set it from the shared editor preference (font buttons /
34
+ // Ctrl+wheel), while the floating window sets it from its own per-window
35
+ // zoom. A plain literal here would freeze the size and make both silent.
37
36
  fontSize: 'var(--rvs-editor-font-size, 13px)',
38
37
  height: '100%',
39
38
  },
@@ -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',
@@ -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,71 @@
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
+ /** The dark scheme palette. */
19
+ export const DARK_TERMINAL_THEME: ITheme = {
20
+ background: '#0e0e13',
21
+ foreground: '#e8e8e8',
22
+ cursor: '#e8e8e8',
23
+ selectionBackground: '#264f78',
24
+ selectionInactiveBackground: '#333c48',
25
+ black: '#000000',
26
+ red: '#cd3131',
27
+ green: '#0dbc79',
28
+ yellow: '#e5e910',
29
+ blue: '#2472c8',
30
+ magenta: '#bc3fbc',
31
+ cyan: '#11a8cd',
32
+ white: '#e5e5e5',
33
+ brightBlack: '#7a7a7a',
34
+ brightRed: '#f14c4c',
35
+ brightGreen: '#23d18b',
36
+ brightYellow: '#f5f543',
37
+ brightBlue: '#3b8eea',
38
+ brightMagenta: '#d670d6',
39
+ brightCyan: '#29b8db',
40
+ brightWhite: '#ffffff',
41
+ }
42
+
43
+ /** The light scheme palette. */
44
+ export const LIGHT_TERMINAL_THEME: ITheme = {
45
+ background: '#ffffff',
46
+ foreground: '#1a1a1a',
47
+ cursor: '#1a1a1a',
48
+ selectionBackground: '#add6ff',
49
+ selectionInactiveBackground: '#d7e7f5',
50
+ black: '#000000',
51
+ red: '#cd3131',
52
+ green: '#00bc67',
53
+ yellow: '#949800',
54
+ blue: '#0451a5',
55
+ magenta: '#bc05bc',
56
+ cyan: '#0598bc',
57
+ white: '#555555',
58
+ brightBlack: '#666666',
59
+ brightRed: '#f14c4c',
60
+ brightGreen: '#23d18b',
61
+ brightYellow: '#f5f543',
62
+ brightBlue: '#3b8eea',
63
+ brightMagenta: '#d670d6',
64
+ brightCyan: '#29b8db',
65
+ brightWhite: '#ffffff',
66
+ }
67
+
68
+ /** The palette for one scheme. */
69
+ export function terminalTheme(dark: boolean): ITheme {
70
+ return dark ? DARK_TERMINAL_THEME : LIGHT_TERMINAL_THEME
71
+ }