dsh-gufa-code 1.3.62 → 1.3.63

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -41,7 +41,7 @@ dsh plugin add dsh-gufa-code
41
41
  - Monaco 编辑器(离线随包分发,无需联网下载);
42
42
  - 多标签、按扩展名语法高亮、面包屑、状态栏(分支 / 行列 / 保存状态);
43
43
  - 保存走磁盘版本冲突检测 + 原子写;未保存标记;
44
- - **全局搜索**(左栏放大镜 / `⌘⇧F`):整个项目的文本搜索,支持区分大小写、正则;结果按文件分组、高亮匹配,点击直接跳到文件对应行列;Git 项目用 `git ls-files` 枚举文件(尊重 `.gitignore`、含未跟踪文件),非 Git 项目遍历目录并自动跳过 `node_modules` 等依赖/缓存目录;
44
+ - **全局搜索 / 替换**(左栏放大镜 / `⌘⇧F`):整个项目的文本搜索,支持区分大小写、正则;结果按文件分组、高亮匹配,点击直接跳到文件对应行列;展开替换栏可**全部替换**或对单个文件替换(替换前会先保存未落盘的编辑器内容,确认后直接写文件);Git 项目用 `git ls-files` 枚举文件(尊重 `.gitignore`、含未跟踪文件),非 Git 项目遍历目录并自动跳过 `node_modules` 等依赖/缓存目录;摸鱼悬浮窗里同样可用;
45
45
  - 资源管理器右键:新建 / 重命名 / 删除 / 复制 / 粘贴 / 打开所在文件夹 / 两文件对比;
46
46
  - **从 Finder 粘贴/拖入文件**:系统剪贴板里复制的文件可直接 ⌘V 粘进资源管理器(写入选中的目录,重名自动加「副本」),也可从 Finder 直接拖进文件树;
47
47
  - **粘贴文件到聊天框 = @引用**:在 Finder 复制文件后在右侧对话输入框 ⌘V,会自动匹配项目内同名同内容文件并插入 `@相对路径` 引用(图片仍按 DSH 默认附件处理);
package/client.js CHANGED
@@ -16,7 +16,7 @@ const GUFA_NS = 'gufa-code'
16
16
  const G = {}
17
17
  G.NS = GUFA_NS
18
18
  /** 客户端构建标记(排查页面是否加载了新代码时看标题栏) */
19
- G.BUILD = '1.3.62'
19
+ G.BUILD = '1.3.63'
20
20
  G.PANEL_ID = 'gufa-code'
21
21
  /** 从哪个工作区点进来的(工作区菜单/节点按钮写入,App 启动时消费)。 */
22
22
  G.pendingEntryWorkspace = null
