dsh-remote-vs 0.24.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 (61) hide show
  1. package/README.en.md +40 -10
  2. package/README.md +31 -9
  3. package/lib/client.js +2616 -542
  4. package/lib/index.js +186 -40
  5. package/lib/types/client/CodeEditor.d.ts +17 -0
  6. package/lib/types/client/EditorPane.d.ts +16 -5
  7. package/lib/types/client/FloatingPlaceholder.d.ts +16 -5
  8. package/lib/types/client/RemoteEditorView.d.ts +13 -10
  9. package/lib/types/client/RemoteRoot.d.ts +5 -5
  10. package/lib/types/client/TerminalSnippets.d.ts +36 -0
  11. package/lib/types/client/TerminalView.d.ts +1 -1
  12. package/lib/types/client/XTerm.d.ts +33 -0
  13. package/lib/types/client/editor-capability.d.ts +27 -0
  14. package/lib/types/client/i18n.d.ts +1 -1
  15. package/lib/types/client/store.d.ts +59 -4
  16. package/lib/types/client/terminal-input.d.ts +23 -0
  17. package/lib/types/client/terminal-snippets.d.ts +86 -0
  18. package/lib/types/client/vsc/breadcrumb.d.ts +30 -0
  19. package/lib/types/client/vsc/editor-caret.d.ts +32 -0
  20. package/lib/types/client/vsc/editor-langs.d.ts +9 -0
  21. package/lib/types/client/vsc/editor-settings.d.ts +55 -0
  22. package/lib/types/client/vsc/image-preview.d.ts +36 -0
  23. package/lib/types/client/vsc/kit.d.ts +2 -0
  24. package/lib/types/client/vsc/terminal-clipboard.d.ts +15 -0
  25. package/lib/types/client/vsc/terminal-line.d.ts +25 -0
  26. package/lib/types/client/vsc/terminal-links.d.ts +62 -0
  27. package/lib/types/client/vsc/terminal-theme.d.ts +22 -0
  28. package/lib/types/client/vsc/terminal-writer.d.ts +52 -0
  29. package/lib/types/pool.d.ts +25 -0
  30. package/lib/types/terminal.d.ts +25 -1
  31. package/package.json +1 -1
  32. package/src/client/CodeEditor.tsx +54 -2
  33. package/src/client/EditorPane.tsx +485 -107
  34. package/src/client/FloatingPlaceholder.tsx +34 -5
  35. package/src/client/RemoteEditorView.tsx +14 -11
  36. package/src/client/RemoteRoot.tsx +20 -125
  37. package/src/client/TerminalSnippets.tsx +357 -0
  38. package/src/client/TerminalView.tsx +50 -1
  39. package/src/client/XTerm.tsx +228 -58
  40. package/src/client/auto-open-remote.ts +11 -9
  41. package/src/client/editor-capability.ts +42 -0
  42. package/src/client/i18n.ts +148 -6
  43. package/src/client/index.tsx +22 -6
  44. package/src/client/store.tsx +165 -13
  45. package/src/client/terminal-input.ts +44 -0
  46. package/src/client/terminal-snippets.ts +216 -0
  47. package/src/client/vsc/breadcrumb.tsx +251 -0
  48. package/src/client/vsc/editor-caret.ts +30 -0
  49. package/src/client/vsc/editor-langs.ts +20 -0
  50. package/src/client/vsc/editor-settings.ts +146 -0
  51. package/src/client/vsc/editor-theme.ts +4 -5
  52. package/src/client/vsc/image-preview.tsx +110 -0
  53. package/src/client/vsc/kit.tsx +20 -1
  54. package/src/client/vsc/terminal-clipboard.ts +19 -0
  55. package/src/client/vsc/terminal-line.ts +101 -0
  56. package/src/client/vsc/terminal-links.ts +166 -0
  57. package/src/client/vsc/terminal-theme.ts +71 -0
  58. package/src/client/vsc/terminal-writer.ts +112 -0
  59. package/src/client/vsc/vsc.css +687 -48
  60. package/src/pool.ts +99 -27
  61. package/src/terminal.ts +160 -6
