dsh-gufa-code 1.3.61 → 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.
@@ -150,7 +150,21 @@ AI 是通过 Host 工具直接写盘,客户端收不到任何通知。
150
150
  签名变化就自动刷新 Git 面板和资源管理器;非 Git 项目每 6s 静默重读已加载目录。
151
151
  窗口 focus / visibilitychange 时也会立即刷新一次。
152
152
 
153
- ## 5.1 摸鱼会话框比编辑器黑:官方会话根节点自己又画了一层底
153
+ ## 全局搜索(1.3.62 新增)
154
+
155
+ - Host 侧新增 `fs.search`:Git 项目先用 `git ls-files -z --cached --others --exclude-standard` 拿文件清单(快、尊重 .gitignore、含未跟踪文件),非 Git 项目才目录遍历(BFS,跳过 node_modules/dist/.venv 等,明显二进制扩展名直接跳过)。
156
+ - 搜索有时限(12s)与扫描上限(默认 20000 文件 / 500 命中 / 200 文件),超出返回 `truncated: true`,UI 会提示「结果过多已截断」。
157
+ - 结果行带 `line/column/start/end/text`,前端高亮 `start..end`;点击结果通过 `G.bus 'editor:reveal'` 让 Monaco 跳到对应行列(tab 切换未完成时事件先存到 `pendingRevealRef`)。
158
+ - **坑**:往 `G.CSS` 模板里加规则时一定插在完整规则之后。曾把搜索样式插进 `.gufa-explorer-notice{...}` 规则中间,CSS nesting 把整块样式变成后代选择器,面板渲染成原生输入框。插入后检查 `client.js` 里 `.gufa-explorer-notice{...}` 的闭合括号是否在搜索块之前。
159
+
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 摸鱼会话框比编辑器黑:官方会话根节点又自己画了一层底
154
168
 
155
169
  - 现象:摸鱼里编辑器/终端都统一了,右侧会话框看起来明显更黑更实。
156
170
  - 实测(同屏同底层对比法):编辑器有效 alpha=0.570,会话框=0.878 → 会话框多叠了一层 ~0.72 的暗底。
package/host/fs.js CHANGED
@@ -4,7 +4,7 @@
4
4
  */
5
5
  import { createHash, randomUUID } from 'node:crypto'
6
6
  import { createReadStream } from 'node:fs'
7
- import { access, cp, lstat, mkdir, open, readdir, realpath, rename, rm, stat, writeFile } from 'node:fs/promises'
7
+ import { access, cp, lstat, mkdir, open, readFile, readdir, realpath, rename, rm, stat, writeFile } from 'node:fs/promises'
8
8
  import { execFile } from 'node:child_process'
9
9
  import { promisify } from 'node:util'
10
10
  import { constants } from 'node:fs'
@@ -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)
@@ -241,6 +332,289 @@ export function register(router, env) {
241
332
  })
242
333
 
243
334
  /** 把系统剪贴板里的文件匹配回项目内已有文件(供聊天框「粘贴文件→@引用」使用)。 */