@@ -202,6 +202,16 @@ const DICT_ZH = {
202
202
  'search.summary': '{count} 个结果 · {files} 个文件',
203
203
  'search.truncated': '结果过多已截断,请缩小范围',
204
204
  'search.error': '搜索失败',
205
+ 'search.replaceToggle': '显示/隐藏替换',
206
+ 'search.replacePlaceholder': '替换为…',
207
+ 'search.replaceAll': '全部替换',
208
+ 'search.replaceThisFile': '替换此文件',
209
+ 'search.replacing': '替换中…',
210
+ 'search.replaced': '已替换 {count} 处({files} 个文件)',
211
+ 'search.confirmReplace': '确定替换 {count} 处({files} 个文件)?直接写文件,编辑器撤销无效。',
212
+ 'search.confirmYes': '确定替换',
213
+ 'search.confirmNo': '取消',
214
+ 'search.replaceError': '替换失败',
205
215
  'explorer.empty': '目录为空',
206
216
  'explorer.newFile': '新建文件',
207
217
  'explorer.newFolder': '新建文件夹',
@@ -434,6 +444,16 @@ const DICT_EN = {
434
444
  'search.summary': '{count} results · {files} files',
435
445
  'search.truncated': 'Too many results, truncated — narrow the query',
436
446
  'search.error': 'Search failed',
447
+ 'search.replaceToggle': 'Show / hide replace',
448
+ 'search.replacePlaceholder': 'Replace with…',
449
+ 'search.replaceAll': 'Replace all',
450
+ 'search.replaceThisFile': 'Replace in this file',
451
+ 'search.replacing': 'Replacing…',
452
+ 'search.replaced': 'Replaced {count} occurrences ({files} files)',
453
+ 'search.confirmReplace': 'Replace {count} occurrences in {files} files? This writes files directly; editor undo will not work.',
454
+ 'search.confirmYes': 'Replace',
455
+ 'search.confirmNo': 'Cancel',
456
+ 'search.replaceError': 'Replace failed',
437
457
  'explorer.empty': 'Folder is empty',
438
458
  'explorer.newFile': 'New file',
439
459
  'explorer.newFolder': 'New folder',
@@ -1705,6 +1725,18 @@ html[data-platform=darwin][data-fullscreen] .gufa-titlebar{height:44px;padding-l
1705
1725
  .gufa-search-line{flex:0 0 auto;min-width:24px;text-align:right;font:11px ui-monospace,Menlo,Consolas,monospace;opacity:.65}
1706
1726
  .gufa-search-text{flex:1 1 auto;min-width:0;font:11.5px ui-monospace,Menlo,Consolas,monospace;white-space:pre;overflow:hidden;text-overflow:ellipsis}
1707
1727
  .gufa-search-hit{background:rgba(192,57,43,.38);color:var(--gufa-text);border-radius:2px;padding:0 1px}
1728
+ .gufa-search-replace-row{margin-top:0}
1729
+ .gufa-search-actions{display:flex;align-items:center;gap:6px;margin-top:6px}
1730
+ .gufa-search-action{height:24px;padding:0 9px;border-radius:6px;border:1px solid var(--gufa-border);background:var(--gufa-layer2);color:var(--gufa-text);font-size:11.5px;cursor:pointer}
1731
+ .gufa-search-action:hover:not(:disabled){border-color:var(--gufa-accent)}
1732
+ .gufa-search-action:disabled{opacity:.5;cursor:default}
1733
+ .gufa-search-action[data-primary]{background:var(--gufa-accent);border-color:var(--gufa-accent);color:#fff}
1734
+ .gufa-search-confirm{margin:6px 8px 0;padding:7px 9px;border-radius:7px;border:1px solid var(--gufa-accent);background:color-mix(in srgb, var(--gufa-accent) 12%, transparent);font-size:11.5px;line-height:1.55;color:var(--gufa-text)}
1735
+ .gufa-search-confirm-actions{display:flex;justify-content:flex-end;gap:6px;margin-top:6px}
1736
+ .gufa-search-notice{margin:6px 8px 0;padding:5px 9px;border-radius:7px;font-size:11.5px;color:var(--dsw-alias-state-success-primary);border:1px solid color-mix(in srgb, var(--dsw-alias-state-success-primary) 45%, transparent)}
1737
+ .gufa-search-error{margin:6px 8px 0;padding:5px 9px;border-radius:7px;font-size:11.5px;color:var(--dsw-alias-state-error-primary);border:1px solid color-mix(in srgb, var(--dsw-alias-state-error-primary) 45%, transparent)}
1738
+ .gufa-search-file-replace{flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px;margin-left:2px;border-radius:4px;color:var(--gufa-text-dim);cursor:pointer}
1739
+ .gufa-search-file-replace:hover{background:var(--gufa-active);color:var(--gufa-text)}
1708
1740
 
1709
1741
  .gufa-tree-chevron{width:14px;flex:0 0 auto;opacity:.7;display:flex;align-items:center;justify-content:center}
1710
1742
  .gufa-tree-icon{width:15px;flex:0 0 auto;opacity:.85;display:flex;align-items:center;justify-content:center}
@@ -7296,6 +7328,12 @@ G.SearchPanel = function SearchPanel(props) {
7296
7328
  const [result, setResult] = useState(null)
7297
7329
  const [error, setError] = useState('')
7298
7330
  const [collapsed, setCollapsed] = useState({})
7331
+ const [replaceOpen, setReplaceOpen] = useState(false)
7332
+ const [replacement, setReplacement] = useState('')
7333
+ const [replacing, setReplacing] = useState(false)
7334
+ const [confirming, setConfirming] = useState(null)
7335
+ const [replaceError, setReplaceError] = useState('')
7336
+ const [notice, setNotice] = useState('')
7299
7337
  const inputRef = useRef(null)
7300
7338
  const requestRef = useRef(0)
7301
7339
 
@@ -7340,6 +7378,41 @@ G.SearchPanel = function SearchPanel(props) {
7340
7378
  }
7341
7379
  }, [root, caseSensitive, regex])
7342
7380
 
7381
+ const requestReplace = useCallback((paths, count, files) => {
7382
+ if (typeof root !== 'string' || root === '' || query.trim() === '' || replacing) return
7383
+ setReplaceError('')
7384
+ setNotice('')
7385
+ setConfirming({ paths: Array.isArray(paths) ? paths : null, count: Number(count) || 0, files: Number(files) || 0 })
7386
+ }, [root, query, replacing])
7387
+
7388
+ const doReplace = useCallback(async () => {
7389
+ const pending = confirming
7390
+ if (pending === null || replacing) return
7391
+ setConfirming(null)
7392
+ setReplacing(true)
7393
+ setReplaceError('')
7394
+ setNotice('')
7395
+ try {
7396
+ await props.onBeforeReplace?.()
7397
+ const value = await G.api('fs.replace', {
7398
+ root,
7399
+ query: query.trim(),
7400
+ replacement,
7401
+ options: { caseSensitive, regex },
7402
+ paths: Array.isArray(pending.paths) ? pending.paths : undefined,
7403
+ })
7404
+ const count = Number(value?.replacedCount) || 0
7405
+ const replacedFiles = Array.isArray(value?.replacedFiles) ? value.replacedFiles : []
7406
+ setNotice(t('search.replaced', { count, files: replacedFiles.length }))
7407
+ await props.onFilesChanged?.(replacedFiles)
7408
+ await runSearch(query)
7409
+ } catch (error) {
7410
+ setReplaceError(G.errorText(error))
7411
+ } finally {
7412
+ setReplacing(false)
7413
+ }
7414
+ }, [confirming, replacing, props.onBeforeReplace, props.onFilesChanged, root, query, replacement, caseSensitive, regex, runSearch, t])
7415
+
7343
7416
  /* 输入防抖搜索(回车立即搜索) */
7344
7417
  useEffect(() => {
7345
7418
  if (typeof root !== 'string' || root === '') return undefined
@@ -7418,6 +7491,22 @@ G.SearchPanel = function SearchPanel(props) {
7418
7491
  h('span', { className: 'gufa-search-file-name' }, G.basename(file.path)),
7419
7492
  h('span', { className: 'gufa-search-file-dir' }, G.dirname(file.path)),
7420
7493
  h('span', { className: 'gufa-search-file-count' }, String(file.matches.length)),
7494
+ replaceOpen
7495
+ ? h(
7496
+ 'span',
7497
+ {
7498
+ className: 'gufa-search-file-replace',
7499
+ title: t('search.replaceThisFile'),
7500
+ role: 'button',
7501
+ onClick: (event) => {
7502
+ event.stopPropagation()
7503
+ event.preventDefault()
7504
+ requestReplace([file.path], file.matches.length, 1)
7505
+ },
7506
+ },
7507
+ h(G.Icon, { name: 'pencil', size: 11 }),
7508
+ )
7509
+ : null,
7421
7510
  ),
7422
7511
  isCollapsed
7423
7512
  ? null
@@ -7473,6 +7562,7 @@ G.SearchPanel = function SearchPanel(props) {
7473
7562
  query === ''
7474
7563
  ? null
7475
7564
  : h(G.IconButton, { title: t('search.clear'), onClick: () => { setQuery(''); focusInput() } }, h(G.Icon, { name: 'close', size: 11 })),
7565
+ h(G.IconButton, { title: t('search.replaceToggle'), onClick: () => setReplaceOpen((value) => !value) }, h(G.Icon, { name: replaceOpen ? 'chevron-up' : 'chevron-down', size: 12 })),
7476
7566
  ),
7477
7567
  h(
7478
7568
  'div',
@@ -7493,6 +7583,60 @@ G.SearchPanel = function SearchPanel(props) {
7493
7583
  }, '.*'),
7494
7584
  h('span', { className: 'gufa-search-summary', title: summary }, summary),
7495
7585
  ),
7586
+ replaceOpen
7587
+ ? h(
7588
+ React.Fragment,
7589
+ null,
7590
+ h(
7591
+ 'div',
7592
+ { className: 'gufa-search-input-wrap gufa-search-replace-row' },
7593
+ h(G.Icon, { name: 'pencil', size: 12 }),
7594
+ h('input', {
7595
+ className: 'gufa-search-input',
7596
+ type: 'text',
7597
+ value: replacement,
7598
+ placeholder: t('search.replacePlaceholder'),
7599
+ spellCheck: false,
7600
+ onChange: (event) => setReplacement(event.target.value),
7601
+ onKeyDown: (event) => {
7602
+ if (event.key !== 'Enter') return
7603
+ event.preventDefault()
7604
+ requestReplace(null, result?.total ?? 0, result?.files?.length ?? 0)
7605
+ },
7606
+ }),
7607
+ ),
7608
+ h(
7609
+ 'div',
7610
+ { className: 'gufa-search-actions' },
7611
+ h(
7612
+ 'button',
7613
+ {
7614
+ type: 'button',
7615
+ className: 'gufa-search-action',
7616
+ 'data-primary': '',
7617
+ disabled: replacing || result === null || result.total === 0,
7618
+ onClick: () => requestReplace(null, result?.total ?? 0, result?.files?.length ?? 0),
7619
+ },
7620
+ replacing ? t('search.replacing') : t('search.replaceAll'),
7621
+ ),
7622
+ ),
7623
+ )
7624
+ : null,
7625
+ confirming !== null
7626
+ ? h(
7627
+ 'div',
7628
+ { className: 'gufa-search-confirm' },
7629
+ h('div', null, t('search.confirmReplace', { count: confirming.count, files: confirming.files })),
7630
+ h(
7631
+ 'div',
7632
+ { className: 'gufa-search-confirm-actions' },
7633
+ h('button', { type: 'button', className: 'gufa-search-action', onClick: () => setConfirming(null) }, t('search.confirmNo')),
7634
+ h('button', { type: 'button', className: 'gufa-search-action', 'data-primary': '', onClick: () => void doReplace() }, t('search.confirmYes')),
7635
+ ),
7636
+ )
7637
+ : null,
7638
+ notice !== '' ? h('div', { className: 'gufa-search-notice' }, notice) : null,
7639
+ replaceError !== '' ? h('div', { className: 'gufa-search-error' }, `${t('search.replaceError')}:${replaceError}`) : null,
7496
7640
  ),
7497
7641
  h('div', { className: 'gufa-panel-body gufa-scroll' }, body),
7498
7642
  )
@@ -10609,6 +10753,49 @@ G.GufaApp = function GufaApp(props) {
10609
10753
  }
10610
10754
  }, [project, patchTab, refreshGit, t])
