dsh-remote-vs 0.19.1 → 0.20.1

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.
@@ -0,0 +1,379 @@
1
+ /**
2
+ * Coloured file-type / folder icons for the remote DIRECTORY TREE
3
+ * (`RemoteExplorer`), so a remote folder looks like the local sidebar's folder.
4
+ *
5
+ * Scope: the tree only. Search hits, SCM rows, commit panes and download rows
6
+ * keep the neutral outline glyphs from `kit.tsx` — this set is deliberately not
7
+ * the fallback of `FileIcon` / `FolderIcon`.
8
+ *
9
+ * Provenance
10
+ * ----------
11
+ * These are a straight port of the icon set the local sidebar plugin draws
12
+ * (`FileTypeIcon` and its amber folder icon): one paper sheet whose colour and
13
+ * bottom-right mark carry the type — TS blue + `<>`, JS yellow + `<>`, Python
14
+ * blue with a yellow mark, Markdown blue + lines, images purple + a mountain,
15
+ * archives yellow + a zip, `.gitignore` orange + a commit graph.
16
+ *
17
+ * The copy exists on purpose: the client bundle may not import another plugin's
18
+ * values (tsdown's purity gate rejects cross-plugin imports), and that plugin
19
+ * publishes no `fileIcon` / `folderIcon` service that `kit.tsx` could call.
20
+ * `kit.tsx` still prefers such a service if a host ever provides one (the
21
+ * better-sidebar contract is where it would come from); this set is the
22
+ * fallback that paints a real, typed tree whenever that plugin is present.
23
+ *
24
+ * One deliberate difference from the source: the image mark used
25
+ * `fill="currentColor"`, which in a tree inherits the row's dim text colour —
26
+ * `.rvs-node-icon` sets `color: var(--rvs-fg3)` — so the mountain would render
27
+ * grey on the purple sheet. Here the mark group pins `color` to the type colour
28
+ * and the artwork stays the colour the palette intends.
29
+ */
30
+ import type { ReactNode } from 'react'
31
+
32
+ /** File paper outline (shared by every file-type icon). */
33
+ const SHEET = 'M4 1.4h5.4l3.6 3.6v9.4c0 .5-.4.9-.9.9H3.1a.9.9 0 0 1-.9-.9V2.3c0-.5.4-.9.9-.9Z'
34
+ /** Top-right fold. */
35
+ const SHEET_FOLD = 'M9.4 1.4v3.6h3.6'
36
+
37
+ /** The bottom-right mark that carries the category (drawn in the type colour). */
38
+ type FileMark =
39
+ | 'code' | 'markup' | 'style' | 'data' | 'doc' | 'image'
40
+ | 'archive' | 'shell' | 'config' | 'git' | 'lock' | 'box' | 'table'
41
+
42
+ /** How one file type looks: sheet colour + category mark + optional mark colour. */
43
+ export interface FileLook {
44
+ color: string
45
+ mark: FileMark
46
+ /** Mark colour; defaults to the sheet colour (Python = blue sheet + yellow mark). */
47
+ markColor?: string
48
+ }
49
+
50
+ /** Extension → look. Brand colours are tuned for readability on dark and light. */
51
+ const BY_EXT: Readonly<Record<string, FileLook>> = { ts: { color: '#519aba', mark: 'code' },
52
+ mts: { color: '#519aba', mark: 'code' },
53
+ cts: { color: '#519aba', mark: 'code' },
54
+ tsx: { color: '#4fc3f7', mark: 'code' },
55
+ js: { color: '#d5c93f', mark: 'code' },
56
+ mjs: { color: '#d5c93f', mark: 'code' },
57
+ cjs: { color: '#d5c93f', mark: 'code' },
58
+ jsx: { color: '#4fc3f7', mark: 'code' },
59
+ json: { color: '#d2b13a', mark: 'data' },
60
+ jsonc: { color: '#d2b13a', mark: 'data' },
61
+ json5: { color: '#d2b13a', mark: 'data' },
62
+ md: { color: '#4b9fe3', mark: 'doc' },
63
+ markdown: { color: '#4b9fe3', mark: 'doc' },
64
+ mdx: { color: '#4b9fe3', mark: 'doc' },
65
+ py: { color: '#3572a5', mark: 'code', markColor: '#ffd75e' },
66
+ pyi: { color: '#3572a5', mark: 'code', markColor: '#ffd75e' },
67
+ java: { color: '#e05a4f', mark: 'code' },
68
+ kt: { color: '#a97bff', mark: 'code' },
69
+ c: { color: '#7f9bd6', mark: 'code' },
70
+ h: { color: '#a074c4', mark: 'code' },
71
+ cpp: { color: '#6295cb', mark: 'code' },
72
+ cc: { color: '#6295cb', mark: 'code' },
73
+ cxx: { color: '#6295cb', mark: 'code' },
74
+ hpp: { color: '#6295cb', mark: 'code' },
75
+ hh: { color: '#6295cb', mark: 'code' },
76
+ cs: { color: '#b878d8', mark: 'code' },
77
+ go: { color: '#00add8', mark: 'code' },
78
+ rs: { color: '#dea584', mark: 'code' },
79
+ php: { color: '#8b9be8', mark: 'code' },
80
+ rb: { color: '#e05a4f', mark: 'code' },
81
+ swift: { color: '#e8743b', mark: 'code' },
82
+ lua: { color: '#5a8fe0', mark: 'code' },
83
+ html: { color: '#e8743b', mark: 'markup' },
84
+ htm: { color: '#e8743b', mark: 'markup' },
85
+ vue: { color: '#41b883', mark: 'markup' },
86
+ svelte: { color: '#ff5c33', mark: 'markup' },
87
+ xml: { color: '#f19a38', mark: 'markup' },
88
+ xsl: { color: '#f19a38', mark: 'markup' },
89
+ css: { color: '#42a5f5', mark: 'style' },
90
+ scss: { color: '#e05a8f', mark: 'style' },
91
+ sass: { color: '#e05a8f', mark: 'style' },
92
+ less: { color: '#42a5f5', mark: 'style' },
93
+ yaml: { color: '#a074c4', mark: 'data' },
94
+ yml: { color: '#a074c4', mark: 'data' },
95
+ toml: { color: '#b08b6a', mark: 'config' },
96
+ ini: { color: '#b08b6a', mark: 'config' },
97
+ conf: { color: '#b08b6a', mark: 'config' },
98
+ cfg: { color: '#b08b6a', mark: 'config' },
99
+ env: { color: '#b08b6a', mark: 'config' },
100
+ sh: { color: '#4ec9b0', mark: 'shell' },
101
+ bash: { color: '#4ec9b0', mark: 'shell' },
102
+ zsh: { color: '#4ec9b0', mark: 'shell' },
103
+ fish: { color: '#4ec9b0', mark: 'shell' },
104
+ ps1: { color: '#4ec9b0', mark: 'shell' },
105
+ psm1: { color: '#4ec9b0', mark: 'shell' },
106
+ bat: { color: '#4ec9b0', mark: 'shell' },
107
+ cmd: { color: '#4ec9b0', mark: 'shell' },
108
+ txt: { color: '#9aa0a6', mark: 'doc' },
109
+ log: { color: '#9aa0a6', mark: 'doc' },
110
+ csv: { color: '#7fb36b', mark: 'table' },
111
+ tsv: { color: '#7fb36b', mark: 'table' },
112
+ xlsx: { color: '#7fb36b', mark: 'table' },
113
+ png: { color: '#b18adf', mark: 'image' },
114
+ jpg: { color: '#b18adf', mark: 'image' },
115
+ jpeg: { color: '#b18adf', mark: 'image' },
116
+ gif: { color: '#b18adf', mark: 'image' },
117
+ webp: { color: '#b18adf', mark: 'image' },
118
+ bmp: { color: '#b18adf', mark: 'image' },
119
+ ico: { color: '#b18adf', mark: 'image' },
120
+ avif: { color: '#b18adf', mark: 'image' },
121
+ svg: { color: '#b18adf', mark: 'image' },
122
+ pdf: { color: '#d94f4f', mark: 'doc' },
123
+ zip: { color: '#d9b64a', mark: 'archive' },
124
+ rar: { color: '#d9b64a', mark: 'archive' },
125
+ '7z': { color: '#d9b64a', mark: 'archive' },
126
+ tar: { color: '#d9b64a', mark: 'archive' },
127
+ gz: { color: '#d9b64a', mark: 'archive' },
128
+ tgz: { color: '#d9b64a', mark: 'archive' },
129
+ bz2: { color: '#d9b64a', mark: 'archive' },
130
+ xz: { color: '#d9b64a', mark: 'archive' },
131
+ lock: { color: '#8b949e', mark: 'lock' },
132
+ dockerfile: { color: '#2496ed', mark: 'box' },
133
+ docker: { color: '#2496ed', mark: 'box' },
134
+ // `demo.gitignore` / `x.gitattributes` derive from the dot-file convention and
135
+ // take the orange branch mark here; the plain names are in BY_NAME.
136
+ gitignore: { color: '#e8703a', mark: 'git' },
137
+ gitattributes: { color: '#e8703a', mark: 'git' },
138
+ gitmodules: { color: '#e8703a', mark: 'git' },
139
+ exe: { color: '#8b949e', mark: 'box' },
140
+ dll: { color: '#8b949e', mark: 'box' },
141
+ so: { color: '#8b949e', mark: 'box' },
142
+ dylib: { color: '#8b949e', mark: 'box' },
143
+ }
144
+
145
+ /** Exact file name → look (extension-less files and conventional names hit here first). */
146
+ const BY_NAME: Readonly<Record<string, FileLook>> = {
147
+ dockerfile: { color: '#2496ed', mark: 'box' },
148
+ 'docker-compose.yml': { color: '#2496ed', mark: 'box' },
149
+ 'docker-compose.yaml': { color: '#2496ed', mark: 'box' },
150
+ makefile: { color: '#b08b6a', mark: 'config' },
151
+ gnumakefile: { color: '#b08b6a', mark: 'config' },
152
+ 'cmakelists.txt': { color: '#b08b6a', mark: 'config' },
153
+ '.gitignore': { color: '#e8703a', mark: 'git' },
154
+ '.gitattributes': { color: '#e8703a', mark: 'git' },
155
+ '.gitmodules': { color: '#e8703a', mark: 'git' },
156
+ '.npmrc': { color: '#b08b6a', mark: 'config' },
157
+ '.editorconfig': { color: '#b08b6a', mark: 'config' },
158
+ '.prettierrc': { color: '#b08b6a', mark: 'config' },
159
+ 'package-lock.json': { color: '#8b949e', mark: 'lock' },
160
+ 'pnpm-lock.yaml': { color: '#8b949e', mark: 'lock' },
161
+ 'yarn.lock': { color: '#8b949e', mark: 'lock' },
162
+ license: { color: '#9aa0a6', mark: 'doc' },
163
+ readme: { color: '#4b9fe3', mark: 'doc' },
164
+ }
165
+
166
+ /** Unrecognised file: grey document. */
167
+ const FALLBACK: FileLook = { color: '#8b949e', mark: 'doc' }
168
+
169
+ /**
170
+ * The extension / exact-name tables, exposed read-only for the gate's full-table
171
+ * snapshot: one changed hex or mark must turn `scripts/check-file-icons.mjs`
172
+ * red, instead of shipping a silently different palette.
173
+ *
174
+ * `baseName` stays private on purpose — `kit.tsx` already exports a `baseName`
175
+ * with different semantics (POSIX only, strips a trailing slash), and exporting
176
+ * both invites the wrong import.
177
+ */
178
+ export const FILE_TYPE_LOOKS: Readonly<Record<string, FileLook>> = BY_EXT
179
+ export const FILE_NAME_LOOKS: Readonly<Record<string, FileLook>> = BY_NAME
180
+
181
+ /** Drawing commands for a category mark (coordinates sit on the sheet's lower half). */
182
+ const MARKS: Readonly<Record<FileMark, ReactNode>> = {
183
+ code: (
184
+ <>
185
+ <path d="M6.4 7.8 5 9.6l1.4 1.8" />
186
+ <path d="M9.6 7.8 11 9.6l-1.4 1.8" />
187
+ </>
188
+ ),
189
+ markup: (
190
+ <>
191
+ <path d="M5.8 7.9 4.4 9.8l1.4 1.9" />
192
+ <path d="M8.6 7.5l-1.6 4.6" />
193
+ <path d="M10.2 7.9l1.4 1.9-1.4 1.9" />
194
+ </>
195
+ ),
196
+ style: (
197
+ <>
198
+ <path d="M7.1 7.6 6.3 12M9.7 7.6l-.8 4.4" />
199
+ <path d="M5.5 9h4.9M5.3 10.6h4.9" />
200
+ </>
201
+ ),
202
+ data: (
203
+ <>
204
+ <path d="M7.1 7.4c-.9 0-.9.7-.9 1.3s0 1.2-.9 1.2c.9 0 .9.6.9 1.2s0 1.3.9 1.3" />
205
+ <path d="M8.9 7.4c.9 0 .9.7.9 1.3s0 1.2.9 1.2c-.9 0-.9.6-.9 1.2s0 1.3-.9 1.3" />
206
+ </>
207
+ ),
208
+ doc: <path d="M5.2 7.8h5.6M5.2 9.7h5.6M5.2 11.6h3.6" />,
209
+ image: (
210
+ <>
211
+ <circle cx="6.4" cy="8.1" r=".85" fill="currentColor" stroke="none" />
212
+ <path d="M4.8 12.2l2.1-2.6 1.5 1.7 1.2-1.3 1.8 2.2Z" fill="currentColor" stroke="none" />
213
+ </>
214
+ ),
215
+ archive: (
216
+ <>
217
+ <path d="M4.8 7.6h6.4v4.6H4.8z" />
218
+ <path d="M4.8 9h6.4" />
219
+ <path d="M7.2 7.6v1.4M7.2 10.4h1.6" />
220
+ </>
221
+ ),
222
+ shell: (
223
+ <>
224
+ <path d="M5.2 8.2 6.9 9.8l-1.7 1.6" />
225
+ <path d="M8.3 11.4h2.7" />
226
+ </>
227
+ ),
228
+ config: (
229
+ <>
230
+ <path d="M5 8.2h6M5 11h6" />
231
+ <circle cx="7" cy="8.2" r="1.05" />
232
+ <circle cx="9.4" cy="11" r="1.05" />
233
+ </>
234
+ ),
235
+ git: (
236
+ <>
237
+ <circle cx="6" cy="7.7" r="1" />
238
+ <circle cx="9.8" cy="10.9" r="1" />
239
+ <path d="M6 8.7v1.3M9.8 8.6c0 1.4-3.8 1.3-3.8 2.3" />
240
+ </>
241
+ ),
242
+ lock: (
243
+ <>
244
+ <rect x="5.4" y="8.6" width="5.2" height="3.8" rx="1" />
245
+ <path d="M6.6 8.6V7.4a1.4 1.4 0 0 1 2.8 0v1.2" />
246
+ </>
247
+ ),
248
+ box: (
249
+ <>
250
+ <path d="M4.6 8.4h2v1.8h-2zM6.9 8.4h2v1.8h-2zM6.9 10.5h2v1.8h-2zM4.6 12.6h6.8" />
251
+ </>
252
+ ),
253
+ table: (
254
+ <>
255
+ <path d="M4.8 7.6h6.4v4.6H4.8z" />
256
+ <path d="M4.8 9.1h6.4M4.8 10.7h6.4M7.5 7.6v4.6" />
257
+ </>
258
+ ),
259
+ }
260
+
261
+ /** Basename of a path that may use either separator. */
262
+ function baseName(path: string): string {
263
+ const normalized = path.replace(/\\/g, '/')
264
+ return normalized.slice(normalized.lastIndexOf('/') + 1)
265
+ }
266
+
267
+ /** Resolve a path's look from its name / extension. */
268
+ export function lookOf(path: string): FileLook {
269
+ const name = baseName(path).toLowerCase()
270
+ const named = BY_NAME[name]
271
+ if (named !== undefined) return named
272
+ if (name.startsWith('.env')) return { color: '#b08b6a', mark: 'config' }
273
+ const dot = name.lastIndexOf('.')
274
+ // dot === 0 is a dot-file such as `.bashrc` with no extension: fall through.
275
+ if (dot <= 0) return FALLBACK
276
+ return BY_EXT[name.slice(dot + 1)] ?? FALLBACK
277
+ }
278
+
279
+ /** Props for {@link FileTypeIcon} / {@link FolderGlyph}. */
280
+ export interface FileIconProps {
281
+ /** Workspace-relative path (any separator); only the basename is read. */
282
+ path: string
283
+ /** Edge length in px, default 16. */
284
+ size?: number
285
+ className?: string
286
+ }
287
+
288
+ /**
289
+ * Coloured file-type icon: sheet + top-right fold + bottom-right category mark.
290
+ *
291
+ * At 16 px this reads better than two-letter badges and does not depend on font
292
+ * rendering.
293
+ */
294
+ export function FileTypeIcon(props: FileIconProps): ReactNode {
295
+ const size = props.size ?? 16
296
+ const look = lookOf(props.path)
297
+ return (
298
+ <svg
299
+ width={size}
300
+ height={size}
301
+ viewBox="0 0 16 16"
302
+ fill="none"
303
+ className={props.className}
304
+ aria-hidden="true"
305
+ >
306
+ <path
307
+ d={SHEET}
308
+ fill={look.color}
309
+ fillOpacity={0.14}
310
+ stroke={look.color}
311
+ strokeWidth={1}
312
+ strokeLinejoin="round"
313
+ />
314
+ <path d={SHEET_FOLD} stroke={look.color} strokeWidth={1} strokeLinejoin="round" />
315
+ <g
316
+ stroke={look.markColor ?? look.color}
317
+ strokeWidth={1.15}
318
+ strokeLinecap="round"
319
+ strokeLinejoin="round"
320
+ // Pins currentColor for the image mark to the type colour: the tree row
321
+ // sets a dim text colour that would otherwise grey the mountain out.
322
+ style={{ color: look.markColor ?? look.color }}
323
+ >
324
+ {MARKS[look.mark]}
325
+ </g>
326
+ </svg>
327
+ )
328
+ }
329
+
330
+ /** Every extension the file-type icon recognises (reporting / gate). */
331
+ export const FILE_TYPE_EXTENSIONS: readonly string[] = Object.keys(BY_EXT).sort()
332
+
333
+ /** Props for the amber folder glyph. */
334
+ export interface FolderGlyphProps {
335
+ /** Expanded: the front flap drops down and reveals the inner sheet (VSCode-like). */
336
+ open?: boolean
337
+ /** Edge length in px, default 16. */
338
+ size?: number
339
+ className?: string
340
+ }
341
+
342
+ /**
343
+ * Amber folder icon. The folder colour is content colour, in the same scheme as
344
+ * the file types — it does not follow the skin.
345
+ */
346
+ export function FolderGlyph(props: FolderGlyphProps): ReactNode {
347
+ const size = props.size ?? 16
348
+ return props.open === true
349
+ ? (
350
+ <svg width={size} height={size} viewBox="0 0 16 16" fill="none" className={props.className} aria-hidden="true">
351
+ <path
352
+ d="M1.9 12V4.3c0-.6.4-1 1-1h3.2l1.5 1.7h5.6c.6 0 1 .4 1 1v5.4"
353
+ fill="#c69a3f"
354
+ stroke="#a8781c"
355
+ strokeWidth=".9"
356
+ strokeLinejoin="round"
357
+ />
358
+ <path
359
+ d="M2 12.6 3.5 8c.1-.4.5-.7.9-.7h9.5c.7 0 1.2.7 1 1.4l-1.3 3.8c-.1.4-.5.7-.9.7H2.9c-.6 0-1-.5-.9-1.1Z"
360
+ fill="#e7b95d"
361
+ stroke="#a8781c"
362
+ strokeWidth=".9"
363
+ strokeLinejoin="round"
364
+ />
365
+ </svg>
366
+ )
367
+ : (
368
+ <svg width={size} height={size} viewBox="0 0 16 16" fill="none" className={props.className} aria-hidden="true">
369
+ <path
370
+ d="M1.9 12.3V4.2c0-.6.4-1 1-1h3.2l1.5 1.7h5.6c.6 0 1 .4 1 1v6.4c0 .6-.4 1-1 1H2.9c-.6 0-1-.4-1-1Z"
371
+ fill="#d9ab4e"
372
+ stroke="#a8781c"
373
+ strokeWidth=".9"
374
+ strokeLinejoin="round"
375
+ />
376
+ <path d="M2.6 5.3h10.8" stroke="#a8781c" strokeWidth=".9" opacity=".45" />
377
+ </svg>
378
+ )
379
+ }
@@ -5,11 +5,18 @@
5
5
  * ships the same split, and the confirm dialogs are what guard destructive
