dsh-remote 1.4.1 → 1.6.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.
package/lib/main.js CHANGED
@@ -23,7 +23,7 @@ import { createGitRoutes } from './remote-git.js'
23
23
  import { createLocalWorkspacePool } from './local-workspace.js'
24
24
  import { LOCAL_MUTATION_TOOLS, remoteLocalMutationDecision } from './local-mutation.js'
25
25
  import { fileChange, changeOutput, presentFileChange } from './file-changes.js'
26
- import { captureRemoteFile, atomicRemoteWrite } from './remote-write.js'
26
+ import { captureRemoteFile, atomicRemoteWrite, missingRemoteFile } from './remote-write.js'
27
27
  import z from '@deepseek-ai/schemastery'
28
28
  import { createAutoUpdater } from './auto-update.js'
29
29
  import { defineTool } from '@deepseek-ai/dsh-tools'
@@ -37,7 +37,7 @@ import iconv from 'iconv-lite'
37
37
 
38
38
  import {
39
39
  shq, normalizeRemotePath, joinRemotePath, joinRemoteRel, resolveRemoteWorkspacePath, remoteDirname, mkdirRemoteDirs,
40
- toShellPath, toDisplayPath, remotePathBase, remoteWorkspaceTitle, truncate, shortHash,
40
+ toShellPath, toDisplayPath, remoteWorkspaceTitle, truncate,
41
41
  } from './paths.js'
42
42
  import { createHostKeyGuard, isHostKeyKnown as _isHostKeyKnown } from './hostkey.js'
43
43
  import { compileIgnore, ignorePatternsFor, DEFAULT_IGNORE } from './ignore.js'
@@ -51,12 +51,15 @@ import { createInstructionIndex, formatInstructionIndex } from './instructions.j
51
51
  import { resolveExecTimeout, formatExecResult, startExecJob, execWithOptionalPromotion } from './exec-job.js'
52
52
  import { createInjectionTracker, refreshTouched, buildInstructionMessage, pickUserMessageFactory, loadBundledUserMessageFactory } from './instructions-dynamic.js'
53
53
  import { REMOTE_SANDBOX_MODES, checkRemoteSandbox, remoteSandboxDenial } from './remote-sandbox.js'
54
- import { mirrorConstrainLocalTarget, mirrorDownloadTarget, assertDownloadHasNoSymlinks } from './mirror-paths.js'
54
+ import {
55
+ mirrorConstrainLocalTarget, mirrorDownloadTarget, assertDownloadHasNoSymlinks,
56
+ mirrorDirectory, mirrorDirectoriesUnder, readMirrorMeta, sameMirrorMachine,
57
+ } from './mirror-paths.js'
55
58
  import { createTerminalManager } from './terminal.js'
56
59
  import { createTerminalRoutes } from './routes-term.js'
57
60
  import { searchRemote } from './search.js'
58
61
  import { installTerminalShell } from './remote-shell.js'
59
- import { resolveMirror, poolKey, lookupSessionCwd, encodeSegmentSafe, readSessionHeaderCwd, requestSessionHint } from './binding.js'
62
+ import { resolveMirror, poolKey, lookupSessionCwd, requestSessionHint } from './binding.js'
60
63
  import { TaskManager } from './tasks.js'
61
64
  import { ForwardManager } from './forwards.js'
62
65
  import { formatAuditLine, readAuditLines } from './audit.js'
@@ -67,6 +70,7 @@ import { startHeartbeat, pseudonym, heartbeatUrl, hasPersistedId, installIdPath,
67
70
  import { loadMachines as _loadMachines, saveMachines as _saveMachines, sanitizeMachine as _sanitizeMachine, applyMachine as _applyMachine, machineId as _machineId, normalizeMachineGroup, filterMachinesByGroup, resolveProbeCredentials } from './registry.js'
68
71
  import { registerHttpTransports } from './http-transport.js'
69
72
  import { createHostApi } from './host-api.js'
73
+ import { isWorkspaceSessionCwd } from './workspace-cleanup.js'
70
74
  import { SshPool, ActivePool, createPool } from './pool.js'
71
75
  import { isSystemOpenSshBackend, sshBinaryAvailable, resolveSshBinary } from './openssh.js'
72
76
  import { createAuditRoutes } from './routes-audit.js'
@@ -80,7 +84,7 @@ import { createWorkspaceRoutes } from './routes-workspace.js'
80
84
  import { listDirStructured, removeRemoteTree } from './remote-fs.js'
81
85
  import { registerRemoteSkills } from './remote-skills.js'
82
86
  import { installWorkspaceFilesRemote } from './workspace-files-remote.js'
83
- import { describeConnect } from './connect-summary.js'
87
+ import { connectFailureText, describeConnect } from './connect-summary.js'
84
88
 
85
89
  export const name = 'dsh-remote'
86
90
 
@@ -151,6 +155,17 @@ export function pickWorkspaceNextStep(localSession) {
151
155
  : 'Run rw_sync to download its files into the local mirror.'
152
156
  }
153
157
 
158
+ /** Issue #205: the closing note when the picking session is ALREADY bound to a
159
+ * different workspace. rw_pick_workspace does not rebind the current session
160
+ * — a model that assumes "paths now resolve against the new pick" silently
161
+ * operates on the old workspace — so the success text must say so explicitly.
162
+ * The parallel-worktree flow (pick each worktree once, one session per
163
+ * mirror) is the documented answer. */
164
+ export function pickWorkspaceRebindNote(currentWs, pickedWs, display) {
165
+ if (!currentWs || currentWs === pickedWs) return null
166
+ return `NOTE: this session is still bound to ${display(currentWs)} — relative paths, rw_exec's working directory and rw_sync keep resolving against IT. To work inside the newly picked workspace, open a session whose workspace is the local mirror path above (for parallel git worktrees: pick each worktree once, one session per mirror), or pass absolute paths / an explicit cd in commands.`
167
+ }
168
+
154
169
  // Web and Desktop share the SSH tools; each optional UI transport is attached
155
170
  // reactively below, so service startup order does not drop the JSON routes.
156
171
  export const inject = ['tools', 'systemPrompt']
@@ -353,12 +368,6 @@ function remoteWorkspacesRoot() {
353
368
  return path.join(dshBase(), 'remote-workspaces')
354
369
  }
355
370
 
356
- /** Local mirrors of one remote host. */
357
- function mirrorRootFor(host, user, port) {
358
- const tag = [host, user, port].filter(Boolean).join('-').replace(/[^a-zA-Z0-9._-]/g, '_')
359
- return path.join(remoteWorkspacesRoot(), tag)
360
- }
361
-
362
371
  /** Generated terminal launchers. Deliberately NOT under `remote-workspaces`: a
363
372
  * launcher there would sit next to the mirrors, where anything that scans the
364
373
  * root for checkouts could pick it up as one. */
@@ -383,34 +392,12 @@ function remoteShellSpec() {
383
392
  }
384
393
  }
385
394
 