10611
10755
 
10756
+ /* 搜索面板批量替换前:先把所有未落盘的编辑器缓冲保存掉,避免磁盘旧内容覆盖用户输入 */
10757
+ const beforeSearchReplace = useCallback(async () => {
10758
+ flushBuffersRef.current?.()
10759
+ const pending = new Set(editorBuffersRef.current.keys())
10760
+ for (const tab of tabsRef.current ?? []) {
10761
+ if (tab !== null && tab !== undefined && tab.dirty === true) pending.add(tab.path)
10762
+ }
10763
+ for (const path of pending) {
10764
+ try {
10765
+ await saveFile(path)
10766
+ } catch {
10767
+ /* 单个保存失败不阻断替换 */
10768
+ }
10769
+ }
10770
+ }, [saveFile])
10771
+
10772
+ /* 搜索面板替换完成后:刷新目录/Git,并把已打开标签同步成磁盘最新内容 */
10773
+ const onSearchFilesChanged = useCallback(async (paths) => {
10774
+ if (project !== null && Array.isArray(paths) && paths.length > 0) {
10775
+ for (const path of paths.slice(0, 30)) {
10776
+ const tab = (tabsRef.current ?? []).find((item) => item !== null && item !== undefined && item.path === path)
10777
+ if (tab === undefined) continue
10778
+ try {
10779
+ const doc = await G.api('fs.read', { root: project.root, path })
10780
+ editorBuffersRef.current.delete(path)
10781
+ patchTab(path, {
10782
+ content: doc.content,
10783
+ revision: doc.revision,
10784
+ savedRevision: doc.revision,
10785
+ savedContent: doc.content,
10786
+ dirty: false,
10787
+ size: doc.size,
10788
+ })
10789
+ } catch {
10790
+ /* 文件已被删除:忽略 */
10791
+ }
10792
+ }
10793
+ }
10794
+ setRefreshToken((token) => token + 1)
10795
+ setGitRefreshToken((token) => token + 1)
10796
+ void refreshGit()
10797
+ }, [project, patchTab, refreshGit])
10798
+
10612
10799
  /** 顶栏提示:错误常驻红色;成功用绿色 toast,1.2 秒后自动消失。 */
10613
10800
  const successTimerRef = useRef(null)
10614
10801
  const showBanner = useCallback((text, tone) => {
@@ -12136,6 +12323,8 @@ G.GufaApp = function GufaApp(props) {
12136
12323
  root: project?.root ?? null,
12137
12324
  active: ui.view === 'search',
12138
12325
  onOpenFile: (path, line, column) => void openFileAt(path, line, column),
12326
+ onBeforeReplace: beforeSearchReplace,
12327
+ onFilesChanged: onSearchFilesChanged,
12139
12328
  })),
