dsh-linked-workspace 0.15.0 → 0.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -18,7 +18,7 @@
18
18
  import { randomUUID } from 'node:crypto'
19
19
  import { chmodSync, closeSync, cpSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
20
20
  import { spawn } from 'node:child_process'
21
- import { mkdir, readdir, stat as fsStat } from 'node:fs/promises'
21
+ import { mkdir, readdir, rm, stat as fsStat } from 'node:fs/promises'
22
22
  import { homedir, tmpdir } from 'node:os'
23
23
  import { basename, dirname, extname, isAbsolute, join, posix, resolve, sep } from 'node:path'
24
24
  import { fileURLToPath } from 'node:url'
@@ -106,6 +106,12 @@ const IMAGE_MIME = Object.freeze({
106
106
  const MAX_NAME_LENGTH = 120
107
107
  const CONNECT_TIMEOUT_MS = 20_000
108
108
  const OP_TIMEOUT_MS = 60_000
109
+ // A failed probe only describes the moment it ran: a socket that never came up
110
+ // says nothing about the next request, which dials again. After this window the
111
+ // state degrades to "unknown" so a single glitch cannot paint a workspace red
112
+ // for the rest of the session. A live connection is different — when it drops,
113
+ // noteConnectionLost() records that, and the next success clears it.
114
+ const STATUS_TTL_MS = 60_000
109
115
  // Directory listings are paged so a folder with tens of thousands of entries
110
116
  // cannot stall the Host or flood the renderer.
111
117
  const LIST_PAGE_SIZE = 500
@@ -920,6 +926,11 @@ export function apply(ctx) {
920
926
  const settingsStore = new SettingsStore(join(dir, 'settings.json'))
921
927
  const linkedStore = new linkedFs.LinkedStore(join(dir, 'linked.json'))
922
928
  const remoteStore = new RemoteWorkspaceStore(join(dir, 'remote-workspaces.json'))
929
+ // Old "open in notepad" copies are dead weight; clear them once per start.
930
+ // Deferred: the helper is declared further down in this function body.
931
+ setTimeout(() => {
932
+ sweepOpenTempCopies().catch((error) => log('warn', `could not sweep the open-file temp dir: ${error && error.message ? error.message : error}`))
933
+ }, 0)
923
934
  // 0.5.0: mirror sync is opt-in. Records created under the old default
924
935
  // (mirror on, never explicitly chosen) are switched off once.
925
936
  for (const existing of linkedStore.list()) {
@@ -1049,11 +1060,30 @@ export function apply(ctx) {
1049
1060
  return runningCache.keys
1050
1061
  }
1051
1062
 
1063
+ /**
1064
+ * Status as the UI should see it. A stale failure is reported as "unknown"
1065
+ * instead of "error": the connection is redialled on demand, so an old failed
1066
+ * attempt proves nothing about the workspace right now.
1067
+ */
1068
+ const hostStatusView = (hostId) => {
1069
+ const status = pool.status(hostId)
1070
+ if (!status || typeof status.state !== 'string' || status.state === '') return { state: 'idle' }
1071
+ const checkedAt = typeof status.checkedAt === 'number' ? status.checkedAt : 0
1072
+ const fresh = checkedAt > 0 && Date.now() - checkedAt <= STATUS_TTL_MS
1073
+ if (status.state === 'error' && !fresh) return { state: 'idle', checkedAt }
1074
+ return {
1075
+ state: status.state,
1076
+ ...(status.reason ? { reason: status.reason } : {}),
1077
+ ...(status.message ? { message: status.message } : {}),
1078
+ ...(typeof status.latencyMs === 'number' ? { latencyMs: status.latencyMs } : {}),
1079
+ ...(checkedAt > 0 ? { checkedAt } : {}),
1080
+ }
1081
+ }
1082
+
1052
1083
  const describeLink = (record, runningKeys) => {
1053
1084
  const host = pool.host(record.hostId)
1054
1085
  const snapshot = record.hostSnapshot || {}
1055
1086
  const workspace = findWorkspaceByPath(linkedRegistry(), record.localPath)
1056
- const status = pool.status(record.hostId)
1057
1087
  return {
1058
1088
  id: record.id,
1059
1089
  name: record.name,
@@ -1069,12 +1099,7 @@ export function apply(ctx) {
1069
1099
  createdAt: record.createdAt,
1070
1100
  workspaceId: workspace ? String(workspace.id) : null,
1071
1101
  workspaceTitle: workspace ? workspace.title : null,
1072
- status: {
1073
- state: status ? status.state : 'idle',
1074
- ...(status && status.reason ? { reason: status.reason } : {}),
1075
- ...(status && status.message ? { message: status.message } : {}),
1076
- ...(status && typeof status.latencyMs === 'number' ? { latencyMs: status.latencyMs } : {}),
1077
- },
1102
+ status: hostStatusView(record.hostId),
1078
1103
  }
1079
1104
  }
1080
1105
 
@@ -1084,7 +1109,6 @@ export function apply(ctx) {
1084
1109
  const describeRemote = (record) => {
1085
1110
  const host = pool.host(record.hostId)
1086
1111
  const snapshot = record.hostSnapshot || {}
1087
- const status = pool.status(record.hostId)
1088
1112
  return {
1089
1113
  id: record.id,
1090
1114
  name: record.name,
@@ -1097,12 +1121,7 @@ export function apply(ctx) {
1097
1121
  placeholderPath: record.placeholderPath,
1098
1122
  workspaceId: record.workspaceId || null,
1099
1123
  createdAt: record.createdAt,
1100
- status: {
1101
- state: status ? status.state : 'idle',
1102
- ...(status && status.reason ? { reason: status.reason } : {}),
1103
- ...(status && status.message ? { message: status.message } : {}),
1104
- ...(status && typeof status.latencyMs === 'number' ? { latencyMs: status.latencyMs } : {}),
1105
- },
1124
+ status: hostStatusView(record.hostId),
1106
1125
  }
1107
1126
  }
1108
1127
 
@@ -1752,6 +1771,23 @@ export function apply(ctx) {
1752
1771
  return { path: destination, files: 1, bytes: read.data.length, skipped: 0, truncated: false }
1753
1772
  }
1754
1773
 
1774
+ // Copies opened in an external editor are throw-away: sweep the ones from
1775
+ // earlier sessions so the temp folder does not grow forever (D4).
1776
+ const OPEN_TEMP_MAX_AGE_MS = 24 * 60 * 60 * 1000
1777
+
1778
+ const sweepOpenTempCopies = async () => {
1779
+ const dir = join(tmpdir(), 'dsh-linked-workspace-open')
1780
+ const names = await readdir(dir).catch(() => [])
1781
+ const now = Date.now()
1782
+ await Promise.all(names.map(async (name) => {
1783
+ const target = join(dir, name)
1784
+ const info = await fsStat(target).catch(() => null)
1785
+ if (!info || !info.isFile()) return
1786
+ if (now - info.mtimeMs < OPEN_TEMP_MAX_AGE_MS) return
1787
+ await rm(target, { force: true }).catch(() => {})
1788
+ }))
1789
+ }
1790
+
1755
1791
  const openTempCopy = async (remote, target, app) => {
1756
1792
  const stat = await remote.stat(target)
1757
1793
  if (stat.type !== 'file') throw new ApiError('FS_IS_DIR', '只能编辑文件')
@@ -2149,6 +2185,26 @@ export function apply(ctx) {
2149
2185
  }
2150
2186
  },
2151
2187
 
2188
+ /**
2189
+ * Cheap connection-state read for the sidebar. Reading it never dials, so the
2190
+ * client can poll it to keep the workspace cards honest: a dropped socket is
2191
+ * recorded by noteConnectionLost(), a successful request by connectHost().
2192
+ */
2193
+ async 'hosts.status'(params = {}) {
2194
+ const requested = Array.isArray(params.hostIds) ? params.hostIds : null
2195
+ const ids = new Set()
2196
+ if (requested) {
2197
+ for (const id of requested) if (typeof id === 'string' && id !== '') ids.add(id)
2198
+ } else {
2199
+ for (const host of await refreshHosts()) ids.add(host.id)
2200
+ for (const record of linkedStore.list()) if (record && record.hostId) ids.add(record.hostId)
2201
+ for (const record of remoteStore.list()) if (record && record.hostId) ids.add(record.hostId)
2202
+ }
2203
+ const statuses = {}
2204
+ for (const id of ids) statuses[id] = hostStatusView(id)
2205
+ return { statuses }
2206
+ },
2207
+
2152
2208
  /**
2153
2209
  * Store a credential for one SSH host on this machine.
2154
2210
  *
@@ -2230,6 +2286,28 @@ export function apply(ctx) {
2230
2286
  return { path: target }
2231
2287
  },
2232
2288
 
2289
+ // Free space on the volume that holds a remote path (F2). `df -Pk` is the
2290
+ // portable form: one line of numbers in 1K blocks.
2291
+ async 'hosts.df'(params = {}) {
2292
+ const host = await findHost(params.hostId)
2293
+ const remote = await connectHost(host)
2294
+ const rawPath = typeof params.path === 'string' && params.path.trim() !== ''
2295
+ ? params.path
2296
+ : await remote.homeDir()
2297
+ const target = await normalizeRemotePath(remote, rawPath)
2298
+ const result = await remote.exec(`df -Pk ${shellQuoteArg(target)} 2>/dev/null || true`)
2299
+ const lines = String(result.stdout || '').trim().split('\n')
2300
+ if (lines.length < 2) return { disk: null }
2301
+ const cols = lines[lines.length - 1].trim().split(/\s+/)
2302
+ if (cols.length < 6) return { disk: null }
2303
+ const size = Number(cols[1]) * 1024
2304
+ const used = Number(cols[2]) * 1024
2305
+ const avail = Number(cols[3]) * 1024
2306
+ if (!Number.isFinite(size) || !Number.isFinite(avail)) return { disk: null }
2307
+ const percent = size > 0 ? Math.round((used / size) * 100) : 0
2308
+ return { disk: { path: target, size, used, avail, percent } }
2309
+ },
2310
+
2233
2311
  async 'fs.list'(params = {}) {
2234
2312
  const scope = await requireScope(params)
2235
2313
  const target = params.path === undefined || params.path === ''
@@ -2271,8 +2349,12 @@ export function apply(ctx) {
2271
2349
  const target = scopeTarget(scope, params.path)
2272
2350
  const stat = await scope.remote.stat(target)
2273
2351
  if (stat.type === 'dir') throw new ApiError('FS_IS_DIR', '目标是目录,无法作为文件读取')
2274
- const limit = Math.min(Math.max(Number(params.maxBytes) || EDITABLE_LIMIT, 1024), READ_CAP)
2275
- const tooLarge = stat.size > EDITABLE_LIMIT
2352
+ // `preview` lifts the editor's 2 MB ceiling to the 8 MB read cap, so a
2353
+ // read-only preview (HTML pages, build logs) can show files the editor
2354
+ // refuses to edit. Editing stays capped at EDITABLE_LIMIT either way.
2355
+ const softLimit = params.preview === true ? READ_CAP : EDITABLE_LIMIT
2356
+ const limit = Math.min(Math.max(Number(params.maxBytes) || softLimit, 1024), READ_CAP)
2357
+ const tooLarge = stat.size > softLimit
2276
2358
  const read = await scope.remote.readFile(target, { maxBytes: tooLarge ? Math.min(PEEK_LIMIT, limit) : limit })
2277
2359
  const truncated = read.truncated || read.data.length < stat.size
2278
2360
  const binary = looksBinary(read.data)
@@ -2660,6 +2742,9 @@ export function apply(ctx) {
2660
2742
  async 'fs.chmod'(params = {}) {
2661
2743
  const scope = await requireScope(params)
2662
2744
  const target = scopeTarget(scope, params.path)
2745
+ // chmod 644 on the root would hide the whole workspace from the plugin
2746
+ // (a directory without the execute bit looks empty and unreadable).
2747
+ if (target === scope.root) throw new ApiError('BAD_REQUEST', '不能修改工作区根目录的权限')
2663
2748
  const mode = String(params.mode || '').trim()
2664
2749
  if (!/^[0-7]{3,4}$/.test(mode)) throw new ApiError('BAD_REQUEST', '权限必须是 3-4 位八进制,例如 644 或 0755')
2665
2750
  await scope.remote.exec(`chmod ${mode} ${shellQuoteArg(target)}`, { timeoutMs: 15000 })
@@ -2821,7 +2906,8 @@ export function apply(ctx) {
2821
2906
  throw mapLocalFsError(error)
2822
2907
  }
2823
2908
  if (info.isDirectory()) throw new ApiError('FS_IS_DIR', '目标是目录,无法作为文件读取')
2824
- const tooLarge = info.size > EDITABLE_LIMIT
2909
+ const softLimit = params.preview === true ? READ_CAP : EDITABLE_LIMIT
2910
+ const tooLarge = info.size > softLimit
2825
2911
  const cap = tooLarge ? PEEK_LIMIT : READ_CAP
2826
2912
  // Read at most `cap` bytes. Reading the whole file first would pull
2827
2913
  // multi-gigabyte files into Host memory (and on Windows readFileSync
@@ -3698,25 +3784,25 @@ export function apply(ctx) {
3698
3784
 
3699
3785
  const host = await findHost(record.hostId)
3700
3786
  const started = Date.now()
3787
+ let remote
3788
+ try {
3789
+ // connectHost() records the connection state itself: connected on
3790
+ // success, error only when the dialect really failed.
3791
+ remote = await connectHost(host)
3792
+ } catch (error) {
3793
+ const apiError = asApiError(error)
3794
+ return { ok: false, error: apiError.message, latencyMs: Date.now() - started }
3795
+ }
3796
+ const latencyMs = Date.now() - started
3701
3797
  try {
3702
- const remote = await connectHost(host)
3703
3798
  const stat = await remote.stat(record.remotePath)
3704
- const latencyMs = Date.now() - started
3705
- pool.setStatus(host.id, { state: 'connected', latencyMs })
3706
- return {
3707
- ok: true,
3708
- latencyMs,
3709
- exists: stat.type === 'dir',
3710
- type: stat.type,
3711
- }
3799
+ return { ok: true, latencyMs, exists: stat.type === 'dir', type: stat.type }
3712
3800
  } catch (error) {
3801
+ // The host answered, so the link is fine; only this workspace's directory
3802
+ // is missing or unreadable. Reporting that as a connection error would
3803
+ // paint every other workspace on the same host red.
3713
3804
  const apiError = asApiError(error)
3714
- pool.setStatus(host.id, { state: 'error', message: apiError.message })
3715
- return {
3716
- ok: false,
3717
- error: apiError.message,
3718
- latencyMs: Date.now() - started,
3719
- }
3805
+ return { ok: false, exists: false, error: apiError.message, latencyMs }
3720
3806
  }
3721
3807
  },
3722
3808
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-linked-workspace",
3
- "version": "0.15.0",
3
+ "version": "0.16.1",
4
4
  "description": "Linked local ⇄ remote workspaces and remote workspaces for DeepSeek Harness: theme-aware split editor, file-type icons, and agent tools that edit remote files directly.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",