dsh-linked-workspace 0.17.0 → 0.19.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,8 +15,8 @@
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'
@@ -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 = 3
41
+ const API_REVISION = 5
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,9 @@ 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 })
59
+ const AUTO_PUSH_DEBOUNCE_MIN = 300
60
+ const AUTO_PUSH_DEBOUNCE_MAX = 60000
59
61
  /** Exec allow-lists travel as arrays, so they are not part of the frozen defaults. */
60
62
  const EMPTY_ID_LIST = Object.freeze([])
61
63
  const EDITOR_THEME_FAMILIES = new Set(['github', 'solarized', 'one', 'dracula', 'monokai', 'nord', 'vscode', 'xcode', 'catppuccin'])
@@ -94,8 +96,7 @@ const PEEK_LIMIT = 512 * 1024
94
96
  const READ_CAP = 8 * 1024 * 1024
95
97
  const MAX_WRITE_BYTES = 8 * 1024 * 1024
96
98
  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. */
99
+ // ── remote command execution (0.17.0) ───────────────────────────────────────/** Longest command line accepted; anything longer is almost always a paste error. */
99
100
  const EXEC_MAX_COMMAND = 8000
100
101
  const EXEC_TIMEOUT_DEFAULT = 60_000
101
102
  const EXEC_TIMEOUT_MAX = 600_000
@@ -449,10 +450,26 @@ function clampInt(value, min, max, fallback) {
449
450
  return Math.min(max, Math.max(min, Math.round(number)))
450
451
  }
451
452
 
453
+ /** Same idea as normalizeIdList, for the auto-push include/exclude patterns. */
454
+ function normalizeStringList(value) {
455
+ if (!Array.isArray(value)) return []
456
+ const seen = new Set()
457
+ const out = []
458
+ for (const item of value) {
459
+ if (typeof item !== 'string') continue
460
+ const pattern = item.trim()
461
+ if (pattern === '' || seen.has(pattern)) continue
462
+ seen.add(pattern)
463
+ out.push(pattern)
464
+ if (out.length >= 100) break
465
+ }
466
+ return out
467
+ }
468
+
452
469
  class SettingsStore {
453
470
  constructor(file) {
454
471
  this.file = file
455
- this.value = { ...SETTINGS_DEFAULTS, execHostIds: [], execWorkspaceIds: [] }
472
+ this.value = { ...SETTINGS_DEFAULTS, execHostIds: [], execWorkspaceIds: [], autoPushInclude: [], autoPushExclude: [] }
456
473
  const raw = readJsonFile(file, { version: SETTINGS_VERSION, settings: {} })
457
474
  const settings = raw && typeof raw === 'object' && raw.settings && typeof raw.settings === 'object'
458
475
  ? raw.settings
@@ -482,6 +499,16 @@ class SettingsStore {
482
499
  if (settings && typeof settings === 'object' && typeof settings.autoSave === 'boolean') {
483
500
  this.value.autoSave = settings.autoSave
484
501
  }
502
+ if (settings && typeof settings === 'object' && typeof settings.autoPushEnabled === 'boolean') {
503
+ this.value.autoPushEnabled = settings.autoPushEnabled
504
+ }
505
+ if (settings && typeof settings === 'object') {
506
+ if (settings.autoPushDebounceMs !== undefined) {
507
+ this.value.autoPushDebounceMs = clampInt(settings.autoPushDebounceMs, AUTO_PUSH_DEBOUNCE_MIN, AUTO_PUSH_DEBOUNCE_MAX, SETTINGS_DEFAULTS.autoPushDebounceMs)
508
+ }
509
+ this.value.autoPushInclude = normalizeStringList(settings.autoPushInclude)
510
+ this.value.autoPushExclude = normalizeStringList(settings.autoPushExclude)
511
+ }
485
512
  if (settings && typeof settings === 'object' && settings.themeExplicit === true) {
486
513
  this.themeExplicit = true
487
514
  }
@@ -514,6 +541,8 @@ class SettingsStore {
514
541
  ...this.value,
515
542
  execHostIds: this.value.execHostIds ? this.value.execHostIds.slice() : [],
516
543
  execWorkspaceIds: this.value.execWorkspaceIds ? this.value.execWorkspaceIds.slice() : [],
544
+ autoPushInclude: this.value.autoPushInclude ? this.value.autoPushInclude.slice() : [],
545
+ autoPushExclude: this.value.autoPushExclude ? this.value.autoPushExclude.slice() : [],
517
546
  }
518
547
  }
519
548
 
@@ -566,6 +595,21 @@ class SettingsStore {
566
595
  }
567
596
  this.value.execShell = patch.execShell
568
597
  }
598
+ if (patch && typeof patch === 'object' && patch.autoPushEnabled !== undefined) {
599
+ if (typeof patch.autoPushEnabled !== 'boolean') throw new ApiError('BAD_REQUEST', '自动推送设置无效')
600
+ this.value.autoPushEnabled = patch.autoPushEnabled
601
+ }
602
+ if (patch && typeof patch === 'object' && patch.autoPushDebounceMs !== undefined) {
603
+ this.value.autoPushDebounceMs = clampInt(patch.autoPushDebounceMs, AUTO_PUSH_DEBOUNCE_MIN, AUTO_PUSH_DEBOUNCE_MAX, SETTINGS_DEFAULTS.autoPushDebounceMs)
604
+ }
605
+ if (patch && typeof patch === 'object' && patch.autoPushInclude !== undefined) {
606
+ if (!Array.isArray(patch.autoPushInclude)) throw new ApiError('BAD_REQUEST', '自动推送包含列表必须是字符串数组')
607
+ this.value.autoPushInclude = normalizeStringList(patch.autoPushInclude)
608
+ }
609
+ if (patch && typeof patch === 'object' && patch.autoPushExclude !== undefined) {
610
+ if (!Array.isArray(patch.autoPushExclude)) throw new ApiError('BAD_REQUEST', '自动推送排除列表必须是字符串数组')
611
+ this.value.autoPushExclude = normalizeStringList(patch.autoPushExclude)
612
+ }
569
613
  writeJsonAtomic(this.file, { version: SETTINGS_VERSION, settings: { ...this.value, themeExplicit: this.themeExplicit === true } })
570
614
  return this.get()
571
615
  }