12140
12329
  h('div', { key: 'git', style: { display: ui.view === 'git' ? 'flex' : 'none', flex: '1 1 auto', minHeight: 0, flexDirection: 'column' } },
12141
12330
  h(G.GitPanel, {
@@ -7,8 +7,8 @@
7
7
  <key>CFBundleDisplayName</key><string>古法编程悬浮层</string>
8
8
  <key>CFBundleExecutable</key><string>gufa-float</string>
9
9
  <key>CFBundlePackageType</key><string>APPL</string>
10
- <key>CFBundleShortVersionString</key><string>1.3.62</string>
11
- <key>CFBundleVersion</key><string>1.3.62</string>
10
+ <key>CFBundleShortVersionString</key><string>1.3.63</string>
11
+ <key>CFBundleVersion</key><string>1.3.63</string>
12
12
  <key>LSUIElement</key><true/>
13
13
  <key>NSHighResolutionCapable</key><true/>
14
14
  <key>NSPrincipalClass</key><string>NSApplication</string>
@@ -157,7 +157,14 @@ AI 是通过 Host 工具直接写盘,客户端收不到任何通知。
157
157
  - 结果行带 `line/column/start/end/text`,前端高亮 `start..end`;点击结果通过 `G.bus 'editor:reveal'` 让 Monaco 跳到对应行列(tab 切换未完成时事件先存到 `pendingRevealRef`)。
158
158
  - **坑**:往 `G.CSS` 模板里加规则时一定插在完整规则之后。曾把搜索样式插进 `.gufa-explorer-notice{...}` 规则中间,CSS nesting 把整块样式变成后代选择器,面板渲染成原生输入框。插入后检查 `client.js` 里 `.gufa-explorer-notice{...}` 的闭合括号是否在搜索块之前。
159
159
 
160
- ## 5.1 摸鱼会话框比编辑器黑:官方会话根节点自己又画了一层底
160
+ ## 全局替换(1.3.63 新增)
161
+
162
+ - Host 侧 `fs.replace`:与 `fs.search` 共用 `listProjectCandidates`(Git 项目 `git ls-files`,非 Git BFS 遍历);按 query 构造正则(字面量走 `escapeRegExp` + 函数 replacer 保持 `$` 字面量,正则模式支持 `$1` 分组),只写内容确实变化的文件。
163
+ - 正则模式禁止「能匹配空字符串」的表达式(如 `a*`),否则会在每个字符间插入替换文本。
164
+ - 替换前客户端先 `beforeSearchReplace`:flush 编辑器缓冲 + 保存所有脏标签,避免磁盘旧内容覆盖用户输入;替换后 `onSearchFilesChanged` 重新读盘并 patch 已打开标签、刷新目录/Git。
165
+ - 前端替换入口在搜索输入框右侧 chevron:展开后出现替换输入、`全部替换`、每个文件头部的单文件替换铅笔按钮;全部替换需要一次内联确认(直接写盘,编辑器撤销无效)。
166
+
167
+ ## 5.1 摸鱼会话框比编辑器黑:官方会话根节点又自己画了一层底
161
168
 
162
169
  - 现象:摸鱼里编辑器/终端都统一了,右侧会话框看起来明显更黑更实。
163
170
  - 实测(同屏同底层对比法):编辑器有效 alpha=0.570,会话框=0.878 → 会话框多叠了一层 ~0.72 的暗底。
package/host/fs.js CHANGED
@@ -87,6 +87,97 @@ async function projectOf(env, body) {
87
87
  return project.root
88
88
  }
89
89
 
90
+ /* ── 全项目搜索/替换共用的目录与文件枚举 ───────────────────────────────── */
91
+ const SEARCH_EXCLUDED = new Set([
92
+ 'node_modules', '.git', 'dist', 'build', 'out', '.next', 'vendor', 'target', '.venv', 'venv',
93
+ '__pycache__', '.idea', '.cache', '.turbo', '.parcel-cache', '.svelte-kit', '.nuxt', '.output',
94
+ 'coverage', '.gradle', 'DerivedData', 'Pods', '.tox', '.mypy_cache', '.pytest_cache', '.ruff_cache',
95
+ '.electron-cache', '.npm-cache', '.pip-cache', '.yarn', '.pnpm-store', '.pnpm',
96
+ ])
97
+ const SEARCH_SKIP_EXT = new Set([
98
+ 'png', 'jpg', 'jpeg', 'gif', 'webp', 'ico', 'icns', 'bmp', 'tiff', 'pdf', 'zip', 'gz', 'tgz', 'tar', '7z', 'rar', 'dmg', 'iso',
99
+ 'mp4', 'mp3', 'wav', 'mov', 'avi', 'mkv', 'flac', 'jar', 'class', 'o', 'a', 'so', 'dylib', 'dll', 'exe', 'bin', 'dat',
100
+ 'woff', 'woff2', 'ttf', 'otf', 'eot', 'wasm', 'pyc', 'node',
101
+ ])
102
+ const SEARCH_EXCLUDE_PREFIXES = ['.venv', '.npm-cache', '.pip-cache', '.electron-cache', '.pnpm', '.yarn', '.cache', '.next-cache']
103
+ function searchDirExcluded(name) {
104
+ if (SEARCH_EXCLUDED.has(name)) return true
105
+ for (const prefix of SEARCH_EXCLUDE_PREFIXES) {
106
+ if (name.startsWith(prefix)) return true
107
+ }
108
+ return false
109
+ }
110
+ function searchExtensionOf(rel) {
111
+ const base = String(rel).split('/').pop() ?? ''
112
+ const dot = base.lastIndexOf('.')
113
+ return dot <= 0 ? '' : base.slice(dot + 1).toLowerCase()
114
+ }
115
+ function escapeRegExp(text) {
116
+ return String(text).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
117
+ }
118
+ async function isGitProject(root, project) {
119
+ if (project !== null && project !== undefined && project.isGit === true) return true
120
+ try {
121
+ const dotGit = await stat(join(root, '.git'))
122
+ return dotGit.isDirectory() || dotGit.isFile()
123
+ } catch {
124
+ return false
125
+ }
126
+ }
127
+ /** 枚举项目内可搜索文件:Git 项目用 git ls-files,否则 BFS 遍历并跳过依赖/缓存目录。 */
128
+ async function listProjectCandidates(root, project, maxScanned) {
129
+ if (await isGitProject(root, project)) {
130
+ try {
131
+ const { stdout } = await runCommand('git', ['ls-files', '-z', '--cached', '--others', '--exclude-standard'], {
132
+ cwd: root,
133
+ maxBuffer: 64 * 1024 * 1024,
134
+ timeout: 15000,
135
+ })
136
+ const files = stdout.split('\0').filter((item) => item !== '')
137
+ files.sort((a, b) => a.localeCompare(b))
138
+ return { files, truncated: false, viaGit: true }
139
+ } catch {
140
+ /* 回退到目录遍历 */
141
+ }
142
+ }
143
+ const queue = ['']
144
+ const files = []
145
+ let head = 0
146
+ let scanned = 0
147
+ let truncated = false
148
+ while (head < queue.length) {
149
+ if (files.length >= maxScanned) {
150
+ truncated = true
151
+ break
152
+ }
153
+ const dirRel = queue[head]
154
+ head += 1
155
+ let entries
156
+ try {
157
+ entries = await readdir(join(root, dirRel), { withFileTypes: true })
158
+ } catch {
159
+ continue
160
+ }
161
+ entries.sort((a, b) => String(a.name).localeCompare(String(b.name)))
162
+ for (const entry of entries) {
163
+ if (entry.isDirectory()) {
164
+ if (!searchDirExcluded(entry.name)) queue.push(dirRel === '' ? entry.name : `${dirRel}/${entry.name}`)
165
+ continue
166
+ }
167
+ if (!entry.isFile() || searchDirExcluded(entry.name)) continue
168
+ const rel = dirRel === '' ? entry.name : `${dirRel}/${entry.name}`
169
+ if (SEARCH_SKIP_EXT.has(searchExtensionOf(rel))) continue
170
+ files.push(rel)
171
+ scanned += 1
172
+ if (files.length >= maxScanned) {
173
+ truncated = true
174
+ break
175
+ }
176
+ }
177
+ }
178
+ return { files, truncated, viaGit: false, scanned }
179
+ }
180
+
90
181
  export function register(router, env) {
91
182
  router.method('fs.list', async (body) => {
92
183
  const root = await projectOf(env, body)
@@ -410,7 +501,7 @@ export function register(router, env) {
410
501
  entries.sort((a, b) => String(a.name).localeCompare(String(b.name)))
411
502
  for (const entry of entries) {
412
503
  if (entry.isDirectory()) {
413
- if (!EXCLUDED.has(entry.name)) queue.push(dirRel === '' ? entry.name : `${dirRel}/${entry.name}`)
504
+ if (!EXCLUDED.has(entry.name) && !SEARCH_EXCLUDE_PREFIXES.some((prefix) => entry.name.startsWith(prefix))) queue.push(dirRel === '' ? entry.name : `${dirRel}/${entry.name}`)
414
505
  continue
415
506
  }
416
507
  if (!entry.isFile() || EXCLUDED.has(entry.name)) continue
@@ -433,6 +524,97 @@ export function register(router, env) {
433
524
  return { query, files, total, truncated, scanned, viaGit: candidates !== null }
434
525
  })
435
526
 
527
+ /** 全项目批量替换(左侧「搜索」面板的替换功能)。只写内容确实变化的文件。 */
528
+ router.method('fs.replace', async (body) => {
529
+ const project = env.projects.ensure(typeof body.root === 'string' ? body.root : '')
530
+ const root = project.root
531
+ const query = typeof body.query === 'string' ? body.query.slice(0, 200) : ''
532
+ const replacement = typeof body.replacement === 'string' ? body.replacement : ''
533
+ if (query === '') return { replacedFiles: [], replacedCount: 0, failed: [], scanned: 0, truncated: false }
534
+ const options = body.options !== null && typeof body.options === 'object' ? body.options : {}
535
+ const caseSensitive = options.caseSensitive === true
536
+ const useRegex = options.regex === true
537
+ const clampInt = (value, fallback, min, max) => {
538
+ const number = Number(value)
539
+ if (!Number.isFinite(number)) return fallback
540
+ return Math.min(Math.max(Math.trunc(number), min), max)
541
+ }
542
+ const maxReplacements = clampInt(body.maxReplacements, 5000, 1, 50000)
543
+ const flags = caseSensitive ? 'g' : 'gi'
544
+ let regex = null
545
+ try {
546
+ regex = new RegExp(useRegex ? query : escapeRegExp(query), flags)
547
+ } catch (error) {
548
+ throw new ApiError('bad-regex', `正则表达式无效:${error.message}`, 400)
549
+ }
550
+ if (useRegex && new RegExp(query, caseSensitive ? '' : 'i').test('')) {
551
+ throw new ApiError('bad-regex', '正则表达式不能匹配空字符串', 400)
552
+ }
553
+ const pathsFilter = Array.isArray(body.paths)
554
+ ? body.paths.filter((item) => typeof item === 'string' && item !== '').slice(0, 200)
555
+ : null
556
+ let candidates = []
557
+ if (pathsFilter !== null) {
558
+ for (const raw of pathsFilter) {
559
+ try {
560
+ const absolute = await resolveProjectPath(root, raw)
561
+ candidates.push(relativePath(root, absolute))
562
+ } catch {
563
+ /* 路径非法/已删除:跳过 */
564
+ }
565
+ }
566
+ } else {
567
+ const listed = await listProjectCandidates(root, project, 20000)
568
+ candidates = listed.files
569
+ }
570
+ const fileSizeLimit = 2 * 1024 * 1024
571
+ const replacedFiles = []
572
+ const failed = []
573
+ let replacedCount = 0
574
+ let truncated = false
575
+ for (const rel of candidates) {
576
+ if (replacedCount >= maxReplacements) {
577
+ truncated = true
578
+ break
579
+ }
580
+ const absolute = join(root, rel)
581
+ const info = await stat(absolute).catch(() => undefined)
582
+ if (info === undefined || !info.isFile() || info.size > fileSizeLimit) continue
583
+ let buffer
584
+ try {
585
+ buffer = await readFile(absolute)
586
+ } catch {
587
+ failed.push(rel)
588
+ continue
589
+ }
590
+ if (buffer.includes(0)) continue
591
+ const text = buffer.toString('utf8')
592
+ regex.lastIndex = 0
593
+ const matches = text.match(regex)
594
+ if (matches === null || matches.length === 0) continue
595
+ if (replacedCount + matches.length > maxReplacements) {
596
+ truncated = true
597
+ break
598
+ }
599
+ let updated
600
+ try {
601
+ updated = text.replace(regex, useRegex ? replacement : () => replacement)
602
+ } catch (error) {
603
+ failed.push(rel)
604
+ continue
605
+ }
606
+ if (updated === text) continue
607
+ try {
608
+ await writeFile(absolute, updated, 'utf8')
609
+ replacedFiles.push(rel)
610
+ replacedCount += matches.length
611
+ } catch {
612
+ failed.push(rel)
613
+ }
614
+ }
615
+ return { replacedFiles, replacedCount, failed, scanned: candidates.length, truncated }
616
+ })
617
+
436
618
  router.method('fs.matchFiles', async (body) => {
437
619
  const root = await projectOf(env, body)
438
620
  const wanted = Array.isArray(body.files)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-gufa-code",
3
- "version": "1.3.62",
3
+ "version": "1.3.63",
4
4
  "description": "古法编程 · AI 辅助:一键把 DSH 主面板变成 VS Code 风格 IDE(Monaco 编辑器、文件树、Git、SSH、真实终端 + 右侧官方会话);主张亲手写、每个改动心中有数,AI 是助理、你是第一责任人",
5
5
  "icon": "icon.svg",
6
6
  "keywords": [
@@ -155,6 +155,36 @@ try {
155
155
  const gitSearch = await call(router, 'fs.search', { root, query: 'answer' })
156
156
  check('search uses git file list', gitSearch.viaGit === true, String(gitSearch.viaGit))
157
157
  check('search finds committed file', gitSearch.files.some((file) => file.path === 'src/main.ts'))
158
+ console.log('fs.replace')
159
+ await call(router, 'fs.create', { root, path: 'replace.txt', kind: 'file' })
160
+ await call(router, 'fs.write', { root, path: 'replace.txt', content: 'foo FOO foo\n' })
161
+ const replaced = await call(router, 'fs.replace', { root, query: 'foo', replacement: 'bar', paths: ['replace.txt'] })
162
+ check('replace count (case-insensitive)', replaced.replacedCount === 3, String(replaced.replacedCount))
163
+ const replacedDoc = await call(router, 'fs.read', { root, path: 'replace.txt' })
164
+ check('replace wrote file', replacedDoc.content === 'bar bar bar\n', JSON.stringify(replacedDoc.content))
165
+ await call(router, 'fs.write', { root, path: 'replace.txt', content: 'v1.2 v3.4\n', expectedRevision: replacedDoc.revision })
166
+ const regexReplaced = await call(router, 'fs.replace', {
167
+ root,
168
+ query: 'v(\\d)\\.(\\d)',
169
+ replacement: 'v$1-$2',
170
+ options: { regex: true },
171
+ paths: ['replace.txt'],
172
+ })
173
+ check('replace regex groups', regexReplaced.replacedCount === 2, String(regexReplaced.replacedCount))
174
+ const regexDoc = await call(router, 'fs.read', { root, path: 'replace.txt' })
175
+ check('replace regex result', regexDoc.content === 'v1-2 v3-4\n', JSON.stringify(regexDoc.content))
176
+ await call(router, 'fs.write', { root, path: 'replace.txt', content: 'abc\n', expectedRevision: regexDoc.revision })
177
+ const literalDollar = await call(router, 'fs.replace', { root, query: 'abc', replacement: '$1', paths: ['replace.txt'] })
178
+ const dollarDoc = await call(router, 'fs.read', { root, path: 'replace.txt' })
179
+ check('literal replacement keeps $', literalDollar.replacedCount === 1 && dollarDoc.content === '$1\n', JSON.stringify(dollarDoc.content))
180
+ let emptyRegexRejected = false
181
+ try {
182
+ await call(router, 'fs.replace', { root, query: 'a*', replacement: 'x', options: { regex: true }, paths: ['replace.txt'] })
183
+ } catch (error) {
184
+ emptyRegexRejected = error.code === 'bad-regex'
185
+ }
186
+ check('replace rejects empty-matching regex', emptyRegexRejected)
187
+ await call(router, 'fs.delete', { root, path: 'replace.txt' })
158
188
  writeFileSync(join(projectDir, 'src/main.ts'), 'const answer = 43\n')
159
189
  const diff = await call(router, 'git.diff', { root, path: 'src/main.ts' })
160
190
  check('diff contains change', diff.patch.includes('43'))
@@ -194,6 +194,16 @@ const DICT_ZH = {
194
194
  'search.summary': '{count} 个结果 · {files} 个文件',
195
195
  'search.truncated': '结果过多已截断,请缩小范围',
196
196
  'search.error': '搜索失败',
197
+ 'search.replaceToggle': '显示/隐藏替换',
198
+ 'search.replacePlaceholder': '替换为…',
199
+ 'search.replaceAll': '全部替换',
200
+ 'search.replaceThisFile': '替换此文件',
201
+ 'search.replacing': '替换中…',
202
+ 'search.replaced': '已替换 {count} 处({files} 个文件)',
203
+ 'search.confirmReplace': '确定替换 {count} 处({files} 个文件)?直接写文件,编辑器撤销无效。',
204
+ 'search.confirmYes': '确定替换',
205
+ 'search.confirmNo': '取消',
206
+ 'search.replaceError': '替换失败',
197
207
  'explorer.empty': '目录为空',
198
208
  'explorer.newFile': '新建文件',
199
209
  'explorer.newFolder': '新建文件夹',
@@ -426,6 +436,16 @@ const DICT_EN = {
426
436
  'search.summary': '{count} results · {files} files',
427
437
  'search.truncated': 'Too many results, truncated — narrow the query',
428
438
  'search.error': 'Search failed',
439
+ 'search.replaceToggle': 'Show / hide replace',
440
+ 'search.replacePlaceholder': 'Replace with…',
441
+ 'search.replaceAll': 'Replace all',
442
+ 'search.replaceThisFile': 'Replace in this file',
443
+ 'search.replacing': 'Replacing…',
444
+ 'search.replaced': 'Replaced {count} occurrences ({files} files)',
445
+ 'search.confirmReplace': 'Replace {count} occurrences in {files} files? This writes files directly; editor undo will not work.',
446
+ 'search.confirmYes': 'Replace',
447
+ 'search.confirmNo': 'Cancel',
448
+ 'search.replaceError': 'Replace failed',
429
449
  'explorer.empty': 'Folder is empty',
430
450
  'explorer.newFile': 'New file',
431
451
  'explorer.newFolder': 'New folder',
@@ -1697,6 +1717,18 @@ html[data-platform=darwin][data-fullscreen] .gufa-titlebar{height:44px;padding-l
1697
1717
  .gufa-search-line{flex:0 0 auto;min-width:24px;text-align:right;font:11px ui-monospace,Menlo,Consolas,monospace;opacity:.65}
1698
1718
  .gufa-search-text{flex:1 1 auto;min-width:0;font:11.5px ui-monospace,Menlo,Consolas,monospace;white-space:pre;overflow:hidden;text-overflow:ellipsis}
1699
1719
  .gufa-search-hit{background:rgba(192,57,43,.38);color:var(--gufa-text);border-radius:2px;padding:0 1px}
1720
+ .gufa-search-replace-row{margin-top:0}
1721
+ .gufa-search-actions{display:flex;align-items:center;gap:6px;margin-top:6px}
1722
+ .gufa-search-action{height:24px;padding:0 9px;border-radius:6px;border:1px solid var(--gufa-border);background:var(--gufa-layer2);color:var(--gufa-text);font-size:11.5px;cursor:pointer}
1723
+ .gufa-search-action:hover:not(:disabled){border-color:var(--gufa-accent)}
1724
+ .gufa-search-action:disabled{opacity:.5;cursor:default}
1725
+ .gufa-search-action[data-primary]{background:var(--gufa-accent);border-color:var(--gufa-accent);color:#fff}
1726
+ .gufa-search-confirm{margin:6px 8px 0;padding:7px 9px;border-radius:7px;border:1px solid var(--gufa-accent);background:color-mix(in srgb, var(--gufa-accent) 12%, transparent);font-size:11.5px;line-height:1.55;color:var(--gufa-text)}
1727
+ .gufa-search-confirm-actions{display:flex;justify-content:flex-end;gap:6px;margin-top:6px}
1728
+ .gufa-search-notice{margin:6px 8px 0;padding:5px 9px;border-radius:7px;font-size:11.5px;color:var(--dsw-alias-state-success-primary);border:1px solid color-mix(in srgb, var(--dsw-alias-state-success-primary) 45%, transparent)}
1729
+ .gufa-search-error{margin:6px 8px 0;padding:5px 9px;border-radius:7px;font-size:11.5px;color:var(--dsw-alias-state-error-primary);border:1px solid color-mix(in srgb, var(--dsw-alias-state-error-primary) 45%, transparent)}
1730
+ .gufa-search-file-replace{flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px;margin-left:2px;border-radius:4px;color:var(--gufa-text-dim);cursor:pointer}
1731
+ .gufa-search-file-replace:hover{background:var(--gufa-active);color:var(--gufa-text)}
1700
1732
 
1701
1733
  .gufa-tree-chevron{width:14px;flex:0 0 auto;opacity:.7;display:flex;align-items:center;justify-content:center}
1702
1734
  .gufa-tree-icon{width:15px;flex:0 0 auto;opacity:.85;display:flex;align-items:center;justify-content:center}
@@ -521,6 +521,12 @@ G.SearchPanel = function SearchPanel(props) {
521
521
  const [result, setResult] = useState(null)
522
522
  const [error, setError] = useState('')
523
523
  const [collapsed, setCollapsed] = useState({})
524
+ const [replaceOpen, setReplaceOpen] = useState(false)
525
+ const [replacement, setReplacement] = useState('')
526
+ const [replacing, setReplacing] = useState(false)
527
+ const [confirming, setConfirming] = useState(null)
528
+ const [replaceError, setReplaceError] = useState('')
529
+ const [notice, setNotice] = useState('')
524
530
  const inputRef = useRef(null)
525
531
  const requestRef = useRef(0)
526
532
 
@@ -565,6 +571,41 @@ G.SearchPanel = function SearchPanel(props) {
565
571
  }
566
572
  }, [root, caseSensitive, regex])
567
573
 
574
+ const requestReplace = useCallback((paths, count, files) => {
575
+ if (typeof root !== 'string' || root === '' || query.trim() === '' || replacing) return
576
+ setReplaceError('')
577
+ setNotice('')
578
+ setConfirming({ paths: Array.isArray(paths) ? paths : null, count: Number(count) || 0, files: Number(files) || 0 })
579
+ }, [root, query, replacing])
580
+
581
+ const doReplace = useCallback(async () => {
582
+ const pending = confirming
583
+ if (pending === null || replacing) return
584
+ setConfirming(null)
585
+ setReplacing(true)
586
+ setReplaceError('')
587
+ setNotice('')
588
+ try {
589
+ await props.onBeforeReplace?.()
590
+ const value = await G.api('fs.replace', {
591
+ root,
592
+ query: query.trim(),
593
+ replacement,
594
+ options: { caseSensitive, regex },
595
+ paths: Array.isArray(pending.paths) ? pending.paths : undefined,
596
+ })
597
+ const count = Number(value?.replacedCount) || 0
598
+ const replacedFiles = Array.isArray(value?.replacedFiles) ? value.replacedFiles : []
599
+ setNotice(t('search.replaced', { count, files: replacedFiles.length }))
600
+ await props.onFilesChanged?.(replacedFiles)
601
+ await runSearch(query)
602
+ } catch (error) {
603
+ setReplaceError(G.errorText(error))
604
+ } finally {
605
+ setReplacing(false)
606
+ }
607
+ }, [confirming, replacing, props.onBeforeReplace, props.onFilesChanged, root, query, replacement, caseSensitive, regex, runSearch, t])
608
+
568
609
  /* 输入防抖搜索(回车立即搜索) */
569
610
  useEffect(() => {
570
611
  if (typeof root !== 'string' || root === '') return undefined
@@ -643,6 +684,22 @@ G.SearchPanel = function SearchPanel(props) {
643
684
  h('span', { className: 'gufa-search-file-name' }, G.basename(file.path)),
644
685
  h('span', { className: 'gufa-search-file-dir' }, G.dirname(file.path)),
645
686
  h('span', { className: 'gufa-search-file-count' }, String(file.matches.length)),
687
+ replaceOpen
688
+ ? h(
689
+ 'span',
690
+ {
691
+ className: 'gufa-search-file-replace',
692
+ title: t('search.replaceThisFile'),
693
+ role: 'button',
694
+ onClick: (event) => {
695
+ event.stopPropagation()
696
+ event.preventDefault()
697
+ requestReplace([file.path], file.matches.length, 1)
698
+ },
699
+ },
700
+ h(G.Icon, { name: 'pencil', size: 11 }),
701
+ )
702
+ : null,
646
703
  ),
647
704
  isCollapsed
648
705
  ? null
@@ -698,6 +755,7 @@ G.SearchPanel = function SearchPanel(props) {
698
755
  query === ''
699
756
  ? null
700
757
  : h(G.IconButton, { title: t('search.clear'), onClick: () => { setQuery(''); focusInput() } }, h(G.Icon, { name: 'close', size: 11 })),
758
+ h(G.IconButton, { title: t('search.replaceToggle'), onClick: () => setReplaceOpen((value) => !value) }, h(G.Icon, { name: replaceOpen ? 'chevron-up' : 'chevron-down', size: 12 })),
701
759
  ),
702
760
  h(
703
761
  'div',
@@ -718,6 +776,60 @@ G.SearchPanel = function SearchPanel(props) {
718
776
  }, '.*'),
719
777
  h('span', { className: 'gufa-search-summary', title: summary }, summary),
720
778
  ),
779
+ replaceOpen
780
+ ? h(
781
+ React.Fragment,
782
+ null,
783
+ h(
784
+ 'div',
785
+ { className: 'gufa-search-input-wrap gufa-search-replace-row' },
786
+ h(G.Icon, { name: 'pencil', size: 12 }),
787
+ h('input', {
788
+ className: 'gufa-search-input',
789
+ type: 'text',
790
+ value: replacement,
791
+ placeholder: t('search.replacePlaceholder'),
792
+ spellCheck: false,
793
+ onChange: (event) => setReplacement(event.target.value),
794
+ onKeyDown: (event) => {
795
+ if (event.key !== 'Enter') return
796
+ event.preventDefault()
797
+ requestReplace(null, result?.total ?? 0, result?.files?.length ?? 0)
798
+ },
799
+ }),
800
+ ),
801
+ h(
802
+ 'div',
803
+ { className: 'gufa-search-actions' },
804
+ h(
805
+ 'button',
806
+ {
807
+ type: 'button',
808
+ className: 'gufa-search-action',
809
+ 'data-primary': '',
810
+ disabled: replacing || result === null || result.total === 0,
811
+ onClick: () => requestReplace(null, result?.total ?? 0, result?.files?.length ?? 0),
812
+ },
813
+ replacing ? t('search.replacing') : t('search.replaceAll'),
814
+ ),
815
+ ),
816
+ )
817
+ : null,
818
+ confirming !== null
819
+ ? h(
820
+ 'div',
821
+ { className: 'gufa-search-confirm' },
822
+ h('div', null, t('search.confirmReplace', { count: confirming.count, files: confirming.files })),
823
+ h(
824
+ 'div',
825
+ { className: 'gufa-search-confirm-actions' },
826
+ h('button', { type: 'button', className: 'gufa-search-action', onClick: () => setConfirming(null) }, t('search.confirmNo')),
827
+ h('button', { type: 'button', className: 'gufa-search-action', 'data-primary': '', onClick: () => void doReplace() }, t('search.confirmYes')),
828
+ ),
829
+ )
830
+ : null,
831
+ notice !== '' ? h('div', { className: 'gufa-search-notice' }, notice) : null,
832
+ replaceError !== '' ? h('div', { className: 'gufa-search-error' }, `${t('search.replaceError')}:${replaceError}`) : null,
721
833
  ),
722
834
  h('div', { className: 'gufa-panel-body gufa-scroll' }, body),
723
835
  )
@@ -608,6 +608,49 @@ G.GufaApp = function GufaApp(props) {
608
608
  }
609
609
  }, [project, patchTab, refreshGit, t])
610
610
 
611
+ /* 搜索面板批量替换前:先把所有未落盘的编辑器缓冲保存掉,避免磁盘旧内容覆盖用户输入 */
612
+ const beforeSearchReplace = useCallback(async () => {
613
+ flushBuffersRef.current?.()
614
+ const pending = new Set(editorBuffersRef.current.keys())
615
+ for (const tab of tabsRef.current ?? []) {
616
+ if (tab !== null && tab !== undefined && tab.dirty === true) pending.add(tab.path)
617
+ }
618
+ for (const path of pending) {
619
+ try {
620
+ await saveFile(path)
621
+ } catch {
622
+ /* 单个保存失败不阻断替换 */
623
+ }
624
+ }
625
+ }, [saveFile])
626
+
627
+ /* 搜索面板替换完成后:刷新目录/Git,并把已打开标签同步成磁盘最新内容 */
628
+ const onSearchFilesChanged = useCallback(async (paths) => {
629
+ if (project !== null && Array.isArray(paths) && paths.length > 0) {
630
+ for (const path of paths.slice(0, 30)) {
631
+ const tab = (tabsRef.current ?? []).find((item) => item !== null && item !== undefined && item.path === path)
632
+ if (tab === undefined) continue
633
+ try {
634
+ const doc = await G.api('fs.read', { root: project.root, path })
635
+ editorBuffersRef.current.delete(path)
636
+ patchTab(path, {
637
+ content: doc.content,
638
+ revision: doc.revision,
639
+ savedRevision: doc.revision,
640
+ savedContent: doc.content,
641
+ dirty: false,
642
+ size: doc.size,
643
+ })
644
+ } catch {
645
+ /* 文件已被删除:忽略 */
646
+ }
647
+ }
648
+ }
649
+ setRefreshToken((token) => token + 1)
650
+ setGitRefreshToken((token) => token + 1)
651
+ void refreshGit()
652
+ }, [project, patchTab, refreshGit])
653
+
611
654
  /** 顶栏提示:错误常驻红色;成功用绿色 toast,1.2 秒后自动消失。 */
612
655
  const successTimerRef = useRef(null)
613
656
  const showBanner = useCallback((text, tone) => {
@@ -2135,6 +2178,8 @@ G.GufaApp = function GufaApp(props) {
2135
2178
  root: project?.root ?? null,
2136
2179
  active: ui.view === 'search',
2137
2180
  onOpenFile: (path, line, column) => void openFileAt(path, line, column),
2181
+ onBeforeReplace: beforeSearchReplace,
2182
+ onFilesChanged: onSearchFilesChanged,
2138
2183
  })),
2139
2184
  h('div', { key: 'git', style: { display: ui.view === 'git' ? 'flex' : 'none', flex: '1 1 auto', minHeight: 0, flexDirection: 'column' } },
2140
2185
  h(G.GitPanel, {