6
6
  * remote git verbs).
7
7
  *
8
- * Icon sourcing: when dsh-better-sidebar is installed its service answers
9
- * `fileIcon` / `folderIcon`, which run the host's own classifier and any
10
- * user-registered icon theme — the remote tree then matches the user's local
11
- * sidebar glyph for glyph. Without that service the built-in SVG set below
12
- * takes over, so the native fallback surface still renders a real tree.
8
+ * Icon sourcing has two tiers. `FileIcon` / `FolderIcon` paint the plain glyphs
9
+ * below (search hits, SCM rows, commit panes, download rows — list chrome where
10
+ * one neutral outline reads best). `ExplorerFileIcon` / `ExplorerFolderIcon`
11
+ * paint the COLOURED type set ported from the local sidebar plugin in
12
+ * `./file-icons.tsx`, so the remote directory tree looks like the local
13
+ * sidebar's tree: one sheet whose colour and mark carry the file type, and an
14
+ * amber folder that opens.
15
+ *
16
+ * Every tier still prefers the host service when one is published (the
17
+ * better-sidebar contract's `fileIcon` / `folderIcon`: host classifier plus any
18
+ * registered icon theme). That plugin publishes none today, so with the local
19
+ * sidebar installed the SVG sets above are what actually render.
13
20
  */
