dsh-remote-vs 0.20.0 → 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.
@@ -8,14 +8,15 @@
8
8
  * Icon sourcing has two tiers. `FileIcon` / `FolderIcon` paint the plain glyphs
9
9
  * below (search hits, SCM rows, commit panes, download rows — list chrome where
10
10
  * one neutral outline reads best). `ExplorerFileIcon` / `ExplorerFolderIcon`
11
- * paint the COLOURED type set ported from dsh-sidebar in `./file-icons.tsx`, so
12
- * the remote directory tree looks like the local sidebar's tree: one sheet
13
- * whose colour and mark carry the file type, and an amber folder that opens.
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.
14
15
  *
15
16
  * Every tier still prefers the host service when one is published (the
16
- * better-sidebar lineage's `fileIcon` / `folderIcon`: host classifier plus any
17
- * registered icon theme). dsh-sidebar itself publishes none today, so in a
18
- * dsh-sidebar profile the SVG sets above are what actually render.
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.
19
20
  */
20
21
  import { type ReactNode } from 'react';
21
22
  type IconProps = {
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Auto-switch decision for a new session born in a remote workspace.
3
+ *
4
+ * Why this module is pure
5
+ * -----------------------
6
+ * The 2026-11-10 bug was "sometimes no preset switch about 3 s after creating a
7
+ * session". Two independent causes had to be found by reading the Host:
8
+ *
9
+ * 1. **The switch only listened to `source === 'startup'`.** The Web client does
10
+ * not always mint a session: `session.create` accepts a named BLANK session
11
+ * and reuses it (`createInWorkspace` passes the first listed blank id), which
12
+ * the Host answers through `agents.resume` → `agent/created` with source
13
+ * `'resume'`. Those sessions never even armed the timer.
14
+ * 2. **A single 2.5 s shot lost every transient state.** At fire time the preset
15
+ * may not be composed yet, the working directory may be unreadable, or the
16
+ * workspace binding may not be listed; each guard returned silently, and the
17
+ * one chance was spent.
18
+ *
19
+ * The fix keeps the "never block session creation" contract and turns the
20
+ * decision into a pure function plus a bounded retry loop, so every branch is
21
+ * covered by a gate instead of being inferred from a silent return.
22
+ *
23
+ * Blankness — no turn started — is the real precondition (`presets.select`
24
+ * enforces exactly that), and it is also what excludes resumed sessions with
25
+ * history. The event source only told us how the session came to be.
26
+ */
27
+ /** Preset id this plugin switches remote sessions to (see `cordis.patch.yml`). */
28
+ export declare const REMOTE_PRESET_ID = "remote";
29
+ /** Delay before each attempt, in order. The first attempt keeps the old 2.5 s. */
30
+ export declare const PRESET_SWITCH_DELAYS_MS: readonly number[];
31
+ /** Why one attempt ended the way it did (logged, never thrown). */
32
+ export type PresetSwitchReason = 'switched' | 'already-remote' | 'custom-preset' | 'routing-off' | 'presets-absent' | 'services-absent' | 'not-blank' | 'preset-unbound' | 'cwd-unavailable' | 'route-unknown' | 'tombstoned' | 'local-session' | 'locked' | 'select-failed';
33
+ /** One attempt's outcome: switch now, try again later, or stop for good. */
34
+ export type PresetSwitchStep = {
35
+ action: 'switch';
36
+ } | {
37
+ action: 'retry';
38
+ reason: PresetSwitchReason;
39
+ } | {
40
+ action: 'stop';
41
+ reason: PresetSwitchReason;
42
+ };
43
+ /** A settled attempt (`switch` is reported as `stop/switched`). */
44
+ export type PresetSwitchSettled = Exclude<PresetSwitchStep, {
45
+ action: 'switch';
46
+ }>;
47
+ /** Everything the decision reads, resolved by the caller (no services here). */
48
+ export interface PresetSwitchFacts {
49
+ /** Routing mode from the plugin config: only `enforce` auto-switches. */
50
+ mode: string;
51
+ /** The preset registry service is mounted at all. */
52
+ hasPresets: boolean;
53
+ /** No turn has started yet (`turnBoundaryOf`): openTurnStartSeq null, lastTurn 0. */
54
+ blank: boolean;
55
+ /** The step also runs for local sessions; the caller decides what to log. */
56
+ cwd: string;
57
+ /** `undefined` when the route lookup threw (retried); false means local. */
58
+ remote: boolean | undefined;
59
+ /** The directory belongs to a retired binding: dead session, never switch. */
60
+ tombstoned: boolean;
61
+ currentPreset: string | undefined;
62
+ defaultPreset: string | undefined;
63
+ }
64
+ /**
65
+ * Decide one attempt.
66
+ *
67
+ * Order matters: the terminal reasons come first (config, history, user choice),
68
+ * then the transient ones (composed preset, cwd, route), then the switch.
69
+ */
70
+ export declare function decidePresetSwitch(facts: PresetSwitchFacts): PresetSwitchStep;
71
+ /** One attempt as the caller sees it: the step plus the facts it was made from. */
72
+ export interface PresetSwitchAttempt {
73
+ step: PresetSwitchSettled;
74
+ facts: PresetSwitchFacts;
75
+ }
76
+ /**
77
+ * Run attempts with the given delays until one stops or switches.
78
+ *
79
+ * A retry is only worth spending for the transient reasons the planner names;
80
+ * the loop itself does not re-classify, so a future terminal reason added to the
81
+ * planner stays terminal automatically.
82
+ *
83
+ * @returns the last attempt and how many attempts were used (1-based).
84
+ */
85
+ export declare function runPresetSwitchAttempts(attempt: () => Promise<PresetSwitchAttempt> | PresetSwitchAttempt, sleep?: (ms: number) => Promise<void>, delays?: readonly number[]): Promise<{
86
+ step: PresetSwitchSettled;
87
+ facts: PresetSwitchFacts | undefined;
88
+ attempts: number;
89
+ }>;
@@ -19963,4 +19963,4 @@ var RemoteWorlds = class {
19963
19963
  }
19964
19964
  };
