dsh-remote 1.3.1 → 1.4.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/README.en.md CHANGED
@@ -18,7 +18,7 @@ Use the normal layout or choose the optional **three-column IDE layout** to view
18
18
 
19
19
  <img src="https://raw.githubusercontent.com/flymysql/dsh-remote/main/docs/shots/workbench-ide.png" alt="DSH remote IDE with file tree, native code editor and agent conversation" width="1200"/>
20
20
 
21
- [1.3.1 release notes](https://github.com/flymysql/dsh-remote/blob/main/docs/release/1.3.1.md): SSH recovery, proxy-aware updates and verified official GitHub fallback.
21
+ [1.4.0 release notes](https://github.com/flymysql/dsh-remote/blob/main/docs/release/1.4.0.md): mirror-session file previews read the remote, Markdown figures render, one OpenSSH connect-timeout retry, workspace picker restored.
22
22
 
23
23
  ## Install
24
24
 
package/README.md CHANGED
@@ -26,7 +26,7 @@ dsh plugin --profile web add dsh-remote
26
26
 
27
27
  安装或升级后,重启 DSH Web 并刷新页面。自动更新状态在设置 → 远程工作区 → 插件偏好中查看。
28
28
 
29
- [1.3.1 更新说明](https://github.com/flymysql/dsh-remote/blob/main/docs/release/1.3.1.md):SSH 连接恢复、代理网络更新与官方 GitHub 下载回退。
29
+ [1.4.0 更新说明](https://github.com/flymysql/dsh-remote/blob/main/docs/release/1.4.0.md):镜像会话文件预览直读远端、Markdown 插图渲染、OpenSSH 建连超时重试、工作区选择器恢复。
30
30
 
31
31
  ## 3 步开始
32
32
 
package/lib/client.js CHANGED
@@ -27,7 +27,7 @@ window.__ModuleLoader__.load({
27
27
 
28
28
  const React = require('react')
29
29
  const name = 'dsh-remote'
30
- const CLIENT_VERSION = '1.3.1'
30
+ const CLIENT_VERSION = '1.4.0'
31
31
 
32
32
  // ── optional host primitives ────────────────────────────────────────────
33
33
  // Issue #74: a remote session's .md link must open over SFTP, NOT via the
@@ -675,6 +675,10 @@ window.__ModuleLoader__.load({
675
675
  'explorer.refresh': '刷新',
676
676
  'explorer.newDir': '新建目录',
677
677
  'explorer.more': '…',
678
+ 'explorer.pickRemote': '选择远程工作区',
679
+ 'explorer.pickRemoteHint': '在远程主机上选择要浏览的目录(只影响这个会话的文件面板,不改动会话的工作区绑定)',
680
+ 'explorer.retry': '重试',
681
+ 'explorer.registryUnavailable': '暂时无法读取远程工作区列表,因此无法判断这个会话是不是远程会话。请重试。',
678
682
  'explorer.remoteWs': '远程工作区: {path}{host}',
679
683
  'explorer.hostTag': ' ({user}@{host})',
680
684
  'explorer.noRemoteWs': '未设置远程工作区',
@@ -1294,6 +1298,10 @@ window.__ModuleLoader__.load({
1294
1298
  'explorer.refresh': 'Refresh',
1295
1299
  'explorer.newDir': 'New directory',
1296
1300
  'explorer.more': '…',
1301
+ 'explorer.pickRemote': 'Pick a remote workspace',
1302
+ 'explorer.pickRemoteHint': 'Pick a directory on the remote host (affects only this session’s file panel; the session’s workspace binding is untouched)',
1303
+ 'explorer.retry': 'Retry',
1304
+ 'explorer.registryUnavailable': 'Could not read the remote workspace list, so this session cannot be classified as local or remote. Please retry.',
1297
1305
  'explorer.remoteWs': 'Remote workspace: {path}{host}',
1298
1306
  'explorer.hostTag': ' ({user}@{host})',
1299
1307
  'explorer.noRemoteWs': 'No remote workspace set',
@@ -5103,6 +5111,11 @@ window.__ModuleLoader__.load({
5103
5111
  const [err, setErr] = React.useState('')
5104
5112
  const [busy, setBusy] = React.useState('')
5105
5113
  const [picker, setPicker] = React.useState(false)
5114
+ // Issue #180: the remote root the user EXPLICITLY picked in this panel.
5115
+ // It only ever overrides what this session's explorer shows — it is never
5116
+ // written into the session's workspace binding and never used as a
5117
+ // fallback for "the current machine" (issue #13).
5118
+ const [pickedRoot, setPickedRoot] = React.useState('')
5106
5119
  const [menu, setMenu] = React.useState(null) // { x, y, path, isDir, name }
5107
5120
  const [rootOpen, setRootOpen] = React.useState(true) // first level expanded by default
5108
5121
  const [hoverPath, setHoverPath] = React.useState('') // row hover highlight
@@ -5235,20 +5248,35 @@ window.__ModuleLoader__.load({
5235
5248
  const resolveRoot = async () => {
5236
5249
  if (opts?.force) await refreshMirrors()
5237
5250
  else await ensureMirrors()
5238
- if (localWorkspaceSession(sessionId)) return fetchWorkspaceContext(sessionId).then(value => value.root || '')
5251
+ // An explicit pick wins over everything below, but ONLY while this
5252
+ // session has no mirror of its own to honour: a session that IS bound
5253
+ // to a remote workspace must always show that binding (issue #13).
5254
+ const picked = String(pickedRoot || '')
5255
+ if (localWorkspaceSession(sessionId)) {
5256
+ if (picked) return picked
5257
+ return fetchWorkspaceContext(sessionId).then(value => value.root || '')
5258
+ }
5239
5259
  if (scopeCwd) {
5240
5260
  return api('GET', '/dsh-remote/resolve-mirror?local=' + encodeURIComponent(scopeCwd))
5241
- .then((r) => (r && r.remotePath) || '')
5261
+ .then((r) => (r && r.remotePath) || picked || '')
5242
5262
 
5243
5263
  }
5244
- if (sessionId) return resolveSessionRemote(sessionId, true)
5245
- return Promise.resolve('')
5264
+ if (sessionId) return resolveSessionRemote(sessionId, true).then((r) => r || picked || '')
5265
+ return Promise.resolve(picked)
5246
5266
  }
5247
5267
  resolveRoot().then((r) => {
5248
5268
  if (!current()) return
5249
5269
  return fetchRemoteStatus(sessionId).then((s) => {
5250
5270
  if (!current()) return
5251
5271
  if (s) setStatus(s)
5272
+ // Issue #180: with the mirror registry unreadable we cannot tell a
5273
+ // local session from a remote one we failed to recognise, so the
5274
+ // "this session is a local workspace" copy is a guess. Say what
5275
+ // actually happened instead of silently showing an empty local pane.
5276
+ if (!r && !localWorkspaceSession(sessionId) && MIRRORS.error) {
5277
+ setErr(tr('explorer.registryUnavailable'))
5278
+ return
5279
+ }
5252
5280
  // Issue #13: NEVER fall back to the machine-level workspace here —
5253
5281
  // a session whose cwd is not a mirror is a LOCAL session and shows
5254
5282
  // the "no remote workspace" empty state instead.
@@ -5261,7 +5289,7 @@ window.__ModuleLoader__.load({
5261
5289
  const previous = dataRef.current[r]
5262
5290
  if (r && previous && previous.entries) storeLevel(r, { ...previous, loading: false, softError: String(e.message || e) })
5263
5291
  })
5264
- }, [scopeCwd, sessionId])
5292
+ }, [scopeCwd, sessionId, pickedRoot])
5265
5293
 
5266
5294
  React.useEffect(() => { refreshStatus() }, [refreshStatus])
5267
5295
  React.useEffect(() => { if (props.visible) refreshStatus({ visible: true }) }, [props.visible])
@@ -5545,6 +5573,11 @@ window.__ModuleLoader__.load({
5545
5573
  React.createElement(WorkbenchAction, { icon: 'branch', label: tr('changes.title'), disabled: !root, onClick: () => { if (props.onOpenChanges) props.onOpenChanges(); else if (SIDEBAR_RIGHT?.openTabIn) SIDEBAR_RIGHT.openTabIn(sessionId, NATIVE_CHANGES); else if (SIDEBAR_RIGHT?.mounted?.getSnapshot?.() === sessionId) SIDEBAR_RIGHT.openTab?.(NATIVE_CHANGES) } }),
5546
5574
  React.createElement(WorkbenchAction, { icon: 'search', label: tr('workbench.filter'), pressed: filterOpen, disabled: !root, onClick: () => { setFilterOpen((v) => !v); setFilter('') } }),
5547
5575
  React.createElement(WorkbenchAction, { icon: 'refresh', label: tr('explorer.refresh'), onClick: () => refreshStatus({ force: true }) }),
5576
+ // Issue #180: this entry point disappeared in 1.0.0 (b28fcc3) while
5577
+ // the empty state still told the user to click it, so "pick a remote
5578
+ // workspace" had no way in at all. `explorer.more` ("…") survived
5579
+ // only as an unused translation string.
5580
+ React.createElement(WorkbenchAction, { icon: 'more', label: tr('explorer.pickRemote'), pressed: picker, onClick: () => setPicker((v) => !v) }),
5548
5581
  React.createElement(WorkbenchAction, { icon: 'collapse', label: tr('workbench.collapse'), disabled: !root, onClick: () => { props.onCollapseAll?.(); setRootOpen(true) } }),
5549
5582
  ),
5550
5583
  React.createElement('div', { className: 'dsh-rw-path', title: root, style: { marginTop: 4, display: 'flex', alignItems: 'center', gap: 6 } },
@@ -5570,12 +5603,28 @@ window.__ModuleLoader__.load({
5570
5603
  React.createElement('button', { type: 'button', className: 'dsh-rw-btn', style: buttonS, onClick: () => refreshStatus({ force: true }) }, tr('project.retry'))) : null,
5571
5604
  remoteTerminal.error ? React.createElement('div', { role: 'alert', style: { padding: '6px 10px', color: T.danger, fontSize: 12 } }, remoteTerminal.error) : null,
5572
5605
  picker ? React.createElement('div', { style: { padding: 8 } }, React.createElement(DirPicker, {
5573
- open: true, busy: false, registerWorkspace: false, initialTab: 'remote', onPicked: () => { setPicker(false); refreshStatus() }, onCancel: () => setPicker(false),
5606
+ open: true, busy: false, registerWorkspace: false, initialTab: 'remote',
5607
+ // Issue #180: the picked path used to be dropped on the floor — the
5608
+ // picker closed, refreshStatus() re-resolved the SAME session cwd, and
5609
+ // the pane did not change. Adopt the picked remote root instead;
5610
+ // `pickedRoot` is part of refreshStatus' identity, so the tree reloads.
5611
+ onPicked: (localMirror, remotePath) => {
5612
+ setPicker(false)
5613
+ const next = String(remotePath || '')
5614
+ if (next) setPickedRoot(next)
5615
+ else refreshStatus({ force: true })
5616
+ },
5617
+ onCancel: () => setPicker(false),
5574
5618
  })) : null,
5575
5619
  root && filterOpen && filter.trim() ? React.createElement(RemoteWorkspaceSearch, { key: sessionId + ':' + root, root, sessionId, query: filter.trim(), mode: searchMode, includeIgnored: searchIgnored, caseSensitive: searchCase, retryKey: searchRetry, onOpenFile: openFile, onRevealDirectory: revealDirectory }) : null,
5576
5620
  React.createElement('div', { role: 'tree', 'aria-label': tr('explorer.tabTitle'), ref: treeRef, onScroll: (e) => explorerMemory.set(sessionId || '', { ...explorerMemory.get(sessionId || ''), scrollTop: e.currentTarget.scrollTop }), onKeyDown: treeKeyDown, style: { flex: 1, overflowY: 'auto', minHeight: 0, padding: '2px 0', display: filterOpen && filter.trim() ? 'none' : undefined } },
5577
5621
  !root
5578
- ? React.createElement('div', { style: { opacity: 0.6, padding: 12, fontSize: 13 } }, err ? tr('explorer.cannotResolve') : tr('explorer.localSession'))
5622
+ ? React.createElement('div', { style: { opacity: 0.6, padding: 12, fontSize: 13 } },
5623
+ err ? tr('explorer.cannotResolve') : tr('explorer.localSession'),
5624
+ // A failure the user can act on must not look like a fact.
5625
+ err ? React.createElement('div', { style: { marginTop: 6, fontSize: 11, opacity: 0.85, wordBreak: 'break-word' }, title: err }, err) : null,
5626
+ err ? React.createElement('div', { style: { marginTop: 8 } },
5627
+ React.createElement('button', { type: 'button', className: 'dsh-rw-btn', style: buttonS, onClick: () => refreshStatus({ force: true }) }, tr('explorer.retry'))) : null)
5579
5628
  : React.createElement('div', { key: root },
5580
5629
  React.createElement('div', {
5581
5630
  role: 'treeitem', className: 'dsh-rw-tree-row', 'data-rw-tree-row': root, 'aria-level': 1, 'aria-expanded': rootOpen, tabIndex: !focusedPath || focusedPath === root ? 0 : -1, onFocus: () => setFocusedPath(root),
@@ -5899,6 +5948,228 @@ window.__ModuleLoader__.load({
5899
5948
  )
5900
5949
  }
5901
5950
 
5951
+ // ── Remote Markdown illustrations ──────────────────────────────────────
5952
+ // The host renderer draws `![alt](destination)` two ways: an absolute
5953
+ // HTTP(S) destination is used as authored, and EVERYTHING ELSE needs the
5954
+ // owner's `pathImages` vocabulary to turn it into a displayable absolute
5955
+ // URL (primitives: `imageSource` → `vocabularyImageUrl`). A miss is not an
5956
+ // error — it degrades to the alt text, which is exactly why a remote .md
5957
+ // showed captions where its figures belong: this pane never passed a
5958
+ // vocabulary at all.
5959
+ //
5960
+ // The built-in document preview supplies one from the LOCAL document path
5961
+ // (`markdownImageUrl` → `api/file?path=…`). That answer is wrong for a
5962
+ // remote document twice over: the path names a different file (or none) on
5963
+ // THIS host, and the host's file route cannot carry bytes that only exist
5964
+ // on the far side of the SSH connection. The remote owner therefore answers
5965
+ // with `data:` URLs built from the bytes the EXISTING `/dsh-remote/read`
5966
+ // route already returns for image extensions (issue #66). `data:` is on the
5967
+ // renderer's rewritten-image allowlist, so the host contract needs no
5968
+ // change — and a data URL cannot alias a local file the way a path could.
5969
+ const MARKDOWN_IMAGE_EXTENSION = /\.(?:png|jpe?g|gif|webp|svg|bmp)$/i
5970
+ // Per-document and per-cache ceilings: a figure set is normally a handful,
5971
+ // and one pathological document must not turn a preview into hundreds of
5972
+ // SFTP reads or megabytes of retained base64.
5973
+ const MARKDOWN_IMAGE_MAX_PER_DOC = 32
5974
+ const MARKDOWN_IMAGE_CACHE_LIMIT = 32
5975
+ const MARKDOWN_IMAGE_MAX_BYTES = 2 * 1024 * 1024
5976
+ /** `sessionId\0remotePath` → data URL, or null when no readable image exists there. */
5977
+ const markdownImageBytes = new Map()
5978
+ /** `sessionId\0remotePath` → the in-flight read, so two tabs of one file share it. */
5979
+ const markdownImageReads = new Map()
5980
+
5981
+ /**
5982
+ * The filesystem path a markdown image destination names.
5983
+ *
5984
+ * Mirrors the host's own reading of a destination (primitives
5985
+ * `markdownImageUrl`): a query/fragment suffix is dropped and the remainder
5986
+ * percent-decoded. A destination carrying a URL scheme is either an
5987
+ * absolute image the renderer handles itself or another owner's address, so
5988
+ * it is NOT resolved here — only local paths are. Windows drive letters are
5989
+ * paths, not schemes.
5990
+ */
5991
+ function markdownImageDestination(value) {
5992
+ const authored = String(value == null ? '' : value)
5993
+ const cut = authored.search(/[?#]/)
5994
+ let path = cut === -1 ? authored : authored.slice(0, cut)
5995
+ try { path = decodeURIComponent(path) } catch { return '' }
5996
+ if (!path) return ''
5997
+ if (/^[a-z]:[\\/]/i.test(path)) return path
5998
+ if (/^[a-z][a-z\d+.-]*:/i.test(path)) return ''
5999
+ // `//host/x` is protocol-relative (a URL the host renderer refuses), not
6000
+ // a remote path; do not turn it into a doomed read.
6001
+ if (path.startsWith('//')) return ''
6002
+ return path
6003
+ }
6004
+
6005
+ /** Parent directory of a POSIX or Windows remote path (string-level). */
6006
+ function remoteParentPath(p) {
6007
+ const value = String(p || '').replace(/[\\/]+$/, '')
6008
+ const index = Math.max(value.lastIndexOf('/'), value.lastIndexOf('\\'))
6009
+ if (index < 0) return ''
6010
+ if (index === 0) return value.startsWith('\\\\') ? value : '/'
6011
+ const parent = value.slice(0, index)
6012
+ // A drive root needs its separator back before a child can be joined.
6013
+ return /^[a-z]:$/i.test(parent) ? parent + (value.includes('\\') ? '\\' : '/') : parent
6014
+ }
6015
+
6016
+ /**
6017
+ * Collapse `.` / `..` and mixed separators in a remote path.
6018
+ *
6019
+ * The read route normalizes again, so this is not a security boundary —
6020
+ * it keeps the CACHE KEY canonical (`a/../img/x.png` and `img/x.png` are
6021
+ * one illustration, not two reads) and keeps audit/log entries legible.
6022
+ * The rules mirror `normalizeRemotePath` on the host side.
6023
+ */
6024
+ function normalizeRemoteImagePath(value) {
6025
+ const raw = String(value || '')
6026
+ if (!raw) return ''
6027
+ let prefix = ''
6028
+ let rest = raw
6029
+ const unc = raw.match(/^(\\\\[^\\/]+\\[^\\/]+)(.*)$/s)
6030
+ const drive = raw.match(/^([a-zA-Z]:)(.*)$/s)
6031
+ if (unc) { prefix = unc[1]; rest = unc[2] || '' }
6032
+ else if (drive) { prefix = drive[1]; rest = drive[2] || '' }
6033
+ else if (raw.startsWith('/')) prefix = '/'
6034
+ const windows = prefix.startsWith('\\\\') || /^[a-zA-Z]:$/.test(prefix)
6035
+ const separator = windows ? '\\' : '/'
6036
+ const parts = []
6037
+ for (const segment of rest.split(/[\\/]+/)) {
6038
+ if (!segment || segment === '.') continue
6039
+ if (segment === '..') { parts.pop(); continue }
6040
+ parts.push(segment)
6041
+ }
6042
+ if (prefix === '/') return '/' + parts.join('/')
6043
+ if (!prefix) return parts.join(separator)
6044
+ const root = prefix.replace(/[\\/]$/, '')
6045
+ if (!parts.length) return windows ? root + separator : root
6046
+ return root + separator + parts.join(separator)
6047
+ }
6048
+
6049
+ /**
6050
+ * Resolve one authored image destination against the document's directory.
6051
+ * Absolute POSIX / Windows / UNC destinations are taken as authored.
6052
+ */
6053
+ function resolveMarkdownImagePath(documentPath, destination) {
6054
+ const dest = String(destination || '')
6055
+ if (!dest) return ''
6056
+ if (dest.startsWith('/') || dest.startsWith('\\\\') || /^[a-z]:[\\/]/i.test(dest)) return normalizeRemoteImagePath(dest)
6057
+ const doc = String(documentPath || '')
6058
+ // The tab always carries an absolute document path; a relative one has
6059
+ // no directory to resolve against and must not become a root-relative
6060
+ // read on the far side.
6061
+ if (!doc || !(doc.startsWith('/') || doc.startsWith('\\\\') || /^[a-z]:[\\/]/i.test(doc))) return ''
6062
+ const parent = remoteParentPath(doc)
6063
+ return normalizeRemoteImagePath(parent ? joinRemote(parent, dest) : dest)
6064
+ }
6065
+
6066
+ /** `sessionId + NUL + path` — the cache and in-flight identity of one illustration. */
6067
+ function markdownImageKey(sessionId, path) {
6068
+ return String(sessionId || '') + '\0' + String(path || '')
6069
+ }
6070
+
6071
+ /**
6072
+ * Every image destination one markdown document can plausibly render,
6073
+ * resolved to remote absolute paths, deduped and capped.
6074
+ *
6075
+ * Deliberately a SUPERSET of what the renderer will ask for: inline
6076
+ * `![alt](dest)` plus link/reference definitions (`[id]: dest`, which also
6077
+ * feed `![alt][id]`). Non-image destinations are dropped BEFORE any read,
6078
+ * so a document's ordinary links never cost a round trip. `resolve()` may
6079
+ * still miss a destination this scan did not predict — the renderer then
6080
+ * keeps the alt text, exactly as before.
6081
+ */
6082
+ function markdownImageTargets(sessionId, documentPath, text) {
6083
+ const targets = []
6084
+ const seen = new Set()
6085
+ const add = (destination) => {
6086
+ if (targets.length >= MARKDOWN_IMAGE_MAX_PER_DOC) return
6087
+ const path = markdownImageDestination(destination)
6088
+ if (!path || !MARKDOWN_IMAGE_EXTENSION.test(path)) return
6089
+ const absolute = resolveMarkdownImagePath(documentPath, path)
6090
+ if (!absolute) return
6091
+ const key = markdownImageKey(sessionId, absolute)
6092
+ if (seen.has(key)) return
6093
+ seen.add(key)
6094
+ targets.push({ key, path: absolute })
6095
+ }
6096
+ const source = String(text || '')
6097
+ const inline = /!\[[^\]]*\]\(\s*(?:<([^<>]*)>|([^\s()]+))/g
6098
+ let match
6099
+ while ((match = inline.exec(source)) !== null) add(match[1] !== undefined ? match[1] : match[2])
6100
+ const definition = /^[ \t]*\[[^\]]*\]:[ \t]*(?:<([^<>]*)>|([^\s]+))/gm
6101
+ while ((match = definition.exec(source)) !== null) add(match[1] !== undefined ? match[1] : match[2])
6102
+ return targets
6103
+ }
6104
+
6105
+ /**
6106
+ * Read one illustration over the session's binding and remember its data
6107
+ * URL. Failures are cached as null (alt text stays) so a missing or
6108
+ * oversized image costs ONE round trip, not one per render.
6109
+ */
6110
+ function readMarkdownImage(sessionId, target) {
6111
+ const existing = markdownImageReads.get(target.key)
6112
+ if (existing) return existing
6113
+ const request = api('POST', '/dsh-remote/read',
6114
+ withSessionBody({ path: target.path, maxBytes: MARKDOWN_IMAGE_MAX_BYTES }, sessionId))
6115
+ .then((payload) => {
6116
+ markdownImageBytes.set(target.key, (payload && payload.image && payload.content && payload.mime)
6117
+ ? 'data:' + String(payload.mime) + ';base64,' + String(payload.content)
6118
+ : null)
6119
+ })
6120
+ .catch(() => { markdownImageBytes.set(target.key, null) })
6121
+ .then(() => {
6122
+ while (markdownImageBytes.size > MARKDOWN_IMAGE_CACHE_LIMIT) {
6123
+ markdownImageBytes.delete(markdownImageBytes.keys().next().value)
6124
+ }
6125
+ })
6126
+ markdownImageReads.set(target.key, request)
6127
+ void request.then(() => { markdownImageReads.delete(target.key) })
6128
+ return request
6129
+ }
6130
+
6131
+ /**
6132
+ * The `pathImages` vocabulary of one remote markdown document.
6133
+ *
6134
+ * `resolve()` must be synchronous and MarkdownText memoizes the vocabulary
6135
+ * (a fresh identity per render would rebuild the host's component table),
6136
+ * so the bytes are prefetched by an effect and the object identity changes
6137
+ * only when new bytes land: revision is the identity knob, not the clock.
6138
+ * Nothing is read while the document is in source mode — the pane only pays
6139
+ * for the figures it actually draws.
6140
+ */
6141
+ function useRemoteMarkdownImages(sessionId, documentPath, text, enabled) {
6142
+ const [revision, setRevision] = React.useState(0)
6143
+ React.useEffect(() => {
6144
+ if (!enabled || !documentPath || !text) return undefined
6145
+ const targets = markdownImageTargets(sessionId, documentPath, text)
6146
+ const missing = targets.filter((target) => !markdownImageBytes.has(target.key))
6147
+ if (!missing.length) return undefined
6148
+ let cancelled = false
6149
+ ;(async () => {
6150
+ for (const target of missing) {
6151
+ if (cancelled) return
6152
+ await readMarkdownImage(sessionId, target)
6153
+ if (cancelled) return
6154
+ setRevision((value) => value + 1)
6155
+ }
6156
+ })()
6157
+ return () => { cancelled = true }
6158
+ }, [enabled, sessionId, documentPath, text])
6159
+ return {
6160
+ pathImages: React.useMemo(() => ({
6161
+ resolve(value) {
6162
+ const path = markdownImageDestination(value)
6163
+ if (!path || !MARKDOWN_IMAGE_EXTENSION.test(path)) return undefined
6164
+ const absolute = resolveMarkdownImagePath(documentPath, path)
6165
+ if (!absolute) return undefined
6166
+ const hit = markdownImageBytes.get(markdownImageKey(sessionId, absolute))
6167
+ return typeof hit === 'string' && hit ? hit : undefined
6168
+ },
6169
+ }), [sessionId, documentPath, revision]),
6170
+ }
6171
+ }
6172
+
5902
6173
  const remoteDrafts = new Map()
5903
6174
  const pendingFileSaves = new Map()
5904
6175
  function RemoteFileTab(props) {
@@ -6106,6 +6377,14 @@ window.__ModuleLoader__.load({
6106
6377
 
6107
6378
  const baseName = path.split(/[\\/]/).pop() || path
6108
6379
  const isMarkdown = /\.(md|markdown)$/i.test(baseName)
6380
+ // A rendered .md owns its figures (see useRemoteMarkdownImages). Only the
6381
+ // branch that actually DRAWS the document pays for them: source mode
6382
+ // never reads an image, and a draft reads only the destinations that are
6383
+ // not cached yet (typing therefore costs nothing until a new figure path
6384
+ // appears). The text is the same one the host renders: the draft while
6385
+ // editing, the loaded document otherwise.
6386
+ const markdownPreview = isMarkdown && !sourceMode && !!MarkdownText
6387
+ const markdownImages = useRemoteMarkdownImages(fileSessionId, path, markdownPreview ? (edit ? draft : originalText) : '', markdownPreview)
6109
6388
  const searchableText = edit ? draft : originalText
6110
6389
  const matches = React.useMemo(() => {
6111
6390
  if (!findQuery) return []
@@ -6218,7 +6497,7 @@ window.__ModuleLoader__.load({
6218
6497
  },
6219
6498
  }, edit ? draft : originalText),
6220
6499
  },
6221
- React.createElement(MarkdownText, { text: edit ? draft : originalText, variant: 'body', labels: markdownLabels })),
6500
+ React.createElement(MarkdownText, { text: edit ? draft : originalText, variant: 'body', labels: markdownLabels, pathImages: markdownImages.pathImages })),
6222
6501
  (data && data.truncated)
6223
6502
  ? React.createElement('div', { style: { color: T.warn, fontSize: 12, marginTop: 8 } }, tr('file.truncated'))
6224
6503
  : null)
package/lib/main.js CHANGED
@@ -79,6 +79,7 @@ import { createWebAttachRoutes } from './routes-web-attach.js'
79
79
  import { createWorkspaceRoutes } from './routes-workspace.js'
80
80
  import { listDirStructured, removeRemoteTree } from './remote-fs.js'
81
81
  import { registerRemoteSkills } from './remote-skills.js'
82
+ import { installWorkspaceFilesRemote } from './workspace-files-remote.js'
82
83
  import { describeConnect } from './connect-summary.js'
83
84
 
84
85
  export const name = 'dsh-remote'
@@ -315,6 +316,10 @@ export const Config = z.object({
315
316
  * transparently falls back to a local shell. `false` keeps "remote ssh"
316
317
  * menu-only. */
317
318
  remoteTerminalDefault: z.boolean().default(true),
319
+ /** Serve the core `workspaceFiles` Remote (file previews, byte windows,
320
+ * workspace listings) from the session's REMOTE origin instead of the
321
+ * local mirror (issue #194). `false` restores the core's mirror behavior. */
322
+ workspaceFilesRemote: z.boolean().default(true),
318
323
  /** TUI integration layer (docs/tui.md): register the `/dsh-remote` scene,
319
324
  * the workspace provider and the `/dsh-remote` slash command when a
320
325
  * dsh-tui profile is present. `false` disables the whole layer — on a Web or
@@ -1484,6 +1489,20 @@ export async function apply(ctx, config) {
1484
1489
  poolForMachine,
1485
1490
  logger: typeof ctx.get === 'function' ? ctx.get('logger') : undefined,
1486
1491
  })
1492
+ // Issue #194: the core `workspaceFiles` Remote resolves every mirror-session
1493
+ // read/stat/list against the LOCAL MIRROR (the header cwd), so previews and
1494
+ // listings could serve silently stale content. Serve those calls from the
1495
+ // remote origin through the same mirror binding the rw_* tools use; scopes
1496
+ // that are not mirror sessions fall through to the core untouched. See
1497
+ // lib/workspace-files-remote.js for the seam analysis and the `changes`
1498
+ // trade-off. Opt-out via the config switch above.
1499
+ const workspaceFilesRemote = config.workspaceFilesRemote === false
1500
+ ? null
1501
+ : installWorkspaceFilesRemote(ctx, {
1502
+ resolveBinding: resolveMirrorForLocal,
1503
+ poolForMachine,
1504
+ logger: typeof ctx.get === 'function' ? ctx.get('logger') : undefined,
1505
+ })
1487
1506
 
1488
1507
  /**
1489
1508
  * The whole local-mirror registry with each mirror's recorded remote origin
package/lib/openssh.js CHANGED
@@ -62,6 +62,7 @@ import { EventEmitter } from 'node:events'
62
62
  import { homedir, tmpdir } from 'node:os'
63
63
  import path from 'node:path'
64
64
  import { Duplex } from 'node:stream'
65
+ import { setTimeout as delay } from 'node:timers/promises'
65
66
  import { buildSftpSurface } from './sftp-surface.js'
66
67
  import { truncate } from './paths.js'
67
68
 
@@ -226,6 +227,74 @@ export function sshBinaryAvailable(binary) {
226
227
  return false
227
228
  }
228
229
 
230
+ /** Backoff between the two connect attempts (issue #188).
231
+ *
232
+ * Short on purpose: the failure being retried is a dropped SYN / unanswered
233
+ * dial, not a slow host, and a caller's read budget is usually far shorter than
234
+ * the 15s connect timeout. A re-dial after this kind of failure was measured at
235
+ * ~700ms, so 400ms of backoff is enough to land on a different path without
236
+ * making the user wait twice for nothing.
237
+ */
238
+ export const CONNECT_RETRY_DELAY_MS = 400
239
+
240
+
241
+ // Connect-stage failures that are DETERMINISTIC, so a second dial only doubles
242
+ // the wait the user stares at. Checked BEFORE the transient list: OpenSSH
243
+ // prefixes several of these with "Connection closed by ...", which would
244
+ // otherwise look retryable.
245
+ const NON_TRANSIENT_CONNECT_PATTERNS = [
246
+ /permission denied/i,
247
+ /too many authentication failures/i,
248
+ /no supported authentication/i,
249
+ /host key verification failed/i,
250
+ /remote host identification has changed/i,
251
+ /could not resolve hostname/i,
252
+ /name or service not known/i,
253
+ /connection refused/i,
254
+ /no route to host/i,
255
+ /network is unreachable/i,
256
+ /no matching (?:key exchange|host key|ciphers|mac)/i,
257
+ ]
258
+
259
+ // Connect-stage failures that are TRANSIENT: the dial or the pre-auth banner
260
+ // exchange was dropped, and the very next attempt usually succeeds.
261
+ const TRANSIENT_CONNECT_PATTERNS = [
262
+ /connection timed out/i,
263
+ /operation timed out/i,
264
+ /connection reset by peer/i,
265
+ // OpenSSH prints an address here, not the word "host":
266
+ // Connection closed by 10.0.0.1 port 22
267
+ /connection closed by /i,
268
+ /kex_exchange_identification/i,
269
+ /connection lost/i,
270
+ ]
271
+
272
+ /**
273
+ * Was this failed connect probe a transient, worth-retrying dial failure?
274
+ *
275
+ * Issue #188: on a corporate link ~6% of fresh openssh connects died with
276
+ * `Connection timed out` after the full 15s `ConnectTimeout`, and an immediate
277
+ * re-dial succeeded in ~700ms every time. The native backend has retried the
278
+ * equivalent case (`SSH_HANDSHAKE_CLOSED`) since #185; this is the same
279
+ * contract for the `ssh` CLI backend.
280
+ *
281
+ * Only the CONNECT stage is classified here. The probe is a bare
282
+ * `ssh -- <host> true`, so nothing authenticated is ever replayed, and host-key
283
+ * / handshake policy is untouched — the retry spawns the identical argv.
284
+ *
285
+ * @param {{code: number|null, signal: string|null, stderr: string}} probe
286
+ * @returns {boolean}
287
+ */
288
+ export function transientConnectFailure(probe) {
289
+ if (!probe) return false
290
+ // Our own timer fired: the host never answered within the connect budget.
291
+ if (probe.signal === 'TIMEOUT') return true
292
+ const text = String(probe.stderr || '')
293
+ if (!text) return false
294
+ if (NON_TRANSIENT_CONNECT_PATTERNS.some((re) => re.test(text))) return false
295
+ return TRANSIENT_CONNECT_PATTERNS.some((re) => re.test(text))
296
+ }
297
+
229
298
  /**
230
299
  * Options shared by every `ssh` invocation for this target.
231
300
  *
@@ -579,13 +648,54 @@ export class SystemOpenSshPool {
579
648
  if (this.client) return Promise.resolve(this.client)
580
649
  if (this.connecting) return this.connecting
581
650
  const epoch = this.epoch
582
- const pending = this._doConnect(epoch)
651
+ const pending = this._connectWithRetry(epoch)
583
652
  this.connecting = pending
584
653
  const clear = () => { if (this.epoch === epoch && this.connecting === pending) this.connecting = null }
585
654
  pending.then(clear, clear)
586
655
  return pending
587
656
  }
588
657
 
658
+ /**
659
+ * Dial, and on a TRANSIENT connect failure dial ONCE more (issue #188).
660
+ *
661
+ * The retry is shared by every concurrent caller because `connect()` memoizes
662
+ * this promise: N simultaneous reads of a dropped link cost exactly one extra
663
+ * dial, not N. Nothing authenticated is replayed — `_doConnect` only runs the
664
+ * `ssh -- <host> true` probe, and the retry spawns the identical argv, so the
665
+ * host-key and handshake policy of the first attempt still applies.
666
+ *
667
+ * A deterministic failure (bad credentials, changed host key, DNS, refused,
668
+ * unreachable) is NOT tagged transient by `transientConnectFailure`, so it
669
+ * surfaces on the first attempt with no extra wait.
670
+ */
671
+ async _connectWithRetry(epoch) {
672
+ const firstStarted = Date.now()
673
+ try {
674
+ return await this._doConnect(epoch)
675
+ } catch (error) {
676
+ if (!error || error.code !== 'SSH_CONNECT_TRANSIENT' || this.epoch !== epoch) throw error
677
+ const firstMs = Date.now() - firstStarted
678
+ await delay(CONNECT_RETRY_DELAY_MS)
679
+ if (this.epoch !== epoch) throw new Error('ssh target changed during connect retry')
680
+ const retryStarted = Date.now()
681
+ try {
682
+ return await this._doConnect(epoch)
683
+ } catch (retryError) {
684
+ const retryMs = Date.now() - retryStarted
685
+ // Both dials failed. Say so explicitly, with BOTH durations: from a
686
+ // single timeout "flaky link" and "host is down" are indistinguishable,
687
+ // and the user's next move differs (retry later vs. check the host).
688
+ const wrapped = new Error(
689
+ String((retryError && retryError.message) || retryError)
690
+ + ` (connect retried once: first attempt ${firstMs}ms, retry ${retryMs}ms)`,
691
+ )
692
+ wrapped.code = retryError && retryError.code
693
+ wrapped.cause = retryError
694
+ throw wrapped
695
+ }
696
+ }
697
+ }
698
+
589
699
  async _doConnect(epoch) {
590
700
  const isCurrent = () => this.epoch === epoch
591
701
  const sshBinary = resolveSshBinary(this.config)
@@ -607,10 +717,14 @@ export class SystemOpenSshPool {
607
717
  // dsh-remote-fix3: _runSsh reports its own timer as code -1 / signal
608
718
  // TIMEOUT with empty stderr, so the old message degraded to a bare
609
719
  // `ssh failed (exit -1)` and told the settings page nothing actionable.
610
- if (probe.signal === 'TIMEOUT') {
611
- throw new Error(`ssh timed out after ${this.config.connectTimeoutMs || 15000}ms (no reply from the host — raise the connect timeout if this link is just slow)`)
612
- }
613
- throw new Error(`ssh failed (exit ${probe.code})${String(probe.stderr || '').trim() ? ': ' + String(probe.stderr).trim() : ''}`)
720
+ const stderrText = String(probe.stderr || '').trim()
721
+ const failure = probe.signal === 'TIMEOUT'
722
+ ? new Error(`ssh timed out after ${this.config.connectTimeoutMs || 15000}ms (no reply from the host — raise the connect timeout if this link is just slow)`)
723
+ : new Error(`ssh failed (exit ${probe.code})${stderrText ? ': ' + stderrText : ''}`)
724
+ // Issue #188: tag the retryable class HERE, where the probe result is
725
+ // known, so the retry decision never has to sniff a message at a distance.
726
+ if (transientConnectFailure(probe)) failure.code = 'SSH_CONNECT_TRANSIENT'
727
+ throw failure
614
728
  }
615
729
  void secret
616
730
  const conn = new OpenSshConnection(this, { sshBinary, secret })
@@ -0,0 +1,479 @@
1
+ // dsh-remote — serve the core `workspaceFiles` Remote from the REMOTE origin
2
+ // for mirror sessions (issue #194).
3
+ //
4
+ // The core service (@deepseek-ai/dsh-api-workspace-files) resolves every
5
+ // read/readBytes/stat/list against the session header's cwd. For a remote
6
+ // Session that cwd is the LOCAL MIRROR, so the core file surfaces answered
7
+ // from the mirror — silently stale whenever the remote changed outside this
8
+ // plugin's own writes, and `list` showed a tree that could lag arbitrarily
9
+ // behind the real workspace. The two surfaces the plugin already owns
10
+ // (NATIVE_LINK file links and the sidebar explorer) never had the bug; this
11
+ // closes the remaining consumers: the `file` resource provider's stat/read,
12
+ // byte windows, workspace listings, and any third-party Remote client.
13
+ //
14
+ // There is no provider vocabulary on this service (unlike `skills`): a second
15
+ // cordis Service under the same name throws, and the wire descriptor stays
16
+ // bound to the core instance. The Gateway resolves methods with Reflect.get on
17
+ // the LIVE service at call time, so the supported seam is an instance-method
18
+ // wrapper — installed inject-scoped, keyed strictly on the mirror binding, and
19
+ // exactly reversible on dispose:
20
+ //
21
+ // • only read / readBytes / stat / list are wrapped. `changes` keeps the
22
+ // core's local watcher: a remote has no inotify over SFTP, and today's
23
+ // local-mirror watch still fires for every write this plugin makes (it
24
+ // syncs the mirror), so remote-external edits remain the only misses —
25
+ // the same trade the file tab already makes. See the issue for the
26
+ // upstream polling vocabulary this would need.
27
+ // • a call is served remotely ONLY when its workspaceFileScope resolves to
28
+ // a usable mirror binding (meta-recorded host/port/user; a mirror whose
29
+ // meta is missing is skipped, never guessed — the resolveMirror rule).
30
+ // Every other scope falls through to the core implementation untouched.
31
+ // • errors propagate with the core's `workspace-file/*` codes — no silent
32
+ // fallback to the stale mirror, which is exactly the bug being fixed.
33
+ // RemoteError is constructed STRUCTURALLY (isDSHRemoteError marker), the
34
+ // same cross-bundle identification the protocol itself uses, so no new
35
+ // peer dependency on the typert package is required.
36
+ // • path mapping reuses resolveRemoteWorkspacePath, the rw_* tools' proven
37
+ // rule: workspace-relative paths join onto the mirror's remotePath, a
38
+ // local path INSIDE the mirror maps to the same remote file, any other
39
+ // absolute path is a path in the session's execution world (the remote).
40
+ //
41
+ // The remote side enforces the same caps the core deployment configures
42
+ // (read off the live service instance when present): maxBytes per page,
43
+ // maxLines per page, maxFileBytes for complete reads, maxEntries per listing.
44
+ // One deliberate addition: paging to a far line requires scanning from byte 0,
45
+ // cheap on a local disk but a slow SFTP round-trip stream remotely — the scan
46
+ // is bounded by maxFileBytes, so an offset deep into a giant file fails fast
47
+ // with `workspace-file/too-large` instead of grinding the connection.
48
+
49
+ import { listDirStructured } from './remote-fs.js'
50
+ import { missingRemoteFile } from './remote-write.js'
51
+ import {
52
+ normalizeRemotePath, joinRemoteRel, remoteDirname, relPathUnder, resolveRemoteWorkspacePath,
53
+ } from './paths.js'
54
+
55
+ // Defaults mirror dsh-api-workspace-files' Config so behavior holds even when
56
+ // the live instance hides its config (a future host build may).
57
+ const DEFAULT_CAPS = Object.freeze({
58
+ maxBytes: 2 * 1024 * 1024,
59
+ maxFileBytes: 32 * 1024 * 1024,
60
+ maxLines: 5000,
61
+ maxEntries: 2000,
62
+ })
63
+
64
+ /** Structural RemoteError — see the header; never `instanceof` across bundles. */
65
+ function remoteError(code, message, details = {}) {
66
+ return Object.assign(new Error(message), {
67
+ name: 'RemoteError', isDSHRemoteError: true, code, details,
68
+ })
69
+ }
70
+
71
+ const badRequest = (message) => remoteError('gateway/bad-request', message, {})
72
+ const notFound = (path) => remoteError('workspace-file/not-found', `no entry at "${path}"`, { path })
73
+ const notRegularFile = (path, kind) =>
74
+ remoteError('workspace-file/not-regular-file', `"${path}" is a ${kind}`, { path, kind })
75
+ const notText = (path) =>
76
+ remoteError('workspace-file/not-text', `"${path}" is not UTF-8 text`, { path })
77
+ const tooLarge = (path, message, limit) =>
78
+ remoteError('workspace-file/too-large', message, { path, limit })
79
+ const notDirectory = (path, kind) =>
80
+ remoteError('workspace-file/not-directory', `"${path}" is a ${kind}`, { path, kind })
81
+ const outsideWorkspace = (path) =>
82
+ remoteError('workspace-file/outside-workspace', `"${path}" is outside the workspace`, { path })
83
+
84
+ const NUL = String.fromCharCode(0)
85
+ const isMissingError = (error) =>
86
+ missingRemoteFile(error) || /no such file|not found|does not exist|enoent|not a directory|enotdir/i.test(String((error && error.message) || error))
87
+
88
+ function throwIfAborted(signal) {
89
+ if (!signal || signal.aborted !== true) return
90
+ throw signal.reason || Object.assign(new Error('remote workspace file read aborted'), { name: 'AbortError' })
91
+ }
92
+
93
+ /** ssh2 Stats → the core's entry vocabulary ('symlink' is the link itself). */
94
+ function attrKind(attrs) {
95
+ if (!attrs || typeof attrs !== 'object') return 'other'
96
+ if (typeof attrs.isDirectory === 'function' && attrs.isDirectory()) return 'directory'
97
+ if (typeof attrs.isSymbolicLink === 'function' && attrs.isSymbolicLink()) return 'symlink'
98
+ if (typeof attrs.isFile === 'function' && attrs.isFile()) return 'file'
99
+ return 'other'
100
+ }
101
+
102
+ /**
103
+ * Opaque freshness token for one remote stat. mtime has second resolution on
104
+ * plain SFTP, so two same-size writes within one second share a version — the
105
+ * client then skips one re-stat of an already-superseded preview. Coarser than
106
+ * the local backend's token, but the honest remote identity available without
107
+ * hashing the whole file.
108
+ */
109
+ function versionOf(attrs) {
110
+ const mtime = typeof attrs?.mtime === 'number' ? attrs.mtime : 0
111
+ const size = typeof attrs?.size === 'number' ? attrs.size : 0
112
+ return `sftp:${mtime}:${size}`
113
+ }
114
+
115
+ /** Caps of the live core service, falling back to the core defaults. */
116
+ function capsOf(service) {
117
+ const config = service && typeof service === 'object' ? service.config : undefined
118
+ if (!config || typeof config !== 'object') return DEFAULT_CAPS
119
+ const pick = (key) => Number.isFinite(Number(config[key])) && Number(config[key]) > 0 ? Number(config[key]) : DEFAULT_CAPS[key]
120
+ return { maxBytes: pick('maxBytes'), maxFileBytes: pick('maxFileBytes'), maxLines: pick('maxLines'), maxEntries: pick('maxEntries') }
121
+ }
122
+
123
+ /**
124
+ * Map one incoming path onto the session's remote execution world. Returns the
125
+ * absolute remote path (rw_* semantics, see the header); an EMPTY input is an
126
+ * error the caller reports before mapping.
127
+ */
128
+ function remoteTargetOf(binding, path) {
129
+ const raw = String(path ?? '')
130
+ if (!raw) throw badRequest('path is required')
131
+ if (raw.includes(NUL)) throw badRequest('path must not contain NUL')
132
+ return resolveRemoteWorkspacePath(binding.remotePath, raw, binding.mirrorDir)
133
+ }
134
+
135
+ /** The mirror binding for one wire scope, or null when the scope is not ours. */
136
+ function bindingOf(resolveBinding, scope) {
137
+ if (!scope || typeof scope !== 'object' || typeof scope.workspaceRoot !== 'string' || !scope.workspaceRoot) return null
138
+ let binding = null
139
+ try { binding = resolveBinding(scope.workspaceRoot) || null } catch { binding = null }
140
+ if (!binding || !binding.machine || !binding.remotePath || !binding.mirrorDir) return null
141
+ return binding
142
+ }
143
+
144
+ async function sftpFor(poolForMachine, binding) {
145
+ return poolForMachine(binding.machine).sftp()
146
+ }
147
+
148
+ /** lstat the final component (the core refuses to read through a symlink). */
149
+ async function lstatEntry(sftp, remote, path) {
150
+ try {
151
+ return await sftp.lstat(remote)
152
+ } catch (error) {
153
+ if (isMissingError(error)) throw notFound(path)
154
+ throw error
155
+ }
156
+ }
157
+
158
+ /** stat (follows links) for identity, size and version. */
159
+ async function statEntry(sftp, remote, path) {
160
+ try {
161
+ return await sftp.stat(remote)
162
+ } catch (error) {
163
+ if (isMissingError(error)) throw notFound(path)
164
+ throw error
165
+ }
166
+ }
167
+
168
+ /** The core's locateFile gates: lstat must see a regular file, stat confirms. */
169
+ async function locateRemoteFile(sftp, remote, path) {
170
+ const entry = await lstatEntry(sftp, remote, path)
171
+ if (attrKind(entry) !== 'file') throw notRegularFile(path, attrKind(entry))
172
+ const attrs = await statEntry(sftp, remote, path)
173
+ if (attrKind(attrs) !== 'file') throw notRegularFile(path, attrKind(attrs))
174
+ return attrs
175
+ }
176
+
177
+ /** Page defaults and caps, the core's resolvePage rules. */
178
+ function resolvePage(range, caps) {
179
+ const rawOffset = range?.offset
180
+ const offset = rawOffset === undefined ? 1 : Math.trunc(Number(rawOffset))
181
+ if (rawOffset !== undefined && (!Number.isFinite(offset) || offset < 1 || Number(rawOffset) !== offset)) {
182
+ throw badRequest('offset must be a positive integer')
183
+ }
184
+ const rawLimit = range?.limit
185
+ const limit = rawLimit === undefined ? caps.maxLines : Math.trunc(Number(rawLimit))
186
+ if (rawLimit !== undefined && (!Number.isFinite(limit) || limit < 1 || Number(rawLimit) !== limit)) {
187
+ throw badRequest('limit must be a positive integer')
188
+ }
189
+ if (limit > caps.maxLines) throw badRequest(`limit must be at most ${caps.maxLines}`)
190
+ return { offset, limit }
191
+ }
192
+
193
+ /** Byte-window defaults and cap, the core's resolveWindow rules. */
194
+ function resolveWindow(range, caps, path) {
195
+ const rawOffset = range?.offset
196
+ const offset = rawOffset === undefined ? 0 : Math.trunc(Number(rawOffset))
197
+ const rawLength = range?.length
198
+ const length = rawLength === undefined ? caps.maxBytes : Math.trunc(Number(rawLength))
199
+ if (rawOffset !== undefined && (!Number.isFinite(offset) || offset < 0 || Number(rawOffset) !== offset)) throw badRequest('offset must be a non-negative integer')
200
+ if (rawLength !== undefined && (!Number.isFinite(length) || length < 1 || Number(rawLength) !== length)) throw badRequest('length must be a positive integer')
201
+ if (offset + length > Number.MAX_SAFE_INTEGER) throw badRequest('offset plus length must stay a safe integer')
202
+ if (length > caps.maxBytes) throw tooLarge(path, `${length} bytes of "${path}" exceed the ${caps.maxBytes} byte cap`, caps.maxBytes)
203
+ return { offset, length }
204
+ }
205
+
206
+ /**
207
+ * Decoded remote text as a chunk stream: SFTP windows fed through an incremental
208
+ * fatal UTF-8 decoder, so the file is never held whole and invalid sequences
209
+ * fail as `workspace-file/not-text` exactly like the core's streamText.
210
+ */
211
+ async function* remoteTextChunks(sftp, remote, size, { chunkBytes = 128 * 1024, maxScanBytes } = {}) {
212
+ const decoder = new TextDecoder('utf-8', { fatal: true })
213
+ let offset = 0
214
+ let scanned = 0
215
+ while (offset < size) {
216
+ const length = Math.min(chunkBytes, size - offset)
217
+ const buf = await sftp.readPartial(remote, offset, length)
218
+ if (!buf || buf.length === 0) break
219
+ offset += buf.length
220
+ scanned += buf.length
221
+ if (maxScanBytes && scanned > maxScanBytes) {
222
+ throw tooLarge(remote, `scanning "${remote}" past ${maxScanBytes} bytes while seeking a page exceeds the full-file cap`, maxScanBytes)
223
+ }
224
+ let text
225
+ try {
226
+ text = decoder.decode(buf, { stream: true })
227
+ } catch {
228
+ throw notText(remote)
229
+ }
230
+ if (text) yield text
231
+ }
232
+ let tail
233
+ try {
234
+ tail = decoder.decode()
235
+ } catch {
236
+ throw notText(remote)
237
+ }
238
+ if (tail) yield tail
239
+ }
240
+
241
+ /**
242
+ * Cut lines offset..offset+limit-1 from decoded chunks. A port of the core's
243
+ * cutPage: lines before the page are counted, not kept; the page is refused the
244
+ * moment its bytes exceed maxBytes (a giant line cannot grow memory past the
245
+ * cap either); the loop stops at the first character past the page.
246
+ */
247
+ async function cutPage(chunks, offset, limit, maxBytes, path) {
248
+ const last = offset + limit - 1
249
+ const lines = []
250
+ let current = ''
251
+ let bytes = 0
252
+ let lineNumber = 1
253
+ const admit = (size) => {
254
+ bytes += size
255
+ if (bytes > maxBytes) {
256
+ throw tooLarge(path, `lines ${offset}-${last} of "${path}" exceed the ${maxBytes} byte cap`, maxBytes)
257
+ }
258
+ }
259
+ const complete = () => {
260
+ if (lines.length > 0) admit(1)
261
+ lines.push(current)
262
+ current = ''
263
+ }
264
+ for await (const chunk of chunks) {
265
+ let position = 0
266
+ while (position < chunk.length) {
267
+ if (lineNumber > last) return { text: lines.join('\n'), lines: lines.length, eof: false }
268
+ const newline = chunk.indexOf('\n', position)
269
+ const segment = newline === -1 ? chunk.slice(position) : chunk.slice(position, newline)
270
+ if (lineNumber >= offset) {
271
+ admit(Buffer.byteLength(segment, 'utf8'))
272
+ current += segment
273
+ }
274
+ if (newline === -1) break
275
+ if (lineNumber >= offset) complete()
276
+ lineNumber += 1
277
+ position = newline + 1
278
+ }
279
+ }
280
+ if (current.length > 0) complete()
281
+ return { text: lines.join('\n'), lines: lines.length, eof: true }
282
+ }
283
+
284
+ /** The four remote implementations. Each takes (binding, args-after-scope, service, deps). */
285
+ const remoteImpl = {
286
+ async read(binding, [path, range, signal], service, deps) {
287
+ const caps = capsOf(service)
288
+ const { offset, limit } = resolvePage(range, caps)
289
+ throwIfAborted(signal)
290
+ const sftp = await sftpFor(deps.poolForMachine, binding)
291
+ const remote = remoteTargetOf(binding, path)
292
+ const attrs = await locateRemoteFile(sftp, remote, path)
293
+ throwIfAborted(signal)
294
+ const page = await cutPage(
295
+ remoteTextChunks(sftp, remote, typeof attrs.size === 'number' ? attrs.size : 0, { maxScanBytes: caps.maxFileBytes }),
296
+ offset, limit, caps.maxBytes, path,
297
+ )
298
+ if (page.text.includes(NUL)) throw notText(path)
299
+ return {
300
+ absolutePath: remote,
301
+ version: versionOf(attrs),
302
+ ...(typeof attrs.size === 'number' ? { bytes: attrs.size } : {}),
303
+ offset,
304
+ text: page.text,
305
+ lines: page.lines,
306
+ eof: page.eof,
307
+ }
308
+ },
309
+
310
+ async readBytes(binding, [path, options, signal], service, deps) {
311
+ const caps = capsOf(service)
312
+ options = options || {}
313
+ throwIfAborted(signal)
314
+ const sftp = await sftpFor(deps.poolForMachine, binding)
315
+ let target = path
316
+ if (options.baseFile !== undefined) {
317
+ // The core resolves a relative target against the BASE file's directory,
318
+ // and the base file must itself be a locatable regular file.
319
+ const base = remoteTargetOf(binding, options.baseFile)
320
+ await locateRemoteFile(sftp, base, options.baseFile)
321
+ const raw = String(path ?? '')
322
+ if (!raw) throw badRequest('path is required')
323
+ if (raw.startsWith('/') || /^[a-zA-Z]:[\\/]/.test(raw) || /^[a-zA-Z][a-zA-Z\d+.-]*:/.test(raw)) {
324
+ throw badRequest('path must be relative when baseFile is provided')
325
+ }
326
+ target = normalizeRemotePath(joinRemoteRel(remoteDirname(base), raw))
327
+ }
328
+ const remote = remoteTargetOf(binding, target)
329
+ const attrs = await locateRemoteFile(sftp, remote, path)
330
+ throwIfAborted(signal)
331
+ if (options.range === undefined) {
332
+ const limit = caps.maxFileBytes
333
+ if (typeof attrs.size === 'number' && attrs.size > limit) {
334
+ throw tooLarge(path, `"${path}" exceeds the ${limit} byte full-file cap`, limit)
335
+ }
336
+ const want = typeof attrs.size === 'number' ? attrs.size : 0
337
+ const data = want > 0 ? await sftp.readPartial(remote, 0, want) : Buffer.alloc(0)
338
+ return {
339
+ absolutePath: remote,
340
+ version: versionOf(attrs),
341
+ ...(typeof attrs.size === 'number' ? { bytes: attrs.size } : {}),
342
+ offset: 0,
343
+ data: data || Buffer.alloc(0),
344
+ eof: true,
345
+ }
346
+ }
347
+ const { offset, length } = resolveWindow(options.range, caps, path)
348
+ const data = await sftp.readPartial(remote, offset, length)
349
+ const got = data ? data.length : 0
350
+ const eof = typeof attrs.size === 'number' ? offset + got >= attrs.size : got < length
351
+ return {
352
+ absolutePath: remote,
353
+ version: versionOf(attrs),
354
+ ...(typeof attrs.size === 'number' ? { bytes: attrs.size } : {}),
355
+ offset,
356
+ data: data || Buffer.alloc(0),
357
+ eof,
358
+ }
359
+ },
360
+
361
+ async stat(binding, [path, signal], service, deps) {
362
+ throwIfAborted(signal)
363
+ const sftp = await sftpFor(deps.poolForMachine, binding)
364
+ const remote = remoteTargetOf(binding, path)
365
+ const attrs = await locateRemoteFile(sftp, remote, path)
366
+ return {
367
+ absolutePath: remote,
368
+ version: versionOf(attrs),
369
+ ...(typeof attrs.size === 'number' ? { bytes: attrs.size } : {}),
370
+ }
371
+ },
372
+
373
+ async list(binding, [path, signal], service, deps) {
374
+ const caps = capsOf(service)
375
+ throwIfAborted(signal)
376
+ const sftp = await sftpFor(deps.poolForMachine, binding)
377
+ const remote = remoteTargetOf(binding, path)
378
+ // Directories stay workspace-scoped, exactly like the core's confine().
379
+ const workspacePath = relPathUnder(binding.remotePath, remote)
380
+ if (workspacePath === null) throw outsideWorkspace(path)
381
+ const entry = await lstatEntry(sftp, remote, path)
382
+ const kind = attrKind(entry)
383
+ if (kind !== 'directory' && kind !== 'symlink') throw notDirectory(path, kind)
384
+ if (kind === 'symlink') {
385
+ const attrs = await statEntry(sftp, remote, path)
386
+ if (attrKind(attrs) !== 'directory') throw notDirectory(path, 'symlink')
387
+ }
388
+ throwIfAborted(signal)
389
+ const listing = await listDirStructured(sftp, remote)
390
+ if (!listing || listing.missing) throw notFound(path)
391
+ const entries = [...listing.items]
392
+ .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
393
+ .map((item) => ({
394
+ name: item.name,
395
+ type: item.type === 'dir' ? 'directory' : 'file',
396
+ // listDirStructured already resolved symlinks to their destination's
397
+ // type and degrades dangling links to 'file'; sockets/devices also
398
+ // report 'file' (the core's 'other' bucket) — an approximation that
399
+ // only affects display, never read authority.
400
+ ...(item.type === 'file' && typeof item.size === 'number' ? { size: item.size } : {}),
401
+ }))
402
+ return {
403
+ path: workspacePath,
404
+ entries: entries.slice(0, caps.maxEntries),
405
+ truncated: entries.length > caps.maxEntries,
406
+ }
407
+ },
408
+ }
409
+
410
+ /** Methods wrapped, and the wire's positional arguments after the scope. */
411
+ const WRAPPED_METHODS = ['read', 'readBytes', 'stat', 'list']
412
+
413
+ /**
414
+ * Wrap the core `workspaceFiles` service so mirror sessions are served from
415
+ * their remote origin. Inert (returns a no-op handle) when the service is
416
+ * absent or exposes none of the expected methods — a composition without the
417
+ * file service keeps whatever behavior it already had.
418
+ *
419
+ * @param {object} ctx - host plugin context.
420
+ * @param {object} opts
421
+ * @param {(local: string) => {mirrorDir: string|null, remotePath: string, machine: object|null}} opts.resolveBinding
422
+ * @param {(machine: object) => object} opts.poolForMachine
423
+ * @param {object} [opts.logger]
424
+ * @returns {{dispose: () => void}}
425
+ */
426
+ export function installWorkspaceFilesRemote(ctx, opts = {}) {
427
+ const { resolveBinding, poolForMachine } = opts
428
+ const noop = { dispose() {} }
429
+ if (typeof ctx?.inject !== 'function' || typeof resolveBinding !== 'function' || typeof poolForMachine !== 'function') return noop
430
+ let installed = null
431
+ let unregistered = false
432
+ ctx.inject(['workspaceFiles'], (scope) => {
433
+ const service = typeof scope?.get === 'function' ? scope.get('workspaceFiles') : scope?.workspaceFiles
434
+ if (!service || typeof service !== 'object' || unregistered) return
435
+ const wrapped = new Map()
436
+ for (const name of WRAPPED_METHODS) {
437
+ const original = service[name]
438
+ if (typeof original !== 'function') continue
439
+ const hadOwn = Object.hasOwn(service, name)
440
+ const routed = (...args) => routeRemote(name, service, original, args, { resolveBinding, poolForMachine })
441
+ try {
442
+ service[name] = routed
443
+ wrapped.set(name, { original, routed, hadOwn })
444
+ } catch {
445
+ // A frozen or readonly service face (an older host build): leave it be.
446
+ }
447
+ }
448
+ if (!wrapped.size) return
449
+ const restore = () => {
450
+ for (const [name, { original, routed, hadOwn }] of wrapped) {
451
+ if (service[name] !== routed) continue // someone else replaced it; theirs wins
452
+ if (hadOwn) service[name] = original
453
+ else delete service[name]
454
+ }
455
+ wrapped.clear()
456
+ }
457
+ installed = { restore }
458
+ if (typeof scope.effect === 'function') {
459
+ scope.effect(() => {
460
+ unregistered = true
461
+ restore()
462
+ })
463
+ }
464
+ })
465
+ return {
466
+ dispose() {
467
+ unregistered = true
468
+ if (installed) installed.restore()
469
+ installed = null
470
+ },
471
+ }
472
+ }
473
+
474
+ /** One gateway call: mirror binding → remote implementation, else the core's. */
475
+ async function routeRemote(name, service, original, args, deps) {
476
+ const binding = bindingOf(deps.resolveBinding, args[0])
477
+ if (!binding) return Reflect.apply(original, service, args)
478
+ return remoteImpl[name](binding, args.slice(1), service, deps)
479
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-remote",
3
- "version": "1.3.1",
3
+ "version": "1.4.0",
4
4
  "description": "SSH remote workspaces for DeepSeek Harness: parallel projects across hosts, remote file browsing and editing, recursive search, terminals, Git diffs, and workspace-bound Agent tools to edit, build and test remotely. Optional IDE layout.",
5
5
  "license": "MIT",
6
6
  "author": "flymysql <flyphp@outlook.com>",
@@ -103,6 +103,6 @@
103
103
  "test:coverage": "node scripts/coverage-union.mjs",
104
104
  "test:coverage:gate": "node scripts/coverage-union.mjs --gate 70 --file-gate 60"
105
105
  },
106
- "readme": "[English](https://github.com/flymysql/dsh-remote/blob/main/README.en.md) · **中文**\n\n# dsh-remote\n\n[![npm version](https://img.shields.io/npm/v/dsh-remote)](https://www.npmjs.com/package/dsh-remote)\n[![downloads](https://img.shields.io/npm/dw/dsh-remote)](https://www.npmjs.com/package/dsh-remote)\n[![downloads](https://img.shields.io/npm/dm/dsh-remote)](https://www.npmjs.com/package/dsh-remote)\n[![license](https://img.shields.io/github/license/flymysql/dsh-remote)](https://github.com/flymysql/dsh-remote/blob/main/LICENSE)\n[![dsh-plugin](https://img.shields.io/badge/topic-dsh--plugin-7a3ef3)](https://github.com/topics/dsh-plugin)\n\n由 [@flymysql](https://github.com/flymysql) 维护 · [主页](https://flymysql.github.io/dsh-remote/) · [用量统计](https://flymysql.github.io/dsh-remote/stats/) · [博客](https://gitpull.cn) · [讨论区](https://github.com/flymysql/dsh-remote/discussions) · [Issue](https://github.com/flymysql/dsh-remote/issues) · [English](https://github.com/flymysql/dsh-remote/blob/main/README.en.md)\n\n![dsh-remote —— 远程项目,完整上下文](https://raw.githubusercontent.com/flymysql/dsh-remote/main/docs/shots/workspace-overview.png)\n\n在 [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) 中,把 SSH 主机变成日常开发工作区:管理多主机项目,浏览和编辑远程文件、递归搜索文件与内容、使用终端、查看 Git 差异、建立本地/反向端口隧道;让 Agent 在所属远程工作区中读写文件、执行命令、构建和测试。多个工作区可独立并行。\n\n可按习惯使用普通布局,或切换 **IDE 三栏布局**,并排查看远程文件、编辑器与原生 Agent 会话;切换时保留任务和未保存编辑。\n\n<img src=\"https://raw.githubusercontent.com/flymysql/dsh-remote/main/docs/shots/workbench-ide.png\" alt=\"DSH 远程工作区 IDE 模式:远程文件树、代码编辑器和原生 Agent 会话三栏\" width=\"1200\"/>\n\n## 安装\n\n```bash\ndsh plugin --profile web add dsh-remote\n```\n\n安装或升级后,重启 DSH Web 并刷新页面。自动更新状态在设置 → 远程工作区 → 插件偏好中查看。\n\n[1.3.1 更新说明](https://github.com/flymysql/dsh-remote/blob/main/docs/release/1.3.1.md):SSH 连接恢复、代理网络更新与官方 GitHub 下载回退。\n\n## 3 步开始\n\n1. **配置主机**:设置 → 远程工作区,编辑 SSH 配置或保存主机凭据;直接写在 `~/.ssh/config` 里的 Host 会出现在主机列表中,点该行的「…」菜单 →「编辑」即可保存成机器并填写登录密码(保存前后入口都是同一个「…」菜单)。打开设置会自动检查连通性,无需手动“连接”。\n2. **创建工作区**:添加工作区 → 远程,选择主机与目录。每个工作区独立绑定主机,设置页不选目录或“当前远程机”。\n3. **开始开发**:打开工作区文件或切换 IDE 模式,文件打开即可编辑并显示语法高亮,在远端搜索、运行命令并与 Agent 协作。\n\n<img src=\"https://raw.githubusercontent.com/flymysql/dsh-remote/main/docs/shots/workspace-picker-browse.png\" alt=\"选择远程目录:固定路径与确认栏,目录列表占据弹窗主要区域\" width=\"720\"/>\n\n## 本地工作区也能用\n\n打开普通本地项目后,点击 **IDE 模式** 或 **工作区文件**,即可使用同一套文件树、高亮编辑、递归搜索、Git 差异与本地终端。无需配置 SSH;Agent 继续使用宿主原生文件和命令工具,多个本地、远程项目可并行工作。\n\n<img src=\"https://raw.githubusercontent.com/flymysql/dsh-remote/main/docs/shots/workbench-local.png\" alt=\"本地工作区:文件搜索、高亮编辑和原生 Agent 会话,Agent 已实际完成本地构建\" width=\"1200\"/>\n\n## 日常开发\n\n### 搜索远端文件与内容\n\n文件、目录和内容递归搜索,无需先展开目录或同步镜像。默认界面只显示搜索范围与进度摘要;按需展开搜索选项、扫描详情,支持大小写、忽略项、停止与重试。点击结果进入目录或文件对应行。\n\n<img src=\"https://raw.githubusercontent.com/flymysql/dsh-remote/main/docs/shots/workbench-search-results.png\" alt=\"简洁远程搜索:名称搜索结果包含嵌套目录与文件\" width=\"675\"/>\n\n### 查看远端 Git 改动\n\n分别查看工作区和已暂存 diff,筛选文件,点击改动行定位源码。面板只读,不提交或修改暂存区。\n\n<img src=\"https://raw.githubusercontent.com/flymysql/dsh-remote/main/docs/shots/workbench-git.png\" alt=\"远端 Git 工作区与已暂存改动、文件列表和源码 diff\" width=\"675\"/>\n\n### 在远端运行终端\n\n终端进入当前会话的远程目录;像素鱼欢迎图后接真实 SSH shell。已保存凭据可自动应答,支持多终端并行。\n\n<img src=\"https://raw.githubusercontent.com/flymysql/dsh-remote/main/docs/shots/workbench-terminal.png\" alt=\"DSH 远程终端:像素鱼欢迎图与实际 SSH 命令输出\" width=\"1000\"/>\n\n### 端口转发(SSH 隧道)\n\n谁要发起访问,就在谁那边开监听口:监听口开在本机是本地转发(`ssh -L`),开在远端是远程转发(`ssh -R`)。可同时运行多条;添加转发时可以选择「主机」,每条转发只属于一台机器——给还没连接的主机也能先存下转发,连上后再启动。每条转发都可以点「编辑」调整方向、端口、目标或所属主机,运行中的会先停止、保存后按新配置重新启动。每行能直接勾选「自动重连」——只恢复上次运行中的转发,且按机器隔离,反向转发首次勾选会提示远端监听风险。\n\n从旧版本升级:旧版没有 `lastActive` 的「自动重连」配置会暂停,行上显示「需重新确认」;重新勾选后才会参与自动恢复(反向转发需重新确认远端监听)。\n\n<img src=\"docs/shots/port-forwards.png\" alt=\"端口转发面板:本地/反向方向、自动重连勾选框与添加转发表单\" width=\"900\"/>\n\n### 与 Agent 一起修改和构建\n\n工具卡展示已应用改动、实际退出码和构建输出,编译诊断可跳转源码。编辑器保存会检测远端冲突、保留 CRLF,并保护保存期间继续输入的内容。\n\n<img src=\"https://raw.githubusercontent.com/flymysql/dsh-remote/main/docs/shots/workbench-applied-diff.png\" alt=\"Agent 远程编辑成功后的已应用 diff、路径与增删行数\" width=\"485\"/>\n\n## 兼容与边界\n\n- 主要面向 **DSH Web 0.2.x**;0.2.2 需要 **Node.js ≥24.9**。旧版宿主回退、Desktop/TUI 与 Agent diff 差异见[兼容说明](https://github.com/flymysql/dsh-remote/blob/main/docs/reference.zh.md#dsh-版本兼容性)。\n- 文件栏直接访问远端;镜像按需同步。草稿在当前页面内存,崩溃或强制退出仍可能丢失。\n- 不提供远端语言服务、扩展宿主或调试器。Agent 使用配置的 SSH 身份执行命令,请只配置可信主机。\n\n## 文档与社区\n\n[完整工具与配置参考](https://github.com/flymysql/dsh-remote/blob/main/docs/reference.zh.md) · [排障](https://github.com/flymysql/dsh-remote/blob/main/docs/troubleshooting.md) · [自更新修复](https://github.com/flymysql/dsh-remote/blob/main/docs/self-heal.md) · [升级指南](https://github.com/flymysql/dsh-remote/blob/main/docs/migration-1.0.md) · [更新记录](https://github.com/flymysql/dsh-remote/blob/main/CHANGELOG.md)\n\n[主页](https://flymysql.github.io/dsh-remote/) · [讨论区](https://github.com/flymysql/dsh-remote/discussions) · [反馈问题](https://github.com/flymysql/dsh-remote/issues) · [贡献指南](https://github.com/flymysql/dsh-remote/blob/main/CONTRIBUTING.md) · [贡献者与致谢](#贡献者与致谢)\n\n由 [@flymysql](https://github.com/flymysql) 与社区共同维护 · [MIT](https://github.com/flymysql/dsh-remote/blob/main/LICENSE)\n\n### 贡献者与致谢\n\n感谢每一位让这个项目更好的朋友(头像可点进主页;按提交数排序,机器人不计):\n\n<p align=\"left\">\n <a href=\"https://github.com/flymysql\"><img src=\"https://avatars.githubusercontent.com/u/37113068?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@flymysql\" title=\"@flymysql\" /></a>\n <a href=\"https://github.com/baiseraku\"><img src=\"https://avatars.githubusercontent.com/u/139727690?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@baiseraku\" title=\"@baiseraku\" /></a>\n <a href=\"https://github.com/glzhangzhi\"><img src=\"https://avatars.githubusercontent.com/u/36995275?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@glzhangzhi\" title=\"@glzhangzhi\" /></a>\n <a href=\"https://github.com/hjwsm1989\"><img src=\"https://avatars.githubusercontent.com/u/1067541?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@hjwsm1989\" title=\"@hjwsm1989\" /></a>\n <a href=\"https://github.com/j10ha0\"><img src=\"https://avatars.githubusercontent.com/u/72346906?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@j10ha0\" title=\"@j10ha0\" /></a>\n <a href=\"https://github.com/FoolishWiser\"><img src=\"https://avatars.githubusercontent.com/u/104308087?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@FoolishWiser\" title=\"@FoolishWiser\" /></a>\n <a href=\"https://github.com/kakaa-nju\"><img src=\"https://avatars.githubusercontent.com/u/79886619?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@kakaa-nju\" title=\"@kakaa-nju\" /></a>\n <a href=\"https://github.com/4FMTWRV\"><img src=\"https://avatars.githubusercontent.com/u/190457700?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@4FMTWRV\" title=\"@4FMTWRV\" /></a>\n <a href=\"https://github.com/dahaipeng\"><img src=\"https://avatars.githubusercontent.com/u/25660610?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@dahaipeng\" title=\"@dahaipeng\" /></a>\n <a href=\"https://github.com/davidlin2k\"><img src=\"https://avatars.githubusercontent.com/u/17074619?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@davidlin2k\" title=\"@davidlin2k\" /></a>\n <a href=\"https://github.com/FlintyLemming\"><img src=\"https://avatars.githubusercontent.com/u/19165511?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@FlintyLemming\" title=\"@FlintyLemming\" /></a>\n <a href=\"https://github.com/GDWhisper\"><img src=\"https://avatars.githubusercontent.com/u/129148123?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@GDWhisper\" title=\"@GDWhisper\" /></a>\n <a href=\"https://github.com/YiHui-Liu\"><img src=\"https://avatars.githubusercontent.com/u/30190271?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@YiHui-Liu\" title=\"@YiHui-Liu\" /></a>\n <a href=\"https://github.com/Minggle\"><img src=\"https://avatars.githubusercontent.com/u/35053182?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@Minggle\" title=\"@Minggle\" /></a>\n <a href=\"https://github.com/nekomona\"><img src=\"https://avatars.githubusercontent.com/u/25474483?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@nekomona\" title=\"@nekomona\" /></a>\n <a href=\"https://github.com/shis23\"><img src=\"https://avatars.githubusercontent.com/u/189869650?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@shis23\" title=\"@shis23\" /></a>\n</p>\n\n<details>\n<summary>贡献记录与早期贡献者</summary>\n\n近期的亮点贡献(欢迎随时加入这个名单):\n\n| 贡献者 | 做了什么 |\n| --- | --- |\n| [@baiseraku](https://github.com/baiseraku) | 整个 dsh-tui 适配层([#92](https://github.com/flymysql/dsh-remote/pull/92))+ 底栏机器名修正([#98](https://github.com/flymysql/dsh-remote/pull/98)) |\n| [@hjwsm1989](https://github.com/hjwsm1989) | 远程 .md 渲染连环两道:memo 守卫([#102](https://github.com/flymysql/dsh-remote/pull/102))+ labels 契约([#107](https://github.com/flymysql/dsh-remote/pull/107)) |\n| [@shis23](https://github.com/shis23) | rw_sync 路径映射纠偏 + SFTP 超时韧性([#105](https://github.com/flymysql/dsh-remote/pull/105)) |\n| [@davidlin2k](https://github.com/davidlin2k) | 无凭据机器走用户自有 ssh([#100](https://github.com/flymysql/dsh-remote/pull/100)) |\n| [@GDWhisper](https://github.com/GDWhisper) | 目录补全逐字符重连修复([#42](https://github.com/flymysql/dsh-remote/pull/42),issue #41) |\n| [@glzhangzhi](https://github.com/glzhangzhi) | 多远端会话的连接池隔离(issue #25 的主体修复) |\n\n早期已合并 PR 的贡献者(考古名单):\n\n\n\n[@dahaipeng](https://github.com/dahaipeng) (#31) ·\n[@YiHui-Liu](https://github.com/YiHui-Liu) (#28) ·\n[@nekomona](https://github.com/nekomona) (#24) ·\n[@zhz1667](https://github.com/zhz1667) (#43) ·\n[FoolishWiser](https://github.com/FoolishWiser) (#17) ·\n[@jace1cch](https://github.com/jace1cch) (#16) ·\n[@Minggle](https://github.com/Minggle) (#10) ·\n[4FMTWRV](https://github.com/4FMTWRV) (#6) ·\n[glzhangzhi](https://github.com/glzhangzhi)(per-session SSH 连接池修复)\n\n> 名单随版本更新;头像墙之外的每一份 issue 报告、复现步骤、根因线索同样珍贵——\n> 本仓库近半修复的起点都是一条写清楚的 issue。\n\n</details>\n",
106
+ "readme": "[English](https://github.com/flymysql/dsh-remote/blob/main/README.en.md) · **中文**\n\n# dsh-remote\n\n[![npm version](https://img.shields.io/npm/v/dsh-remote)](https://www.npmjs.com/package/dsh-remote)\n[![downloads](https://img.shields.io/npm/dw/dsh-remote)](https://www.npmjs.com/package/dsh-remote)\n[![downloads](https://img.shields.io/npm/dm/dsh-remote)](https://www.npmjs.com/package/dsh-remote)\n[![license](https://img.shields.io/github/license/flymysql/dsh-remote)](https://github.com/flymysql/dsh-remote/blob/main/LICENSE)\n[![dsh-plugin](https://img.shields.io/badge/topic-dsh--plugin-7a3ef3)](https://github.com/topics/dsh-plugin)\n\n由 [@flymysql](https://github.com/flymysql) 维护 · [主页](https://flymysql.github.io/dsh-remote/) · [用量统计](https://flymysql.github.io/dsh-remote/stats/) · [博客](https://gitpull.cn) · [讨论区](https://github.com/flymysql/dsh-remote/discussions) · [Issue](https://github.com/flymysql/dsh-remote/issues) · [English](https://github.com/flymysql/dsh-remote/blob/main/README.en.md)\n\n![dsh-remote —— 远程项目,完整上下文](https://raw.githubusercontent.com/flymysql/dsh-remote/main/docs/shots/workspace-overview.png)\n\n在 [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) 中,把 SSH 主机变成日常开发工作区:管理多主机项目,浏览和编辑远程文件、递归搜索文件与内容、使用终端、查看 Git 差异、建立本地/反向端口隧道;让 Agent 在所属远程工作区中读写文件、执行命令、构建和测试。多个工作区可独立并行。\n\n可按习惯使用普通布局,或切换 **IDE 三栏布局**,并排查看远程文件、编辑器与原生 Agent 会话;切换时保留任务和未保存编辑。\n\n<img src=\"https://raw.githubusercontent.com/flymysql/dsh-remote/main/docs/shots/workbench-ide.png\" alt=\"DSH 远程工作区 IDE 模式:远程文件树、代码编辑器和原生 Agent 会话三栏\" width=\"1200\"/>\n\n## 安装\n\n```bash\ndsh plugin --profile web add dsh-remote\n```\n\n安装或升级后,重启 DSH Web 并刷新页面。自动更新状态在设置 → 远程工作区 → 插件偏好中查看。\n\n[1.4.0 更新说明](https://github.com/flymysql/dsh-remote/blob/main/docs/release/1.4.0.md):镜像会话文件预览直读远端、Markdown 插图渲染、OpenSSH 建连超时重试、工作区选择器恢复。\n\n## 3 步开始\n\n1. **配置主机**:设置 → 远程工作区,编辑 SSH 配置或保存主机凭据;直接写在 `~/.ssh/config` 里的 Host 会出现在主机列表中,点该行的「…」菜单 →「编辑」即可保存成机器并填写登录密码(保存前后入口都是同一个「…」菜单)。打开设置会自动检查连通性,无需手动“连接”。\n2. **创建工作区**:添加工作区 → 远程,选择主机与目录。每个工作区独立绑定主机,设置页不选目录或“当前远程机”。\n3. **开始开发**:打开工作区文件或切换 IDE 模式,文件打开即可编辑并显示语法高亮,在远端搜索、运行命令并与 Agent 协作。\n\n<img src=\"https://raw.githubusercontent.com/flymysql/dsh-remote/main/docs/shots/workspace-picker-browse.png\" alt=\"选择远程目录:固定路径与确认栏,目录列表占据弹窗主要区域\" width=\"720\"/>\n\n## 本地工作区也能用\n\n打开普通本地项目后,点击 **IDE 模式** 或 **工作区文件**,即可使用同一套文件树、高亮编辑、递归搜索、Git 差异与本地终端。无需配置 SSH;Agent 继续使用宿主原生文件和命令工具,多个本地、远程项目可并行工作。\n\n<img src=\"https://raw.githubusercontent.com/flymysql/dsh-remote/main/docs/shots/workbench-local.png\" alt=\"本地工作区:文件搜索、高亮编辑和原生 Agent 会话,Agent 已实际完成本地构建\" width=\"1200\"/>\n\n## 日常开发\n\n### 搜索远端文件与内容\n\n文件、目录和内容递归搜索,无需先展开目录或同步镜像。默认界面只显示搜索范围与进度摘要;按需展开搜索选项、扫描详情,支持大小写、忽略项、停止与重试。点击结果进入目录或文件对应行。\n\n<img src=\"https://raw.githubusercontent.com/flymysql/dsh-remote/main/docs/shots/workbench-search-results.png\" alt=\"简洁远程搜索:名称搜索结果包含嵌套目录与文件\" width=\"675\"/>\n\n### 查看远端 Git 改动\n\n分别查看工作区和已暂存 diff,筛选文件,点击改动行定位源码。面板只读,不提交或修改暂存区。\n\n<img src=\"https://raw.githubusercontent.com/flymysql/dsh-remote/main/docs/shots/workbench-git.png\" alt=\"远端 Git 工作区与已暂存改动、文件列表和源码 diff\" width=\"675\"/>\n\n### 在远端运行终端\n\n终端进入当前会话的远程目录;像素鱼欢迎图后接真实 SSH shell。已保存凭据可自动应答,支持多终端并行。\n\n<img src=\"https://raw.githubusercontent.com/flymysql/dsh-remote/main/docs/shots/workbench-terminal.png\" alt=\"DSH 远程终端:像素鱼欢迎图与实际 SSH 命令输出\" width=\"1000\"/>\n\n### 端口转发(SSH 隧道)\n\n谁要发起访问,就在谁那边开监听口:监听口开在本机是本地转发(`ssh -L`),开在远端是远程转发(`ssh -R`)。可同时运行多条;添加转发时可以选择「主机」,每条转发只属于一台机器——给还没连接的主机也能先存下转发,连上后再启动。每条转发都可以点「编辑」调整方向、端口、目标或所属主机,运行中的会先停止、保存后按新配置重新启动。每行能直接勾选「自动重连」——只恢复上次运行中的转发,且按机器隔离,反向转发首次勾选会提示远端监听风险。\n\n从旧版本升级:旧版没有 `lastActive` 的「自动重连」配置会暂停,行上显示「需重新确认」;重新勾选后才会参与自动恢复(反向转发需重新确认远端监听)。\n\n<img src=\"docs/shots/port-forwards.png\" alt=\"端口转发面板:本地/反向方向、自动重连勾选框与添加转发表单\" width=\"900\"/>\n\n### 与 Agent 一起修改和构建\n\n工具卡展示已应用改动、实际退出码和构建输出,编译诊断可跳转源码。编辑器保存会检测远端冲突、保留 CRLF,并保护保存期间继续输入的内容。\n\n<img src=\"https://raw.githubusercontent.com/flymysql/dsh-remote/main/docs/shots/workbench-applied-diff.png\" alt=\"Agent 远程编辑成功后的已应用 diff、路径与增删行数\" width=\"485\"/>\n\n## 兼容与边界\n\n- 主要面向 **DSH Web 0.2.x**;0.2.2 需要 **Node.js ≥24.9**。旧版宿主回退、Desktop/TUI 与 Agent diff 差异见[兼容说明](https://github.com/flymysql/dsh-remote/blob/main/docs/reference.zh.md#dsh-版本兼容性)。\n- 文件栏直接访问远端;镜像按需同步。草稿在当前页面内存,崩溃或强制退出仍可能丢失。\n- 不提供远端语言服务、扩展宿主或调试器。Agent 使用配置的 SSH 身份执行命令,请只配置可信主机。\n\n## 文档与社区\n\n[完整工具与配置参考](https://github.com/flymysql/dsh-remote/blob/main/docs/reference.zh.md) · [排障](https://github.com/flymysql/dsh-remote/blob/main/docs/troubleshooting.md) · [自更新修复](https://github.com/flymysql/dsh-remote/blob/main/docs/self-heal.md) · [升级指南](https://github.com/flymysql/dsh-remote/blob/main/docs/migration-1.0.md) · [更新记录](https://github.com/flymysql/dsh-remote/blob/main/CHANGELOG.md)\n\n[主页](https://flymysql.github.io/dsh-remote/) · [讨论区](https://github.com/flymysql/dsh-remote/discussions) · [反馈问题](https://github.com/flymysql/dsh-remote/issues) · [贡献指南](https://github.com/flymysql/dsh-remote/blob/main/CONTRIBUTING.md) · [贡献者与致谢](#贡献者与致谢)\n\n由 [@flymysql](https://github.com/flymysql) 与社区共同维护 · [MIT](https://github.com/flymysql/dsh-remote/blob/main/LICENSE)\n\n### 贡献者与致谢\n\n感谢每一位让这个项目更好的朋友(头像可点进主页;按提交数排序,机器人不计):\n\n<p align=\"left\">\n <a href=\"https://github.com/flymysql\"><img src=\"https://avatars.githubusercontent.com/u/37113068?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@flymysql\" title=\"@flymysql\" /></a>\n <a href=\"https://github.com/baiseraku\"><img src=\"https://avatars.githubusercontent.com/u/139727690?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@baiseraku\" title=\"@baiseraku\" /></a>\n <a href=\"https://github.com/glzhangzhi\"><img src=\"https://avatars.githubusercontent.com/u/36995275?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@glzhangzhi\" title=\"@glzhangzhi\" /></a>\n <a href=\"https://github.com/hjwsm1989\"><img src=\"https://avatars.githubusercontent.com/u/1067541?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@hjwsm1989\" title=\"@hjwsm1989\" /></a>\n <a href=\"https://github.com/j10ha0\"><img src=\"https://avatars.githubusercontent.com/u/72346906?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@j10ha0\" title=\"@j10ha0\" /></a>\n <a href=\"https://github.com/FoolishWiser\"><img src=\"https://avatars.githubusercontent.com/u/104308087?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@FoolishWiser\" title=\"@FoolishWiser\" /></a>\n <a href=\"https://github.com/kakaa-nju\"><img src=\"https://avatars.githubusercontent.com/u/79886619?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@kakaa-nju\" title=\"@kakaa-nju\" /></a>\n <a href=\"https://github.com/4FMTWRV\"><img src=\"https://avatars.githubusercontent.com/u/190457700?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@4FMTWRV\" title=\"@4FMTWRV\" /></a>\n <a href=\"https://github.com/dahaipeng\"><img src=\"https://avatars.githubusercontent.com/u/25660610?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@dahaipeng\" title=\"@dahaipeng\" /></a>\n <a href=\"https://github.com/davidlin2k\"><img src=\"https://avatars.githubusercontent.com/u/17074619?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@davidlin2k\" title=\"@davidlin2k\" /></a>\n <a href=\"https://github.com/FlintyLemming\"><img src=\"https://avatars.githubusercontent.com/u/19165511?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@FlintyLemming\" title=\"@FlintyLemming\" /></a>\n <a href=\"https://github.com/GDWhisper\"><img src=\"https://avatars.githubusercontent.com/u/129148123?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@GDWhisper\" title=\"@GDWhisper\" /></a>\n <a href=\"https://github.com/YiHui-Liu\"><img src=\"https://avatars.githubusercontent.com/u/30190271?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@YiHui-Liu\" title=\"@YiHui-Liu\" /></a>\n <a href=\"https://github.com/Minggle\"><img src=\"https://avatars.githubusercontent.com/u/35053182?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@Minggle\" title=\"@Minggle\" /></a>\n <a href=\"https://github.com/nekomona\"><img src=\"https://avatars.githubusercontent.com/u/25474483?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@nekomona\" title=\"@nekomona\" /></a>\n <a href=\"https://github.com/shis23\"><img src=\"https://avatars.githubusercontent.com/u/189869650?s=80&v=4\" width=\"40\" height=\"40\" alt=\"@shis23\" title=\"@shis23\" /></a>\n</p>\n\n<details>\n<summary>贡献记录与早期贡献者</summary>\n\n近期的亮点贡献(欢迎随时加入这个名单):\n\n| 贡献者 | 做了什么 |\n| --- | --- |\n| [@baiseraku](https://github.com/baiseraku) | 整个 dsh-tui 适配层([#92](https://github.com/flymysql/dsh-remote/pull/92))+ 底栏机器名修正([#98](https://github.com/flymysql/dsh-remote/pull/98)) |\n| [@hjwsm1989](https://github.com/hjwsm1989) | 远程 .md 渲染连环两道:memo 守卫([#102](https://github.com/flymysql/dsh-remote/pull/102))+ labels 契约([#107](https://github.com/flymysql/dsh-remote/pull/107)) |\n| [@shis23](https://github.com/shis23) | rw_sync 路径映射纠偏 + SFTP 超时韧性([#105](https://github.com/flymysql/dsh-remote/pull/105)) |\n| [@davidlin2k](https://github.com/davidlin2k) | 无凭据机器走用户自有 ssh([#100](https://github.com/flymysql/dsh-remote/pull/100)) |\n| [@GDWhisper](https://github.com/GDWhisper) | 目录补全逐字符重连修复([#42](https://github.com/flymysql/dsh-remote/pull/42),issue #41) |\n| [@glzhangzhi](https://github.com/glzhangzhi) | 多远端会话的连接池隔离(issue #25 的主体修复) |\n\n早期已合并 PR 的贡献者(考古名单):\n\n\n\n[@dahaipeng](https://github.com/dahaipeng) (#31) ·\n[@YiHui-Liu](https://github.com/YiHui-Liu) (#28) ·\n[@nekomona](https://github.com/nekomona) (#24) ·\n[@zhz1667](https://github.com/zhz1667) (#43) ·\n[FoolishWiser](https://github.com/FoolishWiser) (#17) ·\n[@jace1cch](https://github.com/jace1cch) (#16) ·\n[@Minggle](https://github.com/Minggle) (#10) ·\n[4FMTWRV](https://github.com/4FMTWRV) (#6) ·\n[glzhangzhi](https://github.com/glzhangzhi)(per-session SSH 连接池修复)\n\n> 名单随版本更新;头像墙之外的每一份 issue 报告、复现步骤、根因线索同样珍贵——\n> 本仓库近半修复的起点都是一条写清楚的 issue。\n\n</details>\n",
107
107
  "readmeFilename": "README.md"
108
108
  }