335
+ /** 全项目文本搜索(左侧「搜索」面板用)。返回按文件分组、带上行列号的匹配。 */
336
+ router.method('fs.search', async (body) => {
337
+ const project = env.projects.ensure(typeof body.root === 'string' ? body.root : '')
338
+ const root = project.root
339
+ const rawQuery = typeof body.query === 'string' ? body.query : ''
340
+ const query = rawQuery.slice(0, 200)
341
+ if (query === '') return { query: '', files: [], total: 0, truncated: false, scanned: 0, viaGit: false }
342
+ const options = body.options !== null && typeof body.options === 'object' ? body.options : {}
343
+ const caseSensitive = options.caseSensitive === true
344
+ const useRegex = options.regex === true
345
+ const clampInt = (value, fallback, min, max) => {
346
+ const number = Number(value)
347
+ if (!Number.isFinite(number)) return fallback
348
+ return Math.min(Math.max(Math.trunc(number), min), max)
349
+ }
350
+ const maxFiles = clampInt(options.maxFiles, 200, 1, 500)
351
+ const maxMatches = clampInt(options.maxMatches, 500, 1, 2000)
352
+ const maxScanned = clampInt(options.maxScanned, 20000, 100, 100000)
353
+ const fileSizeLimit = 2 * 1024 * 1024
354
+ const timeBudget = 12000
355
+ const startedAt = Date.now()
356
+ let regex = null
357
+ let needle = ''
358
+ if (useRegex) {
359
+ try {
360
+ regex = new RegExp(query, caseSensitive ? 'g' : 'gi')
361
+ } catch (error) {
362
+ throw new ApiError('bad-regex', `正则表达式无效:${error.message}`, 400)
363
+ }
364
+ } else {
365
+ needle = caseSensitive ? query : query.toLowerCase()
366
+ }
367
+ const EXCLUDED = new Set([
368
+ 'node_modules', '.git', 'dist', 'build', 'out', '.next', 'vendor', 'target', '.venv', 'venv',
369
+ '__pycache__', '.idea', '.cache', '.turbo', '.parcel-cache', '.svelte-kit', '.nuxt', '.output',
370
+ 'coverage', '.gradle', 'DerivedData', 'Pods', '.tox', '.mypy_cache', '.pytest_cache', '.ruff_cache',
371
+ '.electron-cache', '.npm-cache', '.pip-cache', '.yarn', '.pnpm-store', '.pnpm',
372
+ ])
373
+ /* 明显是二进制的扩展名:不读文件,避免把大量图片/压缩包计入扫描数 */
374
+ const SKIP_EXT = new Set([
375
+ 'png', 'jpg', 'jpeg', 'gif', 'webp', 'ico', 'icns', 'bmp', 'tiff', 'pdf', 'zip', 'gz', 'tgz', 'tar', '7z', 'rar', 'dmg', 'iso',
376
+ 'mp4', 'mp3', 'wav', 'mov', 'avi', 'mkv', 'flac', 'jar', 'class', 'o', 'a', 'so', 'dylib', 'dll', 'exe', 'bin', 'dat',
377
+ 'woff', 'woff2', 'ttf', 'otf', 'eot', 'wasm', 'pyc', 'node',
378
+ ])
379
+ const extensionOf = (rel) => {
380
+ const base = String(rel).split('/').pop() ?? ''
381
+ const dot = base.lastIndexOf('.')
382
+ return dot <= 0 ? '' : base.slice(dot + 1).toLowerCase()
383
+ }
384
+ const files = []
385
+ let total = 0
386
+ let scanned = 0
387
+ let truncated = false
388
+ const readMatches = (line) => {
389
+ const raw = []
390
+ if (regex !== null) {
391
+ regex.lastIndex = 0
392
+ let match
393
+ while ((match = regex.exec(line)) !== null) {
394
+ if (match[0].length === 0) {
395
+ regex.lastIndex += 1
396
+ continue
397
+ }
398
+ raw.push([match.index, match.index + match[0].length])
399
+ if (raw.length >= 50) break
400
+ }
401
+ return raw
402
+ }
403
+ const haystack = caseSensitive ? line : line.toLowerCase()
404
+ let from = 0
405
+ while (raw.length < 50) {
406
+ const index = haystack.indexOf(needle, from)
407
+ if (index === -1) break
408
+ raw.push([index, index + needle.length])
409
+ from = index + Math.max(needle.length, 1)
410
+ }
411
+ return raw
412
+ }
413
+ const searchFile = async (rel) => {
414
+ const absolute = join(root, rel)
415
+ const info = await stat(absolute).catch(() => undefined)
416
+ if (info === undefined || !info.isFile() || info.size > fileSizeLimit) return []
417
+ let buffer
418
+ try {
419
+ buffer = await readFile(absolute)
420
+ } catch {
421
+ return []
422
+ }
423
+ if (buffer.includes(0)) return []
424
+ const lines = buffer.toString('utf8').split(/\r?\n/)
425
+ const matches = []
426
+ for (let index = 0; index < lines.length && matches.length < 50; index += 1) {
427
+ const line = lines[index]
428
+ for (const range of readMatches(line)) {
429
+ if (matches.length >= 50 || total >= maxMatches) break
430
+ const WINDOW = 300
431
+ const windowStart = line.length > WINDOW ? Math.max(0, Math.min(line.length - WINDOW, range[0] - 80)) : 0
432
+ matches.push({
433
+ line: index + 1,
434
+ column: range[0] + 1,
435
+ start: range[0] - windowStart,
436
+ end: range[1] - windowStart,
437
+ text: line.slice(windowStart, windowStart + WINDOW),
438
+ })
439
+ total += 1
440
+ }
441
+ }
442
+ return matches
443
+ }
444
+ const acceptFile = async (rel) => {
445
+ const matches = await searchFile(rel)
446
+ if (matches.length === 0) return
447
+ files.push({ path: rel, matches })
448
+ }
449
+ /* Git 项目用 git ls-files 拿文件清单(快、尊重 .gitignore、包含未跟踪文件);
450
+ 非 Git 项目才走目录遍历。 */
451
+ let isGitRepo = project.isGit === true
452
+ if (!isGitRepo) {
453
+ try {
454
+ const dotGit = await stat(join(root, '.git'))
455
+ isGitRepo = dotGit.isDirectory() || dotGit.isFile()
456
+ } catch {
457
+ isGitRepo = false
458
+ }
459
+ }
460
+ let candidates = null
461
+ if (isGitRepo) {
462
+ try {
463
+ const { stdout } = await runCommand('git', ['ls-files', '-z', '--cached', '--others', '--exclude-standard'], {
464
+ cwd: root,
465
+ maxBuffer: 64 * 1024 * 1024,
466
+ timeout: 15000,
467
+ })
468
+ candidates = stdout.split('\0').filter((item) => item !== '')
469
+ candidates.sort((a, b) => a.localeCompare(b))
470
+ } catch {
471
+ candidates = null
472
+ }
473
+ }
474
+ if (candidates !== null) {
475
+ for (const rel of candidates) {
476
+ if (files.length >= maxFiles || total >= maxMatches || scanned >= maxScanned || Date.now() - startedAt > timeBudget) {
477
+ truncated = true
478
+ break
479
+ }
480
+ if (SKIP_EXT.has(extensionOf(rel))) continue
481
+ scanned += 1
482
+ await acceptFile(rel)
483
+ }
484
+ if (!truncated && files.length >= maxFiles) truncated = true
485
+ } else {
486
+ const queue = ['']
487
+ let head = 0
488
+ while (head < queue.length) {
489
+ if (files.length >= maxFiles || total >= maxMatches || scanned >= maxScanned || Date.now() - startedAt > timeBudget) {
490
+ truncated = true
491
+ break
492
+ }
493
+ const dirRel = queue[head]
494
+ head += 1
495
+ let entries
496
+ try {
497
+ entries = await readdir(join(root, dirRel), { withFileTypes: true })
498
+ } catch {
499
+ continue
500
+ }
501
+ entries.sort((a, b) => String(a.name).localeCompare(String(b.name)))
502
+ for (const entry of entries) {
503
+ if (entry.isDirectory()) {
504
+ if (!EXCLUDED.has(entry.name) && !SEARCH_EXCLUDE_PREFIXES.some((prefix) => entry.name.startsWith(prefix))) queue.push(dirRel === '' ? entry.name : `${dirRel}/${entry.name}`)
505
+ continue
506
+ }
507
+ if (!entry.isFile() || EXCLUDED.has(entry.name)) continue
508
+ const rel = dirRel === '' ? entry.name : `${dirRel}/${entry.name}`
509
+ if (SKIP_EXT.has(extensionOf(rel))) continue
510
+ if (scanned >= maxScanned) {
511
+ truncated = true
512
+ break
513
+ }
514
+ scanned += 1
515
+ await acceptFile(rel)
516
+ if (files.length >= maxFiles || total >= maxMatches) {
517
+ truncated = true
518
+ break
519
+ }
520
+ }
521
+ }
522
+ }
523
+ files.sort((a, b) => a.path.localeCompare(b.path))
524
+ return { query, files, total, truncated, scanned, viaGit: candidates !== null }
525
+ })
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
+
244
618
  router.method('fs.matchFiles', async (body) => {
245
619
  const root = await projectOf(env, body)
246
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.61",
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": [
@@ -252,6 +252,7 @@ if (windowStub.__GUFA_CODE__?.G?.shortcutAction !== undefined) {
252
252
  G0.shortcutAction(mod({ key: 'e', code: 'KeyE', shiftKey: true })) === 'panelExplorer' &&
253
253
  G0.shortcutAction(mod({ key: 'g', code: 'KeyG', shiftKey: true })) === 'panelGit' &&
254
254
  G0.shortcutAction(mod({ key: 'h', code: 'KeyH', shiftKey: true })) === 'panelSsh')
255
+ check('shortcut: Cmd/Ctrl+Shift+F = panelSearch', G0.shortcutAction(mod({ key: 'f', code: 'KeyF', shiftKey: true })) === 'panelSearch')
255
256
  check('shortcut: Shift+Cmd/Ctrl+` = newTerminal', G0.shortcutAction(mod({ code: 'Backquote', shiftKey: true })) === 'newTerminal')
256
257
  check('shortcut: Cmd/Ctrl+/ = shortcuts help', G0.shortcutAction(mod({ key: '/', code: 'Slash' })) === 'shortcuts')
257
258
  check('shortcut: no modifier ignored', G0.shortcutAction({ ...base, key: 'k', code: 'KeyK' }) === null)
@@ -111,6 +111,32 @@ try {
111
111
  const afterDelete = await call(router, 'fs.list', { root, path: 'src' })
112
112
  check('delete applied', !afterDelete.entries.some((entry) => entry.name === 'helper.ts'))
113
113
 
114
+ console.log('fs.search')
115
+ await call(router, 'fs.create', { root, path: 'search.txt', kind: 'file' })
116
+ await call(router, 'fs.write', { root, path: 'search.txt', content: 'Alpha beta\nBETA gamma\nbeta BETA\n' })
117
+ await call(router, 'fs.create', { root, path: 'node_modules', kind: 'dir' }).catch(() => {})
118
+ await call(router, 'fs.create', { root, path: 'node_modules/hidden.txt', kind: 'file' }).catch(() => {})
119
+ await call(router, 'fs.write', { root, path: 'node_modules/hidden.txt', content: 'beta hidden\n' }).catch(() => {})
120
+ const searchAll = await call(router, 'fs.search', { root, query: 'beta' })
121
+ check('search finds file', searchAll.files.some((file) => file.path === 'search.txt'))
122
+ check('search total (case-insensitive)', searchAll.total === 4, String(searchAll.total))
123
+ check('search excludes node_modules', !searchAll.files.some((file) => file.path.startsWith('node_modules/')))
124
+ const searchFile = searchAll.files.find((file) => file.path === 'search.txt')
125
+ check('search line numbers', searchFile.matches[0].line === 1 && searchFile.matches[0].column === 7, JSON.stringify(searchFile.matches[0]))
126
+ const searchCased = await call(router, 'fs.search', { root, query: 'beta', options: { caseSensitive: true } })
127
+ check('search case sensitive', searchCased.total === 2, String(searchCased.total))
128
+ const searchRegex = await call(router, 'fs.search', { root, query: 'b(eta|ETA)', options: { regex: true } })
129
+ check('search regex', searchRegex.total === 4, String(searchRegex.total))
130
+ let badRegex = false
131
+ try {
132
+ await call(router, 'fs.search', { root, query: '([', options: { regex: true } })
133
+ } catch (error) {
134
+ badRegex = error.code === 'bad-regex'
135
+ }
136
+ check('search invalid regex rejected', badRegex)
137
+ await call(router, 'fs.delete', { root, path: 'search.txt' }).catch(() => {})
138
+ await call(router, 'fs.delete', { root, path: 'node_modules' }).catch(() => {})
139
+
114
140
  console.log('git.status / stage / commit')
115
141
  execFileSync('git', ['init', '-q'], { cwd: projectDir })
116
142
  execFileSync('git', ['config', 'user.email', 'selftest@example.com'], { cwd: projectDir })
@@ -126,6 +152,39 @@ try {
126
152
  check('working tree clean after commit', clean.changes.length === 0, JSON.stringify(clean.changes))
127
153
  const log = await call(router, 'git.log', { root, limit: 5 })
128
154
  check('commit in log', log.commits.length === 1 && log.commits[0].subject === 'feat: selftest')
155
+ const gitSearch = await call(router, 'fs.search', { root, query: 'answer' })
156
+ check('search uses git file list', gitSearch.viaGit === true, String(gitSearch.viaGit))
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' })
129
188
  writeFileSync(join(projectDir, 'src/main.ts'), 'const answer = 43\n')
130
189
  const diff = await call(router, 'git.diff', { root, path: 'src/main.ts' })
131
190
  check('diff contains change', diff.patch.includes('43'))
@@ -112,6 +112,7 @@ const DICT_ZH = {
112
112
  'shortcuts.toggleSidebar': '显示 / 隐藏左侧栏',
113
113
  'shortcuts.closeTab': '关闭当前标签页',
114
114
  'shortcuts.explorer': '聚焦资源管理器',
115
+ 'shortcuts.search': '聚焦全局搜索',
115
116
  'shortcuts.git': '聚焦源代码管理',
116
117
  'shortcuts.ssh': '聚焦 SSH 主机',
117
118
  'shortcuts.newTerminal': '新建终端',
@@ -176,12 +177,33 @@ const DICT_ZH = {
176
177
  'app.manualPath': '或直接输入路径',
177
178
  'app.pathPlaceholder': '例如 /Users/me/project',
178
179
  'activity.explorer': '资源管理器',
180
+ 'activity.search': '搜索',
179
181
  'activity.git': '源代码管理',
180
182
  'activity.ssh': 'SSH 远程',
181
183
  'activity.terminal': '终端',
182
184
  'activity.chat': '古法 AI 助手',
183
185
  'activity.collapseChat': '收起 AI 面板',
184
186
  'activity.expandChat': '展开 AI 面板',
187
+ 'search.placeholder': '搜索项目中的文本,回车立即搜索',
188
+ 'search.caseSensitive': '区分大小写',
189
+ 'search.regex': '使用正则表达式',
190
+ 'search.clear': '清空搜索',
191
+ 'search.searching': '搜索中…',
192
+ 'search.idle': '输入关键字搜索整个项目',
193
+ 'search.noResult': '没有找到匹配结果',
194
+ 'search.summary': '{count} 个结果 · {files} 个文件',
195
+ 'search.truncated': '结果过多已截断,请缩小范围',
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': '替换失败',
185
207
  'explorer.empty': '目录为空',
186
208
  'explorer.newFile': '新建文件',
187
209
  'explorer.newFolder': '新建文件夹',
@@ -341,6 +363,7 @@ const DICT_EN = {
341
363
  'shortcuts.toggleSidebar': 'Toggle sidebar',
342
364
  'shortcuts.closeTab': 'Close current tab',
343
365
  'shortcuts.explorer': 'Focus explorer',
366
+ 'shortcuts.search': 'Focus search',
344
367
  'shortcuts.git': 'Focus source control',
345
368
  'shortcuts.ssh': 'Focus SSH hosts',
346
369
  'shortcuts.newTerminal': 'New terminal',
@@ -396,12 +419,33 @@ const DICT_EN = {
396
419
  'app.manualPath': 'Or type a path',
397
420
  'app.pathPlaceholder': 'e.g. /Users/me/project',
398
421
  'activity.explorer': 'Explorer',
422
+ 'activity.search': 'Search',
399
423
  'activity.git': 'Source control',
400
424
  'activity.ssh': 'SSH',
401
425
  'activity.terminal': 'Terminal',
402
426
  'activity.chat': 'Gufa AI',
403
427
  'activity.collapseChat': 'Collapse AI panel',
404
428
  'activity.expandChat': 'Expand AI panel',
429
+ 'search.placeholder': 'Search text across the project (Enter to run)',
430
+ 'search.caseSensitive': 'Match case',
431
+ 'search.regex': 'Use regular expression',
432
+ 'search.clear': 'Clear search',
433
+ 'search.searching': 'Searching…',
434
+ 'search.idle': 'Type a keyword to search the whole project',
435
+ 'search.noResult': 'No matches found',
436
+ 'search.summary': '{count} results · {files} files',
437
+ 'search.truncated': 'Too many results, truncated — narrow the query',
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',
405
449
  'explorer.empty': 'Folder is empty',
406
450
  'explorer.newFile': 'New file',
407
451
  'explorer.newFolder': 'New folder',
@@ -1651,6 +1695,41 @@ html[data-platform=darwin][data-fullscreen] .gufa-titlebar{height:44px;padding-l
1651
1695
  .gufa-explorer-notice{margin:4px 10px 0;padding:3px 8px;border-radius:6px;font-size:11px;line-height:1.5;color:var(--gufa-text);
1652
1696
  background:color-mix(in srgb, var(--gufa-accent) 14%, transparent);border:0.5px solid color-mix(in srgb, var(--gufa-accent) 40%, transparent);
1653
1697
  overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1698
+ /* ── 搜索面板(全局文本搜索) ───────────────────────────────────────── */
1699
+ .gufa-search-bar{display:flex;flex-direction:column;gap:6px;padding:6px 8px;border-bottom:1px solid var(--gufa-border);flex:0 0 auto}
1700
+ .gufa-search-input-wrap{display:flex;align-items:center;gap:6px;height:28px;padding:0 8px;border-radius:7px;border:1px solid var(--gufa-border);background:var(--gufa-layer2);color:var(--gufa-text-dim)}
1701
+ .gufa-search-input-wrap:focus-within{border-color:var(--gufa-accent)}
1702
+ .gufa-search-input{flex:1 1 auto;min-width:0;height:100%;border:0;background:transparent;color:var(--gufa-text);font-size:12px;outline:none}
1703
+ .gufa-search-input::placeholder{color:var(--gufa-text-dim)}
1704
+ .gufa-search-toggles{display:flex;align-items:center;gap:5px;min-height:22px}
1705
+ .gufa-search-toggle{height:22px;min-width:25px;padding:0 5px;border-radius:5px;border:1px solid var(--gufa-border);background:transparent;color:var(--gufa-text-dim);font:600 11px ui-monospace,Menlo,Consolas,monospace;cursor:pointer}
1706
+ .gufa-search-toggle:hover{color:var(--gufa-text);background:var(--gufa-hover)}
1707
+ .gufa-search-toggle[data-active]{background:var(--gufa-accent);border-color:var(--gufa-accent);color:#fff}
1708
+ .gufa-search-summary{margin-left:auto;font-size:11px;color:var(--gufa-text-dim);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
1709
+ .gufa-search-file{margin:0 6px}
1710
+ .gufa-search-file-head{display:flex;align-items:center;gap:5px;width:100%;height:24px;padding:0 6px;border:0;background:transparent;color:var(--gufa-text);border-radius:5px;cursor:pointer;text-align:left}
1711
+ .gufa-search-file-head:hover{background:var(--gufa-hover)}
1712
+ .gufa-search-file-name{flex:0 0 auto;max-width:55%;font-size:12px;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1713
+ .gufa-search-file-dir{flex:1 1 auto;min-width:0;font-size:10.5px;color:var(--gufa-text-dim);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1714
+ .gufa-search-file-count{flex:0 0 auto;font-size:10.5px;color:var(--gufa-text-dim);border:1px solid var(--gufa-border);border-radius:999px;padding:0 6px;line-height:15px}
1715
+ .gufa-search-match{display:flex;align-items:baseline;gap:8px;width:100%;padding:2px 6px 2px 24px;border:0;background:transparent;color:var(--gufa-text-dim);cursor:pointer;border-radius:5px;text-align:left}
1716
+ .gufa-search-match:hover{background:var(--gufa-hover);color:var(--gufa-text)}
1717
+ .gufa-search-line{flex:0 0 auto;min-width:24px;text-align:right;font:11px ui-monospace,Menlo,Consolas,monospace;opacity:.65}
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}
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)}
1732
+
1654
1733
  .gufa-tree-chevron{width:14px;flex:0 0 auto;opacity:.7;display:flex;align-items:center;justify-content:center}
1655
1734
  .gufa-tree-icon{width:15px;flex:0 0 auto;opacity:.85;display:flex;align-items:center;justify-content:center}
1656
1735
  .gufa-tree-badge{font-size:10px;color:var(--gufa-accent);flex:0 0 auto;font-weight:600}