19965
19965
  //#endregion
19966
- export { storePath as C, keysDir as S, resolveTimeouts as _, pushPipeline as a, dshHome as b, WriteConflictError as c, DEFAULT_READ_TIMEOUT_MS as d, DEFAULT_TIMEOUTS as f, clampExecTimeout as g, MIN_TIMEOUT_MS as h, probe as i, attachmentHeader as l, MAX_TIMEOUT_MS as m, isWindowsAbsolute as n, seedHelperCache as o, DeadlineError as p, helperAvailability as r, RemoteFiles as s, RemoteWorlds as t, DEFAULT_GIT_TIMEOUT_MS as u, require_lib as v, ensurePrivateDir as x, aliasRoot as y };
19966
+ export { keysDir as C, ensurePrivateDir as S, clampExecTimeout as _, probe as a, aliasRoot as b, RemoteFiles as c, DEFAULT_GIT_TIMEOUT_MS as d, DEFAULT_READ_TIMEOUT_MS as f, MIN_TIMEOUT_MS as g, MAX_TIMEOUT_MS as h, helperAvailability as i, WriteConflictError as l, DeadlineError as m, TombstonedError as n, pushPipeline as o, DEFAULT_TIMEOUTS as p, isWindowsAbsolute as r, seedHelperCache as s, RemoteWorlds as t, attachmentHeader as u, resolveTimeouts as v, storePath as w, dshHome as x, require_lib as y };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-remote-vs",
3
3
  "description": "VSCode-style remote development for DSH: SSH host manager (key/password), helper deploy pipeline with version check, remote file explorer + editor + terminal in dsh-better-sidebar.",
4
- "version": "0.20.0",
4
+ "version": "0.20.1",
5
5
  "icon": "icon.svg",
