dsh-linked-workspace 0.18.0 → 0.20.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/index.js CHANGED
@@ -15,14 +15,14 @@
15
15
  * Credentials never leave this process: the client only sees host names,
16
16
  * addresses and workspace paths.
17
17
  */
18
- import { randomUUID } from 'node:crypto'
19
- import { chmodSync, closeSync, cpSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
18
+ import { createHash, randomUUID } from 'node:crypto'
19
+ import { chmodSync, closeSync, cpSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, statSync, watch, writeFileSync } from 'node:fs'
20
20
  import { spawn } from 'node:child_process'
21
21
  import { appendFile, mkdir, readdir, rename, 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'
25
- import { listHosts, RemoteHost, SshError, writeLocalCredential } from './ssh.js'
25
+ import { forgetKnownHost, listHosts, listKnownHosts, RemoteHost, SshError, writeLocalCredential } from './ssh.js'
26
26
  import * as linkedFs from './linked.js'
27
27
  import * as git from './git.js'
28
28
 
@@ -38,7 +38,7 @@ export const inject = ['webServer', 'tools', 'systemPrompt', 'workingDirectory']
38
38
  * is still running an older copy of the Host — refreshing the page only swaps
39
39
  * the browser bundle, so the two halves can drift by one restart.
40
40
  */
41
- const API_REVISION = 4
41
+ const API_REVISION = 6
42
42
 
43
43
  /** When this copy of the Host was loaded; shown by `meta.info`. */
44
44
  const STARTED_AT = new Date().toISOString()
@@ -55,7 +55,13 @@ const PACKAGE_VERSION = (() => {
55
55
 
56
56
  const DATA_VERSION = 1
57
57
  const SETTINGS_VERSION = 1
58
- const SETTINGS_DEFAULTS = Object.freeze({ editorTheme: 'github-light', editorThemeFamily: 'github', editorThemeMode: 'system', fileOpenMode: 'editor', autoSave: false, execEnabled: false, execTimeoutMs: 60000, execMaxOutputChars: 200000, execShell: '' })
58
+ const SETTINGS_DEFAULTS = Object.freeze({ editorTheme: 'github-light', editorThemeFamily: 'github', editorThemeMode: 'system', fileOpenMode: 'editor', autoSave: false, execEnabled: false, execTimeoutMs: 60000, execMaxOutputChars: 200000, execShell: '', autoPushEnabled: false, autoPushDebounceMs: 1500, hostKeyPolicy: 'tofu', outputEncoding: 'utf8' })
59
+ const AUTO_PUSH_DEBOUNCE_MIN = 300
60
+ const AUTO_PUSH_DEBOUNCE_MAX = 60000
61
+ /** `tofu` trusts a new host key once; `strict` refuses one it has never seen. */
62
+ const HOST_KEY_POLICIES = new Set(['tofu', 'strict'])
63
+ /** Command output encoding: `utf8` for POSIX hosts, `gbk` for Chinese Windows. */
64
+ const OUTPUT_ENCODINGS = new Set(['utf8', 'gbk'])
59
65
  /** Exec allow-lists travel as arrays, so they are not part of the frozen defaults. */
60
66
  const EMPTY_ID_LIST = Object.freeze([])
61
67
  const EDITOR_THEME_FAMILIES = new Set(['github', 'solarized', 'one', 'dracula', 'monokai', 'nord', 'vscode', 'xcode', 'catppuccin'])
@@ -94,8 +100,7 @@ const PEEK_LIMIT = 512 * 1024
94
100
  const READ_CAP = 8 * 1024 * 1024
95
101
  const MAX_WRITE_BYTES = 8 * 1024 * 1024
96
102
  const MAX_MEDIA_BYTES = 24 * 1024 * 1024
97
- // ── remote command execution (0.17.0) ───────────────────────────────────────
98
- /** Longest command line accepted; anything longer is almost always a paste error. */
103
+ // ── remote command execution (0.17.0) ───────────────────────────────────────/** Longest command line accepted; anything longer is almost always a paste error. */
99
104
  const EXEC_MAX_COMMAND = 8000
100
105
  const EXEC_TIMEOUT_DEFAULT = 60_000
101
106
  const EXEC_TIMEOUT_MAX = 600_000
@@ -162,6 +167,7 @@ const ERROR_STATUS = {
162
167
  SSH_CONNECT: 502,
163
168
  AUTH_FAILED: 401,
164
169
  HOST_KEY_MISMATCH: 409,
170
+ HOST_KEY_UNKNOWN: 409,
165
171
  TIMEOUT: 408,
166
172
  FS_NOT_FOUND: 404,
167
173
  FS_PERMISSION: 403,
@@ -449,10 +455,26 @@ function clampInt(value, min, max, fallback) {
449
455
  return Math.min(max, Math.max(min, Math.round(number)))
450
456
  }
451
457
 
458
+ /** Same idea as normalizeIdList, for the auto-push include/exclude patterns. */
459
+ function normalizeStringList(value) {
460
+ if (!Array.isArray(value)) return []
461
+ const seen = new Set()
462
+ const out = []
463
+ for (const item of value) {
464
+ if (typeof item !== 'string') continue
465
+ const pattern = item.trim()
466
+ if (pattern === '' || seen.has(pattern)) continue
467
+ seen.add(pattern)
468
+ out.push(pattern)
469
+ if (out.length >= 100) break
470
+ }
471
+ return out
472
+ }
473
+
452
474
  class SettingsStore {
453
475
  constructor(file) {
454
476
  this.file = file
455
- this.value = { ...SETTINGS_DEFAULTS, execHostIds: [], execWorkspaceIds: [] }
477
+ this.value = { ...SETTINGS_DEFAULTS, execHostIds: [], execWorkspaceIds: [], autoPushInclude: [], autoPushExclude: [] }
456
478
  const raw = readJsonFile(file, { version: SETTINGS_VERSION, settings: {} })
457
479
  const settings = raw && typeof raw === 'object' && raw.settings && typeof raw.settings === 'object'
458
480
  ? raw.settings
@@ -482,6 +504,22 @@ class SettingsStore {
482
504
  if (settings && typeof settings === 'object' && typeof settings.autoSave === 'boolean') {
483
505
  this.value.autoSave = settings.autoSave
484
506
  }
507
+ if (settings && typeof settings === 'object' && typeof settings.autoPushEnabled === 'boolean') {
508
+ this.value.autoPushEnabled = settings.autoPushEnabled
509
+ }
510
+ if (settings && typeof settings === 'object') {
511
+ if (settings.autoPushDebounceMs !== undefined) {
512
+ this.value.autoPushDebounceMs = clampInt(settings.autoPushDebounceMs, AUTO_PUSH_DEBOUNCE_MIN, AUTO_PUSH_DEBOUNCE_MAX, SETTINGS_DEFAULTS.autoPushDebounceMs)
513
+ }
514
+ this.value.autoPushInclude = normalizeStringList(settings.autoPushInclude)
515
+ this.value.autoPushExclude = normalizeStringList(settings.autoPushExclude)
516
+ }
517
+ if (settings && typeof settings === 'object' && HOST_KEY_POLICIES.has(settings.hostKeyPolicy)) {
518
+ this.value.hostKeyPolicy = settings.hostKeyPolicy
519
+ }
520
+ if (settings && typeof settings === 'object' && OUTPUT_ENCODINGS.has(settings.outputEncoding)) {
521
+ this.value.outputEncoding = settings.outputEncoding
522
+ }
485
523
  if (settings && typeof settings === 'object' && settings.themeExplicit === true) {
486
524
  this.themeExplicit = true
487
525
  }
@@ -514,6 +552,8 @@ class SettingsStore {
514
552
  ...this.value,
515
553
  execHostIds: this.value.execHostIds ? this.value.execHostIds.slice() : [],
516
554
  execWorkspaceIds: this.value.execWorkspaceIds ? this.value.execWorkspaceIds.slice() : [],
555
+ autoPushInclude: this.value.autoPushInclude ? this.value.autoPushInclude.slice() : [],
556
+ autoPushExclude: this.value.autoPushExclude ? this.value.autoPushExclude.slice() : [],
517
557
  }
518
558
  }
519
559
 
@@ -542,6 +582,14 @@ class SettingsStore {
542
582
  if (typeof patch.autoSave !== 'boolean') throw new ApiError('BAD_REQUEST', '自动保存设置无效')
543
583
  this.value.autoSave = patch.autoSave
544
584
  }
585
+ if (patch && typeof patch === 'object' && patch.hostKeyPolicy !== undefined) {
586
+ if (!HOST_KEY_POLICIES.has(patch.hostKeyPolicy)) throw new ApiError('BAD_REQUEST', '主机密钥策略无效')
587
+ this.value.hostKeyPolicy = patch.hostKeyPolicy
588
+ }
589
+ if (patch && typeof patch === 'object' && patch.outputEncoding !== undefined) {
590
+ if (!OUTPUT_ENCODINGS.has(patch.outputEncoding)) throw new ApiError('BAD_REQUEST', '输出编码无效')
591
+ this.value.outputEncoding = patch.outputEncoding
592
+ }
545
593
  if (patch && typeof patch === 'object' && patch.execEnabled !== undefined) {
546
594
  if (typeof patch.execEnabled !== 'boolean') throw new ApiError('BAD_REQUEST', '远端命令执行设置无效')
547
595
  this.value.execEnabled = patch.execEnabled
@@ -566,6 +614,21 @@ class SettingsStore {
566
614
  }
567
615
  this.value.execShell = patch.execShell
568
616
  }
617
+ if (patch && typeof patch === 'object' && patch.autoPushEnabled !== undefined) {
618
+ if (typeof patch.autoPushEnabled !== 'boolean') throw new ApiError('BAD_REQUEST', '自动推送设置无效')
619
+ this.value.autoPushEnabled = patch.autoPushEnabled
620
+ }
621
+ if (patch && typeof patch === 'object' && patch.autoPushDebounceMs !== undefined) {
622
+ this.value.autoPushDebounceMs = clampInt(patch.autoPushDebounceMs, AUTO_PUSH_DEBOUNCE_MIN, AUTO_PUSH_DEBOUNCE_MAX, SETTINGS_DEFAULTS.autoPushDebounceMs)
623
+ }
624
+ if (patch && typeof patch === 'object' && patch.autoPushInclude !== undefined) {
625
+ if (!Array.isArray(patch.autoPushInclude)) throw new ApiError('BAD_REQUEST', '自动推送包含列表必须是字符串数组')
626
+ this.value.autoPushInclude = normalizeStringList(patch.autoPushInclude)
627
+ }
628
+ if (patch && typeof patch === 'object' && patch.autoPushExclude !== undefined) {
629
+ if (!Array.isArray(patch.autoPushExclude)) throw new ApiError('BAD_REQUEST', '自动推送排除列表必须是字符串数组')
630
+ this.value.autoPushExclude = normalizeStringList(patch.autoPushExclude)
631
+ }
569
632
  writeJsonAtomic(this.file, { version: SETTINGS_VERSION, settings: { ...this.value, themeExplicit: this.themeExplicit === true } })
570
633
  return this.get()
571
634
  }
@@ -866,11 +929,14 @@ function linkedManifestFor(record) {
866
929
  // ── connection pool ─────────────────────────────────────────────────────────
867
930
 
868
931
  class HostPool {
869
- constructor({ knownHostsFile, credentialFile }) {
932
+ constructor({ knownHostsFile, credentialFile, hostKeyPolicy }) {
870
933
  this.knownHostsFile = knownHostsFile
871
934
  // Secrets the user stored from the add-workspace dialog. Kept apart from the
872
935
  // SSH Manager so the plugin works without `dsh-ssh-tunnel`.
873
936
  this.credentialFile = credentialFile || null
937
+ // Function or literal, forwarded to every RemoteHost so the trust policy is
938
+ // decided at connect time rather than at plugin load.
939
+ this.hostKeyPolicy = hostKeyPolicy || 'tofu'
874
940
  this.records = new Map() // hostId -> HostRecord
875
941
  this.connections = new Map() // hostId -> { authority, remote: RemoteHost }
876
942
  this.connecting = new Map() // hostId -> { authority, promise }
@@ -965,6 +1031,7 @@ class HostPool {
965
1031
  host: hostRecord,
966
1032
  knownHostsFile: this.knownHostsFile,
967
1033
  credentialFile: this.credentialFile,
1034
+ hostKeyPolicy: this.hostKeyPolicy,
968
1035
  connectTimeoutMs: CONNECT_TIMEOUT_MS,
969
1036
  logger: log,
970
1037
  onLost: (info) => this.noteConnectionLost(hostRecord.id, remote, info && info.reason),
@@ -1030,6 +1097,8 @@ export function apply(ctx) {
1030
1097
  const pool = new HostPool({
1031
1098
  knownHostsFile: join(dir, 'known_hosts.json'),
1032
1099
  credentialFile: join(dir, 'ssh-credentials.json'),
1100
+ // Read on every connection: the user can switch the policy while running.
1101
+ hostKeyPolicy: () => settingsStore.get().hostKeyPolicy,
1033
1102
  })
1034
1103
 
1035
1104
  let hostsCache = null
@@ -1814,6 +1883,375 @@ export function apply(ctx) {
1814
1883
  job.updatedAt = Date.now()
1815
1884
  }
1816
1885
 
1886
+ // ── local → remote push (0.19.0) ────────────────────────────────────────
1887
+ //
1888
+ // The local directory is the place people edit, and it is also where tools
1889
+ // (formatters, codegen, notebooks) write. `linked.plan` compares the two
1890
+ // sides file by file against the hash recorded at the last successful push,
1891
+ // so "changed here, untouched there" can be pushed safely while a file that
1892
+ // moved on *both* sides is reported as a conflict instead of being clobbered.
1893
+ // The state file is the only new data structure: without a baseline a two
1894
+ // sided hash comparison cannot tell "I edited this" from "they edited this".
1895
+
1896
+ const PUSH_STATE_NAME = 'push-state.json'
1897
+ const PUSH_MAX_FILES = 2000
1898
+ const PUSH_FILES_CONFLICT = new Set(['skip', 'overwrite', 'newer'])
1899
+
1900
+ const pushStateFile = () => join(dir, PUSH_STATE_NAME)
1901
+
1902
+ const readPushState = () => {
1903
+ const raw = readJsonFile(pushStateFile(), { version: 1, byWorkspace: {} })
1904
+ const byWorkspace = raw && typeof raw.byWorkspace === 'object' && raw.byWorkspace ? raw.byWorkspace : {}
1905
+ return { version: 1, byWorkspace }
1906
+ }
1907
+
1908
+ const writePushState = (state) => {
1909
+ writeJsonAtomic(pushStateFile(), state)
1910
+ }
1911
+
1912
+ const hashBytes = (buffer) => createHash('sha256').update(buffer).digest('hex')
1913
+
1914
+ /** Every regular file under the local directory, mirror/excludes skipped. */
1915
+ const walkLocalTree = async (record, limit = PUSH_MAX_FILES) => {
1916
+ const root = resolve(record.localPath)
1917
+ const files = []
1918
+ let truncated = false
1919
+ let skipped = 0
1920
+ const visit = async (current, prefix, depth) => {
1921
+ if (truncated) return
1922
+ if (depth > LINKED_SYNC_MAX_DEPTH) { skipped += 1; return }
1923
+ let entries
1924
+ try {
1925
+ entries = await readdir(current, { withFileTypes: true })
1926
+ } catch {
1927
+ skipped += 1
1928
+ return
1929
+ }
1930
+ for (const entry of entries) {
1931
+ if (files.length >= limit) { truncated = true; return }
1932
+ const name = entry.name
1933
+ if (entry.isDirectory()) {
1934
+ if (name === linkedFs.MIRROR_DIR || LINKED_SYNC_EXCLUDES.has(name) || name === '.remote') continue
1935
+ await visit(join(current, name), prefix === '' ? name : `${prefix}/${name}`, depth + 1)
1936
+ continue
1937
+ }
1938
+ if (!entry.isFile()) { skipped += 1; continue }
1939
+ let info
1940
+ try {
1941
+ info = await fsStat(join(current, name))
1942
+ } catch {
1943
+ skipped += 1
1944
+ continue
1945
+ }
1946
+ files.push({
1947
+ relative: prefix === '' ? name : `${prefix}/${name}`,
1948
+ absolute: join(current, name),
1949
+ size: info.size,
1950
+ mtimeMs: info.mtimeMs,
1951
+ })
1952
+ }
1953
+ }
1954
+ await visit(root, '', 0)
1955
+ return { files, truncated, skipped }
1956
+ }
1957
+
1958
+ const readLocalHash = async (file) => {
1959
+ if (file.size > LINKED_SYNC_FILE) return null
1960
+ try {
1961
+ return hashBytes(readFileSync(file.absolute))
1962
+ } catch {
1963
+ return null
1964
+ }
1965
+ }
1966
+
1967
+ const readRemoteHash = async (remote, remotePath, size) => {
1968
+ if (size > LINKED_SYNC_FILE) return null
1969
+ try {
1970
+ const read = await withTimeout(remote.readFile(remotePath, { maxBytes: LINKED_SYNC_FILE }), LINKED_SYNC_TIMEOUT_MS, 'push plan')
1971
+ return hashBytes(read.data)
1972
+ } catch {
1973
+ return null
1974
+ }
1975
+ }
1976
+
1977
+ /**
1978
+ * Classify every local file against the remote side and the last push:
1979
+ * added — remote has no such file (or it changed and the baseline agrees),
1980
+ * changed — both sides differ from the baseline but remote is untouched,
1981
+ * conflict— remote moved away from the baseline too,
1982
+ * removed — the baseline knows a file that is gone locally (never pushed).
1983
+ */
1984
+ const buildPlan = async (record, remote, options = {}) => {
1985
+ const limit = clampInt(options.maxFiles, 1, 5000, PUSH_MAX_FILES)
1986
+ const walk = await walkLocalTree(record, limit)
1987
+ const state = readPushState()
1988
+ const baseline = state.byWorkspace[record.id] && typeof state.byWorkspace[record.id] === 'object'
1989
+ ? state.byWorkspace[record.id]
1990
+ : {}
1991
+ const buckets = { added: [], changed: [], conflict: [], removed: [] }
1992
+ let unchanged = 0
1993
+ let skipped = walk.skipped
1994
+ for (const file of walk.files) {
1995
+ const localHash = await readLocalHash(file)
1996
+ if (localHash === null) { skipped += 1; continue }
1997
+ const remotePath = posix.join(record.remotePath, file.relative)
1998
+ const known = baseline[file.relative]
1999
+ let remoteStat = null
2000
+ try {
2001
+ remoteStat = await remote.stat(remotePath)
2002
+ } catch {
2003
+ remoteStat = null
2004
+ }
2005
+ if (!remoteStat || remoteStat.type !== 'file') {
2006
+ buckets.added.push({ relative: file.relative, size: file.size, localHash, remoteHash: null })
2007
+ continue
2008
+ }
2009
+ const remoteHash = await readRemoteHash(remote, remotePath, remoteStat.size)
2010
+ if (remoteHash !== null && remoteHash === localHash) {
2011
+ unchanged += 1
2012
+ continue
2013
+ }
2014
+ const baselineHash = known && typeof known.hash === 'string' ? known.hash : ''
2015
+ const entry = { relative: file.relative, size: file.size, localHash, remoteHash }
2016
+ if (baselineHash === '' || baselineHash === remoteHash) buckets.changed.push(entry)
2017
+ else buckets.conflict.push(entry)
2018
+ }
2019
+ for (const relative of Object.keys(baseline)) {
2020
+ if (walk.files.some((file) => file.relative === relative)) continue
2021
+ buckets.removed.push({ relative })
2022
+ }
2023
+ return {
2024
+ linkedId: record.id,
2025
+ localPath: record.localPath,
2026
+ remotePath: record.remotePath,
2027
+ maxFiles: limit,
2028
+ truncated: walk.truncated,
2029
+ skipped,
2030
+ unchanged,
2031
+ added: buckets.added,
2032
+ changed: buckets.changed,
2033
+ conflict: buckets.conflict,
2034
+ removed: buckets.removed,
2035
+ pending: buckets.added.length + buckets.changed.length,
2036
+ }
2037
+ }
2038
+
2039
+ const pushOneFile = async (record, remote, file, baseline) => {
2040
+ const data = readFileSync(file.absolute)
2041
+ const target = posix.join(record.remotePath, file.relative)
2042
+ await remote.mkdirp(posix.dirname(target))
2043
+ await withTimeout(remote.writeFileAtomic(target, data), LINKED_SYNC_TIMEOUT_MS, `push ${file.relative}`)
2044
+ baseline[file.relative] = { hash: hashBytes(data), size: data.length, pushedAt: Date.now() }
2045
+ return data.length
2046
+ }
2047
+
2048
+ const applyPlan = async (record, remote, plan, options = {}, job = null) => {
2049
+ const mode = PUSH_FILES_CONFLICT.has(options.conflict) ? options.conflict : 'skip'
2050
+ const only = Array.isArray(options.paths) && options.paths.length > 0
2051
+ ? new Set(options.paths.map((item) => String(item).replace(/^\/+/, '')))
2052
+ : null
2053
+ const state = readPushState()
2054
+ const baseline = state.byWorkspace[record.id] && typeof state.byWorkspace[record.id] === 'object'
2055
+ ? state.byWorkspace[record.id]
2056
+ : {}
2057
+ const queue = [...plan.added, ...plan.changed].filter((item) => !only || only.has(item.relative))
2058
+ const conflicted = plan.conflict.filter((item) => !only || only.has(item.relative))
2059
+ const pushed = []
2060
+ let bytes = 0
2061
+ let skipped = 0
2062
+ const dryRun = options.dryRun === true
2063
+ for (const item of queue) {
2064
+ if (job && job.cancelled) break
2065
+ if (dryRun) {
2066
+ pushed.push({ relative: item.relative, size: item.size, dryRun: true })
2067
+ continue
2068
+ }
2069
+ try {
2070
+ const written = await pushOneFile(record, remote, {
2071
+ relative: item.relative,
2072
+ absolute: join(record.localPath, item.relative),
2073
+ }, baseline)
2074
+ bytes += written
2075
+ pushed.push({ relative: item.relative, size: written })
2076
+ countTransferred(job, written)
2077
+ } catch (error) {
2078
+ skipped += 1
2079
+ pushed.push({ relative: item.relative, error: error && error.message ? error.message : String(error) })
2080
+ }
2081
+ }
2082
+ let resolvedConflicts = 0
2083
+ if (mode !== 'skip' && !dryRun) {
2084
+ for (const item of conflicted) {
2085
+ if (job && job.cancelled) break
2086
+ const remoteStat = await remote.stat(posix.join(record.remotePath, item.relative)).catch(() => null)
2087
+ const takeLocal = mode === 'overwrite'
2088
+ || (mode === 'newer' && (!remoteStat || Date.now() >= remoteStat.mtime))
2089
+ if (!takeLocal) { skipped += 1; continue }
2090
+ try {
2091
+ const written = await pushOneFile(record, remote, {
2092
+ relative: item.relative,
2093
+ absolute: join(record.localPath, item.relative),
2094
+ }, baseline)
2095
+ bytes += written
2096
+ resolvedConflicts += 1
2097
+ pushed.push({ relative: item.relative, size: written, resolved: 'conflict' })
2098
+ countTransferred(job, written)
2099
+ } catch (error) {
2100
+ skipped += 1
2101
+ pushed.push({ relative: item.relative, error: error && error.message ? error.message : String(error) })
2102
+ }
2103
+ }
2104
+ }
2105
+ if (!dryRun && pushed.some((item) => !item.error)) {
2106
+ state.byWorkspace[record.id] = baseline
2107
+ writePushState(state)
2108
+ appendTransferHistory({
2109
+ kind: 'push',
2110
+ linkedId: record.id,
2111
+ localPath: record.localPath,
2112
+ remotePath: record.remotePath,
2113
+ files: pushed.filter((item) => !item.error).length,
2114
+ bytes,
2115
+ skipped,
2116
+ at: Date.now(),
2117
+ })
2118
+ }
2119
+ return {
2120
+ linkedId: record.id,
2121
+ dryRun,
2122
+ conflict: mode,
2123
+ files: pushed,
2124
+ pushed: pushed.filter((item) => !item.error).length,
2125
+ skipped,
2126
+ conflictsLeft: conflicted.length - resolvedConflicts,
2127
+ bytes,
2128
+ cancelled: Boolean(job && job.cancelled),
2129
+ }
2130
+ }
2131
+
2132
+ // ── transfer history ────────────────────────────────────────────────────
2133
+ //
2134
+ // The queue dialog forgets everything when it closes, so the last few
2135
+ // transfers are persisted: it is the only place to answer "did that upload
2136
+ // actually finish?" after the fact.
2137
+
2138
+ const HISTORY_NAME = 'transfer-history.json'
2139
+ const HISTORY_LIMIT = 50
2140
+
2141
+ const appendTransferHistory = (entry) => {
2142
+ try {
2143
+ const raw = readJsonFile(join(dir, HISTORY_NAME), { version: 1, entries: [] })
2144
+ const entries = Array.isArray(raw && raw.entries) ? raw.entries.slice() : []
2145
+ entries.unshift(entry)
2146
+ writeJsonAtomic(join(dir, HISTORY_NAME), { version: 1, entries: entries.slice(0, HISTORY_LIMIT) })
2147
+ } catch (error) {
2148
+ console.error('[dsh-linked-workspace] transfer history write failed:', error && error.message ? error.message : error)
2149
+ }
2150
+ }
2151
+
2152
+ // ── autoPush ────────────────────────────────────────────────────────────
2153
+ //
2154
+ // Opt-in watcher on the local directory: after a quiet period the changed
2155
+ // files are pushed with `conflict: 'skip'`, so a file that moved on the
2156
+ // remote side is never overwritten by a formatter saving on this side.
2157
+ // `include`/`exclude` are simple globs (`*` only) matched against the
2158
+ // workspace-relative path.
2159
+
2160
+ const AUTO_PUSH_RETRY_MS = 2000
2161
+ const autoPushWatchers = new Map()
2162
+
2163
+ const globToRegExp = (pattern) => {
2164
+ const escaped = String(pattern).replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.')
2165
+ return new RegExp(`^${escaped}$`, 'i')
2166
+ }
2167
+
2168
+ const autoPushMatches = (patterns, relative) => {
2169
+ if (!Array.isArray(patterns) || patterns.length === 0) return null
2170
+ for (const pattern of patterns) {
2171
+ if (typeof pattern === 'string' && globToRegExp(pattern).test(relative)) return true
2172
+ }
2173
+ return false
2174
+ }
2175
+
2176
+ const autoPushFilter = (settings, plan) => {
2177
+ const include = autoPushMatches(settings.autoPushInclude, '')
2178
+ const keep = (item) => {
2179
+ const included = autoPushMatches(settings.autoPushInclude, item.relative)
2180
+ if (included === false) return false
2181
+ const excluded = autoPushMatches(settings.autoPushExclude, item.relative)
2182
+ if (excluded === true) return false
2183
+ return true
2184
+ }
2185
+ void include
2186
+ return { ...plan, added: plan.added.filter(keep), changed: plan.changed.filter(keep) }
2187
+ }
2188
+
2189
+ const stopAutoPush = (id) => {
2190
+ const entry = autoPushWatchers.get(id)
2191
+ if (!entry) return
2192
+ if (entry.timer) clearTimeout(entry.timer)
2193
+ try { entry.watcher.close() } catch { /* already closed */ }
2194
+ autoPushWatchers.delete(id)
2195
+ }
2196
+
2197
+ const runAutoPush = async (record, entry) => {
2198
+ if (entry.running) return
2199
+ entry.running = true
2200
+ try {
2201
+ const settings = settingsStore.get()
2202
+ if (!settings.autoPushEnabled) return
2203
+ const host = await findHost(record.hostId)
2204
+ const remote = await connectHost(host)
2205
+ const plan = autoPushFilter(settings, await buildPlan(record, remote, {}))
2206
+ if (plan.added.length === 0 && plan.changed.length === 0) return
2207
+ const result = await applyPlan(record, remote, plan, { conflict: 'skip' })
2208
+ forgetListings()
2209
+ log('info', `autoPush ${record.name}: ${result.pushed} file(s), ${result.skipped} skipped`)
2210
+ } catch (error) {
2211
+ log('warn', `autoPush ${record.name} failed: ${error && error.message ? error.message : error}`)
2212
+ entry.timer = setTimeout(() => { entry.timer = null; void runAutoPush(record, entry) }, AUTO_PUSH_RETRY_MS)
2213
+ } finally {
2214
+ entry.running = false
2215
+ }
2216
+ }
2217
+
2218
+ const scheduleAutoPush = (record, entry) => {
2219
+ if (entry.timer) clearTimeout(entry.timer)
2220
+ const settings = settingsStore.get()
2221
+ const delay = clampInt(settings.autoPushDebounceMs, AUTO_PUSH_DEBOUNCE_MIN, AUTO_PUSH_DEBOUNCE_MAX, 1500)
2222
+ entry.timer = setTimeout(() => {
2223
+ entry.timer = null
2224
+ void runAutoPush(record, entry)
2225
+ }, delay)
2226
+ if (entry.timer && typeof entry.timer.unref === 'function') entry.timer.unref()
2227
+ }
2228
+
2229
+ /** Start/stop watchers so they match the current settings; safe to call often. */
2230
+ const syncAutoPush = () => {
2231
+ const settings = settingsStore.get()
2232
+ const wanted = settings.autoPushEnabled === true
2233
+ for (const id of [...autoPushWatchers.keys()]) {
2234
+ const record = linkedStore.get(id)
2235
+ if (!wanted || !record) stopAutoPush(id)
2236
+ }
2237
+ if (!wanted) return
2238
+ for (const record of linkedStore.list()) {
2239
+ if (autoPushWatchers.has(record.id)) continue
2240
+ let watcher
2241
+ try {
2242
+ watcher = watch(record.localPath, { recursive: true, persistent: false }, () => {
2243
+ const entry = autoPushWatchers.get(record.id)
2244
+ if (entry) scheduleAutoPush(record, entry)
2245
+ })
2246
+ } catch (error) {
2247
+ log('warn', `autoPush watcher for ${record.name} failed: ${error && error.message ? error.message : error}`)
2248
+ continue
2249
+ }
2250
+ watcher.on('error', () => stopAutoPush(record.id))
2251
+ autoPushWatchers.set(record.id, { watcher, timer: null, running: false })
2252
+ }
2253
+ }
2254
+
1817
2255
  // A content search can run for seconds; the client can stop it by job id the
1818
2256
  // same way it stops a transfer. The flag is checked between files.
1819
2257
  const GREP_JOB_TTL_MS = 60 * 1000
@@ -2619,6 +3057,64 @@ export function apply(ctx) {
2619
3057
 
2620
3058
  // Free space on the volume that holds a remote path (F2). `df -Pk` is the
2621
3059
  // portable form: one line of numbers in 1K blocks.
3060
+ /**
3061
+ * Every remembered host key, so a changed one can be forgotten in the UI
3062
+ * instead of hand-editing `known_hosts.json` (0.20.0).
3063
+ */
3064
+ async 'hosts.hostKeys'() {
3065
+ const entries = await listKnownHosts(join(dir, 'known_hosts.json'))
3066
+ let hosts = []
3067
+ try {
3068
+ hosts = await refreshHosts()
3069
+ } catch {
3070
+ hosts = []
3071
+ }
3072
+ const byAuthority = new Map()
3073
+ for (const host of hosts) {
3074
+ const authority = `${host.host}:${host.port === 22 ? 22 : host.port}`
3075
+ byAuthority.set(authority, { hostId: host.id, hostName: host.name || host.host })
3076
+ }
3077
+ return {
3078
+ entries: entries.map((entry) => {
3079
+ const owner = byAuthority.get(entry.authority) || {}
3080
+ return {
3081
+ authority: entry.authority,
3082
+ fingerprint: entry.fingerprint,
3083
+ firstSeen: entry.firstSeen,
3084
+ hostId: owner.hostId || '',
3085
+ hostName: owner.hostName || '',
3086
+ }
3087
+ }),
3088
+ }
3089
+ },
3090
+
3091
+ /**
3092
+ * Drop the remembered host key for one host. The next connection goes back
3093
+ * to a first-use decision (or a refusal while the policy is `strict`).
3094
+ */
3095
+ async 'hosts.forgetHostKey'(params = {}) {
3096
+ const requestedAuthority = typeof params.authority === 'string' && params.authority.trim() !== ''
3097
+ ? params.authority.trim()
3098
+ : '';
3099
+ let host = null;
3100
+ if (typeof params.hostId === 'string' && params.hostId.trim() !== '') {
3101
+ host = await findHost(params.hostId.trim());
3102
+ } else if (!requestedAuthority) {
3103
+ throw new ApiError('BAD_REQUEST', 'hostId 或 authority 必须提供一个');
3104
+ }
3105
+ const authority = requestedAuthority || `${host.host}:${host.port}`;
3106
+ if (host) {
3107
+ const connection = pool.connections.get(host.id);
3108
+ if (connection) {
3109
+ pool.connections.delete(host.id);
3110
+ await connection.remote.dispose().catch(() => {});
3111
+ }
3112
+ }
3113
+ const removed = await forgetKnownHost(join(dir, 'known_hosts.json'), authority);
3114
+ if (removed) log('info', `forgot the host key for ${authority}`);
3115
+ return { authority, removed };
3116
+ },
3117
+
2622
3118
  async 'hosts.df'(params = {}) {
2623
3119
  const host = await findHost(params.hostId)
2624
3120
  const remote = await connectHost(host)
@@ -2718,7 +3214,7 @@ export function apply(ctx) {
2718
3214
  let result
2719
3215
  try {
2720
3216
  const remote = scope ? scope.remote : await connectHost(host)
2721
- result = await remote.exec(wrapped, { timeoutMs })
3217
+ result = await remote.exec(wrapped, { timeoutMs, encoding: settings.outputEncoding })
2722
3218
  } catch (error) {
2723
3219
  const durationMs = Date.now() - started
2724
3220
  const timedOut = error && error.code === 'TIMEOUT'
@@ -3114,17 +3610,60 @@ export function apply(ctx) {
3114
3610
  const scope = await requireScope(params)
3115
3611
  if (scope.kind !== 'linked') throw new ApiError('BAD_REQUEST', '只有联动工作区支持文件传输')
3116
3612
  const job = beginTransferJob(params.jobId)
3613
+ // 0.19.0: a batch carries several paths, so a multi-selection no longer
3614
+ // turns into N round trips that each rebuild the queue entry.
3615
+ const batch = Array.isArray(params.paths) && params.paths.length > 0
3616
+ ? params.paths.filter((item) => typeof item === 'string' && item.trim() !== '')
3617
+ : null
3117
3618
  try {
3118
3619
  if (params.side === 'local') {
3119
- const result = await transferLocalToRemote(scope.record, scope.remote, params.path, job)
3620
+ const list = batch || [params.path]
3621
+ const total = { side: 'local', files: 0, bytes: 0, skipped: 0, truncated: false, targets: [] }
3622
+ for (const item of list) {
3623
+ const result = await transferLocalToRemote(scope.record, scope.remote, item, job)
3624
+ total.files += result.files
3625
+ total.bytes += result.bytes
3626
+ total.skipped += result.skipped
3627
+ total.truncated = total.truncated || result.truncated
3628
+ total.targets.push(result.target)
3629
+ }
3120
3630
  forgetListings()
3121
3631
  finishTransferJob(job, 'done')
3122
- return result
3632
+ appendTransferHistory({
3633
+ kind: 'transfer',
3634
+ direction: 'local-to-remote',
3635
+ linkedId: scope.record.id,
3636
+ files: total.files,
3637
+ bytes: total.bytes,
3638
+ skipped: total.skipped,
3639
+ truncated: total.truncated,
3640
+ at: Date.now(),
3641
+ })
3642
+ return total
3643
+ }
3644
+ const list = batch || [params.path]
3645
+ const total = { side: 'remote', files: 0, bytes: 0, skipped: 0, truncated: false, targets: [] }
3646
+ for (const item of list) {
3647
+ const target = scopeTarget(scope, item)
3648
+ const result = await transferToMirror(scope.record, scope.remote, target, job)
3649
+ total.files += result.files
3650
+ total.bytes += result.bytes
3651
+ total.skipped += result.skipped
3652
+ total.truncated = total.truncated || result.truncated
3653
+ total.targets.push(result.dest)
3123
3654
  }
3124
- const target = scopeTarget(scope, params.path)
3125
- const result = await transferToMirror(scope.record, scope.remote, target, job)
3126
3655
  finishTransferJob(job, 'done')
3127
- return result
3656
+ appendTransferHistory({
3657
+ kind: 'transfer',
3658
+ direction: 'remote-to-mirror',
3659
+ linkedId: scope.record.id,
3660
+ files: total.files,
3661
+ bytes: total.bytes,
3662
+ skipped: total.skipped,
3663
+ truncated: total.truncated,
3664
+ at: Date.now(),
3665
+ })
3666
+ return total
3128
3667
  } catch (error) {
3129
3668
  finishTransferJob(job, error && error.code === 'CANCELLED' ? 'cancelled' : 'failed', error && error.message ? error.message : '')
3130
3669
  throw error
@@ -3237,7 +3776,11 @@ export function apply(ctx) {
3237
3776
  },
3238
3777
 
3239
3778
  async 'settings.update'(params = {}) {
3240
- return settingsStore.update(params)
3779
+ const next = settingsStore.update(params)
3780
+ // Toggling autoPush (or editing its filters) has to start/stop watchers
3781
+ // without a restart; the call is cheap and idempotent.
3782
+ syncAutoPush()
3783
+ return next
3241
3784
  },
3242
3785
 
3243
3786
  // ── local directories (workspace pickers) ──────────────────────────────
@@ -4156,6 +4699,49 @@ export function apply(ctx) {
4156
4699
  return { cancelled: true }
4157
4700
  },
4158
4701
 
4702
+ /** What the local directory has that the remote side does not (and vice versa). */
4703
+ async 'linked.plan'(params = {}) {
4704
+ const record = requireLinked(params.id)
4705
+ const host = await findHost(record.hostId)
4706
+ const remote = await connectHost(host)
4707
+ return await buildPlan(record, remote, params)
4708
+ },
4709
+
4710
+ /** Write local files back to the remote directory, atomically per file. */
4711
+ async 'linked.push'(params = {}) {
4712
+ const record = requireLinked(params.id)
4713
+ const host = await findHost(record.hostId)
4714
+ const remote = await connectHost(host)
4715
+ const job = beginTransferJob(params.jobId)
4716
+ try {
4717
+ const plan = await buildPlan(record, remote, params)
4718
+ const result = await applyPlan(record, remote, plan, params, job)
4719
+ forgetListings()
4720
+ finishTransferJob(job, result.cancelled ? 'cancelled' : 'done')
4721
+ return result
4722
+ } catch (error) {
4723
+ finishTransferJob(job, error && error.code === 'CANCELLED' ? 'cancelled' : 'failed', error && error.message ? error.message : '')
4724
+ throw error
4725
+ }
4726
+ },
4727
+
4728
+ /** Ask a running push to stop after the file it is writing. */
4729
+ async 'linked.pushCancel'(params = {}) {
4730
+ const id = typeof params.jobId === 'string' ? params.jobId : ''
4731
+ const job = transferJobs.get(id)
4732
+ if (!job) return { cancelled: false }
4733
+ job.cancelled = true
4734
+ job.updatedAt = Date.now()
4735
+ return { cancelled: true }
4736
+ },
4737
+
4738
+ /** The last few transfers and pushes, newest first. */
4739
+ async 'transfer.history'() {
4740
+ const raw = readJsonFile(join(dir, HISTORY_NAME), { version: 1, entries: [] })
4741
+ const entries = Array.isArray(raw && raw.entries) ? raw.entries : []
4742
+ return { entries: entries.slice(0, HISTORY_LIMIT) }
4743
+ },
4744
+
4159
4745
  // ── remote_workspaces methods ───────────────────────────────────────────────
4160
4746
 
4161
4747
  async 'remote_workspaces.list'() {
@@ -4843,6 +5429,17 @@ export function apply(ctx) {
4843
5429
  })
4844
5430
  }, 900)
4845
5431
  if (titleMigrationTimer && typeof titleMigrationTimer.unref === 'function') titleMigrationTimer.unref()
5432
+
5433
+ // autoPush may already be enabled from a previous run: start its watchers and
5434
+ // make sure they are closed when this plugin instance goes away.
5435
+ try {
5436
+ syncAutoPush()
5437
+ } catch (error) {
5438
+ log('warn', `autoPush start failed: ${error && error.message ? error.message : error}`)
5439
+ }
5440
+ ctx.effect(() => () => {
5441
+ for (const id of [...autoPushWatchers.keys()]) stopAutoPush(id)
5442
+ }, 'dsh-linked-workspace: auto push watchers')
4846
5443
  }
4847
5444
 
4848
5445
  // ── response helpers ────────────────────────────────────────────────────────