386
- /** Local mirror dir for a specific remote path (idempotent → returns same dir). */
387
- function mirrorDirFor(remotePath, host, user, port) {
388
- const base = remotePathBase(remotePath)
389
- const root = mirrorRootFor(host, user, port)
390
- const plain = path.join(root, base)
391
- const norm = normalizeRemotePath(remotePath)
392
- // A pre-existing mirror for this exact remote origin → reuse it (idempotent).
393
- try {
394
- const meta = JSON.parse(readFileSync(path.join(plain, '.dsh-remote-meta.json'), 'utf8'))
395
- if (meta.remotePath === norm) return plain
396
- } catch {
397
- /* no mirror yet → fall through */
398
- }
399
- if (!existsSync(plain)) return plain
400
- return path.join(root, base + '-' + shortHash(norm))
395
+ function mirrorDirFor(remotePath, host, user, port, alias = '') {
396
+ return mirrorDirectory(remoteWorkspacesRoot(), remotePath, host, user, port, { alias })
401
397
  }
402
398
 
403
- /** Create the local mirror dir + a meta file describing its remote origin.
404
- * `extra.alias` records the ~/.ssh/config alias a machine was saved as (issue
405
- * #38), so the mirror keeps resolving to its machine even if the alias's
406
- * HostName/user/port change in that file afterwards. */
407
- function ensureMirror(remotePath, host, user, port, extra = {}) {
408
- const dir = mirrorDirFor(remotePath, host, user, port)
409
- mkdirSync(dir, { recursive: true })
410
- const meta = { host, port, username: user, remotePath: normalizeRemotePath(remotePath), createdAt: new Date().toISOString() }
411
- if (extra.alias) meta.alias = String(extra.alias)
412
- writeFileSync(path.join(dir, '.dsh-remote-meta.json'), JSON.stringify(meta, null, 2))
413
- return dir
399
+ function ensureMirror(remotePath, host, user, port, { alias = '' } = {}) {
400
+ return mirrorDirectory(remoteWorkspacesRoot(), remotePath, host, user, port, { alias, create: true })
414
401
  }
415
402
 
416
403
  /** Recursive directory copy (EXDEV fallback for migrateLegacyData). */
@@ -849,6 +836,9 @@ export async function apply(ctx, config) {
849
836
  // Issue #51: the backend is part of the target identity, so a machine switch
850
837
  // between backends must be seen as a change by setTarget.
851
838
  backend: c.backend, sshBinary: c.sshBinary,
839
+ // Issue #206: the per-machine shell is part of the target identity too —
840
+ // a switch that only changes it must reset the cached platform detection.
841
+ shell: c.shell,
852
842
  })
853
843
 
854
844
  /** Fingerprint of the machine record last applied to the shared pool config.
@@ -946,10 +936,9 @@ export async function apply(ctx, config) {
946
936
  * identity, and directly by the alias the mirror recorded — so a mirror keeps
947
937
  * resolving to its machine even after a HostName/port change in ~/.ssh/config,
948
938
  * which is the whole point of not copying those values into the registry. */
949
- const identityOf = (m) => {
950
- const r = withSshConfig(m)
951
- return { host: r.host, port: Number(r.port) || 22, username: r.username || '' }
952
- }
939
+ const resolvedIdentity = (m) => ({ host: m.host, port: Number(m.port) || 22, username: m.username || '' })
940
+ const identityOf = (m) => resolvedIdentity(withSshConfig(m))
941
+ const mirrorOrigin = (resolved) => ({ ...resolvedIdentity(resolved), alias: aliasOf(resolved) })
953
942
  const identityMatches = (m, { host, port, username }) => {
954
943
  if (!m) return false
955
944
  const id = identityOf(m)
@@ -1233,11 +1222,18 @@ export async function apply(ctx, config) {
1233
1222
  /** Mirror-sync matcher for the workspace rooted at `root` (ROOT_IGNORE is
1234
1223
  * merged only for a filesystem-root workspace — issue #60). */
1235
1224
  const ignoreMatcher = (root) => compileIgnore(ignorePatternsFor(root, { fromFile: readUserIgnore() }))
1236
- /** Search-only matcher: same as ignoreMatcher() plus machine-local cache trees
1237
- * (`~/.npm`, `~/.cache`, …) that are huge, almost never what a human is
1238
- * looking for, and the main cause of the issue #44 hang. Mirror sync is
1239
- * deliberately unaffected. An explicit `path` still searches anywhere. */
1240
- const searchIgnoreMatcher = (root) => compileIgnore(ignorePatternsFor(root, { search: true, fromFile: readUserIgnore() }))
1225
+ /** RAW search ignore patterns for the workspace rooted at `root`: the defaults
1226
+ * plus machine-local cache trees (`~/.npm`, `~/.cache`, …) that are huge,
1227
+ * almost never what a human is looking for, and the main cause of the issue
1228
+ * #44 hang, plus the user's `.dsh-remote-ignore`. Mirror sync keeps its own
1229
+ * narrower set and is deliberately unaffected. An explicit `path` still
1230
+ * searches anywhere.
1231
+ *
1232
+ * The POSIX search fast path receives this SAME list (as `ignorePatterns`), so
1233
+ * its rg/grep excludes cannot drift from the matcher the SFTP walk uses. */
1234
+ const searchIgnorePatterns = (root) => ignorePatternsFor(root, { search: true, fromFile: readUserIgnore() })
1235
+ /** Search-only matcher, compiled from exactly the list above. */
1236
+ const searchIgnoreMatcher = (root) => compileIgnore(searchIgnorePatterns(root))
1241
1237
 
1242
1238
  // ── task + forward managers ───────────────────────────────────────────────
1243
1239
  const tasks = new TaskManager()
@@ -1447,7 +1443,8 @@ export async function apply(ctx, config) {
1447
1443
  // invalidate a pool used by another conversation, terminal or file editor.
1448
1444
  const prepareMirrorTarget = async (remotePath, selectedMachine, signal) => {
1449
1445
  const machine = { ...(selectedMachine || activeMachine() || config) }
1450
- const identity = identityOf(machine)
1446
+ const resolved = machine.sshAlias || machine.sshConfigMatched ? machine : withSshConfig(machine)
1447
+ const identity = resolvedIdentity(resolved)
1451
1448
  const base = poolForMachine({ ...identity, alias: aliasOf(machine) })
1452
1449
  const isolated = createPool({ ...base.config }, { knownHostsFile, opensshKnownHostsFile })
1453
1450
  isolated.passwordResolver = base.passwordResolver
@@ -1470,6 +1467,23 @@ export async function apply(ctx, config) {
1470
1467
 
1471
1468
  // ── remote workspace state ────────────────────────────────────────────────
1472
1469
  const wsPath = () => (config.workspace || '').trim()
1470
+ // OpenSSH can dial by name with implicit user/port. A mirror records the
1471
+ // resolved origin of the selected machine, provided its dial target is active.
1472
+ const activeMirrorOrigin = () => {
1473
+ const active = resolvedIdentity(config)
1474
+ const machine = activeMachine()
1475
+ if (machine) {
1476
+ const dial = connectTargetFor(machine)
1477
+ if (dial.host === active.host && dial.username === active.username && (dial.port || 22) === active.port) return mirrorOrigin(machine)
1478
+ }
1479
+ return active
1480
+ }
1481
+ const activeMirrorDir = ({ host, username, port, alias } = activeMirrorOrigin()) =>
1482
+ wsPath() ? mirrorDirFor(wsPath(), host, username, port, alias) : ''
1483
+ const ensureBoundMirror = (remotePath, binding) => {
1484
+ const { host, username, port, alias } = binding.mirrorOrigin || binding
1485
+ return ensureMirror(remotePath, host, username, port, { alias })
1486
+ }
1473
1487
  /** Map a LOCAL path to the remote path its mirror represents ('' when the
1474
1488
  * path is not inside any dsh-remote mirror). Shared by the resolve-mirror
1475
1489
  * route, the session-aware system-prompt injection, and status().
@@ -1604,54 +1618,38 @@ export async function apply(ctx, config) {
1604
1618
  }
1605
1619
  const nextRaw = { host: String(next.host || ''), port: Number(next.port) || 22, username: String(next.username || '') }
1606
1620
  const sameIdentity = (a, b) => a.host === b.host && a.port === b.port && a.username === b.username
1607
- if (!prevAlias && sameIdentity(prevId, nextId) && sameIdentity(prevRaw, nextRaw)) return 0
1608
- if (prevAlias && prevAlias === nextAlias) return 0
1609
- const root = remoteWorkspacesRoot()
1621
+ if (prevAlias === nextAlias && (prevAlias || (sameIdentity(prevId, nextId) && sameIdentity(prevRaw, nextRaw)))) return 0
1622
+ const previous = { ...prevId, alias: prevAlias }
1623
+ const previousRaw = { ...prevRaw, alias: prevAlias }
1610
1624
  let rebound = 0
1611
- let hostDirs = []
1612
- try { hostDirs = readdirSync(root) } catch { return 0 }
1613
- for (const hostDir of hostDirs) {
1614
- const hostPath = path.join(root, hostDir)
1615
- if (!statSync(hostPath, { throwIfNoEntry: false })?.isDirectory?.()) continue
1616
- let entries = []
1617
- try { entries = readdirSync(hostPath) } catch { continue }
1618
- for (const entry of entries) {
1619
- const metaPath = path.join(hostPath, entry, '.dsh-remote-meta.json')
1620
- let meta = null
1621
- try { meta = JSON.parse(readFileSync(metaPath, 'utf8')) } catch { continue }
1622
- if (!meta || !meta.host) continue
1623
- const byAlias = prevAlias && String(meta.alias || '') === prevAlias
1624
- // A meta records the RESOLVED identity at pick time, but that identity
1625
- // can also have been written raw — match on either form of the old
1626
- // identity so a rebind still finds mirrors recorded before a later
1627
- // ssh-config resolution rewrote what "this machine" meant.
1628
- const metaId = { host: String(meta.host), port: Number(meta.port) || 22, username: String(meta.username || '') }
1629
- const byIdentity = sameIdentity(metaId, prevId) || sameIdentity(metaId, prevRaw)
1630
- if (!byAlias && !byIdentity) continue
1631
- const updated = { ...meta }
1632
- if (nextAlias) {
1633
- // Alias machine: the recorded alias is what future resolution keys
1634
- // on; the resolved address refreshes only when it actually resolved
1635
- // (an unmatched alias keeps the old literal values rather than
1636
- // stamping the alias NAME into the address fields).
1637
- updated.alias = nextAlias
1638
- if (nextEff.sshConfigMatched || nextEff.sshAlias) {
1639
- updated.host = nextId.host
1640
- updated.port = nextId.port
1641
- updated.username = nextId.username
1642
- }
1643
- } else {
1644
- delete updated.alias
1645
- updated.host = nextRaw.host
1646
- updated.port = nextRaw.port
1647
- updated.username = nextRaw.username
1625
+ for (const dir of mirrorDirectoriesUnder(remoteWorkspacesRoot())) {
1626
+ const meta = readMirrorMeta(dir)
1627
+ if (typeof meta?.remotePath !== 'string' || !meta.remotePath) continue
1628
+ // Literal mirrors may have recorded the saved or resolved endpoint.
1629
+ if (!sameMirrorMachine(meta, previous) && !sameMirrorMachine(meta, previousRaw)) continue
1630
+ const updated = { ...meta }
1631
+ if (nextAlias) {
1632
+ // Alias machine: the recorded alias is what future resolution keys
1633
+ // on; the resolved address refreshes only when it actually resolved
1634
+ // (an unmatched alias keeps the old literal values rather than
1635
+ // stamping the alias NAME into the address fields).
1636
+ updated.alias = nextAlias
1637
+ if (nextEff.sshConfigMatched || nextEff.sshAlias) {
1638
+ updated.host = nextId.host
1639
+ updated.port = nextId.port
1640
+ updated.username = nextId.username
1648
1641
  }
1649
- updated.reboundAt = new Date().toISOString()
1650
- try {
1651
- writeFileSync(metaPath, JSON.stringify(updated, null, 2))
1652
- rebound++
1653
- } catch { /* leave that mirror as-is */ }
1642
+ } else {
1643
+ delete updated.alias
1644
+ updated.host = nextRaw.host
1645
+ updated.port = nextRaw.port
1646
+ updated.username = nextRaw.username
1654
1647
  }
1648
+ updated.reboundAt = new Date().toISOString()
1649
+ try {
1650
+ writeFileSync(path.join(dir, '.dsh-remote-meta.json'), JSON.stringify(updated, null, 2))
1651
+ rebound++
1652
+ } catch { /* leave that mirror as-is */ }
1655
1653
  }
1656
1654
  if (rebound) {
1657
1655
  // The old identity's pooled connection dials an address the user just
@@ -1666,9 +1664,7 @@ export async function apply(ctx, config) {
1666
1664
  return rebound
1667
1665
  }
1668
1666
 
1669
- if (config.autoPush && wsPath()) {
1670
- startAutoPush(mirrorDirFor(wsPath(), config.host, config.username, config.port))
1671
- }
1667
+ if (config.autoPush && wsPath()) startAutoPush(activeMirrorDir())
1672
1668
  /** The remote path one agent session is bound to, or '' when that session is
1673
1669
  * a plain local one. Walks the mirror registry (host side copy of the
1674
1670
  * resolve-mirror logic) so status / prompt / sidebar agree.
@@ -1679,6 +1675,13 @@ export async function apply(ctx, config) {
1679
1675
  * another machine. Tool calls must never route through this — they resolve
1680
1676
  * their own session through `bindingFor()`, which is authoritative. */
1681
1677
  const sessionsSvc = () => (ctx && typeof ctx.get === 'function' ? ctx.get('sessions') : null)
1678
+ const listLiveWorkspaceSessions = (cwd) => {
1679
+ const ids = []
1680
+ for (const session of sessionsSvc()?.list?.() || []) {
1681
+ if (session?.id && isWorkspaceSessionCwd(cwd, session.header?.cwd)) ids.push(session.id)
1682
+ }
1683
+ return ids
1684
+ }
1682
1685
 
1683
1686
  /** Whether one session is still open somewhere.
1684
1687
  *
@@ -1690,8 +1693,8 @@ export async function apply(ctx, config) {
1690
1693
  */
1691
1694
  const isSessionLive = async (sessionId, dir, opts = {}) => {
1692
1695
  try {
1693
- const live = sessionsSvc()
1694
- if (live && typeof live.get === 'function' && live.get(sessionId)) return true
1696
+ const session = sessionsSvc()?.get?.(sessionId)
1697
+ if (session && isWorkspaceSessionCwd(opts.cwd, session.header?.cwd)) return true
1695
1698
  } catch { /* no sessions service (minimal embedding) */ }
1696
1699
  if (opts && opts.deep === true && process.platform !== 'win32') {
1697
1700
  const lock = path.join(String(dir || ''), 'session.lock')
@@ -1824,13 +1827,15 @@ export async function apply(ctx, config) {
1824
1827
  err.httpStatus = 409
1825
1828
  throw err
1826
1829
  }
1830
+ const mirrorOrigin = activeMirrorOrigin()
1827
1831
  return {
1828
1832
  pool,
1829
1833
  ws: wsPath(),
1830
1834
  host: config.host,
1831
1835
  username: config.username,
1832
1836
  port: config.port,
1833
- mirrorDir: wsPath() ? mirrorDirFor(wsPath(), config.host, config.username, config.port) : null,
1837
+ mirrorOrigin,
1838
+ mirrorDir: activeMirrorDir(mirrorOrigin) || null,
1834
1839
  bound: false,
1835
1840
  local: false,
1836
1841
  }
@@ -1844,7 +1849,7 @@ export async function apply(ctx, config) {
1844
1849
  const binding = await resolveRequestBinding(req, body, { allowLocal: local })
1845
1850
  if (local && !binding.local) throw Object.assign(new Error('Workspace execution context changed; reload before retrying'), { httpStatus: 409 })
1846
1851
  const route = new URL(req.url || '/', 'http://localhost').pathname
1847
- if (binding.local && ['/dsh-remote/ls', '/dsh-remote/read', '/dsh-remote/write', '/dsh-remote/fs'].includes(route)) {
1852
+ if (binding.local && ['/dsh-remote/ls', '/dsh-remote/read', '/dsh-remote/download', '/dsh-remote/write', '/dsh-remote/fs'].includes(route)) {
1848
1853
  for (const field of ['path', 'dest']) {
1849
1854
  const target = body[field] || q.get(field)
1850
1855
  if (target) await binding.pool.checkPath(String(target), { mutation: route === '/dsh-remote/write' || route === '/dsh-remote/fs' })
@@ -1891,13 +1896,15 @@ export async function apply(ctx, config) {
1891
1896
  }
1892
1897
  }
1893
1898
  }
1899
+ const mirrorOrigin = activeMirrorOrigin()
1894
1900
  return {
1895
1901
  pool,
1896
1902
  ws: wsPath(),
1897
1903
  host: config.host,
1898
1904
  username: config.username,
1899
1905
  port: config.port,
1900
- mirrorDir: wsPath() ? mirrorDirFor(wsPath(), config.host, config.username, config.port) : null,
1906
+ mirrorOrigin,
1907
+ mirrorDir: activeMirrorDir(mirrorOrigin) || null,
1901
1908
  bound: false,
1902
1909
  // A caller that identified itself with a cwd, yet resolved to no mirror,
1903
1910
  // is definitively a LOCAL session. Distinguish it from "no caller
@@ -2036,31 +2043,34 @@ export async function apply(ctx, config) {
2036
2043
  const watcher = autoPushWatchers.get(local)
2037
2044
  return { ...observed, ...(watcher && watcher.pending.size ? { phase: 'pending' } : {}), autoPush: !!config.autoPush }
2038
2045
  }
2039
- const status = () => ({
2040
- host: config.host,
2041
- port: config.port,
2042
- username: config.username,
2043
- connected: !!pool.client,
2044
- workspace: toDisplayPath(wsPath(), pool.platform),
2045
- localMirror: wsPath() ? mirrorDirFor(wsPath(), config.host, config.username, config.port) : '',
2046
- currentId: store.currentId || null,
2047
- sync: syncStatusFor(wsPath() ? mirrorDirFor(wsPath(), config.host, config.username, config.port) : ''),
2048
- activeSource: ephemeral ? 'ephemeral' : (store.currentId ? 'machine' : (config.host ? 'config' : 'none')),
2049
- // Issue #13: whether THIS session is in remote mode (cwd inside a mirror).
2050
- // `none`/`local` means the plugin is present but no remote context is
2051
- // active — saved machines stay standby-only.
2052
- sessionMode: sessionRemotePath() ? 'remote' : (store.currentId ? 'standby' : 'local'),
2053
- sessionRemotePath: sessionRemotePath(),
2054
- machines: machinesForClient(),
2055
- hostKeyMode: config.hostKeyMode === 'verify' || config.hostKeyMode === 'off' ? config.hostKeyMode : 'accept-new',
2056
- hostKeyKnown: config.host ? isHostKeyKnown(config.host, config.port) : false,
2057
- forwards: forwards.list(),
2058
- auditEnabled: !!config.auditLog,
2059
- backend: platformBackend(),
2060
- platform: pool.platform,
2061
- shell: pool.shellMode,
2062
- gitBash: pool.gitBashPath || '',
2063
- })
2046
+ const status = () => {
2047
+ const localMirror = activeMirrorDir()
2048
+ return {
2049
+ host: config.host,
2050
+ port: config.port,
2051
+ username: config.username,
2052
+ connected: !!pool.client,
2053
+ workspace: toDisplayPath(wsPath(), pool.platform),
2054
+ localMirror,
2055
+ currentId: store.currentId || null,
2056
+ sync: syncStatusFor(localMirror),
2057
+ activeSource: ephemeral ? 'ephemeral' : (store.currentId ? 'machine' : (config.host ? 'config' : 'none')),
2058
+ // Issue #13: whether THIS session is in remote mode (cwd inside a mirror).
2059
+ // `none`/`local` means the plugin is present but no remote context is
2060
+ // active — saved machines stay standby-only.
2061
+ sessionMode: sessionRemotePath() ? 'remote' : (store.currentId ? 'standby' : 'local'),
2062
+ sessionRemotePath: sessionRemotePath(),
2063
+ machines: machinesForClient(),
2064
+ hostKeyMode: config.hostKeyMode === 'verify' || config.hostKeyMode === 'off' ? config.hostKeyMode : 'accept-new',
2065
+ hostKeyKnown: config.host ? isHostKeyKnown(config.host, config.port) : false,
2066
+ forwards: forwards.list(),
2067
+ auditEnabled: !!config.auditLog,
2068
+ backend: platformBackend(),
2069
+ platform: pool.platform,
2070
+ shell: pool.shellMode,
2071
+ gitBash: pool.gitBashPath || '',
2072
+ }
2073
+ }
2064
2074
 
2065
2075
  // ── remote `@` completion (issue #39) ─────────────────────────────────────
2066
2076
  //
@@ -2259,6 +2269,7 @@ export async function apply(ctx, config) {
2259
2269
  hostKeyMode: { type: 'string', description: 'Host-key policy for this machine: ask | strict | off (default from config)' },
2260
2270
  backend: { type: 'string', description: 'SSH transport backend (issue #51): "native" (default) uses the built-in ssh2 client (password / private key / agent / keyboard-interactive); "openssh" drives the LOCAL ssh command, which is the only way to reach hosts that require GSSAPI/Kerberos (log in once with kinit) and which honours the whole of ~/.ssh/config (ProxyCommand, PKCS11Provider, Match blocks). Prefer "openssh" together with useSshConfig=true so the alias and its settings stay the single source of truth.' },
2261
2271
  sshBinary: { type: 'string', description: 'Path (or PATH name) of the ssh executable the "openssh" backend drives — default "ssh"' },
2272
+ shell: { type: 'string', description: 'Windows remotes: the bash.exe path (or a wrapper script) to use as the remote shell, overriding auto-detection (where bash) — e.g. when auto-detect finds the WSL launcher stub, or Git Bash needs a wrapper to survive sshd. Leave empty to auto-detect.' },
2262
2273
  name: { type: 'string', description: 'Display name for a newly saved machine (default: the host)' },
2263
2274
  useSshConfig: { type: 'boolean', description: 'Treat `host` as a ~/.ssh/config Host alias; resolve host/user/port/key/proxy from that file (issue #38)' },
2264
2275
  save: { type: 'boolean', description: 'Save this machine to the registry and make it current (default true)' },
@@ -2330,6 +2341,9 @@ export async function apply(ctx, config) {
2330
2341
  // handed to ssh verbatim so ~/.ssh/config stays the single source.
2331
2342
  if (args.backend) rec.backend = args.backend === 'openssh' ? 'openssh' : 'native'
2332
2343
  if (args.sshBinary !== undefined) rec.sshBinary = String(args.sshBinary)
2344
+ // Issue #206: the per-machine shell is settable at connect time too,
2345
+ // mirroring sshBinary (it is honored by both backends' detection).
2346
+ if (args.shell !== undefined) rec.shell = String(args.shell)
2333
2347
  // Issue #54: the per-machine `dsh web` command is settable by hand too,
2334
2348
  // not only by the deploy flow (the README told users to set it and the
2335
2349
  // settings UI offered nowhere to type it).
@@ -2388,6 +2402,7 @@ export async function apply(ctx, config) {
2388
2402
  proxy: ct.proxy,
2389
2403
  backend: backendFor(rec, config),
2390
2404
  sshBinary: rec.sshBinary !== undefined ? rec.sshBinary : config.sshBinary,
2405
+ shell: rec.shell !== undefined ? rec.shell : config.shell,
2391
2406
  workspace: config.workspace,
2392
2407
  })
2393
2408
  appliedMachineId = ephemeral.id || null
@@ -2402,7 +2417,7 @@ export async function apply(ctx, config) {
2402
2417
  const res = await pool.exec('echo ok', { timeoutMs: 8000 })
2403
2418
  if (res.code !== 0 && !res.stdout) {
2404
2419
  audit('connect', `connect ${effUser}@${effHost}:${effPort}`, res.code)
2405
- return { text: 'connect failed: ' + (res.stderr || 'exit ' + res.code) }
2420
+ return { text: 'connect failed: ' + connectFailureText(res, { host: effHost, timeoutMs: 8000 }) }
2406
2421
  }
2407
2422
  audit('connect', `connect ${effUser}@${effHost}:${effPort}`, 0)
2408
2423
  // The probe's identity is the DIAL one; on the system-OpenSSH backend
@@ -2490,7 +2505,7 @@ export async function apply(ctx, config) {
2490
2505
  defineTool({
2491
2506
  name: 'rw_pick_workspace',
2492
2507
  description:
2493
- 'Set the remote workspace directory this session should treat as its working root on the connected remote. Verifies it exists (a directory). Use rw_list_dir to browse first if unsure. Accepts POSIX (/home/dev/project) or Windows (C:\\Users\\dev\\project) paths.',
2508
+ 'Set the remote workspace directory for this machine: verifies it exists (a directory), creates its LOCAL MIRROR (auto-push starts watching the mirror), and records it as the machine\'s workspace. Use rw_list_dir to browse first if unsure. SCOPE (issue #205): this does NOT change the current session\'s working directory — a session already bound to another workspace keeps resolving relative paths, rw_exec\'s cwd and rw_sync against ITS OWN workspace until a session is opened inside the new mirror. For parallel git worktrees: pick each worktree once, then open one session per mirror; within a single session use absolute paths or an explicit cd. Accepts POSIX (/home/dev/project) or Windows (C:\\Users\\dev\\project) paths.',
2494
2509
  parameters: {
2495
2510
  path: { type: 'string', required: true, description: 'Absolute remote directory path, e.g. /home/dev/code/project or C:\\Users\\dev\\project' },
2496
2511
  },
@@ -2519,8 +2534,8 @@ export async function apply(ctx, config) {
2519
2534
  if (!ok) return { text: `not a directory (or missing) on ${shown}` }
2520
2535
  // A bound session's workspace lives in its own mirror meta, so the
2521
2536
  // shared active-machine workspace is only updated for the unbound flow.
2537
+ const local = ensureBoundMirror(p, b)
2522
2538
  if (!b.bound) persistWorkspace(p)
2523
- const local = ensureMirror(p, b.host, b.username, b.port, { alias: b.alias || "" })
2524
2539
  startAutoPush(local)
2525
2540
  // Issue #68: discover the workspace's AGENTS.md / CLAUDE.md NOW — the
2526
2541
  // first prompt assembly can come before any rw_sync, and the mirror
@@ -2531,8 +2546,13 @@ export async function apply(ctx, config) {
2531
2546
  // The closing hint depends on where THIS session stands (issue #63):
2532
2547
  // in a LOCAL session "Run rw_sync" is a dead instruction — rw_sync
2533
2548
  // refuses a local session — so say the mirror must be OPENED first.
2549
+ // Issue #205: a session that picks a workspace DIFFERENT from its own
2550
+ // binding must be told the pick does not rebind it — the old text
2551
+ // ("Remote workspace set to …" + "Run rw_sync") read as "paths now
2552
+ // resolve against the new pick", which is not what happens.
2553
+ const rebindNote = pickWorkspaceRebindNote(b.ws, p, (x) => toDisplayPath(x, b.pool.platform))
2534
2554
  return {
2535
- text: `Remote workspace set to ${shown} on ${b.username}@${b.host}.\nLocal mirror (native workspace path): ${local}\n\n${pickWorkspaceNextStep(b.local)}`,
2555
+ text: `Remote workspace set to ${shown} on ${b.username}@${b.host}.\nLocal mirror (native workspace path): ${local}\n\n${rebindNote || pickWorkspaceNextStep(b.local)}`,
2536
2556
  }
2537
2557
  },
2538
2558
  }),
@@ -2552,18 +2572,21 @@ export async function apply(ctx, config) {
2552
2572
  async execute(args, exec) {
2553
2573
  const b = requireBinding(exec, 'rw_sync')
2554
2574
  const p = b.ws
2555
- const local = b.mirrorDir || mirrorDirFor(p, b.host, b.username, b.port)
2575
+ const local = b.bound ? b.mirrorDir : ensureBoundMirror(p, b)
2576
+ assertDownloadHasNoSymlinks(local, local)
2556
2577
  mkdirSync(local, { recursive: true })
2557
2578
  const depth = Math.min(Math.max(Number(args.depth) || 8, 1), 16)
2558
2579
  const maxFiles = Math.min(Math.max(Number(args.maxFiles) || 2000, 1), 20000)
2559
2580
  const isIgnored = ignoreMatcher(p)
2560
2581
  const body = { depth, maxDepth: depth, maxFiles, dryRun: !!args.dryRun, force: !!args.force, isIgnored }
2561
- const runSync = () => syncActivity.run(local, 'download', async (record) => {
2582
+ const runSync = (taskCtx) => syncActivity.run(local, 'download', async (record) => {
2583
+ const isCancelled = () => !!taskCtx?.cancelled
2584
+ mkdirSync(local, { recursive: true })
2562
2585
  let sftp
2563
2586
  try {
2564
2587
  sftp = await b.pool.sftp()
2565
2588
  } catch (err) {
2566
- throw new Error('sftp unavailable: ' + ((err && err.message) || err))
2589
+ if (!isCancelled()) throw new Error('sftp unavailable: ' + ((err && err.message) || err))
2567
2590
  }
2568
2591
  const state = loadSyncState(local)
2569
2592
  const { stats, nextState } = await syncTree(sftp, p, local, {
@@ -2571,10 +2594,12 @@ export async function apply(ctx, config) {
2571
2594
  state,
2572
2595
  maxFileBytes: config.maxFileBytes,
2573
2596
  getSftp: () => b.pool.sftp(),
2597
+ isCancelled,
2574
2598
  })
2575
2599
  record(stats)
2576
- if (!args.dryRun) saveSyncState(local, nextState)
2600
+ if (!args.dryRun && (!stats.cancelled || stats.files)) saveSyncState(local, nextState)
2577
2601
  let text = `${args.dryRun ? 'WOULD download' : 'Downloaded'} ${stats.files} file(s) from ${p} → ${local}.`
2602
+ if (stats.cancelled) text += ' CANCELLED (started downloads were allowed to finish; re-run rw_sync to continue).'
2578
2603
  if (stats.abortedError) text += ` ABORTED early (${stats.abortedError}; re-run rw_sync to resume incremental sync, or use rw_download for a specific file).`
2579
2604
  else if (stats.failed) text += ` ${stats.failed} failed.`
2580
2605
  if (stats.truncated || stats.files >= maxFiles) text += ` TRUNCATED (hit depth=${depth} or maxFiles=${maxFiles} cap; raise maxFiles/depth and re-run).`
@@ -2592,9 +2617,9 @@ export async function apply(ctx, config) {
2592
2617
  // Issue #68: a real sync can pull in (or obsolete) instruction files —
2593
2618
  // refresh the prompt index afterwards. Kept inside the task body so a
2594
2619
  // background sync refreshes when IT finishes, not when it is queued.
2595
- const runSyncAndIndex = async () => {
2596
- const r = await runSync()
2597
- if (!args.dryRun) {
2620
+ const runSyncAndIndex = async (taskCtx) => {
2621
+ const r = await runSync(taskCtx)
2622
+ if (!args.dryRun && !taskCtx?.cancelled) {
2598
2623
  try { await instructionIndex.refresh({ pool: b.pool, ws: p, mirrorDir: local, force: true }) } catch { /* best effort */ }
2599
2624
  }
2600
2625
  return r
@@ -2621,24 +2646,27 @@ export async function apply(ctx, config) {
2621
2646
  async execute(args, exec) {
2622
2647
  const b = requireBinding(exec, 'rw_push')
2623
2648
  const p = b.ws
2624
- const local = b.mirrorDir || mirrorDirFor(p, b.host, b.username, b.port)
2649
+ const local = b.mirrorDir || mirrorDirFor(p, b.host, b.username, b.port, b.alias)
2625
2650
  if (!existsSync(local)) throw new Error(`rw_push: local mirror does not exist — run rw_sync first (${local})`)
2626
2651
  const maxFiles = Math.min(Math.max(Number(args.maxFiles) || 2000, 1), 20000)
2627
2652
  const isIgnored = ignoreMatcher(p)
2628
2653
  const body = { maxFiles, dryRun: !!args.dryRun, force: !!args.force, isIgnored }
2629
- const runPush = () => syncActivity.run(local, 'upload', async (record) => {
2654
+ const runPush = (taskCtx) => syncActivity.run(local, 'upload', async (record) => {
2655
+ const isCancelled = () => !!taskCtx?.cancelled
2630
2656
  let sftp
2631
2657
  try {
2632
2658
  sftp = await b.pool.sftp()
2633
2659
  } catch (err) {
2634
- throw new Error('sftp unavailable: ' + ((err && err.message) || err))
2660
+ if (!isCancelled()) throw new Error('sftp unavailable: ' + ((err && err.message) || err))
2635
2661
  }
2636
2662
  const state = loadSyncState(local)
2637
2663
  try {
2638
- const { stats, nextState } = await pushTree(sftp, local, p, { ...body, state, maxFileBytes: config.maxFileBytes })
2664
+ const { stats, nextState } = await pushTree(sftp, local, p, { ...body, state, maxFileBytes: config.maxFileBytes, isCancelled })
2639
2665
  record(stats)
2640
- if (!args.dryRun) saveSyncState(local, nextState)
2666
+ if (!args.dryRun && (!stats.cancelled || stats.files)) saveSyncState(local, nextState)
2641
2667
  let text = `${args.dryRun ? 'WOULD upload' : 'Uploaded'} ${stats.files} file(s) from ${local} → ${p}.`
2668
+ if (stats.failed) text += ` ${stats.failed} failed.`
2669
+ if (stats.cancelled) text += ' CANCELLED (started uploads were allowed to finish; re-run rw_push to continue).'
2642
2670
  if (stats.truncated || stats.files >= maxFiles) text += ` TRUNCATED (hit maxFiles=${maxFiles} cap; raise maxFiles and re-run).`
2643
2671
  if (stats.skippedUnchanged) text += ` ${stats.skippedUnchanged} unchanged.`
2644
2672
  if (stats.skippedLarge) text += ` ${stats.skippedLarge} too large (over ${config.maxFileBytes} bytes).`
@@ -2928,7 +2956,7 @@ export async function apply(ctx, config) {
2928
2956
  defineTool({
2929
2957
  name: 'rw_remove',
2930
2958
  description:
2931
- 'Delete a remote file (or an empty directory). recursive=true removes a directory tree (bounded). Path is absolute. This is destructive — the agent should confirm intent before calling.',
2959
+ 'Delete a remote file or symbolic link. recursive=true removes a directory tree (bounded). Path is absolute. This is destructive — the agent should confirm intent before calling.',
2932
2960
  parameters: {
2933
2961
  path: { type: 'string', required: true, description: 'Absolute remote path to delete' },
2934
2962
  recursive: { type: 'boolean', description: 'Recursively delete a directory (default false)' },
@@ -2941,13 +2969,17 @@ export async function apply(ctx, config) {
2941
2969
  const p = resolveRemoteArg(b, args.path)
2942
2970
  if (!p || p === '/') throw new Error('rw_remove: a path is required')
2943
2971
  const sftp = await b.pool.sftp()
2944
- const st = await sftp.stat(p).catch(() => null)
2972
+ const st = await sftp.lstat(p).catch(error => { if (missingRemoteFile(error)) return null; throw error })
2945
2973
  if (!st) return { ok: false, text: `not found: ${p}` }
2946
- if (st.isDirectory && st.isDirectory()) {
2974
+ if (st.isDirectory?.()) {
2947
2975
  if (!args.recursive) throw new Error(`rw_remove: ${p} is a directory — pass recursive=true to delete its tree`)
2948
- const removed = await removeRemoteTree(sftp, p)
2976
+ const result = await removeRemoteTree(sftp, p)
2977
+ if (result.error) {
2978
+ audit('remove', result.error, 1, b)
2979
+ return { ok: false, text: result.error }
2980
+ }
2949
2981
  audit('remove', `remove -r ${p}`, 0, b)
2950
- return { ok: true, text: `removed ${removed} entries under ${p}` }
2982
+ return { ok: true, text: `removed ${result.removed} entries under ${p}` }
2951
2983
  }
2952
2984
  await sftp.unlink(p)
2953
2985
  audit('remove', `remove ${p}`, 0, b)
@@ -3104,7 +3136,8 @@ export async function apply(ctx, config) {
3104
3136
  // `running` and cancel/steer did nothing (issue #44).
3105
3137
  const maxFiles = Math.min(Math.max(Number(args.maxEntries) || config.searchMaxEntries, 1), 500000)
3106
3138
  const maxDurationMs = Math.min(Math.max(Number(args.maxDurationMs) || config.searchTimeoutMs, 1000), 600000)
3107
- const matcher = searchIgnoreMatcher(dir)
3139
+ const ignorePatterns = searchIgnorePatterns(dir)
3140
+ const matcher = compileIgnore(ignorePatterns)
3108
3141
  const { matches, scanned, truncated, cancelled } = await searchRemote(b.pool, dir, {
3109
3142
  pattern,
3110
3143
  regex,
@@ -3117,6 +3150,9 @@ export async function apply(ctx, config) {
3117
3150
  signal: exec.signal,
3118
3151
  maxScanBytes: Math.min(config.maxFileBytes || 1024 * 1024, 1024 * 1024),
3119
3152
  isIgnored: (name, isDir) => matcher(name, isDir),
3153
+ // The raw patterns, not the compiled matcher: the POSIX fast path
3154
+ // (rg/grep) needs flags derived from the same rule list.
3155
+ ignorePatterns,
3120
3156
  timeoutMs: Math.min(config.commandTimeoutMs, maxDurationMs),
3121
3157
  })
3122
3158
  const note = cancelled
@@ -3151,7 +3187,7 @@ export async function apply(ctx, config) {
3151
3187
  const p = resolveRemoteArg(b, args.path)
3152
3188
  if (!p || p === '/') throw new Error('rw_download: a remote file path is required')
3153
3189
  const ws = b.ws
3154
- let base = b.mirrorDir || (ws ? mirrorDirFor(ws, b.host, b.username, b.port) : '')
3190
+ const base = b.mirrorDir || (ws ? mirrorDirFor(ws, b.host, b.username, b.port, b.alias) : '')
3155
3191
  if (!ws || !base) throw new Error('rw_download: no remote workspace set — downloads land inside the local mirror of the workspace')
3156
3192
  // Both destination forms resolve inside the mirror with the same
3157
3193
  // grammar-aware mapping + symlink guard the HTTP download route applies
@@ -3161,16 +3197,8 @@ export async function apply(ctx, config) {
3161
3197
  ? mirrorConstrainLocalTarget(base, String(args.localPath))
3162
3198
  : mirrorDownloadTarget(base, ws, p)
3163
3199
  assertDownloadHasNoSymlinks(base, local)
3164
- // Persist the mirror meta once downloads start landing here: the
3165
- // registry lookup is only idempotent when the meta exists, and a
3166
- // session opened inside this mirror binds to the machine through it.
3167
- // Persist the mirror meta before landing anything: the directory
3168
- // lookup is only idempotent once the meta exists, and a bare download
3169
- // used to leave the dir anonymous — the next call would then resolve
3170
- // to a hashed sibling and "move" the mirror. Also lets a session
3171
- // opened inside this mirror bind back to the machine.
3172
- if (!existsSync(path.join(base, '.dsh-remote-meta.json'))) {
3173
- try { ensureMirror(ws, b.host, b.username, b.port) } catch { /* meta is an optimization, not a gate */ }
3200
+ if (!b.bound && ensureBoundMirror(ws, b) !== base) {
3201
+ throw new Error('rw_download: local mirror changed while preparing the download — retry')
3174
3202
  }
3175
3203
  mkdirSync(path.dirname(local), { recursive: true })
3176
3204
  const sftp = await b.pool.sftp()
@@ -3772,6 +3800,12 @@ export async function apply(ctx, config) {
3772
3800
  const prev = i >= 0 ? machines[i] : null
3773
3801
  const credBackend = body.credentialBackend === 'plain' ? 'plain'
3774
3802
  : (body.encryptPassword ? platformBackend() : (prev && prev.credentialBackend ? prev.credentialBackend : 'plain'))
3803
+ // Issue #212: the per-machine plain-login terminal flag. An omitted flag
3804
+ // keeps the stored one (older clients, partial API updates); an explicit
3805
+ // boolean wins — including false, which clears it.
3806
+ const keepNoCommand = body.terminalNoCommand === undefined
3807
+ ? !!(prev && prev.terminalNoCommand)
3808
+ : !!body.terminalNoCommand
3775
3809
  const rec = {
3776
3810
  id,
3777
3811
  name: String(body.name || '').trim() || host,
@@ -3816,6 +3850,14 @@ export async function apply(ctx, config) {
3816
3850
  credentialBackend: prev && prev.credentialBackend,
3817
3851
  }, config),
3818
3852
  sshBinary: String(body.sshBinary || '').trim(),
3853
+ ...(keepNoCommand ? { terminalNoCommand: true } : {}),
3854
+ // Issue #206: the per-machine shell. A form that omits it (or an older
3855
+ // client) keeps the stored value — a rebuild that dropped the field used
3856
+ // to wipe a hand-edited shell on the next save (picking a workspace was
3857
+ // enough); an explicit '' clears it.
3858
+ shell: body.shell === undefined
3859
+ ? String((prev && prev.shell) || '')
3860
+ : String(body.shell || '').trim(),
3819
3861
  // Issue #54: the per-machine `dsh web` launch command was only
3820
3862
  // ever writable by the deploy flow or by hand-editing
3821
3863
  // machines.json — the README told users to set it and the
@@ -4175,6 +4217,7 @@ export async function apply(ctx, config) {
4175
4217
  port: t.aliasNative ? 22 : (Number(eff.port) || 22),
4176
4218
  username: t.aliasNative ? '' : String(eff.username || ''),
4177
4219
  alias: aliasOf(eff),
4220
+ mirrorOrigin: mirrorOrigin(eff),
4178
4221
  }
4179
4222
  }
4180
4223
  const rec = store.currentId && machineIndex(store.currentId) >= 0 ? machines[machineIndex(store.currentId)] : null
@@ -4191,6 +4234,7 @@ export async function apply(ctx, config) {
4191
4234
  port: t.aliasNative ? 22 : (Number(m.port) || 22),
4192
4235
  username: t.aliasNative ? '' : String(m.username || ''),
4193
4236
  alias: aliasOf(m),
4237
+ mirrorOrigin: mirrorOrigin(m),
4194
4238
  }
4195
4239
  }
4196
4240
 
@@ -4402,81 +4446,22 @@ export async function apply(ctx, config) {
4402
4446
  handler: async (req, res) => {
4403
4447
  if (req.method !== 'GET') return sendJson(res, 405, { error: 'method not allowed' })
4404
4448
  try {
4405
- const q = new URL(req.url, 'http://localhost').searchParams
4406
- let local = q.get('local') ? decodeURIComponent(q.get('local')) : ''
4407
- const sessionId = q.get('sessionId') ? decodeURIComponent(q.get('sessionId')) : ''
4449
+ let { local, sessionId } = requestSessionHint(req)
4408
4450
  let resolvedVia = 'query'
4409
4451
  if (!local && sessionId) {
4410
- // 1) Live in-memory session header (active sessions only).
4411
- try {
4412
- const sessions = ctx && typeof ctx.get === 'function' ? ctx.get('sessions') : null
4413
- const session = sessions && typeof sessions.get === 'function' ? sessions.get(sessionId) : null
4414
- const header = session && session.header ? session.header : null
4415
- if (header && header.cwd) {
4416
- local = String(header.cwd)
4417
- resolvedVia = 'session'
4418
- }
4419
- } catch { /* sessions service unavailable */ }
4420
- // 2) Durable session log header (works for historical sessions too):
4421
- // walk $DSH_HOME/sessions/<projectKey>/<sessionId>/session.jsonl.zstd
4422
- // and read the header line (first zstd frame) for cwd.
4423
- if (!local) {
4424
- try {
4425
- const sessionsRoot = path.join(dshBase(), 'sessions')
4426
- if (existsSync(sessionsRoot)) {
4427
- const targetDir = encodeSegmentSafe(sessionId)
4428
- for (const projDir of readdirSync(sessionsRoot)) {
4429
- const projPath = path.join(sessionsRoot, projDir)
4430
- if (!statSync(projPath, { throwIfNoEntry: false })?.isDirectory?.()) continue
4431
- const sessDir = path.join(projPath, targetDir)
4432
- if (!statSync(sessDir, { throwIfNoEntry: false })?.isDirectory?.()) continue
4433
- const logFile = ['session.jsonl.zstd', 'session.jsonl', 'session.jsonl.gz'].map((n) => path.join(sessDir, n)).find((p) => existsSync(p))
4434
- if (!logFile) continue
4435
- const cwd = readSessionHeaderCwd(logFile)
4436
- if (cwd) {
4437
- local = cwd
4438
- resolvedVia = 'session-log'
4439
- break
4440
- }
4441
- }
4442
- }
4443
- } catch { /* session log scan failed */ }
4452
+ local = lookupSessionCwd(sessionId, { sessions: sessionsSvc() })
4453
+ if (local) resolvedVia = 'session'
4454
+ else {
4455
+ local = lookupSessionCwd(sessionId, { dshHome: dshBase() })
4456
+ if (local) resolvedVia = 'session-log'
4444
4457
  }
4445
4458
  }
4446
- const root = remoteWorkspacesRoot()
4447
- const norm = (p) => path.resolve(String(p || '')).replace(/[\\/]+$/, '') || ''
4448
- let matched = ''
4449
- let matchedRemote = ''
4450
- if (local && existsSync(root)) {
4451
- const base = norm(local)
4452
- for (const hostDir of readdirSync(root)) {
4453
- const hostPath = path.join(root, hostDir)
4454
- if (!statSync(hostPath, { throwIfNoEntry: false })?.isDirectory?.()) continue
4455
- for (const mirrorDir of readdirSync(hostPath)) {
4456
- const metaPath = path.join(hostPath, mirrorDir, '.dsh-remote-meta.json')
4457
- if (!existsSync(metaPath)) continue
4458
- try {
4459
- const meta = JSON.parse(readFileSync(metaPath, 'utf8'))
4460
- const mirrorAbs = norm(path.join(hostPath, mirrorDir))
4461
- // Exact mirror dir match, or the local path is inside the mirror dir.
4462
- if (mirrorAbs === base || base.startsWith(mirrorAbs + path.sep) || base.startsWith(mirrorAbs + '/')) {
4463
- if (mirrorAbs.length > matched.length) {
4464
- matched = mirrorAbs
4465
- matchedRemote = String(meta.remotePath || '')
4466
- }
4467
- }
4468
- } catch { /* skip unparsable meta */ }
4469
- }
4470
- }
4471
- }
4472
- // Issue #13: a non-mirror session is LOCAL — remotePath stays empty.
4473
- const remotePath = matchedRemote || ''
4459
+ const { remotePath, mirrorDir } = resolveMirrorForLocal(local)
4460
+ // Issue #13: sessions without a mirror never fall back to the active machine.
4474
4461
  return sendJson(res, 200, {
4475
- local, remotePath, mirrorDir: matched || null,
4476
- // `fallback:true` now means "this session is NOT a remote session"
4477
- // (used to mean "fell back to machine workspace").
4478
- fallback: !matchedRemote,
4479
- mode: matchedRemote ? 'remote' : 'local',
4462
+ local, remotePath, mirrorDir,
4463
+ fallback: !remotePath,
4464
+ mode: remotePath ? 'remote' : 'local',
4480
4465
  resolvedVia,
4481
4466
  })
4482
4467
  } catch (err) {
@@ -4508,14 +4493,15 @@ export async function apply(ctx, config) {
4508
4493
  // Mirror/connection surface (extracted for issue #82).
4509
4494
  ...createWorkspaceRoutes({
4510
4495
  sendJson, readBody, parseJsonObject, config, pool, backendFor, status, isRemoteDir, persistWorkspace, ensureMirror,
4511
- aliasOf, activeMachine, startAutoPush, applyRequestedMachine, registerMirroredWorkspace, localPickCapability,
4496
+ aliasOf, activeMachine, activeMirrorOrigin, startAutoPush, applyRequestedMachine, registerMirroredWorkspace, localPickCapability,
4512
4497
  pickLocalNative, listLocalDrives, probeMachineRecord, setCurrent, knownHostsFile, prepareMirrorTarget, machineForId: (id) => machines.find((m) => m.id === id),
4513
4498
  }),
4514
4499
  ...createSearchRoutes({ searches: workspaceSearches, sendJson, readBody, resolveRequestBinding: resolveWorkbenchBinding, isIgnoredFor: searchIgnoreMatcher }),
4515
4500
  ...createGitRoutes({ sendJson, resolveRequestBinding: resolveWorkbenchBinding, decodeBuf, config }),
4516
4501
  ...createFsRoutes({
4517
- sendJson, readBody, resolveRequestBinding: resolveWorkbenchBinding, decodeBuf, encodeText, audit, config, mirrorDirFor,
4502
+ sendJson, readBody, resolveRequestBinding: resolveWorkbenchBinding, decodeBuf, encodeText, audit, config, mirrorDirFor, ensureBoundMirror,
4518
4503
  onRemoteMutation: () => { if (remoteSkills) remoteSkills.invalidate() },
4504
+ openLocalPath, mirrorRoot: remoteWorkspacesRoot,
4519
4505
  }),
4520
4506
 
4521
4507
  // Embedded terminal (P1): one host-owned PTY session per machine, polled.
@@ -4659,7 +4645,10 @@ export async function apply(ctx, config) {
4659
4645
  resolveDirBinding: listDirBindingForApi,
4660
4646
  listRemoteProjects: listRemoteProjectsForApi,
4661
4647
  revealMirrorFolderRecord: revealMirrorFolderForApi,
4662
- resolveMachine: resolveMachineForApi,
4648
+ resolveMachine: (id) => {
4649
+ const machine = resolveMachineForApi(id)
4650
+ return { ...machine, ...machine.mirrorOrigin }
4651
+ },
4663
4652
  ensureMirror,
4664
4653
  registerMirroredWorkspace,
4665
4654
  checkRemoteDir: checkRemoteDirForApi,
@@ -4668,6 +4657,7 @@ export async function apply(ctx, config) {
4668
4657
  workspaceRegistry: () => (ctx && typeof ctx.get === 'function' ? ctx.get('workspaceRegistry') : undefined),
4669
4658
  forgetRemotePath,
4670
4659
  isSessionLive,
4660
+ listLiveWorkspaceSessions,
4671
4661
  })
4672
4662
  // cordis 4: `ctx.provide(name, value)` is the raw service registry (the
4673
4663
  // `Service` base class is only sugar around it). Guarded because a minimal