6
6
  "keywords": [
7
7
  "dsh",
@@ -11,13 +11,14 @@ import { createPortal } from 'react-dom'
11
11
  import type { Context } from '@deepseek-ai/cordis'
12
12
  import { EditorSelection, EditorState, StateEffect, StateField, Compartment, type Extension, type Text } from '@codemirror/state'
13
13
  import { Decoration, EditorView, highlightActiveLine, keymap, lineNumbers, type DecorationSet } from '@codemirror/view'
14
- import { defaultKeymap, history, historyKeymap } from '@codemirror/commands'
14
+ import { history } from '@codemirror/commands'
15
15
  import { bracketMatching, ensureSyntaxTree, indentOnInput } from '@codemirror/language'
16
16
  import { closeBrackets } from '@codemirror/autocomplete'
17
17
  import { search } from '@codemirror/search'
18
18
  import { syntaxHighlighting } from '@codemirror/language'
19
19
  import { vscodeHighlightStyle } from './vsc/editor-palette.ts'
20
20
  import { FindWidget, clearFindMarks, findMatchHighlight, stepFind } from './vsc/FindWidget.tsx'
21
+ import { editorKeymap } from './vsc/editor-keymap.ts'
21
22
  import { javascript } from '@codemirror/lang-javascript'
22
23
  import { python } from '@codemirror/lang-python'
23
24
  import { json } from '@codemirror/lang-json'
@@ -587,72 +588,33 @@ export const CodeEditor = forwardRef<CodeEditorHandle, {
587
588
  if (host === null) return
588
589
  const extensions: Extension[] = [
589
590
  history(),
590
- keymap.of([
591
- ...defaultKeymap,
592
- ...historyKeymap,
593
- { key: 'Mod-s', run: () => { propsRef.current.onSave(); return true }, preventDefault: true },
594
- // Ctrl/Cmd+F opens OUR widget (the built-in search panel is never
595
- // mounted, so `searchKeymap` is deliberately absent). A selection seeds
596
- // the query, the way it does in VS Code, so find-on-selection is one
597
- // keystroke instead of a copy-paste.
598
- {
599
- key: 'Mod-f',
600
- run: (view) => {
601
- const sel = view.state.selection.main
602
- if (!sel.empty) {
603
- const text = view.state.sliceDoc(sel.from, sel.to)
604
- if (text !== '' && text.length <= 200) {
605
- setFindSeed(prev => ({ text, id: prev.id + 1 }))
606
- }
591
+ keymap.of(editorKeymap({
592
+ save: () => { propsRef.current.onSave() },
593
+ openFindForSelection: (view) => {
594
+ const sel = view.state.selection.main
595
+ if (!sel.empty) {
596
+ const text = view.state.sliceDoc(sel.from, sel.to)
597
+ if (text !== '' && text.length <= 200) {
598
+ setFindSeed(prev => ({ text, id: prev.id + 1 }))
607
599
  }
608
- setFindOpen(true)
609
- return true
610
- },
611
- preventDefault: true,
600
+ }
601
+ setFindOpen(true)
612
602
  },
613
- { key: 'F3', run: (view) => { stepFind(view, true); return true }, preventDefault: true },
614
- { key: 'Shift-F3', run: (view) => { stepFind(view, false); return true }, preventDefault: true },
615
- /**
616
- * 上一个 / 下一个改动点。
617
- *
618
- * `Mod-Shift-Alt-ArrowUp/Down` 是挑出来的空位:`@codemirror/commands` 的
619
- * defaultKeymap 里 `Mod-Alt-ArrowUp/Down`(多光标)、`Alt-ArrowUp/Down`
620
- * (移动行)、`Shift-Alt-ArrowUp/Down`(复制行)都被占了,三者之上再加
621
- * Shift 的这两个组合它没有用;浏览器侧 Ctrl+Shift+Alt+方向键也没有默认
622
- * 行为(选中/滚动都落在更低的组合上)。
623
- *
624
- * 没有 `onStepHunk`(面板没开)时返回 false,按键照旧落回 CodeMirror 的
625
- * 默认处理,不会平白吞掉一个组合键。
626
- */
627
- {
628
- key: 'Mod-Shift-Alt-ArrowDown',
629
- run: () => {
630
- const step = propsRef.current.onStepHunk
631
- if (step === undefined) return false
632
- step(1)
633
- return true
634
- },
635
- preventDefault: true,
603
+ stepFind: (view, forward) => {
604
+ stepFind(view, forward)
636
605
  },
637
- {
638
- key: 'Mod-Shift-Alt-ArrowUp',
639
- run: () => {
640
- const step = propsRef.current.onStepHunk
641
- if (step === undefined) return false
642
- step(-1)
643
- return true
644
- },
645
- preventDefault: true,
606
+ stepHunk: (delta) => {
607
+ const step = propsRef.current.onStepHunk
608
+ if (step === undefined) return false
609
+ step(delta)
610
+ return true
646
611
  },
647
- {
648
- key: 'Escape',
649
- run: () => {
650
- if (!findOpenRef.current) return false
651
- setFindOpen(false)
652
- return true
653
- },
612
+ closeFind: () => {
613
+ if (!findOpenRef.current) return false
614
+ setFindOpen(false)
615
+ return true
654
616
  },
655
- ]),
617
+ })),
656
618
  lineNumbers(),
657
619
  highlightActiveLine(),
658
620
  indentOnInput(),
@@ -85,9 +85,9 @@ export function apply(ctx: Context): void {
85
85
  if (sidebar === undefined) return false
86
86
  // Optional host icon classifier: a better-sidebar release may publish
87
87
  // `fileIcon` / `folderIcon` alongside `registerTab`, and then the remote
88
- // tree follows the user's registered icon theme. dsh-sidebar (the local
89
- // sidebar this plugin usually runs next to) publishes none, so in practice
90
- // the built-in colour set in `vsc/file-icons.tsx` is what paints the tree.
88
+ // tree follows the user's registered icon theme. The local sidebar plugin
89
+ // this one usually runs next to publishes none, so in practice the
90
+ // built-in colour set in `vsc/file-icons.tsx` is what paints the tree.
91
91
  try {
92
92
  const candidate = sidebar as unknown as Partial<IconServiceLike>
93
93
  if (typeof candidate.fileIcon === 'function' && typeof candidate.folderIcon === 'function') {
@@ -0,0 +1,97 @@
1
+ /**
2
+ * The editor's key bindings, in one testable place.
3
+ *
4
+ * Why this module exists
5
+ * ----------------------
6
+ * Bug (2026-11-10, user report): "the remote editor cannot input Tab".
7
+ *
8
+ * CodeMirror 6's `defaultKeymap` deliberately does NOT bind Tab — the browser
9
+ * default (move focus) stays available for accessibility. Indentation is the
10
+ * opt-in `indentWithTab` binding, and this plugin never added it, so Tab fell
11
+ * through to the browser: the caret left the editor instead of indenting. The
12
+ * local sidebar editor binds it, which is why the same key worked there.
13
+ *
14
+ * The binding list used to live inline inside the CodeMirror mount effect, which
15
+ * meant the only way to test it was to render the whole component. It lives here
16
+ * so `scripts/check-editor-tab.mjs` can mount a real CodeMirror with the REAL
17
+ * binding list and dispatch real Tab/Shift-Tab presses.
18
+ *
19
+ * Handlers are injected (no React, no editor state): the component wires them to
20
+ * its refs/stores.
21
+ */
22
+ import type { EditorView, KeyBinding } from '@codemirror/view'
23
+ import { defaultKeymap, historyKeymap, indentWithTab } from '@codemirror/commands'
24
+
25
+ /** The editor actions the key bindings dispatch into. */
26
+ export interface EditorKeyHandlers {
27
+ /** Ctrl/Cmd+S → the pane's save path. */
28
+ save(): void
29
+ /** Ctrl/Cmd+F → seed our find widget from the selection and open it. */
30
+ openFindForSelection(view: EditorView): void
31
+ /** F3 / Shift+F3 → step through matches. */
32
+ stepFind(view: EditorView, forward: boolean): void
33
+ /** Jump to the previous/next change hunk; false when the panel is closed. */
34
+ stepHunk(delta: 1 | -1): boolean
35
+ /** Escape → close the find widget; false when it was not open. */
36
+ closeFind(): boolean
37
+ }
38
+
39
+ /**
40
+ * Build the editor keymap.
41
+ *
42
+ * Order: the stock keymaps first, then the two additions that make this editor
43
+ * behave like VS Code — `indentWithTab` (Tab / Shift-Tab indent or dedent) and
44
+ * our own shortcuts. `indentWithTab` is deliberately NOT part of CodeMirror's
45
+ * defaults, which is exactly what shipped the "Tab does nothing" bug; a red
46
+ * proof in the gate removes it again.
47
+ */
48
+ export function editorKeymap(handlers: EditorKeyHandlers): KeyBinding[] {
49
+ return [
50
+ ...defaultKeymap,
51
+ ...historyKeymap,
52
+ // Tab inserts a unit of indentation at the caret line; Shift-Tab dedents the
53
+ // selected lines. Read-only views make `indentMore` return false, so the key
54
+ // still falls through to the browser there (diff panes stay navigable).
55
+ indentWithTab,
56
+ { key: 'Mod-s', run: () => { handlers.save(); return true }, preventDefault: true },
57
+ // Ctrl/Cmd+F opens OUR widget (the built-in search panel is never mounted,
58
+ // so `searchKeymap` is deliberately absent). A selection seeds the query,
59
+ // the way it does in VS Code, so find-on-selection is one keystroke.
60
+ {
61
+ key: 'Mod-f',
62
+ run: (view) => {
63
+ handlers.openFindForSelection(view)
64
+ return true
65
+ },
66
+ preventDefault: true,
67
+ },
68
+ { key: 'F3', run: (view) => { handlers.stepFind(view, true); return true }, preventDefault: true },
69
+ { key: 'Shift-F3', run: (view) => { handlers.stepFind(view, false); return true }, preventDefault: true },
70
+ /**
71
+ * Previous / next change hunk.
72
+ *
73
+ * `Mod-Shift-Alt-ArrowUp/Down` is the free combination: defaultKeymap already
74
+ * uses `Mod-Alt-Arrow*` (multi-cursor), `Alt-Arrow*` (move line) and
75
+ * `Shift-Alt-Arrow*` (copy line), and browsers leave this extra Shift alone.
76
+ *
77
+ * NO `preventDefault: true` here, deliberately: CodeMirror prevents the
78
+ * default whenever a binding for that key sets the flag, even if every
79
+ * command returns false (view keymap `runFor`). With the panel closed the
80
+ * handler returns false, and the key must fall through instead of being
81
+ * swallowed — the 2026-11-10 gate found this latent swallow while pinning
82
+ * the Tab fix.
83
+ */
84
+ {
85
+ key: 'Mod-Shift-Alt-ArrowDown',
86
+ run: () => handlers.stepHunk(1),
87
+ },
88
+ {
89
+ key: 'Mod-Shift-Alt-ArrowUp',
90
+ run: () => handlers.stepHunk(-1),
91
+ },
92
+ {
93
+ key: 'Escape',
94
+ run: () => handlers.closeFind(),
95
+ },
96
+ ]
97
+ }
@@ -8,19 +8,18 @@
8
8
  *
9
9
  * Provenance
10
10
  * ----------
11
- * These are a straight port of the local sidebar plugin's artwork (`FileTypeIcon`
12
- * and its amber `FolderIcon` in dsh-sidebar's `src/client/icons.tsx`, package
13
- * name `dsh-sidebar`): one paper sheet whose colour and bottom-right mark carry
14
- * the type — TS blue + `<>`, JS yellow + `<>`, Python blue with a yellow mark,
15
- * Markdown blue + lines, images purple + a mountain, archives yellow + a zip,
16
- * `.gitignore` orange + a commit graph.
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.
17
16
  *
18
17
  * The copy exists on purpose: the client bundle may not import another plugin's
19
- * values (tsdown's purity gate rejects cross-plugin imports), and dsh-sidebar
18
+ * values (tsdown's purity gate rejects cross-plugin imports), and that plugin
20
19
  * publishes no `fileIcon` / `folderIcon` service that `kit.tsx` could call.
21
20
  * `kit.tsx` still prefers such a service if a host ever provides one (the
22
- * better-sidebar lineage is where that contract would come from); this set is
23
- * the fallback that paints a real, typed tree in a dsh-sidebar profile.
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.
24
23
  *
25
24
  * One deliberate difference from the source: the image mark used
26
25
  * `fill="currentColor"`, which in a tree inherits the row's dim text colour —
@@ -8,14 +8,15 @@
8
8
  * Icon sourcing has two tiers. `FileIcon` / `FolderIcon` paint the plain glyphs
9
9
  * below (search hits, SCM rows, commit panes, download rows — list chrome where
10
10
  * one neutral outline reads best). `ExplorerFileIcon` / `ExplorerFolderIcon`
11
- * paint the COLOURED type set ported from dsh-sidebar in `./file-icons.tsx`, so
12
- * the remote directory tree looks like the local sidebar's tree: one sheet
13
- * whose colour and mark carry the file type, and an amber folder that opens.
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.
14
15
  *
15
16
  * Every tier still prefers the host service when one is published (the
16
- * better-sidebar lineage's `fileIcon` / `folderIcon`: host classifier plus any
17
- * registered icon theme). dsh-sidebar itself publishes none today, so in a
18
- * dsh-sidebar profile the SVG sets above are what actually render.
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.
19
20
  */
20
21
  import {
21
22
  createElement,
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()