fix(fs-search): direct-open for pasted paths + fragment path matching (#879)

A query carrying a path separator can never match an entry NAME — names
never contain separators — so pasting any path into the search box was
structurally guaranteed to return {matches:[],truncated:true} while the
walk burned its full 100k-visit budget (measured: 1.9s on a Rust repo
whose two worktree forests alone held 97k entries; real directories were
never reached).

searchFiles now routes by query shape, all three modalities sharing one
result contract:

- A query naming one path (absolute, ~/…, ./x, ../x) resolves through
  resolveTarget — the SAME primitive fs.read uses, so ~ expands (#713),
  dot-anchored spellings join onto the session cwd, and win32
  WSL/dsh-remote namespaces reinterpret — then stats the target. The hit
  is the RESOLVED path (resolve() strips shell-completion trailing
  separators, which the client's exact-string row comparisons could never
  match); a missing target answers empty immediately. Directory targets
  ride the #801 dirs contract. The exclude pref does not apply: a pasted
  path is explicit intent, same as the fs.read the click performs.
- A separator-carrying relative fragment (records/exp1) matches by
  root-relative PATH in the walk; the engines are name matchers (fd has
  no --full-path here, rg's globs are single-segment) so argv
  construction is untouched.
- Plain name queries are unchanged, and no NAME query is stolen: on
  POSIX a backslash is a name character (the ~\ gesture counts only on
  win32; util.ts~ / ~$doc.docx / .env stay name queries).

SKIP_DIR_NAMES gains the budget-eating forests seen in the wild:
.worktrees/.worktree (git worktree layouts), target, venv/.venv and
__pycache__ — shared by the walk and both engine argvs as before.

Client: a directory hit OUTSIDE the cwd (newly reachable via the paste
branch) only clears the query — the tree is cwd-rooted, and the old
ancestorDirs call synthesized junk expanded entries for foreign paths.

Verified: vitest fs-search/smoke/search-persist suites green; full run
2171 passed with one failure proven pre-existing on the clean tree
(git.spec checkout case, host git lacks --end-of-options; #841);
typecheck/lint clean.
This commit is contained in:
NolanHo committed 2026-10-06 08:25:30 -07:00
1 parent 4e51e0789c
commit 0d9fee85b8
12 files changed
+471 -56

No files matched your search

+3
View File
@@ -4,6 +4,9 @@
### Unreleased
- 🔎 **搜索框支持直接粘贴路径:指名路径 stat 直开、相对片段按路径匹配**([#879](https://github.com/omdsh-dev/DSH-better-sidebar/issues/879)):`fs.search` 之前把整个输入当作文件名子串在整个 cwd 树里递归匹配——文件名永不包含分隔符,所以粘贴任何带 `/` 的路径都是**结构性零命中**,却仍烧满 10 万条访问预算(实测含 worktree 森林的 Rust 仓库上 1.9s 返回 `{matches:[],truncated:true}`,工作区外文件如 `/tmp` 下的实验产物图因此在右侧无从预览)。现在 `searchFiles` 按查询形态分流:**指名单一目标的 query(绝对路径、`~/…`、`./x`、`../x`)经 `resolveTarget`——与 fs.read 同一解析原语(`~` 展开 #713、会话 cwd 拼接、win32 WSL/dsh-remote 命名空间改写、词法 resolve)——stat 直取**,命中返回**解析后的绝对路径**(resolve 剥掉 shell 补全带的尾分隔符;客户端对匹配行与树行做精确字符串比对,客户端 `resolveSidebarPath` 对绝对路径透传,TreePanel 现有点击链路零改动即可打开),目录目标按 #801 契约同列 `dirs`(行内树导航而非按文件打开;**工作区外的目录命中行只清空查询**——树以 cwd 为根,没有可导航的行,客户端守卫同时避免了 `ancestorDirs` 为外部路径合成垃圾 `expanded` 条目),目标缺失立即返回空结果(不再烧预算换一个注定为空的遍历);**含分隔符的相对片段按根相对路径匹配**(大小写不敏感,Windows 两种分隔符都收;同名文件消歧正是 #306 的诉求)。引擎不参与路径分支——fd 的 `--fixed-strings` 不带 `--full-path`、rg 的三个 glob 以单路径段为匹配单元,路径语义由遍历独占,引擎 argv 构造零改动(新 skip 名仍由 `SKIP_DIR_NAMES` 派生进 fd `--exclude` / rg glob,`check:engines` 门禁不受影响)。用户 exclude 列表不作用于直开分支:粘贴路径是显式意图,与点击后的 `fs.read` 行为一致(fs.read 同样不应用 exclude)。POSIX 上 `\` 仍是文件名合法字符而非分隔符(`~\foo` 形态仅在 win32 计入路径手势);单独的 `~` 按客户端 `isAbsolutePath` 的口径视为指名 home 目录,其余不带分隔符的 `~`/点前缀拼写(`util.ts~`、`~$doc.docx`、`.env`)仍是名字查询,引擎资格不受影响。
- 🧹 **噪声目录名单补 worktree 森林与语言环境**:`SKIP_DIR_NAMES` 增加 `.worktrees` / `.worktree`(两种 git worktree 布局拼写,`.worktrees/` 正是 DeepSeek Harness 自己的约定)、`target`(Rust / Maven 构建产物)、`venv` / `.venv` / `__pycache__`(Python 环境与字节码缓存)——此前两片 worktree 森林实测可烧掉 100k 预算的 97k,真实目录从未被遍历、`truncated` 恒真。walk 与两条引擎 argv 共用同一名单(fd `--exclude` 与 rg glob 对自动派生),引擎与遍历的跳过行为保持一致。
- 🧪 测试:`tests/fs-search.spec.ts` 新增 9 条——路径片段匹配(深度无关 / 大小写 / 目录行的 dirs 拆分 / 噪声围栏照常生效)、直开分支(文件与目录目标、目标缺失即空且 `maxVisited:1` 下仍 `truncated:false` 钉住「未走遍历」、尾分隔符 / `./` / `../` / `~` 经 `resolveTarget` 解析后返回解析路径)、`probed===false` 证明路径分支不触引擎、不带分隔符的 `~`/点前缀拼写仍是名字查询(引擎资格保持)、分隔符 query 不进引擎(假引擎返回污染行判别)、POSIX 反斜杠名字(探针式 skipIf 只在名字可存在的平台运行)、worktree/语言环境森林不进入;`tests/smoke.spec.ts` 新增 1 条路由级用例(绝对命中 / 立即空结果 / 相对片段 / `./` 锚定解析四态穿真实 mount);`tests/file-tree-search-persist.spec.tsx` 新增 1 条(工作区外目录命中行只清空查询、不触发任何 toggle)。判别性:还原 `fs-search.ts` 的分支即红(引擎污染行会浮出来);还原 skip 名单即红(森林内的 guide.md 命中);拿掉客户端守卫即红(外部路径的垃圾 toggle 浮出)。
- 🪟 **修掉 CRLF 行尾文件在预览里的三层 `\r` 误判与「预览渲染两遍」(ci-windows 上暴露)**:Windows 检出下 README 的锚点用例全红,根因不是 slug 而是① `markdown-html.ts` 的 `isBlank`、`mermaid-blocks.ts` 的 `CLOSE_FENCE_RE`、`markdown-code.ts` 的 `closesFence` 都把行尾的 `\r` 当内容——于是 **HTML 段永不终止**(实测 `splitHtmlBlocks(README.md)`:LF 36 段 vs CRLF **4 段**,`# b` 被当原始 HTML 文字渲染)、**mermaid 围栏吞掉文件余下部分**、**链接改写从第一个围栏起全部失效**(首个分歧在第 16883 字节);② `TextEditor` 的 draft 快照把 CodeMirror 归一化后的 LF 文档在挂载后一个 commit 发布出去,`previewMdText` 从 CRLF 翻成 LF,宿主 `MarkdownText` 于是重建了文本变化的标题节点——挂载那一趟写入的 **26/26 个 id 被丢弃**(断言时只剩 7/26、13/15 个 TOC 锚点 `id=missing`),MutationObserver 一个微任务后才自愈。现已把 draft 定义成「编辑」:与已加载正文逐字节相等(或行尾归一后相等)时不发布。
- 🧪 测试:新增 `tests/markdown-crlf.spec.ts`(7 条 **CRLF ≡ LF** 不变式,覆盖分段器 / mask / 两个改写器 / mermaid 分段器)与两条真实渲染器用例(含把 `README.md` **在内存里**转成 CRLF,让 ubuntu / macOS lane 也跑 Windows 的拼写);测试脚手架 `scanDocumentAnchors` 改为 CRLF 安全(实测 CRLF 标题 0 → 26)。判别性:还原三个扫描文件 → 9 条红;还原 `TextEditor` → CRLF 检出下 2 条红(即 CI 原症状)。
- 📝 **已知未修(另立 [#871](https://github.com/omdsh-dev/DSH-better-sidebar/issues/871))**:同一归一化意味着**保存会把 CRLF 文件写成 LF**(一次内容修改变成整文件 diff),需要产品取舍;本轮只修读取侧。
+1 -1
View File
@@ -48,7 +48,7 @@
相比 DSH 官方侧边栏,本插件补上的关键能力:
- **🖥️ 可编辑的代码编辑器**:官方文档预览是**只读**的 → 插件保留**可编辑**的 CodeMirror 编辑器(保存、语法高亮、预览切换);Markdown / HTML 也走插件自有渲染(Mermaid 图表安全渲染 + 点击放大、README 级内嵌 HTML、浮动目录大纲、HTML 沙箱预览)
- **🗂️ 增强文件树**:接管内置「文件」页——懒加载目录树、**展开的目录实时 watch 自动刷新**、软链接识别、全局文件名搜索、拖拽上传、悬浮 `@文件` 一键引用进输入框;**Ctrl/Cmd 多选 + Shift 连选**(批量复制路径 / 批量删除)、**Git 变更着色 + 状态字母**(VS Code 同款)、**新建文件夹 / 新建文件**(行内输入;服务端拒绝非法名、Windows 保留设备名与已存在的目标,绝不截断同名文件)、**排序**(名称 / 类型 + 文件夹优先开关,默认与宿主原有顺序一致)、**多选右键「压缩并打包下载」**(服务端流式打 ZIP,无第三方依赖);右键「打开方式」= **DSH 自带 open-in-app**(宿主探测到的本机关联应用 + 文件管理器显示)**+ 插件自研打开方式**(资源管理器 / VS Code / Cursor / Zed / 自定义编辑器 URL 模板、SSH 远端、固定到菜单)两者并存
- **🗂️ 增强文件树**:接管内置「文件」页——懒加载目录树、**展开的目录实时 watch 自动刷新**、软链接识别、全局文件名搜索(**粘贴绝对路径直开、相对路径按路径匹配**)、拖拽上传、悬浮 `@文件` 一键引用进输入框;**Ctrl/Cmd 多选 + Shift 连选**(批量复制路径 / 批量删除)、**Git 变更着色 + 状态字母**(VS Code 同款)、**新建文件夹 / 新建文件**(行内输入;服务端拒绝非法名、Windows 保留设备名与已存在的目标,绝不截断同名文件)、**排序**(名称 / 类型 + 文件夹优先开关,默认与宿主原有顺序一致)、**多选右键「压缩并打包下载」**(服务端流式打 ZIP,无第三方依赖);右键「打开方式」= **DSH 自带 open-in-app**(宿主探测到的本机关联应用 + 文件管理器显示)**+ 插件自研打开方式**(资源管理器 / VS Code / Cursor / Zed / 自定义编辑器 URL 模板、SSH 远端、固定到菜单)两者并存
- **🌿 文件变动**(官方侧栏没有 Git 面板):Git 视角(暂存 / 提交 / 历史 / 工作树与子仓库)+ 本轮 AI 改动视角双合一,统一 diff 渲染(行内字符级高亮、语法着色、敏感内容脱敏);两视角共用一套 28px 行、单一空态/错误通道与吸底提交条
- **🧩 任务管理**(官方没有):子代理拓扑实时预览 + 后台任务清单(退出码 / 实时输出 / 强制终止)
- **💬 侧边对话**(官方没有,beta):Codex 风格侧边线程——继承主会话完整上下文独立运行,可持续追问,一键提升为顶层会话
+1 -1
View File
@@ -48,7 +48,7 @@
What this plugin adds on top of DSH's stock sidebar:
- **✏️ Editable editor**: the host's document preview is **read-only** → the plugin keeps an **editable** CodeMirror editor (save, syntax highlighting, preview toggle); Markdown / HTML also render through the plugin's own pipeline (Mermaid diagrams with safe rendering + click-to-zoom, README-level inline HTML, floating table of contents, sandboxed HTML preview)
- **🗂️ Enhanced file tree**: takes over the built-in Files page — lazy-loading tree, **expanded directories watched live and auto-refreshed**, symlink awareness, global filename search, drag-and-drop upload, hover `@file` to drop a reference into the input box; **Ctrl/Cmd multi-select and Shift range-select** (copy or delete a batch), **VS Code-style git status colors + M/A/D/U letters**, **new folder / new file** (inline editor; the server refuses illegal names, Windows reserved device names and an existing destination — a same-named file is never truncated), **sorting** (by name / by type, plus a folders-first switch; the default is the host's own order), **multi-select “Zip and download”** (the host streams a ZIP built with no third-party dependency), and an “Open with” menu that COMBINES DSH’s own open-in-app (the host’s probed OS handlers + file-manager reveal) with the plugin’s own targets (file manager / VS Code / Cursor / Zed / custom editor URL templates, SSH remotes, pin-to-menu)
- **🗂️ Enhanced file tree**: takes over the built-in Files page — lazy-loading tree, **expanded directories watched live and auto-refreshed**, symlink awareness, global filename search (**paste an absolute path to open it directly; relative paths match by path**), drag-and-drop upload, hover `@file` to drop a reference into the input box; **Ctrl/Cmd multi-select and Shift range-select** (copy or delete a batch), **VS Code-style git status colors + M/A/D/U letters**, **new folder / new file** (inline editor; the server refuses illegal names, Windows reserved device names and an existing destination — a same-named file is never truncated), **sorting** (by name / by type, plus a folders-first switch; the default is the host's own order), **multi-select “Zip and download”** (the host streams a ZIP built with no third-party dependency), and an “Open with” menu that COMBINES DSH’s own open-in-app (the host’s probed OS handlers + file-manager reveal) with the plugin’s own targets (file manager / VS Code / Cursor / Zed / custom editor URL templates, SSH remotes, pin-to-menu)
- **🌿 Changes** (no Git panel in the stock sidebar): two lenses in one tab — **Git** (diff / history / stage·commit·revert) and **This Session** (every file the model touched) — with a unified diff renderer (intra-line character highlights, syntax coloring, secret redaction); the two lenses now share one 36px header (host SegmentedControl), 28px rows, a single empty state and a sticky commit bar, and the git snapshot is shared with the file tree so staging recolors the tree too
- **🧩 Background Tasks** (absent upstream): agent topology preview + background task list (exit codes / live output / force-kill)
- **💬 Side Chat** (absent upstream, beta): Codex-style side threads — inheriting the full parent context, running independently, promotable to a top-level session
+1 -1
View File
@@ -1217,7 +1217,7 @@ better-sidebar 的内置 tab 和 viewer 就是参考实现("吃狗粮"),
- **`src/client/SideCardSection.tsx`**:声明式设置页(注册表驱动清单 + 嵌套设置行 + 开关持久化)
- **`src/client/api.ts`**:`/sidebar` API 的封装(复制其 fetch 模式到你的插件)
- **`src/client/plugins-tabs.ts`** / **`plugins-viewers.ts`**:推荐插件目录(「添加插件」弹窗数据源;加一条数据即上架,`tests/plugin-list.spec.ts` 守护)
- **`src/client/FileTree.tsx`** / **`TreePanel.tsx`** / **`src/fs-search.ts`** / **`src/search-engines.ts`**:文件树 / 树面板 / host 文件名搜索(`fs.search`)。搜索优先探测本机 fd / rg(DSH 自带 ripgrep 优先),缺失或运行失败回退 JS 遍历,两条路径共用同一份 `exclude` 探针(引擎侧是输出后置过滤:匹配条目不出现、被排除目录不下钻);`dirs` 让目录命中行导航文件树而不是当文件打开;调试插桩 `DSH_SEARCH_DEBUG=1` 写 `$DSH_HOME/search-debug.log`,缺省 `~/.dsh`。host 的 `listDirectory` 给目录行标记 `compact`(仅一个非 symlink 有效子项;POSIX 隐藏与 `explorerExclude` 排除条目不计入),client 的 `file-tree-compact.ts` 把单目录链折叠成 `a/b/c` 面包屑行并整链展开/折叠;`explorerExclude`(VS Code `files.exclude` 风格 glob 子集,见 `exclude-patterns.ts`;editor 卡片的声明式 patterns 行可编辑)把匹配条目从树与搜索中彻底移除,两个界面共用同一 host 侧编译好的 matcher;host 侧目录缓存按「路径 + 行额 + 模式集身份」分键,改排除列表即换键。测试:`tests/fs-tree-compact.spec.ts` / `file-tree-compact.spec.ts` / `fs-tree-exclude.spec.ts` / `exclude-patterns.spec.ts` / `fs-search.spec.ts` / `search-engines.spec.ts`
- **`src/client/FileTree.tsx`** / **`TreePanel.tsx`** / **`src/fs-search.ts`** / **`src/search-engines.ts`**:文件树 / 树面板 / host 文件搜索(`fs.search`)。查询分三态(#879):**普通名字**走引擎链——优先探测本机 fd / rg(DSH 自带 ripgrep 优先),缺失或运行失败回退 JS 遍历,两条路径共用同一份 `exclude` 探针(引擎侧是输出后置过滤:匹配条目不出现、被排除目录不下钻);**带分隔符的相对片段**(如 `records/exp1`,名字永不包含分隔符)由 JS 遍历按根相对路径匹配、不进引擎;**指名单一目标的查询**(绝对路径、`~/…`、`./x`、`../x`)经 `resolveTarget`(与 fs.read 同一解析原语:`~` 展开、会话 cwd 拼接、win32 WSL/dsh-remote 命名空间改写、词法 resolve)stat 直取,命中返回解析后的绝对路径、目标缺失立即空结果(不烧遍历预算,exclude 不作用于显式路径意图)。`dirs` 让目录命中行导航文件树而不是当文件打开;调试插桩 `DSH_SEARCH_DEBUG=1` 写 `$DSH_HOME/search-debug.log`,缺省 `~/.dsh`。host 的 `listDirectory` 给目录行标记 `compact`(仅一个非 symlink 有效子项;POSIX 隐藏与 `explorerExclude` 排除条目不计入),client 的 `file-tree-compact.ts` 把单目录链折叠成 `a/b/c` 面包屑行并整链展开/折叠;`explorerExclude`(VS Code `files.exclude` 风格 glob 子集,见 `exclude-patterns.ts`;editor 卡片的声明式 patterns 行可编辑)把匹配条目从树与搜索中彻底移除,两个界面共用同一 host 侧编译好的 matcher;host 侧目录缓存按「路径 + 行额 + 模式集身份」分键,改排除列表即换键。测试:`tests/fs-tree-compact.spec.ts` / `file-tree-compact.spec.ts` / `fs-tree-exclude.spec.ts` / `exclude-patterns.spec.ts` / `fs-search.spec.ts` / `search-engines.spec.ts`
- **`src/client/markdown-html.ts`** / **`MarkdownHtml.tsx`** / **`md-toc.tsx`**:markdown 内嵌 HTML 管线与目录大纲(注意 `md-toc.tsx` 头注释的「子组件读父 ref 为 null」时序陷阱)
- **`src/agent-opens.ts`** / **`/sidebar/ws/agent-opens`**:模型主动打开(`sidebar_open` 工具 + `agentOpenTools` 设置,默认关闭);文件夹窗口 = `meta.dir: true` 的 editor tab([设计文档](plans/2026-08-23-agent-open-tools-design.md))
- **`tests/service.spec.ts`** / **`tests/builtins.spec.ts`**:注册表生命周期 / 匹配算法 / dedupe / createTab / 启用态 gating;内置清单断言(6 tab + 3 viewer + 声明式元数据,并显式断言 image / pdf / binary-download **不在**内置清单里、但作为公开契约仍可被第三方注册)
+7 -2
View File
@@ -31,7 +31,7 @@ import { IconUploadOutline16 } from './icons.tsx'
import type { OpenInApp } from './open-in-app.ts'
import type { OpenWithTarget } from './open-with.ts'
import { t } from './locales.ts'
import { resolveSidebarPath } from './paths.ts'
import { isWithinWorkspace, resolveSidebarPath } from './paths.ts'
import { IconButton } from './ui/index.ts'
import { UploadOverlay } from './UploadOverlay.tsx'
import {
@@ -230,9 +230,14 @@ export function TreePanel(props: {
* paths are touched — and clear the query so the tree, not the parked
* results panel, is what the user sees next.
*/
// A directory hit OUTSIDE the cwd (a pasted absolute path from the
// direct-open branch) has no tree rows to expand: the tree is cwd-rooted,
// and `ancestorDirs` would synthesize cwd-length prefixes of a foreign
// path that toggle nothing and persist as junk `expanded` entries. Such a
// row only clears the query.
const openSearchDir = (rel: string): void => {
const target = resolveSidebarPath(cwd, rel)
if (cwd !== undefined) {
if (cwd !== undefined && isWithinWorkspace(cwd, target)) {
for (const path of [...ancestorDirs(cwd, [target]), target]) {
if (!expanded.includes(path)) onToggle(path)
}
+10 -6
View File
@@ -356,12 +356,16 @@ export const api = {
*/
fsTrees: (scope: SessionScope, paths: readonly string[], exclude?: readonly string[], signal?: AbortSignal) =>
call<{ levels: FsLevel[] }>('fs.trees', scopePayload(scope, { paths: [...paths], exclude }), signal),
/** Global recursive file-name search rooted at the session cwd (the editor
* side panel's search box); matches are cwd-relative '/'-separated paths,
* and `dirs` names the subset that is a directory (the list navigates the
* tree for those — `fs.read` refuses a directory). `exclude` carries the
* explorerExclude pref: matched entries never match and are never
* descended (host-side, in lockstep with the tree). */
/** Global recursive file search rooted at the session cwd (the editor
* side panel's search box). A name query matches cwd-relative
* '/'-separated paths; a separator-carrying fragment matches by PATH;
* a query naming one path (absolute, `~/…`, `./x`, `../x`) is stat'ed
* through the same resolution fs.read uses and yields the RESOLVED
* absolute target as the single match. `dirs` names the subset that is a
* directory (the list navigates the tree for those — `fs.read` refuses a
* directory). `exclude` carries the explorerExclude pref: matched entries
* never match and are never descended (host-side, in lockstep with the
* tree; a pasted direct-open path is explicit intent and skips it). */
fsSearch: (scope: SessionScope, query: string, exclude?: readonly string[], signal?: AbortSignal) =>
call<{ matches: string[]; dirs: string[]; truncated: boolean }>('fs.search', scopePayload(scope, { query, exclude }), signal),
fsRead: (scope: SessionScope, path: string, signal?: AbortSignal) =>
+125 -30
View File
@@ -1,11 +1,28 @@
/**
* Recursive file-name search for the editor's merged-mode side panel.
* Streams the tree with opendir and matches the query as a case-insensitive
* substring of each entry's NAME (paths stay relative to the search root —
* the client resolves them against the session cwd). No .gitignore semantics
* (this is a name lookup, not a code search), but known noise directories
* (`.git`, `node_modules`, package-manager stores, build caches) are
* skipped outright and symlink directories are NOT descended (cycle safety).
* Recursive file search for the editor's merged-mode side panel. Three query
* modalities share one result contract:
*
* - A plain name query streams the tree with opendir and matches the query
* as a case-insensitive substring of each entry's NAME (paths stay relative
* to the search root — the client resolves them against the session cwd).
* No .gitignore semantics (this is a name lookup, not a code search), but
* known noise directories (`.git`, `node_modules`, package-manager
* stores, build caches, worktree forests) are skipped outright and symlink
* directories are NOT descended (cycle safety).
* - A query carrying a path separator can never hit a NAME (names never
* contain separators), so it matches against the entry's root-relative
* PATH instead (#879): a pasted `records/exp1` finds the file at any
* depth, which name matching structurally cannot (#306).
* - A query that NAMES one path (an absolute path, a `~`-relative home
* spelling, or a dot-anchored `./x` / `../x`) is an open-this-file
* gesture, not a filter: `searchFiles` resolves the target through the
* SAME primitive every fs route uses (`resolveTarget` — `~` expansion,
* session-cwd join, win32 WSL / dsh-remote reinterpretation, lexical
* resolve), stats it, and returns the RESOLVED path as the single hit (a
* trailing separator from shell completion is stripped by the resolve, and
* the client's resolveSidebarPath passes absolute paths through — the fs
* routes reach any host-user path since the workspace fence came off). A
* missing target is an immediate empty result.
*
* Two performance budgets bound the walk: `maxMatches` (the client renders
* the flat list) and `maxVisited` (a runaway tree — a home directory root
@@ -17,28 +34,34 @@
* the tree for those rows instead of opening them as files.
*
* `searchFiles` (the dispatch the fs.search route calls) first tries the
* probed native engines (fd / rg — see search-engines.ts); when none are
* available or all failed at runtime it falls back to this walk (exported as
* `searchFilesPlain` for tests). Both paths fill the same contract — the
* `opts.exclude` probe included: the walk skips a match before descending,
* the engine path post-filters its flat listing (see engineExcludeProbe).
* probed native engines (fd / rg — see search-engines.ts) for NAME queries;
* when none are available or all failed at runtime it falls back to this walk
* (exported as `searchFilesPlain` for tests). Both paths fill the same
* contract — the `opts.exclude` probe included: the walk skips a match
* before descending, the engine path post-filters its flat listing (see
* engineExcludeProbe). Separator queries never reach the engines: the
* engines are name matchers (fd takes --fixed-strings without --full-path,
* rg's globs match single path segments), so the walk owns the fragment
* semantics alone.
*/
import type { Dirent } from 'node:fs'
import { opendir, stat } from 'node:fs/promises'
import { join, relative, sep } from 'node:path'
import { isAbsolute, join, sep } from 'node:path'
import { homedir } from 'node:os'
import type { ExcludeTest } from './exclude-patterns.ts'
import { resolveTarget } from './path-security.ts'
import { SKIP_DIR_NAMES, runEngine, usableEngines } from './search-engines.ts'
import { debugLog } from './search-debug.ts'
/** One search: the relative paths of the matching entries (dirs included so
* the client can hint where matches live) plus the truncation flag. */
/** One search: the paths of the matching entries (root-relative,
* '/'-separated for tree searches; a direct-path query yields the RESOLVED
* absolute target) plus the truncation flag. */
export interface FsSearchResult {
matches: string[]
/** The subset of `matches` that are DIRECTORIES (same relative, '/'-separated
* form). The client navigates the tree for these instead of opening them:
* `fs.read` refuses a directory, so treating a hit as a file surfaces a bare
* `"…" is a directory` error. */
/** The subset of `matches` that are DIRECTORIES (same form as their match
* row). The client navigates the tree for these instead of opening them:
* `fs.read` refuses a directory, so treating a hit as a file surfaces a
* bare `"…" is a directory` error. */
dirs: string[]
truncated: boolean
}
@@ -93,11 +116,42 @@ async function isDirectoryEntry(absolute: string, dirent: Dirent): Promise<boole
return info?.isDirectory() === true
}
/**
* Whether `query` carries a path separator: such a query can never hit an
* entry NAME and takes the path branches instead of name matching. Only the
* platform's own separators count — on POSIX a backslash is a legal name
* character, not a separator (the engines must stay eligible for names
* like `back\slash.ts`).
*/
function hasSeparator(query: string): boolean {
return query.includes('/') || (process.platform === 'win32' && query.includes('\\'))
}
/**
* Whether `query` NAMES one path (a direct-open gesture) instead of
* filtering: node's own absolute forms, the `~`-relative home spellings the
* resolution primitive expands (#713 — the client's own `isAbsolutePath`
* treats the same forms as absolute), and dot-anchored relative paths
* (`./x`, `../x`). No entry NAME can take these shapes — a name never
* contains a separator — so the predicate steals no name query, with one
* platform-bent exception: the `~\` form counts only on win32, because on
* POSIX a backslash is a legal name character and `~\foo` can be a file's
* NAME. Plain fragments (`records/exp1`) stay with the path-fragment branch.
*/
function isDirectPathQuery(query: string): boolean {
return isAbsolute(query)
|| query === '~' || query.startsWith('~/') || (process.platform === 'win32' && query.startsWith('~\\'))
|| /^\.+[/\\]/.test(query)
}
/**
* The plain-JS fallback walk: search `root` recursively for entries whose
* name contains `query` (case-insensitive).
* name contains `query` (case-insensitive), or — for a query carrying a
* path separator, which no NAME can contain — whose root-relative path
* does.
* @param root - absolute search root.
* @param query - the name substring; empty matches nothing.
* @param query - the name substring, or the path fragment for
* separator-carrying queries; empty matches nothing.
* @param opts - budget overrides (tests).
* @returns the matching paths RELATIVE to `root` ('/'-separated), sorted,
* plus which of them are directories and whether a budget cut the walk
@@ -109,13 +163,17 @@ export async function searchFilesPlain(root: string, query: string, opts: FsSear
if (needle === '') return { matches: [], dirs: [], truncated: false }
const maxMatches = opts.maxMatches ?? DEFAULT_MAX_MATCHES
const maxVisited = opts.maxVisited ?? DEFAULT_MAX_VISITED
// Path-fragment matching folds the needle's '/' onto the platform's own
// separator (Windows users paste both styles); POSIX backslashes inside
// the needle stay literal name characters.
const pathNeedle = hasSeparator(needle) ? needle.replace(/\//g, sep) : undefined
const matches: string[] = []
const dirs: string[] = []
let visited = 0
let truncated = false
const walk = async (dir: string): Promise<void> => {
const walk = async (dir: string, relDir: string): Promise<void> => {
if (truncated) return
const level = await opendir(dir).catch(() => undefined)
if (level === undefined) return
@@ -130,14 +188,17 @@ export async function searchFilesPlain(root: string, query: string, opts: FsSear
// gitdir) is VCS noise too — the name check covers both shapes,
// parity with the engines' .git exclusion (SKIP_DIR_NAMES).
if (SEARCH_SKIP_DIRS.has(dirent.name.toLowerCase())) continue
const relativePath = relDir === '' ? dirent.name : `${relDir}${sep}${dirent.name}`
const absolute = join(dir, dirent.name)
// The user's exclude list removes entries from search exactly like the
// tree listing (no match, no descent).
if (opts.exclude !== undefined && opts.exclude(absolute, dirent.name)) continue
if (dirent.name.toLowerCase().includes(needle)) {
const hit = join(relative(root, dir), dirent.name)
matches.push(hit)
if (await isDirectoryEntry(absolute, dirent)) dirs.push(hit)
const hit = pathNeedle === undefined
? dirent.name.toLowerCase().includes(needle)
: relativePath.toLowerCase().includes(pathNeedle)
if (hit) {
matches.push(relativePath)
if (await isDirectoryEntry(absolute, dirent)) dirs.push(relativePath)
if (matches.length >= maxMatches) {
truncated = true
return
@@ -146,12 +207,12 @@ export async function searchFilesPlain(root: string, query: string, opts: FsSear
// Descend real directories only: a symlinked directory may point back
// up the tree (cycle).
if (dirent.isDirectory() && !dirent.isSymbolicLink()) {
await walk(absolute)
await walk(absolute, relativePath)
if (truncated) return
}
}
}
await walk(root)
await walk(root, '')
// '/' separators on every platform: the client joins onto the cwd itself.
const normalize = (path: string): string => path.split(sep).join('/')
return { matches: matches.sort().map(normalize), dirs: dirs.sort().map(normalize), truncated }
@@ -190,7 +251,9 @@ function engineExcludeProbe(root: string, exclude: ExcludeTest): (relativePath:
}
/**
* The fs.search dispatch: native engines first (when verified and healthy),
* The fs.search dispatch: an absolute query is stat'ed directly (see the
* module header), a separator-carrying fragment goes to the walk, and plain
* name queries run the native engines first (when verified and healthy) with
* the plain walk as fallback. Engine output is normalized onto the walk
* contract — root-relative, '/'-separated, sorted, and split into
* matches/dirs — so the route and the client stay unchanged. A blank query
@@ -204,8 +267,40 @@ function engineExcludeProbe(root: string, exclude: ExcludeTest): (relativePath:
export async function searchFiles(root: string, query: string, opts: FsSearchOptions = {}): Promise<FsSearchResult> {
const needle = query.trim()
if (needle === '') return { matches: [], dirs: [], truncated: false }
const maxMatches = opts.maxMatches ?? DEFAULT_MAX_MATCHES
const started = performance.now()
// #879: a query that NAMES one path is a direct-open gesture. Name
// matching is guaranteed-empty for it (names never contain separators),
// so the engines and the walk would only burn the visit budget to report
// the same nothing. The target goes through the SAME resolution primitive
// every fs route uses, so the hit opens exactly what the click's fs.read
// opens — `~` expansion, session-cwd join for the dot-anchored spellings,
// win32 WSL / dsh-remote reinterpretation — and the RESOLVED path is
// returned, not the pasted spelling: resolve() strips the trailing
// separator shell completion adds, and the client compares match rows
// exactly against tree paths that never carry one. The user's exclude
// list does not apply here — a pasted path is an explicit intent, and
// fs.read applies no exclude either.
if (isDirectPathQuery(needle)) {
const target = resolveTarget(root, needle)
const info = await stat(target).catch(() => undefined)
const result: FsSearchResult = info === undefined
? { matches: [], dirs: [], truncated: false }
: info.isDirectory()
? { matches: [target], dirs: [target], truncated: false }
: { matches: [target], dirs: [], truncated: false }
debugLog(`[dsh-search] engine=stat root=${relRoot(root)} query="${needle}" hits=${result.matches.length} truncated=${result.truncated} ${(performance.now() - started).toFixed(0)}ms`)
return result
}
// A separator-carrying RELATIVE query is a path fragment (#879): it can
// never hit a name, and the engines are name matchers (fd's
// --fixed-strings has no --full-path; rg's globs match single segments),
// so the walk's path matching is the single semantics for fragments.
if (hasSeparator(needle)) {
const result = await searchFilesPlain(root, query, opts)
debugLog(`[dsh-search] engine=plain root=${relRoot(root)} query="${needle}" hits=${result.matches.length} truncated=${result.truncated} ${(performance.now() - started).toFixed(0)}ms`)
return result
}
const maxMatches = opts.maxMatches ?? DEFAULT_MAX_MATCHES
const isExcluded = opts.exclude === undefined ? undefined : engineExcludeProbe(root, opts.exclude)
for (const probe of await usableEngines()) {
try {
+7 -3
View File
@@ -573,9 +573,13 @@ function buildApi(
return { levels }
},
'fs.search': async (payload) => {
// The editor side panel's global name search: rooted at the session
// cwd (not caller-targetable — the walk is unbounded by design and
// must never escape the workspace), budgeted inside searchFiles.
// The editor side panel's global search. Name queries stay rooted at
// the session cwd (not caller-targetable — the walk is unbounded by
// design), budgeted inside searchFiles. A query carrying a path
// separator can never match a NAME, so searchFiles routes it
// differently: an absolute query stats its target (the same
// any-host-path reach fs.read has had since the workspace fence came
// off) and a relative fragment matches by path.
const { cwd } = await cwdOf(payload)
const record = payload as { exclude?: unknown }
const query = requireString(payload, 'query')
+12 -1
View File
@@ -215,7 +215,8 @@ export function escapeGlob(query: string): string {
}
/** Directory names that are never useful filename-search results (VCS
* internals, dependency forests, package-manager stores, build caches).
* internals, dependency forests, package-manager stores, build caches,
* worktree forests, language environments).
* The plain walk in fs-search.ts builds its case-insensitive skip set
* from this list, and BOTH engine argvs exclude every name — with
* --no-ignore active an rg/fd run would otherwise re-enter node_modules
@@ -238,6 +239,16 @@ export const SKIP_DIR_NAMES: readonly string[] = [
'dist',
'build',
'out',
// #879: git-worktree forests (both spellings; `.worktrees/` is the
// layout DeepSeek Harness itself uses) burned the whole 100k visit budget
// on real projects before the walk reached project files. Language
// environments and their bytecode caches are noise of the same class.
'.worktrees',
'.worktree',
'target',
'venv',
'.venv',
'__pycache__',
'.umi',
'.umi-production',
'.dumi',
+19
View File
@@ -247,4 +247,23 @@ describe('TreePanel directory hits navigate instead of opening', () => {
// A file open keeps the results list up (only a navigation clears it).
expect(resultsBody(harness.container).hasAttribute('hidden')).toBe(false)
})
// #879's direct-open branch can hand the list a DIRECTORY outside the cwd
// (a pasted absolute path). The tree is cwd-rooted, so there is nothing to
// expand: the row must clear the query WITHOUT toggling — `ancestorDirs`
// would otherwise synthesize cwd-length prefixes of the foreign path that
// match no tree row and persist as junk `expanded` entries.
it('clears the query for a directory hit outside the cwd without toggling anything', async () => {
fsSearch.mockResolvedValue({ matches: ['/elsewhere/records'], dirs: ['/elsewhere/records'], truncated: false })
const onToggle = vi.fn()
harness = mountPanel({ onToggle })
await act(async () => {})
await search(harness.container, '/elsewhere/records')
const dirRow = resultRows(harness.container).find(row => row.textContent === '/elsewhere/records')!
expect(dirRow.getAttribute('data-dsh-search-dir')).toBe('true')
await act(async () => { dirRow.dispatchEvent(new MouseEvent('click', { bubbles: true })) })
expect(onToggle).not.toHaveBeenCalled()
expect(harness.container.querySelector<HTMLInputElement>('input[class*="editorSearchInput"]')!.value).toBe('')
})
})
+256 -11
View File
@@ -1,18 +1,22 @@
/**
* fs-search: the host's recursive file-name search behind the editor side
* panel's search box. Matches are case-insensitive name substrings, reported
* RELATIVE to the root ('/'-separated); noise directories (`.git`,
* `node_modules`, build caches) are skipped, symlinked directories are
* never descended (cycle safety), and the maxMatches/maxVisited budgets
* stop a runaway walk with `truncated: true`. `searchFiles` is the dispatch
* the route calls (native engines first, this walk as fallback) — the walk
* itself is pinned directly as `searchFilesPlain`, and the dispatch cases
* below inject fake engines so no machine binary is required.
* fs-search: the host's recursive file search behind the editor side panel's
* search box. Name queries match case-insensitive name substrings, reported
* RELATIVE to the root ('/'-separated); a separator-carrying query matches
* the root-relative PATH instead (names never contain separators); and a
* query naming one path (absolute, `~/…`, `./x`, `../x`) is resolved through
* the same primitive fs.read uses and stat'ed into a direct-open hit (#879).
* Noise directories (`.git`, `node_modules`, build caches, worktree
* forests) are skipped, symlinked directories are never descended (cycle
* safety), and the maxMatches/maxVisited budgets stop a runaway walk with
* `truncated: true`. `searchFiles` is the dispatch the route calls (native
* engines for name queries, this walk for fragments and as fallback) — the
* walk itself is pinned directly as `searchFilesPlain`, and the dispatch
* cases below inject fake engines so no machine binary is required.
*/
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { homedir, tmpdir } from 'node:os'
import { join, resolve as resolvePath } from 'node:path'
import { compileExcludePatterns } from '../src/exclude-patterns.ts'
import { searchFiles, searchFilesPlain } from '../src/fs-search.ts'
import type { EngineProbe } from '../src/search-engines.ts'
@@ -34,6 +38,24 @@ const canSymlink = (() => {
}
})()
/**
* A file NAMED `back\slash.ts` (the backslash is part of the name, not a
* separator) is creatable on POSIX only — NTFS rejects a backslash inside a
* name. The probe keeps the backslash-is-a-name-character case below
* runnable exactly where such a name can exist, mirroring `canSymlink`.
*/
const canBackslashName = (() => {
const dir = mkdtempSync(join(tmpdir(), 'dsh-sidebar-search-probe-'))
try {
writeFileSync(join(dir, 'back\\slash.ts'), 'x')
return true
} catch {
return false
} finally {
rmSync(dir, { recursive: true, force: true })
}
})()
/** A scratch tree: nested matches, a .git dir, and unrelated noise. */
function makeFixture(): string {
const dir = mkdtempSync(join(tmpdir(), 'dsh-sidebar-search-'))
@@ -170,6 +192,71 @@ describe('fs-search', () => {
}
})
// #879: git worktree forests (both spellings — `.worktrees/` is the layout
// DeepSeek Harness itself uses) and Python envs / bytecode caches burned
// the whole visit budget on real projects before the walk ever reached
// project files, leaving `truncated: true` on every query. They are noise
// of exactly the node_modules class: never matched, never descended.
it('never descends into worktree forests or language environment dirs', async () => {
const dir = makeFixture()
try {
for (const noise of ['.worktrees', '.worktree', 'target', 'venv', '.venv', '__pycache__']) {
mkdirSync(join(dir, noise, 'pkg'), { recursive: true })
writeFileSync(join(dir, noise, 'pkg', 'guide.md'), 'noise')
}
expect((await searchFilesPlain(dir, 'guide')).matches).toEqual(['docs/guide.md'])
expect((await searchFilesPlain(dir, 'worktrees')).matches).toEqual([])
expect((await searchFilesPlain(dir, 'target')).matches).toEqual([])
expect((await searchFilesPlain(dir, 'venv')).matches).toEqual([])
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
// #879 / #306: a query carrying a path separator can never hit an entry
// NAME (names never contain separators), so such a query matches against
// the entry's root-relative PATH instead — a pasted `records/exp1` finds
// the file under any depth, which name matching structurally cannot.
it('a separator-carrying query matches the root-relative path, case-insensitively', async () => {
const dir = makeFixture()
try {
mkdirSync(join(dir, 'deep', 'records'), { recursive: true })
writeFileSync(join(dir, 'deep', 'records', 'exp1.txt'), 'x')
// Fragment at depth, plus a root-anchored fragment against the fixture.
expect(await searchFilesPlain(dir, 'records/exp1')).toEqual({ matches: ['deep/records/exp1.txt'], dirs: [], truncated: false })
expect(await searchFilesPlain(dir, 'docs/guide')).toEqual({ matches: ['docs/guide.md'], dirs: [], truncated: false })
expect((await searchFilesPlain(dir, 'RECORDS/EXP1')).matches).toEqual(['deep/records/exp1.txt'])
// A fragment can hit a DIRECTORY by its path; the dirs split survives.
expect(await searchFilesPlain(dir, 'deep/records')).toEqual({
matches: ['deep/records', 'deep/records/exp1.txt'],
dirs: ['deep/records'],
truncated: false,
})
// The noise fences still apply to path matching.
mkdirSync(join(dir, 'node_modules', 'records'), { recursive: true })
writeFileSync(join(dir, 'node_modules', 'records', 'exp1.txt'), 'dep')
expect((await searchFilesPlain(dir, 'records/exp1')).matches).toEqual(['deep/records/exp1.txt'])
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
// POSIX: a backslash is a legal NAME character, not a separator — the
// separator predicate must stay platform-faithful or name queries for
// such files silently lose engine eligibility (the dispatch case below
// pins that half). Here the WALK must find the file by its literal name.
it.skipIf(!canBackslashName)('matches a literal backslash in an entry name (POSIX name character)', async () => {
const dir = mkdtempSync(join(tmpdir(), 'dsh-sidebar-search-backslash-'))
try {
writeFileSync(join(dir, 'back\\slash.ts'), 'x')
writeFileSync(join(dir, 'plain.ts'), 'x')
expect((await searchFilesPlain(dir, 'back\\slash')).matches).toEqual(['back\\slash.ts'])
expect((await searchFilesPlain(dir, 'slash')).matches).toEqual(['back\\slash.ts'])
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('an empty (or whitespace) query matches nothing without walking', async () => {
const dir = makeFixture()
try {
@@ -315,6 +402,164 @@ describe('fs-search dispatch', () => {
expect(probed).toBe(false)
})
// #879: a query that IS an absolute path is an open-this-file gesture.
// It can never match a NAME, so every engine/walk pass below is
// guaranteed-empty while still burning the visit budget. The target is
// stat'ed instead: the hit is the path as pasted (the client's
// resolveSidebarPath passes absolute paths through, and the fs routes
// reach any host-user path since the workspace fence came off).
it('an absolute query stats its target instead of searching', async () => {
const dir = makeFixture()
try {
let probed = false
setEngineHooks({
prober: async () => { probed = true; return [fakeFd] },
runner: async () => ({ paths: ['engine-would-return-this'], dirs: [], truncated: false }),
})
const target = join(dir, 'src', 'util.ts')
expect(await searchFiles(dir, target)).toEqual({ matches: [target], dirs: [], truncated: false })
// A directory target is reported through the #801 contract: the row
// navigates the tree instead of being opened as a file.
const folder = join(dir, 'src')
expect(await searchFiles(dir, folder)).toEqual({ matches: [folder], dirs: [folder], truncated: false })
expect(probed).toBe(false)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('an absolute query that matches nothing is an immediate empty result', async () => {
const dir = makeFixture()
try {
let probed = false
setEngineHooks({
prober: async () => { probed = true; return [fakeFd] },
runner: async () => ({ paths: ['engine-would-return-this'], dirs: [], truncated: false }),
})
// maxVisited: 1 pins immediacy: a fall-through to any walk would abort
// the traversal at the first entry and answer truncated:true, so
// truncated:false proves the miss was answered without walking.
expect(await searchFiles(dir, join(dir, 'gone.md'), { maxVisited: 1 })).toEqual({ matches: [], dirs: [], truncated: false })
expect(probed).toBe(false)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
// The direct-open spellings resolve through the SAME primitive fs.read
// uses (`resolveTarget`), and the RESOLVED path comes back — not the pasted
// spelling: shell completion appends a trailing separator, and the client
// compares match rows exactly against tree paths that never carry one.
// `./x` / `../x` resolve against the session cwd; `~` names the home
// directory (#713 — the resolution primitive expands it).
it('direct-path spellings resolve like fs.read and yield the resolved path', async () => {
const parent = mkdtempSync(join(tmpdir(), 'dsh-sidebar-search-anchor-'))
const dir = join(parent, 'workspace')
mkdirSync(dir, { recursive: true })
try {
mkdirSync(join(dir, 'src'), { recursive: true })
writeFileSync(join(dir, 'src', 'util.ts'), 'code')
mkdirSync(join(parent, 'sibling'), { recursive: true })
writeFileSync(join(parent, 'sibling', 'note.md'), 'doc')
setEngineHooks({ prober: async () => [] })
// Trailing separators (directory and file spellings) resolve away.
expect(await searchFiles(dir, `${join(dir, 'src')}/`)).toEqual({
matches: [join(dir, 'src')], dirs: [join(dir, 'src')], truncated: false,
})
expect(await searchFiles(dir, `${join(dir, 'src', 'util.ts')}/`)).toEqual({
matches: [join(dir, 'src', 'util.ts')], dirs: [], truncated: false,
})
// Dot-anchored spellings resolve against the session cwd…
expect(await searchFiles(dir, './src/util.ts')).toEqual({
matches: [join(dir, 'src', 'util.ts')], dirs: [], truncated: false,
})
// …including one level up, which lands outside the cwd — the same
// reach the workspace fence removal granted every fs route.
expect(await searchFiles(dir, '../sibling/note.md')).toEqual({
matches: [join(parent, 'sibling', 'note.md')], dirs: [], truncated: false,
})
// `~` expands to the home directory (the resolution primitive's own
// #713 behavior); the hit is the resolved home path.
expect((await searchFiles(dir, '~')).dirs).toEqual([resolvePath(homedir())])
// A missing `~`-anchored target is the same immediate empty.
expect(await searchFiles(dir, '~/dsh-sidebar-no-such-entry')).toEqual({ matches: [], dirs: [], truncated: false })
} finally {
rmSync(parent, { recursive: true, force: true })
}
})
// The direct-path predicate must steal no NAME query: only `~` followed by
// a separator (or a bare `~`) is a path gesture, and only a dot followed
// by a separator is. Backup files (`util.ts~`), Office lock files
// (`~$doc.docx`) and dotfiles (`.env`) are NAMES and keep the name path.
it('tilde and dot spellings without a separator stay name queries', async () => {
const dir = makeFixture()
try {
writeFileSync(join(dir, 'util.ts~'), 'backup')
writeFileSync(join(dir, '~$lock.docx'), 'lock')
writeFileSync(join(dir, '.env'), 'env')
let probed = false
setEngineHooks({
prober: async () => { probed = true; return [fakeFd] },
runner: async () => ({ paths: [], dirs: [], truncated: false }),
})
// Engine eligibility IS the assertion (the fake engine answers empty —
// a successful engine never falls back to the walk).
await searchFiles(dir, 'util.ts~')
expect(probed).toBe(true)
// The name matches are proven on the walk (no engine probed). The
// probe result is process-cached, so the hook swap needs a reset
// before the engine-less prober takes effect.
resetEngines()
setEngineHooks({ prober: async () => [] })
expect((await searchFiles(dir, 'util.ts~')).matches).toEqual(['util.ts~'])
expect((await searchFiles(dir, '~$lock')).matches).toEqual(['~$lock.docx'])
expect((await searchFiles(dir, '.env')).matches).toEqual(['.env'])
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
// The engines are NAME matchers (fd takes --fixed-strings without
// --full-path; rg's three globs match single path segments), so a path
// fragment would come back empty from fd and root-anchored-only from rg.
// The walk's path matching is the single semantics for fragments.
it('a separator query never reaches the name-matching engines', async () => {
const dir = makeFixture()
try {
let probed = false
setEngineHooks({
prober: async () => { probed = true; return [fakeFd] },
runner: async () => ({ paths: ['engine-would-return-this'], dirs: [], truncated: false }),
})
expect((await searchFiles(dir, 'docs/guide')).matches).toEqual(['docs/guide.md'])
expect(probed).toBe(false)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
// POSIX: a backslash is a legal name character, so a backslash query
// stays a NAME query and keeps engine eligibility. If the separator
// predicate ever treats '\' as a separator on POSIX, the probe assert
// turns this red (the fragment branch bypasses engines).
it.skipIf(!canBackslashName)('a backslash query stays a name query on POSIX (engines stay eligible)', async () => {
const dir = mkdtempSync(join(tmpdir(), 'dsh-sidebar-search-backslash-'))
try {
writeFileSync(join(dir, 'back\\slash.ts'), 'x')
let probed = false
setEngineHooks({
prober: async () => { probed = true; return [fakeFd] },
runner: async () => ({ paths: ['back\\slash.ts'], dirs: [], truncated: false }),
})
expect((await searchFiles(dir, 'back\\slash')).matches).toEqual(['back\\slash.ts'])
expect(probed).toBe(true)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('caps engine output at maxMatches and reports truncated', async () => {
setEngineHooks({
prober: async () => [fakeFd],
+29
View File
@@ -1046,6 +1046,35 @@ describe('session cwd resolution over the API route', () => {
}
})
// #879: a pasted absolute path is an open-this-file gesture, not a name
// filter. The route returns the stat'ed target as the single hit (the
// client resolves absolute match rows straight to the editor), and a
// missing target is an immediate empty result instead of a walk that burns
// its whole visit budget to report the same nothing.
it('fs.search stats an absolute query into a single direct-open hit', async () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-fs-search-path-'))
const workspace = join(root, 'workspace')
mkdirSync(join(workspace, 'src'), { recursive: true })
writeFileSync(join(workspace, 'src', 'index.ts'), 'code')
try {
const route = mount({ sessions: { get: () => ({ header: { cwd: workspace } }) } })
const target = join(workspace, 'src', 'index.ts')
const hit = await invoke(route, 'fs.search', { sessionId: 's-search', query: target })
expect(hit.value).toEqual({ matches: [target], dirs: [], truncated: false })
const miss = await invoke(route, 'fs.search', { sessionId: 's-search', query: join(workspace, 'gone.ts') })
expect(miss.value).toEqual({ matches: [], dirs: [], truncated: false })
// A relative fragment searches the workspace tree by PATH (the name
// walk can never match a separator-carrying query), and a dot-anchored
// spelling resolves against the session cwd like fs.read does.
const fragment = await invoke(route, 'fs.search', { sessionId: 's-search', query: 'src/index' })
expect(fragment.value).toEqual({ matches: ['src/index.ts'], dirs: [], truncated: false })
const anchored = await invoke(route, 'fs.search', { sessionId: 's-search', query: './src/index.ts' })
expect(anchored.value).toEqual({ matches: [join(workspace, 'src', 'index.ts')], dirs: [], truncated: false })
} finally {
rmSync(root, { recursive: true, force: true })
}
})
it('fs.trees rejects an empty list and an oversized batch', async () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-fs-trees-guard-'))
const workspace = join(root, 'workspace')