@@ -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
+ }
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Terminal OUTPUT writer: an ordered, coalescing buffer between the WebSocket
3
+ * frames and `term.write`.
4
+ *
5
+ * Why this is not just `term.write(frame.d)` per frame, and NOT a chain of
6
+ * `write(..., callback)`:
7
+ *
8
+ * - xterm parses writes in slices of a few milliseconds; handing it one string
9
+ * per frame costs per-call overhead on a busy stream (`cat`, `dmesg`).
10
+ * - chaining on the write CALLBACK couples our queue to xterm's parse/render
11
+ * completion. A callback is delivered after the data is parsed AND rendered,
12
+ * and rendering is driven by the browser's frames — a throttled window, an
13
+ * occluded tab or a very large previous chunk delays it, and while it is
14
+ * delayed this queue refuses to hand xterm anything new. That is exactly the
15
+ * "typing sometimes has no echo for a while, then it catches up" symptom:
16
+ * the echo was sitting in our queue behind a callback that had not fired yet.
17
+ *
18
+ * So: order is preserved by APPENDING to one buffer and flushing it on a timer
19
+ * (or immediately when the buffer is large). Nothing here waits for a write to
20
+ * finish — xterm's own queue already serialises the chunks we hand it.
21
+ *
22
+ * Pure for the gate (`scripts/check-terminal-writer.mjs`): the scheduler and the
23
+ * write sink are injected, no DOM, no timers at import time.
24
+ */
25
+
26
+ /** Dependencies of {@link createTerminalWriter}. */
27
+ export interface TerminalWriterDeps {
28
+ /** Hand one chunk to the terminal (xterm's `write`). Must not throw. */
29
+ write: (text: string) => void
30
+ /** Schedule one flush; the default is `setTimeout(run, 0)`. */
31
+ schedule?: (run: () => void) => unknown
32
+ /**
33
+ * Largest string handed to `write` in one call.
34
+ *
35
+ * Joining a multi-megabyte backlog into ONE string would itself block the main
36
+ * thread (and the join is O(total) on every flush), so a big queue is written
37
+ * in pieces and the rest is scheduled immediately.
38
+ */
39
+ maxChunkChars?: number
40
+ }
41
+
42
+ /** Handle returned by {@link createTerminalWriter}. */
43
+ export interface TerminalWriter {
44
+ /** Append output; the returned value is ignored (kept for symmetry/tests). */
45
+ push: (text: string) => void
46
+ /** Flush everything right now (tab closing, exit frame). */
47
+ flush: () => void
48
+ /** Characters still waiting (diagnostics/tests). */
49
+ pendingChars: () => number
50
+ }
51
+
52
+ /** Default cap for one `write` call (256 Ki UTF-16 units). */
53
+ export const WRITER_MAX_CHUNK_CHARS = 256 * 1024
54
+
55
+ /** Create one ordered, coalescing writer. */
56
+ export function createTerminalWriter(deps: TerminalWriterDeps): TerminalWriter {
57
+ const schedule = deps.schedule ?? ((run: () => void) => setTimeout(run, 0))
58
+ const maxChunk = deps.maxChunkChars ?? WRITER_MAX_CHUNK_CHARS
59
+ /** Queued chunks, in arrival order (joined only at flush time). */
60
+ let queue: string[] = []
61
+ let queuedChars = 0
62
+ let scheduled = false
63
+
64
+ const take = (limit: number): string => {
65
+ // Walk whole CHUNKS until the limit would be exceeded, so a normal burst
66
+ // (small frames) costs one join and a huge backlog is split without slicing
67
+ // a surrogate pair in half.
68
+ let taken = ''
69
+ while (queue.length > 0) {
70
+ const head = queue[0] as string
71
+ if (taken !== '' && taken.length + head.length > limit) break
72
+ queue.shift()
73
+ queuedChars -= head.length
74
+ taken += head
75
+ if (taken.length >= limit) break
76
+ }
77
+ return taken
78
+ }
79
+
80
+ const flush = (): void => {
81
+ scheduled = false
82
+ if (queue.length === 0) return
83
+ const chunk = take(maxChunk)
84
+ if (chunk === '') return
85
+ deps.write(chunk)
86
+ // More to send: keep the ORDER and get back to the event loop first, so a
87
+ // long backlog cannot starve input handling (keystrokes are separate tasks).
88
+ if (queue.length > 0) scheduleFlush()
89
+ }
90
+
91
+ const scheduleFlush = (): void => {
92
+ if (scheduled) return
93
+ scheduled = true
94
+ schedule(flush)
95
+ }
96
+
97
+ return {
98
+ push: (text: string): void => {
99
+ if (text === '') return
100
+ queue.push(text)
101
+ queuedChars += text.length
102
+ // A large buffer is flushed at once (the timer would only add latency);
103
+ // a small one waits one tick so a burst of frames becomes one write.
104
+ if (queuedChars >= maxChunk) flush()
105
+ else scheduleFlush()
106
+ },
107
+ flush: (): void => {
108
+ flush()
109
+ },
110
+ pendingChars: (): number => queuedChars,
111
+ }
112
+ }