14
21
  import {
15
22
  createElement,
@@ -25,6 +32,7 @@ import {
25
32
  } from 'react'
26
33
  import { createPortal } from 'react-dom'
27
34
  import { detectLang, makeT } from '../i18n.ts'
35
+ import { FileTypeIcon, FolderGlyph } from './file-icons.tsx'
28
36
 
29
37
  // ------------------------------------------------------------------ icons
30
38
 
@@ -330,6 +338,28 @@ export function FolderIcon(props: { path: string; open: boolean; size?: number;
330
338
  return <IconFolder size={size} open={props.open} className={props.className} />
331
339
  }
332
340
 
341
+ // --------------------------------------------------- directory-tree icons
342
+ //
343
+ // The tree is the one surface that has to match the local sidebar, so it uses
344
+ // the coloured type set (see `./file-icons.tsx`) instead of the plain glyphs
345
+ // above. Host service still wins, so a user-registered icon theme keeps working.
346
+
347
+ /** Explorer file row: host glyph when available, else the coloured type icon. */
348
+ export function ExplorerFileIcon(props: { path: string; size?: number; className?: string }): ReactNode {
349
+ const size = props.size ?? 16
350
+ const fromHost = tryService(() => iconService?.fileIcon(props.path, size))
351
+ if (fromHost !== undefined) return fromHost
352
+ return <FileTypeIcon path={props.path} size={size} className={props.className} />
353
+ }
354
+
355
+ /** Explorer directory row: host glyph when available, else the amber folder. */
356
+ export function ExplorerFolderIcon(props: { path: string; open: boolean; size?: number; className?: string }): ReactNode {
357
+ const size = props.size ?? 16
358
+ const fromHost = tryService(() => iconService?.folderIcon(props.path, props.open, size))
359
+ if (fromHost !== undefined) return fromHost
360
+ return <FolderGlyph open={props.open} size={size} className={props.className} />
361
+ }
362
+
333
363
  // ------------------------------------------------------------- file kinds
334
364
 
335
365
  const IMAGE_EXTS = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg', 'bmp', 'ico', 'avif'])
package/src/index.ts CHANGED
@@ -8,7 +8,7 @@
8
8
  */
9
9
  import type { Context } from '@deepseek-ai/cordis'
10
10
  import z from '@deepseek-ai/schemastery'
11
- import type {} from '@deepseek-ai/dsh-agent'
11
+ import type { Agent } from '@deepseek-ai/dsh-agent'
12
12
  import type {} from '@deepseek-ai/dsh-agent-preset-registry'
13
13
  import type {} from '@deepseek-ai/dsh-host-webserver'
14
14
  import type {} from '@deepseek-ai/dsh-system-prompt'
@@ -27,7 +27,14 @@ import {
27
27
  MIN_TIMEOUT_MS,
28
28
  resolveTimeouts,
29
29
  } from './timeouts.ts'
30
- import { RemoteWorlds, type RoutingMode, type WorldRoute } from './p2/worlds.ts'
30
+ import { RemoteWorlds, TombstonedError, type RoutingMode, type WorldRoute } from './p2/worlds.ts'
31
+ import {
32
+ REMOTE_PRESET_ID,
33
+ decidePresetSwitch,
34
+ runPresetSwitchAttempts,
35
+ type PresetSwitchAttempt,
36
+ type PresetSwitchFacts,
37
+ } from './preset-switch.ts'
31
38
  import { SessionChanges } from './changes/recorder.ts'
32
39
  import {
33
40
  remoteExecTool,
@@ -449,60 +456,116 @@ export function apply(ctx: Context, config?: ResolvedConfig): void {
449
456
  }
450
457
 
451
458
  ctx.on('loader/volatile-update', () => { sync() })
452
- // Phase 4b auto-switch (race-free take 2, 2026-10-13): new sessions born in
453
- // a remote workspace switch to Remote once. Calling select() synchronously
454
- // from agent/created races the initial mount (both preset trees register
455
- // tools concurrently → `subagent already registered` → session creation
456
- // dies), so the listener DETACHES: it returns immediately (creation never
457
- // blocks) and a delayed attempt runs after mount fibers settle (ms-scale;
458
- // 2.5s is forever). Guards re-checked at fire time; a started turn (locked)
459
- // or any failure silently keeps standard (routing still works, bash tool
460
- // excepted) — manual selection remains the fallback. Nothing here can fail
461
- // session creation: the worst case is today's manual behavior plus a warn.
459
+ /**
460
+ * Preset auto-switch for a new session born in a remote workspace (Phase 4b).
461
+ *
462
+ * 2026-11-10, bug "sometimes no Remote preset ~3 s after creating a session":
463
+ *
464
+ * - The Web client does not always MINT a session. `createInWorkspace` reuses
465
+ * the first listed BLANK session of the workspace by passing its id, and the
466
+ * Host answers that through `agents.resume` → `agent/created` with source
467
+ * `'resume'`. The old `source !== 'startup'` guard silently skipped exactly
468
+ * those sessions. Blankness (no turn started) is the precondition the preset
469
+ * registry itself enforces, so it is what we check now — a resumed session
470
+ * with history is excluded by it.
471
+ * - One 2.5 s shot also lost every transient state: the preset may not be
472
+ * composed yet, the working directory may be unreadable, or the workspace
473
+ * binding may not be listed. `runPresetSwitchAttempts` retries those for a
474
+ * bounded time and stops on terminal reasons (routing off, history, user's
475
+ * own preset, local directory).
476
+ *
477
+ * The listener still DETACHES: it returns immediately, so session creation
478
+ * never waits for a switch (the original 2026-10-13 race: selecting during
479
+ * creation while both preset trees register tools could kill the session).
480
+ * Failure modes are logged, never thrown; manual selection stays the fallback.
481
+ */
482
+ const attemptPresetSwitch = async (agent: Agent): Promise<PresetSwitchAttempt> => {
483
+ const presets = ctx.get('agentPresets')
484
+ const agents = ctx.get('agents') as
485
+ | { turnBoundaryOf?: (session: unknown) => { openTurnStartSeq: number | null; lastTurn: number } | undefined }
486
+ | undefined
487
+ const workingDirectory = ctx.get('workingDirectory') as
488
+ | { get?: (session: unknown) => unknown }
489
+ | undefined
490
+ let boundary: { openTurnStartSeq: number | null; lastTurn: number } | undefined
491
+ try {
492
+ boundary = agents?.turnBoundaryOf?.(agent.session)
493
+ } catch {
494
+ boundary = undefined
495
+ }
496
+ let cwd = ''
497
+ try {
498
+ const current = workingDirectory?.get?.(agent.session)
499
+ if (typeof current === 'string') cwd = current
500
+ } catch {
501
+ // Soft read: an unbound session stays unreadable and retries.
502
+ }
503
+ let remote: boolean | undefined
504
+ let tombstoned = false
505
+ if (cwd !== '') {
506
+ try {
507
+ remote = worlds.routeDir(cwd).kind === 'remote'
508
+ } catch (error) {
509
+ if (error instanceof TombstonedError) tombstoned = true
510
+ }
511
+ }
512
+ // Service reads can throw during (re)mount; a throw is transient, so the
513
+ // facts fall back to "not composed yet" and the loop retries instead of
514
+ // losing the one chance (2026-11-10: that silent loss was the bug).
515
+ let currentPreset: string | undefined
516
+ let defaultPreset: string | undefined
517
+ try {
518
+ currentPreset = presets?.composedPreset(agent.ctx)
519
+ defaultPreset = presets?.defaultId
520
+ } catch {
521
+ currentPreset = undefined
522
+ defaultPreset = undefined
523
+ }
524
+ const facts: PresetSwitchFacts = {
525
+ mode: worlds.mode,
526
+ hasPresets: presets !== undefined,
527
+ blank: boundary !== undefined && boundary.openTurnStartSeq === null && boundary.lastTurn === 0,
528
+ cwd,
529
+ remote,
530
+ tombstoned,
531
+ currentPreset,
532
+ defaultPreset,
533
+ }
534
+ const step = decidePresetSwitch(facts)
535
+ if (step.action !== 'switch') return { step, facts }
536
+ if (presets === undefined) return { step: { action: 'stop', reason: 'presets-absent' }, facts }
537
+ try {
538
+ await presets.select(agent, REMOTE_PRESET_ID)
539
+ return { step: { action: 'stop', reason: 'switched' }, facts }
540
+ } catch (error) {
541
+ // agent-preset/locked = the user already started a turn: respect it.
542
+ const locked = error instanceof Error && /locked|already started/i.test(error.message)
543
+ return { step: { action: locked ? 'stop' : 'retry', reason: locked ? 'locked' : 'select-failed' }, facts }
544
+ }
545
+ }
462
546
  ctx.on('agent/created', (payload) => {
463
- if (payload.source !== 'startup') return undefined
464
- const timer = setTimeout(() => {
465
- void (async () => {
547
+ void (async () => {
548
+ try {
549
+ const { step, facts, attempts } = await runPresetSwitchAttempts(() => attemptPresetSwitch(payload.agent))
466
550
  try {
467
- const presets = ctx.get('agentPresets')
468
- if (presets === undefined) return
469
- if (worlds.mode !== 'enforce') return
470
- const current = presets.composedPreset(payload.agent.ctx)
471
- if (current !== presets.defaultId || current === 'remote') return
472
- const workingDirectory = ctx.get('workingDirectory')
473
- if (workingDirectory === undefined) return
474
- let cwd: string
475
- try {
476
- cwd = workingDirectory.get(payload.agent.session)
477
- } catch {
478
- return
479
- }
480
- let remote = false
481
- try {
482
- remote = worlds.routeDir(cwd).kind === 'remote'
483
- } catch {
484
- return
485
- }
486
- if (!remote) return
487
- await presets.select(payload.agent, 'remote')
488
- try {
489
- ctx.logger.info(`[remote-vs] new remote session entered ${cwd}; preset switched to remote`)
490
- } catch {
491
- // Logging must never break routing.
492
- }
493
- } catch (error) {
494
- // agent-preset/locked = user already started a turn: respect it.
495
- const locked = error instanceof Error && /locked|already started/i.test(error.message)
496
- if (locked) return
497
- try {
498
- ctx.logger.warn(`[remote-vs] preset auto-switch skipped: ${error instanceof Error ? error.message : String(error)}`)
499
- } catch {
500
- // Ignore.
551
+ if (step.reason === 'switched' && facts?.remote === true) {
552
+ ctx.logger.info(`[remote-vs] remote session ${facts.cwd}: preset switched to ${REMOTE_PRESET_ID} after ${attempts} attempt(s)`)
553
+ } else if (step.action === 'retry') {
554
+ ctx.logger.warn(`[remote-vs] preset auto-switch gave up after ${attempts} attempt(s): ${step.reason}`)
555
+ } else if (facts?.remote === true) {
556
+ ctx.logger.info(`[remote-vs] preset auto-switch skipped for ${facts.cwd}: ${step.reason}`)
501
557
  }
558
+ } catch {
559
+ // Logging must never break routing.
502
560
  }
503
- })()
504
- }, 2500)
505
- timer.unref?.()
561
+ } catch (error) {
562
+ try {
563
+ ctx.logger.warn(`[remote-vs] preset auto-switch skipped: ${error instanceof Error ? error.message : String(error)}`)
564
+ } catch {
565
+ // Ignore.
566
+ }
567
+ }
568
+ })()
506
569
  return undefined
507
570
  })
508
571
  sync()