@@ -1536,6 +1580,7 @@ export function apply(ctx) {
1536
1580
  '- Writes are atomic. Pass `if_modified_since` (epoch milliseconds from a previous read/stat) to refuse a stale overwrite.',
1537
1581
  '- action "sync" archives the remote tree into `.remote/` and only exists for a linked workspace (a remote workspace has no local copy).',
1538
1582
  '- action "exec" runs ONE non-interactive command on the remote host (builds, tests, logs). It only works when the user switched remote execution on and allow-listed this host/workspace; every attempt is audited.',
1583
+ '- action "references" lists workspace paths matching a query (best match first, directories marked `dir`), which is how you resolve a remote path a user mentioned by name.',
1539
1584
  'The workspace is resolved from the session working directory; pass `workspace` (id, local path, placeholder path or name) when working elsewhere.',
1540
1585
  'For a REMOTE workspace do not create project files in the placeholder and do not expect local paths to exist: read, write, build and inspect logs on the remote host, through linked_workspace actions or `ssh` when an action does not fit. Prefer action "exec" over `ssh` when it is enabled: it keeps the audit trail and the output limits.',
1541
1586
  'Locally installed skills (~/.dsh/skills, ~/.agents/skills) remain available; use `linked_skills` to list or read them. A linked workspace also sees the project skills of its local directory.',
@@ -1813,6 +1858,391 @@ export function apply(ctx) {
1813
1858
  job.updatedAt = Date.now()
1814
1859
  }
1815
1860
 
1861
+ // ── local → remote push (0.19.0) ────────────────────────────────────────
1862
+ //
1863
+ // The local directory is the place people edit, and it is also where tools
1864
+ // (formatters, codegen, notebooks) write. `linked.plan` compares the two
1865
+ // sides file by file against the hash recorded at the last successful push,
1866
+ // so "changed here, untouched there" can be pushed safely while a file that
1867
+ // moved on *both* sides is reported as a conflict instead of being clobbered.
1868
+ // The state file is the only new data structure: without a baseline a two
1869
+ // sided hash comparison cannot tell "I edited this" from "they edited this".
1870
+
1871
+ const PUSH_STATE_NAME = 'push-state.json'
1872
+ const PUSH_MAX_FILES = 2000
1873
+ const PUSH_FILES_CONFLICT = new Set(['skip', 'overwrite', 'newer'])
1874
+
1875
+ const pushStateFile = () => join(dir, PUSH_STATE_NAME)
1876
+
1877
+ const readPushState = () => {
1878
+ const raw = readJsonFile(pushStateFile(), { version: 1, byWorkspace: {} })
1879
+ const byWorkspace = raw && typeof raw.byWorkspace === 'object' && raw.byWorkspace ? raw.byWorkspace : {}
1880
+ return { version: 1, byWorkspace }
1881
+ }
1882
+
1883
+ const writePushState = (state) => {
1884
+ writeJsonAtomic(pushStateFile(), state)
1885
+ }
1886
+
1887
+ const hashBytes = (buffer) => createHash('sha256').update(buffer).digest('hex')
1888
+
1889
+ /** Every regular file under the local directory, mirror/excludes skipped. */
1890
+ const walkLocalTree = async (record, limit = PUSH_MAX_FILES) => {
1891
+ const root = resolve(record.localPath)
1892
+ const files = []
1893
+ let truncated = false
1894
+ let skipped = 0
1895
+ const visit = async (current, prefix, depth) => {
1896
+ if (truncated) return
1897
+ if (depth > LINKED_SYNC_MAX_DEPTH) { skipped += 1; return }
1898
+ let entries
1899
+ try {
1900
+ entries = await readdir(current, { withFileTypes: true })
1901
+ } catch {
1902
+ skipped += 1
1903
+ return
1904
+ }
1905
+ for (const entry of entries) {
1906
+ if (files.length >= limit) { truncated = true; return }
1907
+ const name = entry.name
1908
+ if (entry.isDirectory()) {
1909
+ if (name === linkedFs.MIRROR_DIR || LINKED_SYNC_EXCLUDES.has(name) || name === '.remote') continue
1910
+ await visit(join(current, name), prefix === '' ? name : `${prefix}/${name}`, depth + 1)
1911
+ continue
1912
+ }
1913
+ if (!entry.isFile()) { skipped += 1; continue }
1914
+ let info
1915
+ try {
1916
+ info = await fsStat(join(current, name))
1917
+ } catch {
1918
+ skipped += 1
1919
+ continue
1920
+ }
1921
+ files.push({
1922
+ relative: prefix === '' ? name : `${prefix}/${name}`,
1923
+ absolute: join(current, name),
1924
+ size: info.size,
1925
+ mtimeMs: info.mtimeMs,
1926
+ })
1927
+ }
1928
+ }
1929
+ await visit(root, '', 0)
1930
+ return { files, truncated, skipped }
1931
+ }
1932
+
1933
+ const readLocalHash = async (file) => {
1934
+ if (file.size > LINKED_SYNC_FILE) return null
1935
+ try {
1936
+ return hashBytes(readFileSync(file.absolute))
1937
+ } catch {
1938
+ return null
1939
+ }
1940
+ }
1941
+
1942
+ const readRemoteHash = async (remote, remotePath, size) => {
1943
+ if (size > LINKED_SYNC_FILE) return null
1944
+ try {
1945
+ const read = await withTimeout(remote.readFile(remotePath, { maxBytes: LINKED_SYNC_FILE }), LINKED_SYNC_TIMEOUT_MS, 'push plan')
1946
+ return hashBytes(read.data)
1947
+ } catch {
1948
+ return null
1949
+ }
1950
+ }
1951
+
1952
+ /**
1953
+ * Classify every local file against the remote side and the last push:
1954
+ * added — remote has no such file (or it changed and the baseline agrees),
1955
+ * changed — both sides differ from the baseline but remote is untouched,
1956
+ * conflict— remote moved away from the baseline too,
1957
+ * removed — the baseline knows a file that is gone locally (never pushed).
1958
+ */
1959
+ const buildPlan = async (record, remote, options = {}) => {
1960
+ const limit = clampInt(options.maxFiles, 1, 5000, PUSH_MAX_FILES)
1961
+ const walk = await walkLocalTree(record, limit)
1962
+ const state = readPushState()
1963
+ const baseline = state.byWorkspace[record.id] && typeof state.byWorkspace[record.id] === 'object'
1964
+ ? state.byWorkspace[record.id]
1965
+ : {}
1966
+ const buckets = { added: [], changed: [], conflict: [], removed: [] }
1967
+ let unchanged = 0
1968
+ let skipped = walk.skipped
1969
+ for (const file of walk.files) {
1970
+ const localHash = await readLocalHash(file)
1971
+ if (localHash === null) { skipped += 1; continue }
1972
+ const remotePath = posix.join(record.remotePath, file.relative)
1973
+ const known = baseline[file.relative]
1974
+ let remoteStat = null
1975
+ try {
1976
+ remoteStat = await remote.stat(remotePath)
1977
+ } catch {
1978
+ remoteStat = null
1979
+ }
1980
+ if (!remoteStat || remoteStat.type !== 'file') {
1981
+ buckets.added.push({ relative: file.relative, size: file.size, localHash, remoteHash: null })
1982
+ continue
1983
+ }
1984
+ const remoteHash = await readRemoteHash(remote, remotePath, remoteStat.size)
1985
+ if (remoteHash !== null && remoteHash === localHash) {
1986
+ unchanged += 1
1987
+ continue
1988
+ }
1989
+ const baselineHash = known && typeof known.hash === 'string' ? known.hash : ''
1990
+ const entry = { relative: file.relative, size: file.size, localHash, remoteHash }
1991
+ if (baselineHash === '' || baselineHash === remoteHash) buckets.changed.push(entry)
1992
+ else buckets.conflict.push(entry)
1993
+ }
1994
+ for (const relative of Object.keys(baseline)) {
1995
+ if (walk.files.some((file) => file.relative === relative)) continue
1996
+ buckets.removed.push({ relative })
1997
+ }
1998
+ return {
1999
+ linkedId: record.id,
2000
+ localPath: record.localPath,
2001
+ remotePath: record.remotePath,
2002
+ maxFiles: limit,
2003
+ truncated: walk.truncated,
2004
+ skipped,
2005
+ unchanged,
2006
+ added: buckets.added,
2007
+ changed: buckets.changed,
2008
+ conflict: buckets.conflict,
2009
+ removed: buckets.removed,
2010
+ pending: buckets.added.length + buckets.changed.length,
2011
+ }
2012
+ }
2013
+
2014
+ const pushOneFile = async (record, remote, file, baseline) => {
2015
+ const data = readFileSync(file.absolute)
2016
+ const target = posix.join(record.remotePath, file.relative)
2017
+ await remote.mkdirp(posix.dirname(target))
2018
+ await withTimeout(remote.writeFileAtomic(target, data), LINKED_SYNC_TIMEOUT_MS, `push ${file.relative}`)
2019
+ baseline[file.relative] = { hash: hashBytes(data), size: data.length, pushedAt: Date.now() }
2020
+ return data.length
2021
+ }
2022
+
2023
+ const applyPlan = async (record, remote, plan, options = {}, job = null) => {
2024
+ const mode = PUSH_FILES_CONFLICT.has(options.conflict) ? options.conflict : 'skip'
2025
+ const only = Array.isArray(options.paths) && options.paths.length > 0
2026
+ ? new Set(options.paths.map((item) => String(item).replace(/^\/+/, '')))
2027
+ : null
2028
+ const state = readPushState()
2029
+ const baseline = state.byWorkspace[record.id] && typeof state.byWorkspace[record.id] === 'object'
2030
+ ? state.byWorkspace[record.id]
2031
+ : {}
2032
+ const queue = [...plan.added, ...plan.changed].filter((item) => !only || only.has(item.relative))
2033
+ const conflicted = plan.conflict.filter((item) => !only || only.has(item.relative))
2034
+ const pushed = []
2035
+ let bytes = 0
2036
+ let skipped = 0
2037
+ const dryRun = options.dryRun === true
2038
+ for (const item of queue) {
2039
+ if (job && job.cancelled) break
2040
+ if (dryRun) {
2041
+ pushed.push({ relative: item.relative, size: item.size, dryRun: true })
2042
+ continue
2043
+ }
2044
+ try {
2045
+ const written = await pushOneFile(record, remote, {
2046
+ relative: item.relative,
2047
+ absolute: join(record.localPath, item.relative),
2048
+ }, baseline)
2049
+ bytes += written
2050
+ pushed.push({ relative: item.relative, size: written })
2051
+ countTransferred(job, written)
2052
+ } catch (error) {
2053
+ skipped += 1
2054
+ pushed.push({ relative: item.relative, error: error && error.message ? error.message : String(error) })
2055
+ }
2056
+ }
2057
+ let resolvedConflicts = 0
2058
+ if (mode !== 'skip' && !dryRun) {
2059
+ for (const item of conflicted) {
2060
+ if (job && job.cancelled) break
2061
+ const remoteStat = await remote.stat(posix.join(record.remotePath, item.relative)).catch(() => null)
2062
+ const takeLocal = mode === 'overwrite'
2063
+ || (mode === 'newer' && (!remoteStat || Date.now() >= remoteStat.mtime))
2064
+ if (!takeLocal) { skipped += 1; continue }
2065
+ try {
2066
+ const written = await pushOneFile(record, remote, {
2067
+ relative: item.relative,
2068
+ absolute: join(record.localPath, item.relative),
2069
+ }, baseline)
2070
+ bytes += written
2071
+ resolvedConflicts += 1
2072
+ pushed.push({ relative: item.relative, size: written, resolved: 'conflict' })
2073
+ countTransferred(job, written)
2074
+ } catch (error) {
2075
+ skipped += 1
2076
+ pushed.push({ relative: item.relative, error: error && error.message ? error.message : String(error) })
2077
+ }
2078
+ }
2079
+ }
2080
+ if (!dryRun && pushed.some((item) => !item.error)) {
2081
+ state.byWorkspace[record.id] = baseline
2082
+ writePushState(state)
2083
+ appendTransferHistory({
2084
+ kind: 'push',
2085
+ linkedId: record.id,
2086
+ localPath: record.localPath,
2087
+ remotePath: record.remotePath,
2088
+ files: pushed.filter((item) => !item.error).length,
2089
+ bytes,
2090
+ skipped,
2091
+ at: Date.now(),
2092
+ })
2093
+ }
2094
+ return {
2095
+ linkedId: record.id,
2096
+ dryRun,
2097
+ conflict: mode,
2098
+ files: pushed,
2099
+ pushed: pushed.filter((item) => !item.error).length,
2100
+ skipped,
2101
+ conflictsLeft: conflicted.length - resolvedConflicts,
2102
+ bytes,
2103
+ cancelled: Boolean(job && job.cancelled),
2104
+ }
2105
+ }
2106
+
2107
+ // ── transfer history ────────────────────────────────────────────────────
2108
+ //
2109
+ // The queue dialog forgets everything when it closes, so the last few
2110
+ // transfers are persisted: it is the only place to answer "did that upload
2111
+ // actually finish?" after the fact.
2112
+
2113
+ const HISTORY_NAME = 'transfer-history.json'
2114
+ const HISTORY_LIMIT = 50
2115
+
2116
+ const appendTransferHistory = (entry) => {
2117
+ try {
2118
+ const raw = readJsonFile(join(dir, HISTORY_NAME), { version: 1, entries: [] })
2119
+ const entries = Array.isArray(raw && raw.entries) ? raw.entries.slice() : []
2120
+ entries.unshift(entry)
2121
+ writeJsonAtomic(join(dir, HISTORY_NAME), { version: 1, entries: entries.slice(0, HISTORY_LIMIT) })
2122
+ } catch (error) {
2123
+ console.error('[dsh-linked-workspace] transfer history write failed:', error && error.message ? error.message : error)
2124
+ }
2125
+ }
2126
+
2127
+ // ── autoPush ────────────────────────────────────────────────────────────
2128
+ //
2129
+ // Opt-in watcher on the local directory: after a quiet period the changed
2130
+ // files are pushed with `conflict: 'skip'`, so a file that moved on the
2131
+ // remote side is never overwritten by a formatter saving on this side.
2132
+ // `include`/`exclude` are simple globs (`*` only) matched against the
2133
+ // workspace-relative path.
2134
+
2135
+ const AUTO_PUSH_RETRY_MS = 2000
2136
+ const autoPushWatchers = new Map()
2137
+
2138
+ const globToRegExp = (pattern) => {
2139
+ const escaped = String(pattern).replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.')
2140
+ return new RegExp(`^${escaped}$`, 'i')
2141
+ }
2142
+
2143
+ const autoPushMatches = (patterns, relative) => {
2144
+ if (!Array.isArray(patterns) || patterns.length === 0) return null
2145
+ for (const pattern of patterns) {
2146
+ if (typeof pattern === 'string' && globToRegExp(pattern).test(relative)) return true
2147
+ }
2148
+ return false
2149
+ }
2150
+
2151
+ const autoPushFilter = (settings, plan) => {
2152
+ const include = autoPushMatches(settings.autoPushInclude, '')
2153
+ const keep = (item) => {
2154
+ const included = autoPushMatches(settings.autoPushInclude, item.relative)
2155
+ if (included === false) return false
2156
+ const excluded = autoPushMatches(settings.autoPushExclude, item.relative)
2157
+ if (excluded === true) return false
2158
+ return true
2159
+ }
2160
+ void include
2161
+ return { ...plan, added: plan.added.filter(keep), changed: plan.changed.filter(keep) }
2162
+ }
2163
+
2164
+ const stopAutoPush = (id) => {
2165
+ const entry = autoPushWatchers.get(id)
2166
+ if (!entry) return
2167
+ if (entry.timer) clearTimeout(entry.timer)
2168
+ try { entry.watcher.close() } catch { /* already closed */ }
2169
+ autoPushWatchers.delete(id)
2170
+ }
2171
+
2172
+ const runAutoPush = async (record, entry) => {
2173
+ if (entry.running) return
2174
+ entry.running = true
2175
+ try {
2176
+ const settings = settingsStore.get()
2177
+ if (!settings.autoPushEnabled) return
2178
+ const host = await findHost(record.hostId)
2179
+ const remote = await connectHost(host)
2180
+ const plan = autoPushFilter(settings, await buildPlan(record, remote, {}))
2181
+ if (plan.added.length === 0 && plan.changed.length === 0) return
2182
+ const result = await applyPlan(record, remote, plan, { conflict: 'skip' })
2183
+ forgetListings()
2184
+ log('info', `autoPush ${record.name}: ${result.pushed} file(s), ${result.skipped} skipped`)
2185
+ } catch (error) {
2186
+ log('warn', `autoPush ${record.name} failed: ${error && error.message ? error.message : error}`)
2187
+ entry.timer = setTimeout(() => { entry.timer = null; void runAutoPush(record, entry) }, AUTO_PUSH_RETRY_MS)
2188
+ } finally {
2189
+ entry.running = false
2190
+ }
2191
+ }
2192
+
2193
+ const scheduleAutoPush = (record, entry) => {
2194
+ if (entry.timer) clearTimeout(entry.timer)
2195
+ const settings = settingsStore.get()
2196
+ const delay = clampInt(settings.autoPushDebounceMs, AUTO_PUSH_DEBOUNCE_MIN, AUTO_PUSH_DEBOUNCE_MAX, 1500)
2197
+ entry.timer = setTimeout(() => {
2198
+ entry.timer = null
2199
+ void runAutoPush(record, entry)
2200
+ }, delay)
2201
+ if (entry.timer && typeof entry.timer.unref === 'function') entry.timer.unref()
2202
+ }
2203
+
2204
+ /** Start/stop watchers so they match the current settings; safe to call often. */
2205
+ const syncAutoPush = () => {
2206
+ const settings = settingsStore.get()
2207
+ const wanted = settings.autoPushEnabled === true
2208
+ for (const id of [...autoPushWatchers.keys()]) {
2209
+ const record = linkedStore.get(id)
2210
+ if (!wanted || !record) stopAutoPush(id)
2211
+ }
2212
+ if (!wanted) return
2213
+ for (const record of linkedStore.list()) {
2214
+ if (autoPushWatchers.has(record.id)) continue
2215
+ let watcher
2216
+ try {
2217
+ watcher = watch(record.localPath, { recursive: true, persistent: false }, () => {
2218
+ const entry = autoPushWatchers.get(record.id)
2219
+ if (entry) scheduleAutoPush(record, entry)
2220
+ })
2221
+ } catch (error) {
2222
+ log('warn', `autoPush watcher for ${record.name} failed: ${error && error.message ? error.message : error}`)
2223
+ continue
2224
+ }
2225
+ watcher.on('error', () => stopAutoPush(record.id))
2226
+ autoPushWatchers.set(record.id, { watcher, timer: null, running: false })
2227
+ }
2228
+ }
2229
+
2230
+ // A content search can run for seconds; the client can stop it by job id the
2231
+ // same way it stops a transfer. The flag is checked between files.
2232
+ const GREP_JOB_TTL_MS = 60 * 1000
2233
+ const grepJobs = new Map()
2234
+
2235
+ const beginGrepJob = (id) => {
2236
+ if (typeof id !== 'string' || id.trim() === '') return null
2237
+ const now = Date.now()
2238
+ for (const [key, value] of grepJobs) {
2239
+ if (now - value.startedAt > GREP_JOB_TTL_MS) grepJobs.delete(key)
2240
+ }
2241
+ const job = { id, cancelled: false, startedAt: now }
2242
+ grepJobs.set(id, job)
2243
+ return job
2244
+ }
2245
+
1816
2246
  /** Download one remote file/folder into the OS Downloads folder. */
1817
2247
  const downloadRemotePath = async (remote, target, destDir) => {
1818
2248
  await mkdir(destDir, { recursive: true })
@@ -2077,9 +2507,16 @@ export function apply(ctx) {
2077
2507
  const GREP_MAX_FILES = 2000
2078
2508
  const GREP_MAX_BYTES = 8 * 1024 * 1024
2079
2509
  const GREP_DEADLINE_MS = 5000
2510
+ const GREP_DEADLINE_MAX = 10000
2080
2511
  const GREP_PREVIEW_CHARS = 120
2081
2512
  const GREP_MAX_QUERY = 200
2082
2513
 
2514
+ // Path completion (`fs.references`) is about names, not contents, so it walks
2515
+ // more entries but reads no files.
2516
+ const REFERENCE_MAX_RESULTS = 200
2517
+ const REFERENCE_MAX_ENTRIES = 20000
2518
+ const REFERENCE_DEADLINE_MS = 3000
2519
+
2083
2520
  // Dependency trees and build output make a content search useless: they
2084
2521
  // dwarf the project and always win the result budget. Both sides skip them.
2085
2522
  const GREP_EXCLUDED_DIRS = [
@@ -2089,7 +2526,13 @@ export function apply(ctx) {
2089
2526
  '.ipynb_checkpoints', '.gradle', '.idea', '.vscode',
2090
2527
  ]
2091
2528
 
2092
- function grepDirectoryExcluded(name) {
2529
+ // Version-control metadata stays hidden even when the user asks for ignored
2530
+ // directories: nobody wants `.git/objects` in a completion list.
2531
+ const GREP_ALWAYS_EXCLUDED = new Set(['.git', '.hg', '.svn'])
2532
+
2533
+ function grepDirectoryExcluded(name, includeIgnored) {
2534
+ if (GREP_ALWAYS_EXCLUDED.has(name)) return true
2535
+ if (includeIgnored) return false
2093
2536
  return LINKED_SYNC_EXCLUDES.has(name) || GREP_EXCLUDED_DIRS.indexOf(name) !== -1
2094
2537
  }
2095
2538
 
@@ -2126,21 +2569,51 @@ export function apply(ctx) {
2126
2569
  return { line: 0, preview: '' }
2127
2570
  }
2128
2571
 
2572
+ /** Count occurrences of the query in one file body (used by `files` mode). */
2573
+ function countMatches(text, query, options) {
2574
+ if (query === '') return 0
2575
+ if (options && options.regex) {
2576
+ let expression
2577
+ try {
2578
+ expression = new RegExp(query, options.ignoreCase ? 'gi' : 'g')
2579
+ } catch {
2580
+ return 0
2581
+ }
2582
+ const found = text.match(expression)
2583
+ return found ? found.length : 0
2584
+ }
2585
+ const haystack = options && options.ignoreCase ? text.toLowerCase() : text
2586
+ const needle = options && options.ignoreCase ? query.toLowerCase() : query
2587
+ let count = 0
2588
+ let index = haystack.indexOf(needle)
2589
+ while (index !== -1) {
2590
+ count += 1
2591
+ index = haystack.indexOf(needle, index + needle.length)
2592
+ }
2593
+ return count
2594
+ }
2595
+
2129
2596
  function contentSearchLocal(root, query, maxResults, options = {}) {
2130
2597
  const matcher = compileSearch(query, options)
2131
2598
  const entries = []
2132
2599
  const started = Date.now()
2600
+ const maxFiles = clampInt(options.maxFiles, 1, GREP_MAX_FILES, GREP_MAX_FILES)
2601
+ const maxFileBytes = clampInt(options.maxFileBytes, 1024, GREP_MAX_FILE_BYTES, GREP_MAX_FILE_BYTES)
2602
+ const deadline = clampInt(options.timeoutMs, 500, GREP_DEADLINE_MAX, GREP_DEADLINE_MS)
2603
+ const filesOnly = options.resultMode === 'files'
2133
2604
  let files = 0
2134
2605
  let bytes = 0
2606
+ let skippedFiles = 0
2135
2607
  let truncatedReason = ''
2136
2608
  const stop = (reason) => {
2137
2609
  if (truncatedReason === '') truncatedReason = reason
2138
2610
  }
2139
2611
  const visit = (directory, prefix) => {
2140
2612
  if (truncatedReason !== '') return
2141
- if (files >= GREP_MAX_FILES) return stop('files')
2613
+ if (files >= maxFiles) return stop('files')
2142
2614
  if (bytes >= GREP_MAX_BYTES) return stop('bytes')
2143
- if (Date.now() - started > GREP_DEADLINE_MS) return stop('deadline')
2615
+ if (Date.now() - started > deadline) return stop('deadline')
2616
+ if (options.job && options.job.cancelled) return stop('cancelled')
2144
2617
  let listing
2145
2618
  try {
2146
2619
  listing = readdirSync(directory, { withFileTypes: true })
@@ -2149,7 +2622,8 @@ export function apply(ctx) {
2149
2622
  }
2150
2623
  for (const entry of listing) {
2151
2624
  if (truncatedReason !== '') return
2152
- if (grepDirectoryExcluded(entry.name)) continue
2625
+ if (options.job && options.job.cancelled) return stop('cancelled')
2626
+ if (grepDirectoryExcluded(entry.name, options.includeIgnored)) continue
2153
2627
  const absolute = join(directory, entry.name)
2154
2628
  const relative = prefix === '' ? entry.name : `${prefix}/${entry.name}`
2155
2629
  if (entry.isDirectory()) {
@@ -2157,21 +2631,26 @@ export function apply(ctx) {
2157
2631
  continue
2158
2632
  }
2159
2633
  if (!entry.isFile()) continue
2160
- if (files >= GREP_MAX_FILES) return stop('files')
2634
+ if (files >= maxFiles) return stop('files')
2161
2635
  if (bytes >= GREP_MAX_BYTES) return stop('bytes')
2162
- if (Date.now() - started > GREP_DEADLINE_MS) return stop('deadline')
2636
+ if (Date.now() - started > deadline) return stop('deadline')
2163
2637
  files += 1
2164
2638
  // Skip oversized files before reading them: pulling a 2 GB blob into
2165
2639
  // memory to answer a text query would stall the whole Host.
2166
2640
  try {
2167
- if (statSync(absolute).size > GREP_MAX_FILE_BYTES) continue
2641
+ if (statSync(absolute).size > maxFileBytes) {
2642
+ skippedFiles += 1
2643
+ continue
2644
+ }
2168
2645
  } catch {
2646
+ skippedFiles += 1
2169
2647
  continue
2170
2648
  }
2171
2649
  let data
2172
2650
  try {
2173
2651
  data = readFileSync(absolute)
2174
2652
  } catch {
2653
+ skippedFiles += 1
2175
2654
  continue
2176
2655
  }
2177
2656
  bytes += data.length
@@ -2179,12 +2658,25 @@ export function apply(ctx) {
2179
2658
  const text = data.toString('utf8')
2180
2659
  if (!matcher.test(text)) continue
2181
2660
  if (entries.length >= maxResults) return stop('results')
2182
- const hit = firstMatchLine(text, matcher)
2183
- entries.push({ path: absolute, relative, size: data.length, line: hit.line, preview: hit.preview })
2661
+ if (filesOnly) {
2662
+ entries.push({ path: absolute, relative, size: data.length, line: 0, preview: '', matches: countMatches(text, query, options) })
2663
+ } else {
2664
+ const hit = firstMatchLine(text, matcher)
2665
+ entries.push({ path: absolute, relative, size: data.length, line: hit.line, preview: hit.preview })
2666
+ }
2184
2667
  }
2185
2668
  }
2186
2669
  visit(resolve(root), '')
2187
- return { ok: true, query, entries, truncated: truncatedReason !== '', truncatedReason }
2670
+ return {
2671
+ ok: true,
2672
+ query,
2673
+ entries,
2674
+ truncated: truncatedReason !== '',
2675
+ truncatedReason,
2676
+ scannedFiles: files,
2677
+ scannedBytes: bytes,
2678
+ skippedFiles,
2679
+ }
2188
2680
  }
2189
2681
 
2190
2682
  async function contentSearchRemote(remote, root, query, maxResults, options = {}) {
@@ -2206,17 +2698,26 @@ export function apply(ctx) {
2206
2698
  if (normalized === '..' || normalized.startsWith('../')) throw new ApiError('BAD_REQUEST', '搜索路径超出工作区范围')
2207
2699
  searchRoot = normalized === '' ? root : posix.join(root, normalized)
2208
2700
  }
2209
- const excludes = GREP_EXCLUDED_DIRS.map((dir) => `--exclude-dir=${shellQuoteArg(dir)}`).join(' ')
2701
+ const ignores = options.includeIgnored
2702
+ ? [...GREP_ALWAYS_EXCLUDED]
2703
+ : GREP_EXCLUDED_DIRS
2704
+ const excludes = ignores.map((dir) => `--exclude-dir=${shellQuoteArg(dir)}`).join(' ')
2210
2705
  const pattern = useRegex ? `-E ${shellQuoteArg(query)}` : `-e ${shellQuoteArg(query)}`
2211
- const command = `grep -rIn${ignoreCase ? 'i' : ''} --binary-files=without-match ${excludes} ${pattern}`
2706
+ const filesOnly = options.resultMode === 'files'
2707
+ const deadline = clampInt(options.timeoutMs, 500, GREP_DEADLINE_MAX, GREP_DEADLINE_MS)
2708
+ const listFlag = filesOnly ? 'Il' : 'In'
2709
+ const command = `grep -r${listFlag}${ignoreCase ? 'i' : ''} --binary-files=without-match ${excludes} ${pattern}`
2212
2710
  + ` -- ${shellQuoteArg(searchRoot)} 2>/dev/null | head -n ${maxResults + 1}`
2213
2711
  let result
2214
2712
  try {
2215
- result = await remote.exec(command, { timeoutMs: 20000 })
2713
+ result = await remote.exec(command, { timeoutMs: Math.max(deadline + 2000, 20000) })
2216
2714
  } catch (error) {
2217
2715
  // A timeout means "we looked, but not everywhere": report it as a
2218
2716
  // truncated result instead of failing the whole search.
2219
- return { ok: true, query, entries: [], truncated: true, truncatedReason: 'deadline' }
2717
+ return {
2718
+ ok: true, query, entries: [], truncated: true, truncatedReason: 'deadline',
2719
+ scannedFiles: 0, scannedBytes: 0, skippedFiles: 0,
2720
+ }
2220
2721
  }
2221
2722
  if (result.code !== 0 && String(result.stdout || '').trim() === '') {
2222
2723
  // grep exits 1 when nothing matched; a real failure has code > 1.
@@ -2225,30 +2726,145 @@ export function apply(ctx) {
2225
2726
  if (result.code === 2 && /invalid/i.test(detail)) throw new ApiError('BAD_REQUEST', `正则表达式无效:${detail}`)
2226
2727
  throw new ApiError('INTERNAL', `内容搜索失败:${detail}`)
2227
2728
  }
2228
- return { ok: true, query, entries: [], truncated: false, truncatedReason: '' }
2729
+ return {
2730
+ ok: true, query, entries: [], truncated: false, truncatedReason: '',
2731
+ scannedFiles: 0, scannedBytes: 0, skippedFiles: 0,
2732
+ }
2229
2733
  }
2230
- const lines = String(result.stdout || '').split('\n').filter((line) => line.trim() !== '')
2734
+ const lines = String(result.stdout || '').replace(/\r/g, '').split('\n').filter((line) => line.trim() !== '')
2231
2735
  const entries = []
2736
+ const seen = new Set()
2232
2737
  let truncatedReason = ''
2233
2738
  for (const raw of lines) {
2234
2739
  if (entries.length >= maxResults) {
2235
2740
  truncatedReason = 'results'
2236
2741
  break
2237
2742
  }
2238
- const match = /^(.*?):(\d+):(.*)$/.exec(raw)
2239
- if (!match) continue
2240
- const file = match[1]
2743
+ const common = filesOnly ? /^(.*)$/.exec(raw) : /^(.*?):(\d+):(.*)$/.exec(raw)
2744
+ if (!common) continue
2745
+ const file = common[1]
2746
+ seen.add(file)
2241
2747
  const relative = file.startsWith(`${searchRoot}/`) ? file.slice(searchRoot.length + 1) : file
2242
2748
  entries.push({
2243
2749
  path: file,
2244
2750
  relative,
2245
2751
  size: null,
2246
- line: Number(match[2]),
2247
- preview: match[3].replace(/\s+/g, ' ').trim().slice(0, GREP_PREVIEW_CHARS),
2752
+ line: filesOnly ? 0 : Number(common[2]),
2753
+ preview: filesOnly ? '' : common[3].replace(/\s+/g, ' ').trim().slice(0, GREP_PREVIEW_CHARS),
2248
2754
  })
2249
2755
  }
2250
2756
  if (truncatedReason === '' && lines.length > maxResults) truncatedReason = 'results'
2251
- return { ok: true, query, entries, truncated: truncatedReason !== '', truncatedReason }
2757
+ return {
2758
+ ok: true,
2759
+ query,
2760
+ entries,
2761
+ truncated: truncatedReason !== '',
2762
+ truncatedReason,
2763
+ scannedFiles: seen.size,
2764
+ scannedBytes: 0,
2765
+ skippedFiles: 0,
2766
+ }
2767
+ }
2768
+
2769
+ // ── path completion (`fs.references`, 0.18.0) ─────────────────────────────
2770
+ // Ordering rule: an exact file name wins, then names that start with the
2771
+ // query, then anything else — shorter paths first inside each group, so the
2772
+ // obvious candidate is always at the top of the list.
2773
+
2774
+ function rankReferenceCandidates(list, needle, limit) {
2775
+ const scored = list.map((item) => {
2776
+ const name = item.name.toLowerCase()
2777
+ let score = 2
2778
+ if (name === needle) score = 0
2779
+ else if (name.startsWith(needle)) score = 1
2780
+ return { item, score }
2781
+ })
2782
+ scored.sort((left, right) => {
2783
+ if (left.score !== right.score) return left.score - right.score
2784
+ if (left.item.relative.length !== right.item.relative.length) {
2785
+ return left.item.relative.length - right.item.relative.length
2786
+ }
2787
+ return left.item.relative.localeCompare(right.item.relative)
2788
+ })
2789
+ return scored.slice(0, limit).map((entry) => entry.item)
2790
+ }
2791
+
2792
+ function referenceCandidatesLocal(root, query, limit, options = {}) {
2793
+ const needle = query.toLowerCase()
2794
+ const started = Date.now()
2795
+ const hits = []
2796
+ let visited = 0
2797
+ let truncated = false
2798
+ const walk = (directory, prefix) => {
2799
+ if (truncated) return
2800
+ if (visited >= REFERENCE_MAX_ENTRIES || Date.now() - started > REFERENCE_DEADLINE_MS) {
2801
+ truncated = true
2802
+ return
2803
+ }
2804
+ let listing
2805
+ try {
2806
+ listing = readdirSync(directory, { withFileTypes: true })
2807
+ } catch {
2808
+ return
2809
+ }
2810
+ for (const entry of listing) {
2811
+ if (visited >= REFERENCE_MAX_ENTRIES || Date.now() - started > REFERENCE_DEADLINE_MS) {
2812
+ truncated = true
2813
+ return
2814
+ }
2815
+ if (grepDirectoryExcluded(entry.name, options.includeIgnored)) continue
2816
+ visited += 1
2817
+ const relative = prefix === '' ? entry.name : `${prefix}/${entry.name}`
2818
+ if (entry.isDirectory()) {
2819
+ if (relative.toLowerCase().indexOf(needle) !== -1) {
2820
+ hits.push({ relative, name: entry.name, kind: 'directory' })
2821
+ }
2822
+ walk(join(directory, entry.name), relative)
2823
+ } else if (entry.isFile() && relative.toLowerCase().indexOf(needle) !== -1) {
2824
+ hits.push({ relative, name: entry.name, kind: 'file' })
2825
+ }
2826
+ }
2827
+ }
2828
+ walk(resolve(root), '')
2829
+ const candidates = rankReferenceCandidates(hits, needle, limit)
2830
+ return { ok: true, query, candidates, total: hits.length, truncated, scannedEntries: visited }
2831
+ }
2832
+
2833
+ async function referenceCandidatesRemote(remote, root, query, limit, options = {}) {
2834
+ const needle = query.toLowerCase()
2835
+ const ignores = options.includeIgnored ? [...GREP_ALWAYS_EXCLUDED] : GREP_EXCLUDED_DIRS
2836
+ const excluded = ignores.length === 0
2837
+ ? ''
2838
+ : ` | grep -Ev ${shellQuoteArg(ignores.map((dir) => `/${dir}/`).join('|'))}`
2839
+ const command = `find ${shellQuoteArg(root)} -mindepth 1 -printf '%y\\t%p\\n' 2>/dev/null`
2840
+ + `${excluded} | head -n ${REFERENCE_MAX_ENTRIES + 1}`
2841
+ let result
2842
+ try {
2843
+ result = await remote.exec(command, { timeoutMs: 20000 })
2844
+ } catch {
2845
+ return { ok: true, query, candidates: [], total: 0, truncated: true, scannedEntries: 0 }
2846
+ }
2847
+ const rows = String(result.stdout || '').split('\n').filter((line) => line.indexOf('\t') !== -1)
2848
+ const truncated = rows.length > REFERENCE_MAX_ENTRIES
2849
+ const hits = []
2850
+ for (const row of rows.slice(0, REFERENCE_MAX_ENTRIES)) {
2851
+ const tab = row.indexOf('\t')
2852
+ const kindCode = row.slice(0, tab)
2853
+ const absolute = row.slice(tab + 1)
2854
+ const kind = kindCode === 'd' ? 'directory' : kindCode === 'f' ? 'file' : ''
2855
+ if (kind === '') continue
2856
+ const relative = absolute.startsWith(`${root}/`) ? absolute.slice(root.length + 1) : absolute
2857
+ if (relative.toLowerCase().indexOf(needle) === -1) continue
2858
+ hits.push({ relative, name: posix.basename(relative), kind })
2859
+ }
2860
+ return {
2861
+ ok: true,
2862
+ query,
2863
+ candidates: rankReferenceCandidates(hits, needle, limit),
2864
+ total: hits.length,
2865
+ truncated,
2866
+ scannedEntries: rows.length,
2867
+ }
2252
2868
  }
2253
2869
 
2254
2870
  // ── remote command execution ──────────────────────────────────────────────
@@ -2911,17 +3527,60 @@ export function apply(ctx) {
2911
3527
  const scope = await requireScope(params)
2912
3528
  if (scope.kind !== 'linked') throw new ApiError('BAD_REQUEST', '只有联动工作区支持文件传输')
2913
3529
  const job = beginTransferJob(params.jobId)
3530
+ // 0.19.0: a batch carries several paths, so a multi-selection no longer
3531
+ // turns into N round trips that each rebuild the queue entry.
3532
+ const batch = Array.isArray(params.paths) && params.paths.length > 0
3533
+ ? params.paths.filter((item) => typeof item === 'string' && item.trim() !== '')
3534
+ : null
2914
3535
  try {
2915
3536
  if (params.side === 'local') {
2916
- const result = await transferLocalToRemote(scope.record, scope.remote, params.path, job)
3537
+ const list = batch || [params.path]
3538
+ const total = { side: 'local', files: 0, bytes: 0, skipped: 0, truncated: false, targets: [] }
3539
+ for (const item of list) {
3540
+ const result = await transferLocalToRemote(scope.record, scope.remote, item, job)
3541
+ total.files += result.files
3542
+ total.bytes += result.bytes
3543
+ total.skipped += result.skipped
3544
+ total.truncated = total.truncated || result.truncated
3545
+ total.targets.push(result.target)
3546
+ }
2917
3547
  forgetListings()
2918
3548
  finishTransferJob(job, 'done')
2919
- return result
3549
+ appendTransferHistory({
3550
+ kind: 'transfer',
3551
+ direction: 'local-to-remote',
3552
+ linkedId: scope.record.id,
3553
+ files: total.files,
3554
+ bytes: total.bytes,
3555
+ skipped: total.skipped,
3556
+ truncated: total.truncated,
3557
+ at: Date.now(),
3558
+ })
3559
+ return total
3560
+ }
3561
+ const list = batch || [params.path]
3562
+ const total = { side: 'remote', files: 0, bytes: 0, skipped: 0, truncated: false, targets: [] }
3563
+ for (const item of list) {
3564
+ const target = scopeTarget(scope, item)
3565
+ const result = await transferToMirror(scope.record, scope.remote, target, job)
3566
+ total.files += result.files
3567
+ total.bytes += result.bytes
3568
+ total.skipped += result.skipped
3569
+ total.truncated = total.truncated || result.truncated
3570
+ total.targets.push(result.dest)
2920
3571
  }
2921
- const target = scopeTarget(scope, params.path)
2922
- const result = await transferToMirror(scope.record, scope.remote, target, job)
2923
3572
  finishTransferJob(job, 'done')
2924
- return result
3573
+ appendTransferHistory({
3574
+ kind: 'transfer',
3575
+ direction: 'remote-to-mirror',
3576
+ linkedId: scope.record.id,
3577
+ files: total.files,
3578
+ bytes: total.bytes,
3579
+ skipped: total.skipped,
3580
+ truncated: total.truncated,
3581
+ at: Date.now(),
3582
+ })
3583
+ return total
2925
3584
  } catch (error) {
2926
3585
  finishTransferJob(job, error && error.code === 'CANCELLED' ? 'cancelled' : 'failed', error && error.message ? error.message : '')
2927
3586
  throw error
@@ -3034,7 +3693,11 @@ export function apply(ctx) {
3034
3693
  },
3035
3694
 
3036
3695
  async 'settings.update'(params = {}) {
3037
- return settingsStore.update(params)
3696
+ const next = settingsStore.update(params)
3697
+ // Toggling autoPush (or editing its filters) has to start/stop watchers
3698
+ // without a restart; the call is cheap and idempotent.
3699
+ syncAutoPush()
3700
+ return next
3038
3701
  },
3039
3702
 
3040
3703
  // ── local directories (workspace pickers) ──────────────────────────────
@@ -3493,19 +4156,59 @@ export function apply(ctx) {
3493
4156
  const scope = await requireScope(params)
3494
4157
  const query = typeof params.query === 'string' ? params.query.trim() : ''
3495
4158
  const maxResults = Math.min(Math.max(Number(params.maxResults) || 200, 1), 1000)
3496
- if (query === '') return { ok: true, query: '', entries: [], truncated: false, truncatedReason: '' }
4159
+ if (query === '') {
4160
+ return {
4161
+ ok: true, query: '', entries: [], truncated: false, truncatedReason: '',
4162
+ scannedFiles: 0, scannedBytes: 0, skippedFiles: 0,
4163
+ }
4164
+ }
3497
4165
  if (query.length > GREP_MAX_QUERY) throw new ApiError('BAD_REQUEST', `搜索词过长(最多 ${GREP_MAX_QUERY} 个字符)`)
3498
4166
  const side = params.side === 'local' ? 'local' : 'remote'
3499
4167
  const options = {
3500
4168
  path: typeof params.path === 'string' ? params.path : '',
3501
4169
  ignoreCase: params.ignoreCase !== false,
3502
4170
  regex: Boolean(params.regex),
4171
+ includeIgnored: params.includeIgnored === true,
4172
+ resultMode: params.resultMode === 'files' ? 'files' : 'lines',
4173
+ maxFiles: params.maxFiles,
4174
+ maxFileBytes: params.maxFileBytes,
4175
+ timeoutMs: params.timeoutMs,
4176
+ job: beginGrepJob(params.jobId),
3503
4177
  }
3504
4178
  if (side === 'remote') return await contentSearchRemote(scope.remote, scope.root, query, maxResults, options)
3505
4179
  if (scope.kind !== 'linked') throw new ApiError('BAD_REQUEST', '只有联动工作区有本地目录')
3506
4180
  return contentSearchLocal(scope.record.localPath, query, maxResults, options)
3507
4181
  },
3508
4182
 
4183
+ /** Stop a running `fs.grep` (checked between files on the Host). */
4184
+ async 'fs.grepCancel'(params = {}) {
4185
+ const id = typeof params.jobId === 'string' ? params.jobId : ''
4186
+ const job = grepJobs.get(id)
4187
+ if (!job) return { cancelled: false }
4188
+ job.cancelled = true
4189
+ return { cancelled: true }
4190
+ },
4191
+
4192
+ /**
4193
+ * Path completion for `@`-style references (0.18.0). Returns candidate
4194
+ * paths relative to the remote root, best match first. Names only.
4195
+ */
4196
+ async 'fs.references'(params = {}) {
4197
+ const scope = await requireScope(params)
4198
+ const query = typeof params.query === 'string' ? params.query.trim() : ''
4199
+ const limit = clampInt(params.limit, 1, REFERENCE_MAX_RESULTS, 50)
4200
+ const options = { includeIgnored: params.includeIgnored === true }
4201
+ if (query.length > GREP_MAX_QUERY) throw new ApiError('BAD_REQUEST', `搜索词过长(最多 ${GREP_MAX_QUERY} 个字符)`)
4202
+ if (query === '') {
4203
+ return { ok: true, query: '', candidates: [], total: 0, truncated: false, scannedEntries: 0 }
4204
+ }
4205
+ if (params.side === 'local') {
4206
+ if (scope.kind !== 'linked') throw new ApiError('BAD_REQUEST', '只有联动工作区有本地目录')
4207
+ return referenceCandidatesLocal(scope.record.localPath, query, limit, options)
4208
+ }
4209
+ return await referenceCandidatesRemote(scope.remote, scope.root, query, limit, options)
4210
+ },
4211
+
3509
4212
  /**
3510
4213
  * Read-only comparison of one directory pair. Lists files that exist on one
3511
4214
  * side only and files whose size or mtime disagree; it never touches data.
@@ -3913,6 +4616,49 @@ export function apply(ctx) {
3913
4616
  return { cancelled: true }
3914
4617
  },
3915
4618
 
4619
+ /** What the local directory has that the remote side does not (and vice versa). */
4620
+ async 'linked.plan'(params = {}) {
4621
+ const record = requireLinked(params.id)
4622
+ const host = await findHost(record.hostId)
4623
+ const remote = await connectHost(host)
4624
+ return await buildPlan(record, remote, params)
4625
+ },
4626
+
4627
+ /** Write local files back to the remote directory, atomically per file. */
4628
+ async 'linked.push'(params = {}) {
4629
+ const record = requireLinked(params.id)
4630
+ const host = await findHost(record.hostId)
4631
+ const remote = await connectHost(host)
4632
+ const job = beginTransferJob(params.jobId)
4633
+ try {
4634
+ const plan = await buildPlan(record, remote, params)
4635
+ const result = await applyPlan(record, remote, plan, params, job)
4636
+ forgetListings()
4637
+ finishTransferJob(job, result.cancelled ? 'cancelled' : 'done')
4638
+ return result
4639
+ } catch (error) {
4640
+ finishTransferJob(job, error && error.code === 'CANCELLED' ? 'cancelled' : 'failed', error && error.message ? error.message : '')
4641
+ throw error
4642
+ }
4643
+ },
4644
+
4645
+ /** Ask a running push to stop after the file it is writing. */
4646
+ async 'linked.pushCancel'(params = {}) {
4647
+ const id = typeof params.jobId === 'string' ? params.jobId : ''
4648
+ const job = transferJobs.get(id)
4649
+ if (!job) return { cancelled: false }
4650
+ job.cancelled = true
4651
+ job.updatedAt = Date.now()
4652
+ return { cancelled: true }
4653
+ },
4654
+
4655
+ /** The last few transfers and pushes, newest first. */
4656
+ async 'transfer.history'() {
4657
+ const raw = readJsonFile(join(dir, HISTORY_NAME), { version: 1, entries: [] })
4658
+ const entries = Array.isArray(raw && raw.entries) ? raw.entries : []
4659
+ return { entries: entries.slice(0, HISTORY_LIMIT) }
4660
+ },
4661
+
3916
4662
  // ── remote_workspaces methods ───────────────────────────────────────────────
3917
4663
 
3918
4664
  async 'remote_workspaces.list'() {
@@ -4187,7 +4933,7 @@ export function apply(ctx) {
4187
4933
  properties: {
4188
4934
  action: {
4189
4935
  type: 'string',
4190
- enum: ['list', 'info', 'list_dir', 'read', 'write', 'replace', 'stat', 'mkdir', 'rename', 'delete', 'sync', 'exec'],
4936
+ enum: ['list', 'info', 'list_dir', 'read', 'write', 'replace', 'stat', 'mkdir', 'rename', 'delete', 'sync', 'exec', 'references'],
4191
4937
  description: 'Operation to perform. sync only applies to a linked workspace with mirroring on. exec needs the remote-execution switch and allow-lists.',
4192
4938
  },
4193
4939
  workspace: {
@@ -4208,6 +4954,8 @@ export function apply(ctx) {
4208
4954
  command: { type: 'string', description: 'Command line for exec (≤ 8000 characters). Runs non-interactively on the remote host.' },
4209
4955
  cwd: { type: 'string', description: 'Working directory for exec: relative to the workspace root (or an absolute path inside it).' },
4210
4956
  timeout_ms: { type: 'number', description: 'exec timeout in milliseconds (default from settings, max 600000).' },
4957
+ query: { type: 'string', description: 'Search text for references (matches the path, case-insensitive; ≤ 200 characters).' },
4958
+ limit: { type: 'number', description: 'How many candidates references returns (default 50, max 200).' },
4211
4959
  },
4212
4960
  required: ['action'],
4213
4961
  },
@@ -4436,6 +5184,20 @@ export function apply(ctx) {
4436
5184
  return toolText(lines.join('\n'))
4437
5185
  }
4438
5186
 
5187
+ if (action === 'references') {
5188
+ const query = String((args && args.query) || ((args && args.path) || ''))
5189
+ if (query.trim() === '') throw new ApiError('BAD_REQUEST', 'query is required for references')
5190
+ const result = await methods['fs.references'](
5191
+ remoteKind
5192
+ ? { remoteId: link.id, query, limit: args.limit }
5193
+ : { linkedId: link.id, query, limit: args.limit },
5194
+ )
5195
+ if (result.candidates.length === 0) return toolText('(no matching path)')
5196
+ const lines = result.candidates.map((item) => `${item.kind === 'directory' ? 'dir ' : 'file'} ${item.relative}`)
5197
+ if (result.truncated) lines.push(`… stopped after ${result.scannedEntries} entries; narrow the query`)
5198
+ return toolText(lines.join('\n'))
5199
+ }
5200
+
4439
5201
  throw new ApiError('BAD_REQUEST', `unknown action: ${action}`)
4440
5202
  } catch (error) {
4441
5203
  const apiError = asApiError(error)
@@ -4584,6 +5346,17 @@ export function apply(ctx) {
4584
5346
  })
4585
5347
  }, 900)
4586
5348
  if (titleMigrationTimer && typeof titleMigrationTimer.unref === 'function') titleMigrationTimer.unref()
5349
+
5350
+ // autoPush may already be enabled from a previous run: start its watchers and
5351
+ // make sure they are closed when this plugin instance goes away.
5352
+ try {
5353
+ syncAutoPush()
5354
+ } catch (error) {
5355
+ log('warn', `autoPush start failed: ${error && error.message ? error.message : error}`)
5356
+ }
5357
+ ctx.effect(() => () => {
5358
+ for (const id of [...autoPushWatchers.keys()]) stopAutoPush(id)
5359
+ }, 'dsh-linked-workspace: auto push watchers')
4587
5360
  }
4588
5361
 
4589
5362
  // ── response helpers ────────────────────────────────────────────────────────