From 5254c031b1ef40148828e59c67b9220007bc0595 Mon Sep 17 00:00:00 2001 From: Menghuan1918 Date: Mon, 5 Oct 2026 02:13:53 +0800 Subject: [PATCH] =?UTF-8?q?feat(explorer):=20=E6=96=87=E4=BB=B6=E6=A0=91?= =?UTF-8?q?=E9=9D=A2=E5=8C=85=E5=B1=91=E6=8A=98=E5=8F=A0=20+=20VS=20Code?= =?UTF-8?q?=20=E9=A3=8E=E6=A0=BC=E5=8F=AF=E9=85=8D=E7=BD=AE=E6=8E=92?= =?UTF-8?q?=E9=99=A4=E6=A8=A1=E5=BC=8F=EF=BC=88=E7=A7=BB=E6=A4=8D=20#264?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 按当前 dev 重写贡献者 PR #264 的两项核心意图: 1. 面包屑折叠(VSCode "compact folders"):host 给「内容恰为一个有效 子项」的目录行标记 `compact`,client 把单目录链折叠成一行 `a/b/c` 并整链展开/折叠。 2. `explorerExclude`(VS Code `files.exclude` 风格的 glob 子集):匹配 条目从文件树与文件名搜索中彻底移除;树与搜索共用同一份 host 侧编译 好的 matcher,两个界面永不失配。 为什么按 dev 现有结构重写而不是机械解冲突——证据卡逐条点名的 dev 侧变化: - **客户端树已换成 DirRow 记忆化组件 + loadLevels/api.fsTrees 批量路由**。 PR 改的是旧的 `expanded.includes(...)` 内联目录行与单路径 `api.fsTree`, 该上下文在 dev 已不存在。折叠因此接在 renderLevel/visibleRows 的链上, 并新增「每级缓存修订一次」的链缓存:DirRow 按 prop 身份 memo,每次渲染 新建数组会让选择/悬停把每个目录行都重渲。 - **`api.fsTree(scope, path, signal?)` 的第三位已经是 AbortSignal**,PR 的 `api.fsTree(scope, dir, exclude)` 会把数组当 signal。exclude 统一排在 signal 之前(`fsTree`/`fsTrees`/`fsSearch` 三处一致)。 - **dev 的 `listDirectory` 有 1.5s TTL 缓存,PR 是直接读盘**。照搬会让不同 排除集共用一份缓存(改完排除列表仍读到旧行),而 pref 变更没有可搭的 失效钩子。故把模式集的身份并入 cacheKey(新增 `ExcludeMatcher.key`,含 锚点 root 与大小写折叠语义):同列表命中缓存,改列表即换键。 - **文件树的真实入口是批量路由 `fs.trees`**(挂载/展开一次 POST),PR 只 改了 `fs.tree`/`fs.search` 两处——不接批量路由等于 exclude 不生效。 - PR body 声称移除 `explorerShowHidden`,但净 diff 对它零命中、dev 与 PR 合并基也都没有该键,属失效声明,不做产品取舍。 复用的部分(与 dev 无耦合):`src/exclude-patterns.ts` 与 `src/client/file-tree-compact.ts` 两个纯逻辑模块逐字取用(前者仅新增缓存 身份 `ExcludeMatcher.key`)。设置 UI 沿用 PR 的声明式 `patterns` 行类型 (chips + 删除钮 + 常驻添加输入框,原子提交整表),5 个新词条按仓库规则 同步全部 21 份词典;`src/client/service.ts` 的能力清单新增 `settingPatterns` 并同步 docs/external-plugin-guide.md。 门禁:pnpm typecheck 0;pnpm exec vitest run --maxWorkers=3 全绿 (165 files / 1847 passed / 13 skipped);npx eslint 45 个改动文件 0; 新增与改动的 spec 单跑 154 passed;pnpm build 0。 Refs #264 Co-authored-by: shyuan-hub <311810858+shyuan-hub@users.noreply.github.com> --- AGENTS.md | 2 +- docs/external-plugin-guide.md | 17 +- src/client/EditorHost.tsx | 11 ++ src/client/FileTree.tsx | 161 +++++++++++++--- src/client/SideCardSection.module.css | 64 +++++++ src/client/SideCardSection.tsx | 99 +++++++++- src/client/TreePanel.tsx | 18 +- src/client/api.ts | 21 ++- src/client/builtins/tabs.tsx | 9 +- src/client/file-tree-compact.ts | 77 ++++++++ src/client/locales-ar.ts | 5 + src/client/locales-de.ts | 5 + src/client/locales-fr.ts | 5 + src/client/locales-hi.ts | 5 + src/client/locales-id.ts | 5 + src/client/locales-it.ts | 5 + src/client/locales-ja.ts | 5 + src/client/locales-ko.ts | 5 + src/client/locales-nl.ts | 5 + src/client/locales-pl.ts | 5 + src/client/locales-pt.ts | 5 + src/client/locales-ru.ts | 5 + src/client/locales-sv.ts | 5 + src/client/locales-th.ts | 5 + src/client/locales-tr.ts | 5 + src/client/locales-vi.ts | 5 + src/client/locales-zh-HK.ts | 5 + src/client/locales-zh-MO.ts | 5 + src/client/locales-zh-TW.ts | 5 + src/client/locales.ts | 10 + src/client/prefs.ts | 20 ++ src/client/service.ts | 12 +- src/config.ts | 3 + src/exclude-patterns.ts | 163 +++++++++++++++++ src/fs-search.ts | 8 + src/fs-tree.ts | 129 +++++++++++-- src/index.ts | 19 +- src/prefs-shared.ts | 16 ++ tests/builtins.spec.ts | 10 +- tests/exclude-patterns.spec.ts | 121 ++++++++++++ tests/file-tree-compact-fold.spec.tsx | 253 ++++++++++++++++++++++++++ tests/file-tree-compact.spec.ts | 143 +++++++++++++++ tests/fs-search.spec.ts | 25 +++ tests/fs-tree-compact.spec.ts | 127 +++++++++++++ tests/fs-tree-exclude.spec.ts | 155 ++++++++++++++++ tests/prefs.spec.ts | 15 ++ tests/side-card-section.spec.tsx | 4 + tests/smoke.spec.ts | 37 ++++ 48 files changed, 1769 insertions(+), 75 deletions(-) create mode 100644 src/client/file-tree-compact.ts create mode 100644 src/exclude-patterns.ts create mode 100644 tests/exclude-patterns.spec.ts create mode 100644 tests/file-tree-compact-fold.spec.tsx create mode 100644 tests/file-tree-compact.spec.ts create mode 100644 tests/fs-tree-compact.spec.ts create mode 100644 tests/fs-tree-exclude.spec.ts diff --git a/AGENTS.md b/AGENTS.md index bf86c0c5..03118c28 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -136,4 +136,4 @@ - **设计文档**:[docs/plans/](docs/plans/)(30+ 份逐特性设计,含实施偏差记录)。 - **Issue / PR 分诊 skill**:[.agents/skills/issue-triage/SKILL.md](.agents/skills/issue-triage/SKILL.md)——把 open issue 与 PR 分类(类型/领域/优先级)、判动作(关/追/等/留)、并按批次同步到排期看板(`scripts/snapshot.mjs` 取快照、`scripts/board-sync.mjs` 幂等写看板+回读校验);口径见 `references/taxonomy.md`,GitHub API 的坑见 `references/gh-gotchas.md`。 - **测试不得依赖非普适二进制**:CI 跑 ubuntu + windows 两个 runner,`rg` / `fd` / `jq` 这类「开发机上有」的工具在 runner 上没有,代价是整个 spec 在**收集阶段**失败(`spawnSync rg ENOENT`)而本地永远绿——上一版的 `tests/primitives-exports.spec.ts` 就这么让分支红了两轮。取文件清单用 `readdirSync` 自己走,或只用 `git` / `tar` / `pnpm` / node 内置能力;确需外部工具时先探测存在性并跳过。 -- **关键测试守护**:`tests/service.spec.ts` / `builtins.spec.ts`(注册表与内置清单:**5 tab + 3 viewer**——终端与浏览器已交还宿主,只读预览也按 §3.2 第 5 条让出,只剩 markdown / html / code)/ `market-manifest.spec.ts`(市场约束,含 `pnpm pack` 后的产物面)/ `manifest-consistency.spec.ts`(registry 通道形状)/ `e2e-host-protocol.spec.ts`(RPC 双协议)/ `native-surface.spec.ts`(原生右侧栏承载面:guide 条目 id 唯一性、以及 `canOpen` 的「拒绝清单不得宽于宿主渲染器」双向边界)/ `native-registration.spec.ts`(原生 tab 注册生命周期:`files` 接管不得被通知拆建、注册失败必须回滚已占用的 id 与已建槽位;断言写在注册表的事件日志上)/ `file-open-claim.spec.ts`(文件打开的认领判定:插件一切文件入口先问 `sidebarRightTabs.candidates`,被第三方认领的文件改走 `openResource`,无人认领/无注册表/探测抛错逐字保持 editor 原路径——#695,PR #696 移植;`editor-host.spec.tsx` 另钉合并模式原地切换同样让位)/ `theme.spec.ts`(皮肤契约,含空白面板胶囊几何)/ `plugin-list.spec.ts`(推荐插件目录)/ `fs-search.spec.ts`(host 文件名搜索)/ `fs-watch.spec.ts`(文件树目录 watch 的去抖、句柄上限与错误路径)/ `smoke.spec.ts` 的 settings 段(按 entry id 读写表单、**一次性 legacy 迁移**、open 工具门控)。 +- **关键测试守护**:`tests/service.spec.ts` / `builtins.spec.ts`(注册表与内置清单:**5 tab + 3 viewer**——终端与浏览器已交还宿主,只读预览也按 §3.2 第 5 条让出,只剩 markdown / html / code)/ `market-manifest.spec.ts`(市场约束,含 `pnpm pack` 后的产物面)/ `manifest-consistency.spec.ts`(registry 通道形状)/ `e2e-host-protocol.spec.ts`(RPC 双协议)/ `native-surface.spec.ts`(原生右侧栏承载面:guide 条目 id 唯一性、以及 `canOpen` 的「拒绝清单不得宽于宿主渲染器」双向边界)/ `native-registration.spec.ts`(原生 tab 注册生命周期:`files` 接管不得被通知拆建、注册失败必须回滚已占用的 id 与已建槽位;断言写在注册表的事件日志上)/ `file-open-claim.spec.ts`(文件打开的认领判定:插件一切文件入口先问 `sidebarRightTabs.candidates`,被第三方认领的文件改走 `openResource`,无人认领/无注册表/探测抛错逐字保持 editor 原路径——#695,PR #696 移植;`editor-host.spec.tsx` 另钉合并模式原地切换同样让位)/ `theme.spec.ts`(皮肤契约,含空白面板胶囊几何)/ `plugin-list.spec.ts`(推荐插件目录)/ `fs-search.spec.ts`(host 文件名搜索,含 `explorerExclude` 排除探针:匹配条目不出现也不下钻)/ `fs-watch.spec.ts`(文件树目录 watch 的去抖、句柄上限与错误路径)/ `exclude-patterns.spec.ts` / `fs-tree-exclude.spec.ts` / `fs-tree-compact.spec.ts` / `file-tree-compact.spec.ts` / `file-tree-compact-fold.spec.tsx`(资源管理器排除模式与面包屑折叠:glob 子集编译器及其**缓存身份**——host 目录缓存按「路径 + 行额 + 模式集身份」分键,改排除列表即换键;`compact` 单目录链的 host 标记、client 折叠/整链开关与折叠链预加载)/ `smoke.spec.ts` 的 settings 段(按 entry id 读写表单、**一次性 legacy 迁移**、open 工具门控)。 diff --git a/docs/external-plugin-guide.md b/docs/external-plugin-guide.md index a325d8d1..d1b56d85 100644 --- a/docs/external-plugin-guide.md +++ b/docs/external-plugin-guide.md @@ -164,14 +164,15 @@ export function apply(ctx: Context): void { ### 4.1 `TabDescriptor` 完整字段 ```ts -// 设置行控件形状(settings.toggles / settings.pluginToggles 共用;text/number v0.11.0+,select v0.13.0+): +// 设置行控件形状(settings.toggles / settings.pluginToggles 共用;text/number v0.11.0+,select v0.13.0+,patterns 为可编辑字符串数组): interface SettingRow { key: string // toggles: SidebarPrefs 字段名;pluginToggles: 插件局部 key title: string | (() => string) desc?: string | (() => string) - type?: 'switch' | 'text' | 'number' | 'select' // 缺省 'switch' + type?: 'switch' | 'text' | 'number' | 'select' | 'patterns' // 缺省 'switch' min?: number; max?: number // number 行提交钳制 placeholder?: string; unit?: string // text 行占位符 / 单位后缀(如 'px') + patternsPlaceholder?: string // patterns 行添加输入框占位符 options?: readonly { // select 行选项 value: string | number | boolean title: string | (() => string) @@ -430,7 +431,7 @@ ctx.effect(() => { | id | order | single | hidden | 用途 | |---|---|---|---|---| -| `editor` | 10 | 否(按 path 去重) | 否 | 唯一「文件窗口」(编辑/预览 + 资源管理)。chrome 恒合并形态:路径输入框 + 编辑器控件 + 可开关内嵌文件树(全局搜索 `fs.search`;状态存 `tab.meta.treeOpen/treeWidth`)。`editorExplorer`:关(默认)= 按 path 新开,无路径窗口 = 纯资源管理器;开 = 树点击/Enter 经 `updateTab` 原地切换(id/meta 不变),无路径窗口 = 带 chrome 空窗口。树右键「在新 Tab 中打开」「在侧边打开」(pane 右侧 split)。新会话 seed 空文件窗口(`title:'Files'`);旧 `explorer` tab 经 `sanitizeState` 迁移 | +| `editor` | 10 | 否(按 path 去重) | 否 | 唯一「文件窗口」(编辑/预览 + 资源管理)。chrome 恒合并形态:路径输入框 + 编辑器控件 + 可开关内嵌文件树(全局搜索 `fs.search`;状态存 `tab.meta.treeOpen/treeWidth`)。`editorExplorer`:关(默认)= 按 path 新开,无路径窗口 = 纯资源管理器;开 = 树点击/Enter 经 `updateTab` 原地切换(id/meta 不变),无路径窗口 = 带 chrome 空窗口。树右键「在新 Tab 中打开」「在侧边打开」(pane 右侧 split)。新会话 seed 空文件窗口(`title:'Files'`);旧 `explorer` tab 经 `sanitizeState` 迁移。树 listing 与文件名搜索应用 `explorerExclude` 排除模式(editor 卡片齿轮弹窗可编辑;host 侧过滤,匹配条目彻底移除且永不阻塞折叠);单目录链折叠为 `a/b/c` 面包屑行(POSIX 隐藏与排除条目不计入唯一子项判定) | | `git` | 20 | 是 | 是(本轮文件操作数) | 「文件变动」统一 tab(id 保留 `git` 以兼容持久化布局):**Git 视角**(原 Git 面板:staged/unstaged / 提交 / 历史 / worktree·子仓库选择)+ **本轮文件视角**(原 file-trace:模型读/写/编辑实时折叠,按文件分组、类型筛选);会话事件经插件自有宿主路由 `changes.ops` 供给(live 日志优先、冷会话回放持久化记录,`afterSeq` 增量),badge 读 tab 轮询写入的同步缓存。两视角共用底部可拖拽预览面板(`tab.meta.lens/previewH` 持久化),diff 渲染统一走 `src/client/diff/`(`DiffRows`/`DiffFiles`:mod 配对 + 行内高亮 + 语法着色 + 上下文折叠);Git 目标可展开为独立 diff tab(落进工作台的 diff 分栏) | | `subagent` | 30 | 是 | 否 | 任务管理(工作流图/树、团队任务板、后台任务抽屉) | | `sidechat` | 35 | 否(`sidechat:`,按 `meta.threadId` 去重) | 否 | 侧边对话(每对话一 Tab):打开即建空线程(首条消息赢得标签并同步标题);线程 = 插件自建子会话(种子继承父会话上下文,进行中回合以 `interrupted` 闭合;种子带合法 `subagent/descriptor`,SubagentView 按 `Side: ` 前缀过滤),`origin:'subagent'` 隐藏于主列表;走 `/sidebar/api/sidechat.*` 路由;头部菜单切换/重开(`parkSidechatReopen` + 确定性 id),关 Tab 释放 live agent;重开经 `collectOwnEvents` 回源到种子边界;「保存为新会话」= `session.fork`(`this` 敏感)。[设计文档](plans/2026-08-20-sidechat-tab-design.md) | @@ -609,7 +610,7 @@ const { value } = await res.json() // 错误时 { ok: false, error: { code, me | 方法 | 说明 | |---|---| | `session.cwd` | 会话权威 cwd(`{ cwd, root, parent }`) | -| `fs.tree` | 目录列表(`{ path, entries: FsEntry[], truncated }`;FsEntry 含 `isSymlink`/`broken`,目录软链接的 `isDir` 按目标类型) | +| `fs.tree` / `fs.trees` | 目录列表(`{ path, entries: FsEntry[], truncated }`;FsEntry 含 `isSymlink`/`broken`,目录软链接的 `isDir` 按目标类型;请求可带 `exclude` 模式串,行上可带 `compact` 标记——单目录链由 client 折叠为面包屑行,匹配条目从列表与折叠探测中彻底移除)。`fs.trees` 是批量版(文件树的真实入口,同样吃 `exclude`) | | `fs.trees` | **批量**目录列表(v0.23.0+):入参 `{ sessionId, cwd?, paths: string[] }`(最多 64 条,绝对或会话相对),一次请求返回 `{ levels: [{ path, entries, truncated, error? }] }`。每层与 `fs.tree` 同解析、同缓存;**某一层失败只在该层带 `error`**(`entries: []`),整个批次仍是成功响应——树的一次挂载/刷新因此是 1 个请求而不是 N 个 | | `fs.read` | 读文件:文本返回 `{ kind: 'text', content, truncated, mtimeMs }`;二进制返回 `{ kind: 'binary', size, truncated, mtimeMs, head }`(head = base64 前 4KB;`mtimeMs` = 本次读取的磁盘 mtime,保存冲突基线) | | `fs.write` | 原子写文件:`{ path, content, expectedMtimeMs? }`。带 `expectedMtimeMs` 时是乐观并发门——磁盘 mtime 与基线不符则拒绝(409,wire 错误码 `fs-conflict`),不覆盖对方字节;省略则不做门禁。成功返回 `{ ok: true, mtimeMs }`(新基线) | @@ -729,7 +730,7 @@ interface BetterSidebarService { /** 能力清单(只增不删,唯一例外:v0.19.0 删除了 'floatWindows'): * 'badge' | 'tabLifecycle' | 'updateTab' | 'openFile' | 'targetedOpen' | * 'stateSubscription' | 'tabMeta' | 'pluginSettings' | 'urlTarget' | - * 'settingSelect' | 'fileIcons' | 'rightActions' + * 'settingSelect' | 'fileIcons' | 'rightActions' | 'settingPatterns' * ——用 `features.includes('xxx')` 按能力 gate。 */ readonly features: readonly string[] /** 当前快照:激活 sessionId + 其状态(面板几何/打开的 tabs/展开集)+ prefs。 @@ -899,7 +900,7 @@ ctx.effect(() => - 展示:小卡片网格(图标 + 标题 + 类型 id),**高亮 = 启用**,勾选徽标钉在卡片最右端;viewer 卡片额外显示扩展名。 - 持久化:开关写入 `SidebarPrefs.tabsEnabled / viewersEnabled`(开放 map,**缺省 = 启用**,显式 `false` 才禁用)。 - 关闭语义:tab 从 `+` 菜单消失、`openTab` 拒绝新开(`console.warn`)、派生流程(子代理自动展开、agent 终端自动补 tab)停止,**已打开的 tab 保留**;viewer 被 `matchFileViewer` 跳过,文件落到下一个匹配。 -- `settings.toggles`(可选):在卡片行下追加**嵌套设置行**(仅父级启用时显示),绑定 `SidebarPrefs` 字段;通过卡片底部「功能设置」条在原生弹窗中编辑。行控件形状见 §4.1 的 `SettingRow`:`type: 'switch' | 'text' | 'number'`(v0.11.0+;text/number 行 blur/Enter 提交,number 行按 min/max 钳制,unit 渲染单位后缀)与 `type: 'select'`(v0.13.0+;`options` 支持 value/title/desc/icon,`multi` 多选存数组并按 options 顺序提交;任一项带 icon 时渲染大图标选项卡)。内置示例:subagent tab 的 `autoOpenSubagent`、editor tab 的 `editorExplorer` 图标化下拉(工作区路径围栏与它的开关已移除,见 §8.1)。 +- `settings.toggles`(可选):在卡片行下追加**嵌套设置行**(仅父级启用时显示),绑定 `SidebarPrefs` 字段;通过卡片底部「功能设置」条在原生弹窗中编辑。行控件形状见 §4.1 的 `SettingRow`:`type: 'switch' | 'text' | 'number'`(v0.11.0+;text/number 行 blur/Enter 提交,number 行按 min/max 钳制,unit 渲染单位后缀)与 `type: 'select'`(v0.13.0+;`options` 支持 value/title/desc/icon,`multi` 多选存数组并按 options 顺序提交;任一项带 icon 时渲染大图标选项卡)与 `type: 'patterns'`(可编辑字符串数组——chips + 删除钮 + 常驻添加输入框,add/remove 均原子提交整表,占位符走 `patternsPlaceholder`,值必须存 `string[]`;能力 gate `settingPatterns`)。内置示例:subagent tab 的 `autoOpenSubagent`、editor tab 的 `editorExplorer` 图标化下拉(工作区路径围栏与它的开关已移除,见 §8.1)与 `explorerExclude` 排除模式行。 - `settings.pluginToggles`(可选,v0.12.0+):**插件自有设置行**,行控件与 toggles 相同,但 key 是插件局部的——持久化在 prefs 文档的 `pluginSettings[]`(开放 map,无需宿主 schema 字段)。tab 与 viewer 都可用(v0.12.0 起 viewer 卡片也有设置条)。 - `settings.render`(可选,v0.12.0+):**自定义设置面板**——追加渲染在行列表之后,可单独存在。props 含 store/service/prefs、本 descriptor 的 `pluginSettings` blob、`updatePluginSetting(key, value)` 与 `close()`;抛错会被吞掉并显示内联错误。 @@ -939,7 +940,7 @@ ctx.effect(() => ) ``` -> ⚠️ **`toggles` 的 key 必须是本插件 `PrefsSchema` 的字段**(`PrefsSchema` 已并入本插件 Loader 行的 `Config`;内置键:`autoOpenSubagent` / `autoOpenJobs` / `tasksViewMode` / `mobileNoAutoOpen` / `mobileDefaultTree` / `agentOpenTools` / `editorExplorer` / `titleBarScheme` / `titleBarPresetId` / `customCss` / `titleBarCompat` / `titleBarStripPx` / `htmlViewerNoSandbox` / `htmlViewerDefaultUnsafe` / `tabsEnabled` / `viewersEnabled` / `pluginSettings`;**已删除**:`workspaceFence`(v0.23.0,围栏整体移除,见 §8.1)/ `agentTerminalTools` / `terminalShell` / `terminalShellArgs` / `terminalFontFamily` / `terminalFontSize` / `bottomPanelAutoTerminal` / `browserNoSandbox` / `browserAllowedLoopback` / 三个按协议分流的旧外链接管键)。**v0.12.0 起设置 seam 已开放**:你自己的设置走 `pluginToggles`(声明式行)或 `render`(自定义面板),值持久化在 `pluginSettings[id]`——不再需要本插件的 schema 字段,也不再被 seam 丢弃。值须 JSON 可序列化(行控件只产出 string/number/boolean;自定义面板自行负责)。 +> ⚠️ **`toggles` 的 key 必须是本插件 `PrefsSchema` 的字段**(`PrefsSchema` 已并入本插件 Loader 行的 `Config`;内置键:`autoOpenSubagent` / `autoOpenJobs` / `tasksViewMode` / `mobileNoAutoOpen` / `mobileDefaultTree` / `agentOpenTools` / `editorExplorer` / `explorerExclude` / `titleBarScheme` / `titleBarPresetId` / `customCss` / `titleBarCompat` / `titleBarStripPx` / `htmlViewerNoSandbox` / `htmlViewerDefaultUnsafe` / `tabsEnabled` / `viewersEnabled` / `pluginSettings`;**已删除**:`workspaceFence`(v0.23.0,围栏整体移除,见 §8.1)/ `agentTerminalTools` / `terminalShell` / `terminalShellArgs` / `terminalFontFamily` / `terminalFontSize` / `bottomPanelAutoTerminal` / `browserNoSandbox` / `browserAllowedLoopback` / 三个按协议分流的旧外链接管键)。**v0.12.0 起设置 seam 已开放**:你自己的设置走 `pluginToggles`(声明式行)或 `render`(自定义面板),值持久化在 `pluginSettings[id]`——不再需要本插件的 schema 字段,也不再被 seam 丢弃。值须 JSON 可序列化(行控件只产出 string/number/boolean;自定义面板自行负责)。 ### 8.2 宿主设置表单(DSH 0.1.7+:`SettingsForms`) @@ -1166,7 +1167,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`**:文件树 / 树面板 / host 文件名搜索(`fs.search`;`tests/fs-search.spec.ts`) +- **`src/client/FileTree.tsx`** / **`TreePanel.tsx`** / **`src/fs-search.ts`**:文件树 / 树面板 / host 文件名搜索(`fs.search`)。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` - **`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;内置清单断言(5 tab + 3 viewer + 声明式元数据,并显式断言 image / pdf / binary-download **不在**内置清单里、但作为公开契约仍可被第三方注册) diff --git a/src/client/EditorHost.tsx b/src/client/EditorHost.tsx index bcde823c..d692be41 100644 --- a/src/client/EditorHost.tsx +++ b/src/client/EditorHost.tsx @@ -146,6 +146,15 @@ export function EditorHost(props: { useCallback((callback: () => void) => store.subscribe(callback), [store]), useCallback(() => store.getSnapshot().prefs.editorExplorer, [store]), ) + // The exclude-pattern list (VS Code files.exclude style): the HOST filters + // the listing with it, so a changed list reloads the tree (FileTree wipes + // its level cache when the list's VALUE changes). The snapshot array + // identity is stable until prefs are rewritten, so useSyncExternalStore + // stays quiet. + const exclude = useSyncExternalStore( + useCallback((callback: () => void) => store.subscribe(callback), [store]), + useCallback(() => store.getSnapshot().prefs.explorerExclude, [store]), + ) // The DSH-native "open with" capability (host open-in-app): one adapter per // window, shared by every row menu below. The plugin no longer owns a // target list, a URL vocabulary or a spawn route — the host reports which @@ -467,6 +476,7 @@ export function EditorHost(props: { onReferenceFile={onReferenceFile} onPathRenamed={onPathRenamed} onPathDeleted={onPathDeleted} + exclude={exclude} service={ctx.get('betterSidebar')} /> @@ -594,6 +604,7 @@ export function EditorHost(props: { onReferenceFile={onReferenceFile} onPathRenamed={onPathRenamed} onPathDeleted={onPathDeleted} + exclude={exclude} service={ctx.get('betterSidebar')} /> diff --git a/src/client/FileTree.tsx b/src/client/FileTree.tsx index 8c31b7f2..7118e9b8 100644 --- a/src/client/FileTree.tsx +++ b/src/client/FileTree.tsx @@ -6,7 +6,9 @@ * directories sort first, hidden entries render dimmed. The expansion set * lives in the per-session state (owned by the caller); the caller also owns * the refresh affordance — a `refreshTick` bump wipes the level cache so the - * visible set reloads. + * visible set reloads. Chains of dirs holding exactly one real dir child each + * fold into one breadcrumb row (`a/b/c`, VSCode "compact folders"); clicking + * the row toggles the whole chain. * * Selection (VS Code semantics, no modifier = the old click semantics * untouched): Ctrl/Cmd+click toggles a row and sets the anchor, Shift+click @@ -50,6 +52,7 @@ import { import { SiCursor, SiZedindustries } from 'react-icons/si' import { VscFolderOpened, VscLinkExternal, VscPin, VscPinned } from 'react-icons/vsc' import { api, archiveBuild, archiveDownloadUrl, archiveStatus, downloadUrl, type FsEntry, type FsLevel } from './api.ts' +import { compactChain, compactLoadTargets } from './file-tree-compact.ts' import { FS_TREES_MAX_PATHS } from '../fs-batch.ts' import { builtinFileIcon, builtinFolderIcon } from './file-icons.tsx' import { IconUploadOutline16, IconVscode16 } from './icons.tsx' @@ -181,7 +184,13 @@ interface ActivateModifiers { * one reads the live props/state through the refs the tree maintains. */ interface RowActions { - activate(event: ActivateModifiers, path: string, isDir: boolean): void + /** + * Activate one row. `path` is the row's IDENTITY (the fold chain's head, so + * selection stays keyed to the rendered row); `chain` — directories only — + * names the links a plain click toggles, so a folded `a/b/c` row opens and + * closes as one row instead of only ever toggling its head. + */ + activate(event: ActivateModifiers, path: string, isDir: boolean, chain?: readonly FsEntry[]): void contextMenu(event: MouseEvent, path: string, isDir: boolean): void reference(path: string, isDir: boolean): void dragOver(event: DragEvent, dir: string): void @@ -283,6 +292,13 @@ const FileRow = memo(function FileRow(props: FileRowProps): ReactNode { /** One directory row's props (same stability rules as {@link FileRowProps}). */ interface DirRowProps { entry: FsEntry + /** + * The fold chain this row renders: `[entry]` for an ordinary directory, or + * the singleton-dir breadcrumb (`a` → `a/b` → `a/b/c`) VSCode calls + * "compact folders". The array identity is stable while the level cache + * stands (see the chain cache in the tree body), so memo() still bails out. + */ + chain: readonly FsEntry[] depth: number expanded: boolean iconsVersion: number @@ -297,9 +313,13 @@ interface DirRowProps { } const DirRow = memo(function DirRow(props: DirRowProps): ReactNode { - const { entry, depth, expanded, iconsVersion, service, selected, revealed, dropTarget, gitChanged, copied, actions } = props + const { entry, chain, depth, expanded, iconsVersion, service, selected, revealed, dropTarget, gitChanged, copied, actions } = props void iconsVersion - const icon = service !== undefined ? service.folderIcon(entry.path, expanded, 14) : builtinFolderIcon(expanded, 14) + // The row's ACTIONS target the chain's deepest link: that is the directory + // the user sees expanded (`a/b/c`), so dropping into it, renaming it or + // opening a menu on it must address `c`, not the fold head `a`. + const target = chain[chain.length - 1]! + const icon = service !== undefined ? service.folderIcon(target.path, expanded, 14) : builtinFolderIcon(expanded, 14) return (
{ actions.activate(event, entry.path, true) }} + // A folded row renders the whole chain (`a/b/c`) and a plain click + // toggles every link at once, so the breadcrumb opens and closes as one. + title={chain.length > 1 ? target.path : undefined} + onClick={(event) => { actions.activate(event, entry.path, true, chain) }} onKeyDown={(event: KeyboardEvent) => { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault() - actions.activate(event, entry.path, true) + actions.activate(event, entry.path, true, chain) } }} - onDragOver={(event) => { actions.dragOver(event, entry.path) }} - onDrop={(event) => { actions.drop(event, entry.path, true) }} - onContextMenu={(event) => { actions.contextMenu(event, entry.path, true) }} + onDragOver={(event) => { actions.dragOver(event, target.path) }} + onDrop={(event) => { actions.drop(event, target.path, true) }} + onContextMenu={(event) => { actions.contextMenu(event, target.path, true) }} > {icon} - {entry.name} + + {chain.length > 1 ? chain.map(link => link.name).join('/') : entry.name} + {entry.isSymlink && } {copied ? {t('copied')} @@ -338,7 +363,7 @@ const DirRow = memo(function DirRow(props: DirRowProps): ReactNode { title={t('referenceFile')} onClick={(event) => { event.stopPropagation() - actions.reference(entry.path, true) + actions.reference(target.path, true) }} > {t('referenceFile')} @@ -433,6 +458,10 @@ export function FileTree(props: { onToggleOpenWithPin?: (targetId: string) => void /** Insert `@` into the composer draft (file vs directory). */ onReferenceFile: (path: string, isDir: boolean) => void + /** The explorerExclude pref patterns: the HOST filters the listing with + * them (excluded rows never arrive), so changing the list wipes the level + * cache and reloads — the rows themselves need no client-side filter. */ + exclude?: readonly string[] /** A rename landed (old row path → new path): the caller retargets open tabs. */ onPathRenamed?: (oldPath: string, newPath: string) => void /** A delete landed: the caller closes tabs at or under the removed path. */ @@ -477,7 +506,7 @@ export function FileTree(props: { const { sessionId, cwd, expanded, revealed, onOpenFileNewTab, onOpenFileSide, openInApp, openWithTargets, openWithPinned, openWithSsh, onOpenWith, onToggleOpenWithPin, - openWithShowPluginTargets, + openWithShowPluginTargets, exclude, onPathRenamed, onPathDeleted, refreshTick, onUploadRequest, busy, hidden, visible, service, } = props /** The live props for the stable callbacks below (identity churns per render). */ @@ -633,6 +662,15 @@ export function FileTree(props: { setData(dataRef.current) }, []) + /** + * The exclude list by VALUE. The caller owns the array identity (the prefs + * store hands out one stable reference per document), but the level cache, + * the request payload and the reload effect all key on the CONTENT: a + * value-equal list that churned identity would otherwise re-list the whole + * tree on every render. Declared here because `loadLevels` below reads it. + */ + const excludeKey = (exclude ?? []).join('\0') + /** * List a SET of directories into the cache with ONE `fs.trees` request. * @@ -693,7 +731,7 @@ export function FileTree(props: { | { batch: string[]; ok: false; message: string } void Promise.all(batches.map(async (batch): Promise => { try { - return { batch, ok: true, levels: (await api.fsTrees({ sessionId, cwd }, batch)).levels } + return { batch, ok: true, levels: (await api.fsTrees({ sessionId, cwd }, batch, excludeKey === '' ? undefined : excludeKey.split('\0'))).levels } } catch (error: unknown) { return { batch, ok: false, message: error instanceof Error ? error.message : String(error) } } @@ -727,7 +765,7 @@ export function FileTree(props: { // fresher. With nothing to keep, the per-level rows already say it. if (failure !== '') setLoadError(keptListing ? failure : null) }) - }, [sessionId, cwd, storeLevel]) + }, [sessionId, cwd, excludeKey, storeLevel]) /** * Re-list one directory in place (a watch notice, or the parent of a landed @@ -802,6 +840,20 @@ export function FileTree(props: { forceNextLoad.current = true }, [refreshTick]) + // The exclude patterns are applied HOST-side, so a changed list makes every + // cached level stale (the old rows include entries the list now removes, and + // miss entries it no longer hides): wipe the cache and let the load effect + // below re-list the visible set in one batch. Declared BEFORE it so the wipe + // lands first; the first pass only records the list. + const lastExclude = useRef(excludeKey) + useEffect(() => { + if (lastExclude.current === excludeKey) return + lastExclude.current = excludeKey + generationRef.current += 1 + dataRef.current = {} + setData({}) + }, [excludeKey]) + useEffect(() => { // Load the visible set in ONE batch request; already-loaded levels (kept // in the cache) are not refetched, so this asks only for what is new — a @@ -813,6 +865,16 @@ export function FileTree(props: { loadLevels([root, ...expanded], { force }) }, [cwd, expanded, refreshTick, loadLevels]) + useEffect(() => { + // A fold chain runs through COLLAPSED singleton directories, so their + // levels are loaded ahead of any expansion (without them the breadcrumb + // label would grow one segment at a time as the user clicks). Each arrival + // can reveal the next link, hence the rescan on every cache update; + // loadLevels skips what is already loaded, so this settles. + if (cwd === undefined) return + loadLevels(compactLoadTargets(dataRef.current)) + }, [cwd, data, loadLevels]) + // A torn-down tree must not write the answer of an in-flight batch into a // dead component: bumping the generation makes every late response stale. useEffect(() => () => { generationRef.current += 1 }, []) @@ -939,7 +1001,7 @@ export function FileTree(props: { } // ── Stable row actions ───────────────────────────────────────────────── - const handleActivate = useCallback((event: ActivateModifiers, path: string, isDir: boolean): void => { + const handleActivate = useCallback((event: ActivateModifiers, path: string, isDir: boolean, chain?: readonly FsEntry[]): void => { if (event.ctrlKey || event.metaKey) { toggleSelect(path, isDir) return @@ -950,8 +1012,18 @@ export function FileTree(props: { } // Plain click: the original semantics, plus dropping any selection. clearSelection() - if (isDir) propsRef.current.onToggle(path) - else propsRef.current.onOpenFile(path) + if (!isDir) { + propsRef.current.onOpenFile(path) + return + } + // A folded row toggles the WHOLE chain: expanding every link is what makes + // the tail's children render, and collapsing every link is the only way to + // close a chain an earlier expansion (before the fold formed) left open. + const links = chain !== undefined && chain.length > 0 ? chain.map(link => link.path) : [path] + const open = links.some(link => expandedSetRef.current.has(link)) + for (const link of links) { + if (expandedSetRef.current.has(link) === open) propsRef.current.onToggle(link) + } }, [clearSelection, selectRange, toggleSelect]) const handleContextMenu = useCallback((event: MouseEvent, path: string, isDir: boolean): void => { @@ -1478,6 +1550,24 @@ export function FileTree(props: { * a parked tab unsubscribes from the poll. */ const gitStatus = useGitStatus({ sessionId, cwd }, { visible: visible !== false }) + /** + * Fold chains (VSCode "compact folders"): resolved ONCE per level-cache + * revision and REUSED while it stands. {@link DirRow} is memoized on prop + * identity, so handing it a freshly built array on every render would + * re-render every directory row for a selection, a hover or a copy flash — + * exactly what the row memoization exists to prevent. + */ + const chainFor = useMemo(() => { + const cache = new Map() + return (entry: FsEntry): readonly FsEntry[] => { + const cached = cache.get(entry.path) + if (cached !== undefined) return cached + const chain: readonly FsEntry[] = entry.compact === true ? compactChain(entry, path => data[path]) : [entry] + cache.set(entry.path, chain) + return chain + } + }, [data]) + // The Shift range walks the rows the user can actually see: depth-first, // expanded state decides. Recomputed with the level cache, never rendered. const visibleRows = useMemo(() => { @@ -1486,13 +1576,19 @@ export function FileTree(props: { const level = data[dir] if (level?.entries === undefined) return for (const entry of level.entries) { + // A folded row IS one row: its identity is the chain head (the level + // entry the walk is on), and it descends into the chain TAIL — the + // same shape `renderLevel` draws, so a Shift range covers what the + // user sees. rows.push({ path: entry.path, isDir: entry.isDir }) - if (entry.isDir && expandedSet.has(entry.path)) walk(entry.path) + if (!entry.isDir) continue + const chain = chainFor(entry) + if (chain.some(link => expandedSet.has(link.path))) walk(chain[chain.length - 1]!.path) } } if (root !== undefined) walk(root) return rows - }, [data, expandedSet, root]) + }, [chainFor, data, expandedSet, root]) visibleRowsRef.current = visibleRows /** @@ -1618,28 +1714,41 @@ export function FileTree(props: { <> {head} {entries.map((entry) => { + // Fold chains (VSCode "compact folders"): a chain of dirs holding + // exactly one real dir child each renders as ONE `a/b/c` row; the + // chain pauses at whatever the level cache has loaded. Resolved for + // directories only, and through the per-revision cache so DirRow's + // memoization survives an unrelated re-render. + const chain = entry.isDir ? chainFor(entry) : undefined // The row being renamed renders as its editor (no button semantics: // an editor is not a click target — and a nested interactive inside - // role="button" would be invalid anyway). - if (renaming?.path === entry.path) return renderRenameRow(entry, depth) - if (entry.isDir) { - const isOpen = expandedSet.has(entry.path) + // role="button" would be invalid anyway). A folded row's menu + // addressed its TAIL, so any chain link puts the whole row here. + if (renaming !== null && (renaming.path === entry.path || chain?.some(link => link.path === renaming.path) === true)) { + return renderRenameRow(entry, depth) + } + if (chain !== undefined) { + const tail = chain[chain.length - 1]! + const isOpen = chain.some(link => expandedSet.has(link.path)) return (
revealedSet.has(link.path))} + dropTarget={dropTarget === tail.path} gitChanged={gitStatus.dirHasChanges(entry.path)} copied={copiedPath === entry.path} actions={actions} /> - {isOpen && renderLevel(entry.path, depth + 1)} + {isOpen && renderLevel(tail.path, depth + 1)}
) } diff --git a/src/client/SideCardSection.module.css b/src/client/SideCardSection.module.css index ff19d7cf..b02ed392 100644 --- a/src/client/SideCardSection.module.css +++ b/src/client/SideCardSection.module.css @@ -616,6 +616,70 @@ outline-offset: 1px; } +/* Patterns rows (type 'patterns'): an editable string list — removable + chips over the committed values plus one always-present add input. The + row stacks vertically (title/desc, then chips, then the input) because + the list needs the popup's full width. */ +.patternsRow { + display: flex; + flex-direction: column; + gap: 10px; + min-width: 0; + padding: 14px 16px; + border: 1px solid var(--dsw-alias-border-l2); + border-radius: 12px; +} + +.patternsChips { + display: flex; + flex-wrap: wrap; + gap: 6px; +} + +.patternsChip { + display: inline-flex; + align-items: center; + gap: 2px; + padding: 2px 4px 2px 9px; + border: 1px solid var(--dsw-alias-border-l2); + border-radius: 999px; + background: var(--dsw-alias-bg-layer-2); + font-size: 12px; + line-height: 18px; + color: var(--dsw-alias-label-primary); +} + +.patternsChipRemove { + display: inline-flex; + align-items: center; + justify-content: center; + width: 16px; + height: 16px; + border: none; + border-radius: 999px; + background: transparent; + color: var(--dsw-alias-label-tertiary); + font-size: 13px; + line-height: 1; + cursor: pointer; +} + +.patternsChipRemove:hover { + background: var(--dsw-alias-interactive-bg-hover); + color: var(--dsw-alias-label-primary); +} + +.patternsAdd { + display: flex; + align-items: center; + gap: 8px; +} + +.patternsInput { + flex: 1 1 auto; + min-width: 0; +} + .error { padding: 10px 0 2px; font-size: 12px; diff --git a/src/client/SideCardSection.tsx b/src/client/SideCardSection.tsx index 1676586c..94c8be53 100644 --- a/src/client/SideCardSection.tsx +++ b/src/client/SideCardSection.tsx @@ -226,6 +226,9 @@ export function FeatureSettingsRows(props: { * of picked values (`multi: true`). Optional: rows with no handler are * display-only. */ onSelectValue?: (toggle: SidebarSettingToggle, next: unknown) => void + /** Commit one patterns row: the whole string list after an add/remove. + * Optional: rows with no handler are display-only. */ + onPatterns?: (toggle: SidebarSettingToggle, next: string[]) => void /** Explicit value source (v0.12.0+): when given, rows read their values * from it instead of the `prefs` face — plugin-owned rows read their * own blob, so a plugin key can never collide with (or silently read) @@ -233,12 +236,23 @@ export function FeatureSettingsRows(props: { * the latter collides with the inherited Object.prototype.valueOf.) */ valueSource?: (key: string) => unknown }) { - const { toggles, prefs, onToggle, onCommit, onSelectValue, valueSource } = props + const { toggles, prefs, onToggle, onCommit, onSelectValue, onPatterns, valueSource } = props const read = valueSource ?? ((key: string): unknown => (prefs as unknown as Record)[key]) return (
{toggles.map(toggle => { const title = textOf(toggle.title) + if (toggle.type === 'patterns') { + return ( + + ) + } if (toggle.type === 'select') { return ( void +}) { + const { toggle, title, value, onPatterns } = props + const patterns = Array.isArray(value) ? value.filter(item => typeof item === 'string') as string[] : [] + const [draft, setDraft] = useState('') + const commitAdd = (): void => { + const next = draft.trim() + setDraft('') + if (next === '' || patterns.includes(next)) return + onPatterns?.(toggle, [...patterns, next]) + } + return ( +
+ + {title} + {textOf(toggle.desc) !== '' && {textOf(toggle.desc)}} + + {patterns.length > 0 && ( +
+ {patterns.map((pattern, index) => ( + + {pattern} + + + ))} +
+ )} +
+ { setDraft(event.currentTarget.value) }} + onKeyDown={event => { + if (event.key === 'Enter') { + event.preventDefault() + commitAdd() + } + }} + /> + +
+
+ ) +} + /** * The secondary settings popup body of one feature (tab or viewer): * - the host-prefs `toggles` rows, then the plugin-owned `pluginToggles` @@ -504,13 +588,15 @@ export function SettingsBody(props: { onToggle: (toggle: SidebarSettingToggle, next: boolean) => void onCommit: (toggle: SidebarSettingToggle, raw: string) => string onSelectValue: (toggle: SidebarSettingToggle, next: unknown) => void + onPatterns: (toggle: SidebarSettingToggle, next: string[]) => void onPluginToggle: (toggle: SidebarSettingToggle, next: boolean) => void onPluginCommit: (toggle: SidebarSettingToggle, raw: string) => string onPluginSelectValue: (toggle: SidebarSettingToggle, next: unknown) => void + onPluginPatterns: (toggle: SidebarSettingToggle, next: string[]) => void onPluginWrite: (key: string, value: unknown) => void onClose: () => void }) { - const { feature, prefs, store, service, onToggle, onCommit, onSelectValue, onPluginToggle, onPluginCommit, onPluginSelectValue, onPluginWrite, onClose } = props + const { feature, prefs, store, service, onToggle, onCommit, onSelectValue, onPatterns, onPluginToggle, onPluginCommit, onPluginSelectValue, onPluginPatterns, onPluginWrite, onClose } = props const render = feature.settings?.render const toggles = feature.settings?.toggles ?? [] const pluginToggles = feature.settings?.pluginToggles ?? [] @@ -531,6 +617,7 @@ export function SettingsBody(props: { onToggle={onToggle} onCommit={onCommit} onSelectValue={onSelectValue} + onPatterns={onPatterns} /> )} {pluginToggles.length > 0 && ( @@ -540,6 +627,7 @@ export function SettingsBody(props: { onToggle={onPluginToggle} onCommit={onPluginCommit} onSelectValue={onPluginSelectValue} + onPatterns={onPluginPatterns} valueSource={(key) => pluginBlob[key]} /> )} @@ -685,6 +773,11 @@ export function SideCardSection({ store, service }: SideCardSectionProps) { applyPref({ [toggle.key]: next }) } + /** Commit one declaratively-declared patterns row (the whole string list). */ + const onPatternsSetting = (toggle: SidebarSettingToggle, next: string[]): void => { + applyPref({ [toggle.key]: next }) + } + /** * Commit one declaratively-declared text/number row. Numbers are parsed * and clamped to the toggle's declared min/max (an unparsable input falls @@ -1042,9 +1135,11 @@ export function SideCardSection({ store, service }: SideCardSectionProps) { onToggle={onToggleSetting} onCommit={onCommitSetting} onSelectValue={onSelectSetting} + onPatterns={onPatternsSetting} onPluginToggle={(toggle, next) => { onPluginToggle(settingsFor.id, toggle, next) }} onPluginCommit={(toggle, raw) => onPluginCommitSetting(settingsFor.id, toggle, raw)} onPluginSelectValue={(toggle, next) => { applyPluginSetting(settingsFor.id, toggle.key, next) }} + onPluginPatterns={(toggle, next) => { applyPluginSetting(settingsFor.id, toggle.key, next) }} onPluginWrite={(key, value) => { applyPluginSetting(settingsFor.id, key, value) }} onClose={() => { setSettingsFor(null) }} store={store} diff --git a/src/client/TreePanel.tsx b/src/client/TreePanel.tsx index 64acbd8f..8e35aad7 100644 --- a/src/client/TreePanel.tsx +++ b/src/client/TreePanel.tsx @@ -74,6 +74,10 @@ export function TreePanel(props: { * through to FileTree). */ openWithShowPluginTargets?: boolean onReferenceFile: (path: string, isDir: boolean) => void + /** The explorerExclude pref patterns: the host filters the tree listing AND + * the name search with them (passed through to FileTree, and carried on the + * search request so both surfaces agree). */ + exclude?: readonly string[] /** A tree rename landed (passed through to FileTree for tab retargeting). */ onPathRenamed?: (oldPath: string, newPath: string) => void /** A tree delete landed (passed through to FileTree for tab closing). */ @@ -90,7 +94,7 @@ export function TreePanel(props: { const { sessionId, cwd, expanded, revealed, onToggle, onOpenFile, onOpenFileNewTab, onOpenFileSide, openInApp, openWithTargets, openWithPinned, openWithSsh, onOpenWith, onToggleOpenWithPin, - openWithShowPluginTargets, + openWithShowPluginTargets, exclude, onReferenceFile, onPathRenamed, onPathDeleted, visible, full, service, } = props const [query, setQuery] = useState('') @@ -172,6 +176,12 @@ export function TreePanel(props: { const needle = query.trim() const searching = needle !== '' + // The search effect below must re-run on a CHANGED list, never on a churned + // array identity: the prefs store hands out one stable reference per + // document, but keying on the value is what makes that a guarantee rather + // than an assumption (a re-run resets the 300ms debounce, so a per-render + // identity would keep the search from ever settling). + const excludeKey = (exclude ?? []).join('\0') useEffect(() => { if (needle === '') { setResults(null) @@ -179,8 +189,9 @@ export function TreePanel(props: { return } const controller = new AbortController() + const patterns = excludeKey === '' ? undefined : excludeKey.split('\0') const timer = window.setTimeout(() => { - api.fsSearch({ sessionId, cwd }, needle, controller.signal).then((found) => { + api.fsSearch({ sessionId, cwd }, needle, patterns, controller.signal).then((found) => { setResults(found) setError(null) }).catch((failure: unknown) => { @@ -193,7 +204,7 @@ export function TreePanel(props: { window.clearTimeout(timer) controller.abort() } - }, [sessionId, cwd, needle]) + }, [sessionId, cwd, needle, excludeKey]) const busy = upload !== null /** Directory hits (the host reports them separately): a click navigates the @@ -327,6 +338,7 @@ export function TreePanel(props: { onOpenWith={onOpenWith} onToggleOpenWithPin={onToggleOpenWithPin} openWithShowPluginTargets={openWithShowPluginTargets} + exclude={exclude} onReferenceFile={onReferenceFile} onPathRenamed={onPathRenamed} onPathDeleted={onPathDeleted} diff --git a/src/client/api.ts b/src/client/api.ts index 3455e9cd..a27a5b65 100644 --- a/src/client/api.ts +++ b/src/client/api.ts @@ -38,6 +38,9 @@ export interface FsEntry { isSymlink: boolean /** For symlinks: the target is missing or unreadable (stat failed). */ broken: boolean + /** Directory rows only: the contents are exactly one non-symlink child + * — the explorer folds such chains into one breadcrumb row. */ + compact?: boolean } /** One level of a `fs.trees` batch: a listing, or that level's failure. */ @@ -282,21 +285,25 @@ function openExternal(payload: OpenExternalPayload): Promise export const api = { sessionCwd: (scope: SessionScope, signal?: AbortSignal) => call<{ sessionId: string; cwd: string; root: string; parent: string | null }>('session.cwd', scopePayload(scope, {}), signal), - fsTree: (scope: SessionScope, path: string, signal?: AbortSignal) => - call<{ path: string; entries: FsEntry[]; truncated: boolean }>('fs.tree', scopePayload(scope, { path }), signal), + fsTree: (scope: SessionScope, path: string, exclude?: readonly string[], signal?: AbortSignal) => + call<{ path: string; entries: FsEntry[]; truncated: boolean }>('fs.tree', scopePayload(scope, { path, exclude }), signal), /** * Batch listing: every requested level in ONE request (the tree's mount and * refresh send the expanded set instead of N `fsTree` calls). A level that * failed carries `error` in place — the batch itself still succeeds. + * `exclude` carries the explorerExclude pref: matched entries never arrive + * (the host filters, so no client-side pass is needed). */ - fsTrees: (scope: SessionScope, paths: readonly string[], signal?: AbortSignal) => - call<{ levels: FsLevel[] }>('fs.trees', scopePayload(scope, { paths: [...paths] }), signal), + 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). */ - fsSearch: (scope: SessionScope, query: string, signal?: AbortSignal) => - call<{ matches: string[]; dirs: string[]; truncated: boolean }>('fs.search', scopePayload(scope, { query }), signal), + * 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). */ + 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) => call('fs.read', scopePayload(scope, { path }), signal), /** Save a file. `expectedMtimeMs` is the mtime the draft was based on: a diff --git a/src/client/builtins/tabs.tsx b/src/client/builtins/tabs.tsx index 03d06c7a..34f82197 100644 --- a/src/client/builtins/tabs.tsx +++ b/src/client/builtins/tabs.tsx @@ -43,7 +43,8 @@ export function builtinTabs(): readonly TabDescriptor[] { dedupeKey: (tab) => tab.path, // Declarative settings: the file-open behavior picker (in-place switch // vs per-path windows) renders as an iconed select row under the - // editor card's gear in the Side card settings page; the "open with" + // editor card's gear in the Side card settings page; the exclude-pattern + // rows (VS Code files.exclude style) sit below it, and the "open with" // configuration (SSH host + custom editors) is the custom panel BELOW // those rows — the settings seam renders rows first, custom panel after. // The workspace-fence switch is GONE: there is no containment to toggle. @@ -67,6 +68,12 @@ export function builtinTabs(): readonly TabDescriptor[] { desc: () => t('editorExplorerSplitDesc'), }, ], + }, { + key: 'explorerExclude', + type: 'patterns', + title: () => t('explorerExclude'), + desc: () => t('explorerExcludeDesc'), + patternsPlaceholder: t('explorerExcludePlaceholder'), }], // Plugin-owned rows (values live in `pluginSettings['editor']`): the // plugin's own open-with targets are shown only when the host reports diff --git a/src/client/file-tree-compact.ts b/src/client/file-tree-compact.ts new file mode 100644 index 00000000..5c5e6494 --- /dev/null +++ b/src/client/file-tree-compact.ts @@ -0,0 +1,77 @@ +/** + * Pure logic behind the explorer's breadcrumb folder compaction (VSCode's + * "compact folders"): a directory whose contents are exactly one child + * (host flag `compact`) folds together with its sole directory children + * into one `a/b/c` row — the chain extends only through DIRECTORY links, + * the terminal link's sole child may be a file. The host only ever marks + * non-symlink children, so a fold chain can never cycle through the + * filesystem — the visited guard is belt-and-braces against a stale or + * hostile cache. The chain walk skips POSIX-hidden entries (the host probe + * marks `compact` with the same filter), so junk like macOS's `.DS_Store` + * beside the sole child never snaps a chain open — regardless of whether + * the user's "show hidden files" switch renders them. + */ +import type { FsEntry } from './api.ts' + +/** One cached level as FileTree stores it (entries arrive async; error set on failure). */ +export interface CompactLevel { + entries?: FsEntry[] + error?: string +} + +/** + * Safety cap on one fold chain. Real directories cannot cycle, so this is + * never reached on a healthy cache — it bounds the chain when a stale cache + * lies about a level's contents. + */ +export const MAX_COMPACT_DEPTH = 32 + +/** + * The fold chain starting at `entry`: successive sole directory children + * while each link's level is loaded, still holds exactly one healthy + * directory child, and the chain stays within the depth cap. The returned + * chain always starts with `entry` itself; its LAST element is the level + * the expanded row renders. + */ +export function compactChain(entry: FsEntry, levelOf: (path: string) => CompactLevel | undefined): FsEntry[] { + const chain = [entry] + const visited = new Set([entry.path]) + let current = entry + while (current.compact === true && chain.length < MAX_COMPACT_DEPTH) { + const level = levelOf(current.path) + // Unloaded / failed / stale level: the chain pauses at the current link + // (the caller keeps loading while the tail stays `compact`). + if (level === undefined || level.error !== undefined || level.entries === undefined) break + // Hidden (dot-prefixed) entries don't count as children — the host + // probe marked `compact` with the same filter, so hidden junk beside + // the sole child must not snap the chain open here. + const visible = level.entries.filter(entry => entry.hidden !== true) + if (visible.length !== 1) break + const child = visible[0]! + if (!child.isDir || child.broken || visited.has(child.path)) break + visited.add(child.path) + chain.push(child) + current = child + } + return chain +} + +/** + * The collapsed singleton directories whose levels still need loading, so + * fold chains can extend past what the user has expanded. Scans every + * LOADED level once; each arrival may reveal the next link, so the caller + * re-runs this after every cache update. Chains cannot cycle (host never + * marks symlink children), so the walk terminates at the chain's real end. + */ +export function compactLoadTargets(levels: Record): string[] { + const targets = new Set() + for (const level of Object.values(levels)) { + if (level.entries === undefined) continue + for (const entry of level.entries) { + if (entry.isDir && entry.compact === true && levels[entry.path] === undefined) { + targets.add(entry.path) + } + } + } + return [...targets] +} diff --git a/src/client/locales-ar.ts b/src/client/locales-ar.ts index 9075c183..a23caf0c 100644 --- a/src/client/locales-ar.ts +++ b/src/client/locales-ar.ts @@ -50,6 +50,11 @@ export const ar: Record = { editorExplorerMergedDesc: 'الملفات تتبدّل في مكانها داخل نفس النافذة؛ النوافذ الجديدة تبدأ بالشجرة مفتوحة', editorExplorerSplit: 'منفصل', editorExplorerSplitDesc: 'النوافذ بلا مسار هي المستكشف المستقل (شجرة فقط)؛ كل ملف يفتح نافذته الخاصة (الشجرة مرساة، مغلقة افتراضياً)', + explorerExclude: 'أنماط الاستثناء', + explorerExcludeDesc: 'يزيل الإدخالات المطابقة تمامًا من شجرة الملفات والبحث (يدعم * و ?، و**/ في البداية يطابق أي عمق)؛ الإدخالات المستثناة لا تعيق طي مسار التنقل أبدًا', + explorerExcludePlaceholder: 'أضف نمطًا، مثل node_modules أو *.log أو **/.git', + explorerExcludeAdd: 'إضافة', + explorerExcludeRemove: 'إزالة', editorTreeToggle: 'لوحة شجرة الملفات', editorPathPlaceholder: 'مسار الملف (نسبي لدليل الجلسة أو مطلق)، Enter للفتح', editorSearchPlaceholder: 'البحث في الملفات بالاسم…', diff --git a/src/client/locales-de.ts b/src/client/locales-de.ts index ec01af62..0cbc6f43 100644 --- a/src/client/locales-de.ts +++ b/src/client/locales-de.ts @@ -35,6 +35,11 @@ export const de: Record = { editorExplorerMergedDesc: 'Dateien wechseln im selben Fenster; neue Fenster starten mit geöffneter Baumansicht', editorExplorerSplit: 'Getrennt', editorExplorerSplitDesc: 'Fenster ohne Pfad sind der eigenständige Explorer (nur Dateibaum); jede Datei öffnet ein eigenes Fenster (mit angedocktem, standardmäßig eingeklapptem Baum)', + explorerExclude: 'Ausschlussmuster', + explorerExcludeDesc: 'Entfernt übereinstimmende Einträge vollständig aus dem Dateibaum und der Suche (* und ? Wildcards, ein **/-Anfang trifft in jeder Tiefe); ausgeschlossene Einträge blockieren das Breadcrumb-Falten nie', + explorerExcludePlaceholder: 'Muster hinzufügen, z. B. node_modules, *.log, **/.git', + explorerExcludeAdd: 'Hinzufügen', + explorerExcludeRemove: 'Entfernen', editorTreeToggle: 'Dateibaum-Panel', editorPathPlaceholder: 'Dateipfad (relativ zum Sitzungsverzeichnis oder absolut), Enter zum Öffnen', editorSearchPlaceholder: 'Nach Dateiname suchen…', diff --git a/src/client/locales-fr.ts b/src/client/locales-fr.ts index 3f6324cf..3e475607 100644 --- a/src/client/locales-fr.ts +++ b/src/client/locales-fr.ts @@ -42,6 +42,11 @@ export const fr: Record = { editorExplorerMergedDesc: 'Les fichiers se remplacent dans la même fenêtre ; les nouvelles fenêtres ouvrent l’arborescence par défaut', editorExplorerSplit: 'Séparé', editorExplorerSplitDesc: 'Les fenêtres sans chemin sont l’explorateur autonome (arborescence uniquement) ; chaque fichier ouvre sa propre fenêtre (avec arborescence, réduite par défaut)', + explorerExclude: 'Motifs d’exclusion', + explorerExcludeDesc: 'Supprime entièrement les entrées correspondantes de l’arborescence et de la recherche (wildcards * et ?, un préfixe **/ correspond à toute profondeur) ; les entrées exclues ne bloquent jamais le repli en fil d’Ariane', + explorerExcludePlaceholder: 'Ajouter un motif, ex. node_modules, *.log, **/.git', + explorerExcludeAdd: 'Ajouter', + explorerExcludeRemove: 'Supprimer', editorTreeToggle: 'Panneau d’arborescence', editorPathPlaceholder: 'Saisissez un chemin de fichier (relatif au répertoire de session ou absolu), Entrée pour ouvrir', editorSearchPlaceholder: 'Rechercher par nom de fichier…', diff --git a/src/client/locales-hi.ts b/src/client/locales-hi.ts index 33b6e8e7..8a0425bc 100644 --- a/src/client/locales-hi.ts +++ b/src/client/locales-hi.ts @@ -49,6 +49,11 @@ export const hi: Record = { editorExplorerMergedDesc: 'फ़ाइलें उसी विंडो में स्थान पर स्विच होती हैं; नई विंडो फ़ाइल ट्री खुला हुआ शुरू होती है', editorExplorerSplit: 'अलग', editorExplorerSplitDesc: 'पथ-रहित विंडो एक्सप्लोरर है (केवल ट्री); प्रत्येक फ़ाइल अपनी नई विंडो खोलती है (ट्री साथ, डिफ़ॉल्ट रूप से संक्षिप्त)', + explorerExclude: 'बहिष्करण पैटर्न', + explorerExcludeDesc: 'मेल खाती प्रविष्टियों को फ़ाइल ट्री और खोज से पूरी तरह हटाता है (* और ? समर्थित, **/ उपसर्ग किसी भी गहराई से मेल खाता है); बहिष्कृत प्रविष्टियाँ ब्रेडक्रंब फ़ोल्डिंग में कभी बाधा नहीं डालतीं', + explorerExcludePlaceholder: 'पैटर्न जोड़ें, जैसे node_modules, *.log, **/.git', + explorerExcludeAdd: 'जोड़ें', + explorerExcludeRemove: 'हटाएँ', editorTreeToggle: 'फ़ाइल ट्री पैनल', editorPathPlaceholder: 'फ़ाइल पथ दर्ज करें (सत्र डायरेक्टरी के सापेक्ष या निरपेक्ष), Enter से खोलें', editorSearchPlaceholder: 'फ़ाइल नाम से खोजें…', diff --git a/src/client/locales-id.ts b/src/client/locales-id.ts index 71845308..507ca711 100644 --- a/src/client/locales-id.ts +++ b/src/client/locales-id.ts @@ -47,6 +47,11 @@ export const id: Record = { editorExplorerMergedDesc: 'Berkas beralih di tempat di jendela yang sama; jendela baru memulai dengan pohon terbuka', editorExplorerSplit: 'Terpisah', editorExplorerSplitDesc: 'Jendela tanpa path adalah explorer mandiri (pohon saja); setiap berkas membuka jendelanya sendiri (pohon terpasang, tertutup secara default)', + explorerExclude: 'Pola pengecualian', + explorerExcludeDesc: 'Menghapus entri yang cocok sepenuhnya dari pohon berkas dan pencarian (mendukung * dan ?, awalan **/ cocok di kedalaman apa pun); entri yang dikecualikan tidak pernah menghambat pelipatan breadcrumb', + explorerExcludePlaceholder: 'Tambahkan pola, mis. node_modules, *.log, **/.git', + explorerExcludeAdd: 'Tambah', + explorerExcludeRemove: 'Hapus', editorTreeToggle: 'Panel pohon berkas', editorPathPlaceholder: 'Path berkas (relatif terhadap direktori sesi atau absolut), Enter untuk membuka', editorSearchPlaceholder: 'Cari berkas berdasarkan nama…', diff --git a/src/client/locales-it.ts b/src/client/locales-it.ts index 1f2094d8..27657fbc 100644 --- a/src/client/locales-it.ts +++ b/src/client/locales-it.ts @@ -40,6 +40,11 @@ export const it: Record = { editorExplorerMergedDesc: 'I file cambiano sul posto nella stessa finestra; le nuove finestre avviano l’albero espanso', editorExplorerSplit: 'Separato', editorExplorerSplitDesc: 'Le finestre senza percorso sono l’esplora risorse autonomo (solo albero dei file); ogni file apre la propria finestra (albero agganciato, chiuso per impostazione predefinita)', + explorerExclude: 'Modelli di esclusione', + explorerExcludeDesc: 'Rimuove completamente le voci corrispondenti dall’albero dei file e dalla ricerca (supporta * e ?, un prefisso **/ corrisponde a qualsiasi profondità); le voci escluse non bloccano mai la compressione dei breadcrumb', + explorerExcludePlaceholder: 'Aggiungi un modello, es. node_modules, *.log, **/.git', + explorerExcludeAdd: 'Aggiungi', + explorerExcludeRemove: 'Rimuovi', editorTreeToggle: 'Pannello dell’albero dei file', editorPathPlaceholder: 'Percorso del file (relativo alla directory della sessione o assoluto), Invio per aprire', editorSearchPlaceholder: 'Cerca file per nome…', diff --git a/src/client/locales-ja.ts b/src/client/locales-ja.ts index 02cb4cc4..decc0ac0 100644 --- a/src/client/locales-ja.ts +++ b/src/client/locales-ja.ts @@ -49,6 +49,11 @@ export const ja: Record = { editorExplorerMergedDesc: '同じウィンドウ内でファイルを切り替え。新しいウィンドウはファイルツューを展開した状態で開く', editorExplorerSplit: '個別', editorExplorerSplitDesc: 'パスなしウィンドウはエクスプローラー単体(ツリーのみ)。各ファイルは別ウィンドウで開く(ツリーは格納済み、デフォルトで折りたたみ)', + explorerExclude: '除外パターン', + explorerExcludeDesc: '一致するエントリをファイルツリーと検索から完全に除外します(* と ? をサポート、**/ 接頭辞で任意の深さに一致)。除外項はパンくず折りたたみを妨げません', + explorerExcludePlaceholder: 'パターンを追加(例: node_modules、*.log、**/.git)', + explorerExcludeAdd: '追加', + explorerExcludeRemove: '削除', editorTreeToggle: 'ファイルツリーパネル', editorPathPlaceholder: 'ファイルパス(セッションディレクトリからの相対 or 絶対)、Enter で開く', editorSearchPlaceholder: 'ファイル名で検索…', diff --git a/src/client/locales-ko.ts b/src/client/locales-ko.ts index ed7b7baa..3e7deac8 100644 --- a/src/client/locales-ko.ts +++ b/src/client/locales-ko.ts @@ -41,6 +41,11 @@ export const ko: Record = { editorExplorerMergedDesc: '파일이 같은 창에서 그 자리로 전환됩니다. 새 창은 기본으로 파일 트리가 펼쳐집니다', editorExplorerSplit: '분리', editorExplorerSplitDesc: '경로가 없는 창은 파일 탐색기(파일 트리만)입니다. 파일은 각자 새 창(파일 트리 포함, 기본 접힘)으로 열립니다', + explorerExclude: '제외 패턴', + explorerExcludeDesc: '일치하는 항목을 파일 트리와 검색에서 완전히 제거합니다(* 및 ? 지원, **/ 접두사는 모든 깊이에 일칩니다). 제외된 항목은 탐색경로 접기에 영향을 주지 않습니다', + explorerExcludePlaceholder: '패턴 추가, 예: node_modules, *.log, **/.git', + explorerExcludeAdd: '추가', + explorerExcludeRemove: '제거', editorTreeToggle: '파일 트리 패널', editorPathPlaceholder: '파일 경로 입력(세션 디렉터리 기준 상대 경로 또는 절대 경로), Enter로 열기', editorSearchPlaceholder: '파일 이름으로 검색…', diff --git a/src/client/locales-nl.ts b/src/client/locales-nl.ts index 9747a675..79716168 100644 --- a/src/client/locales-nl.ts +++ b/src/client/locales-nl.ts @@ -47,6 +47,11 @@ export const nl: Record = { editorExplorerMergedDesc: 'Bestanden wisselen in-place in hetzelfde venster; nieuwe vensters beginnen met de boom open', editorExplorerSplit: 'Afzonderlijk', editorExplorerSplitDesc: 'Vensters zonder pad zijn de zelfstandige verkenner (alleen bestandsboom); elk bestand opent een eigen venster (boom gedockt, standaard gesloten)', + explorerExclude: 'Uitsluitingspatronen', + explorerExcludeDesc: 'Verwijdert overeenkomende items volledig uit de bestandsboom en het zoeken (ondersteunt * en ?, een **/-voorvoegsel matcht elke diepte); uitgesloten items blokkeren het broodkruimelsamenvouwen nooit', + explorerExcludePlaceholder: 'Patroon toevoegen, bijv. node_modules, *.log, **/.git', + explorerExcludeAdd: 'Toevoegen', + explorerExcludeRemove: 'Verwijderen', editorTreeToggle: 'Bestandsboompaneel', editorPathPlaceholder: 'Voer een bestandspad in (relatief aan de sessiemap of absoluut), Enter om te openen', editorSearchPlaceholder: 'Zoek op bestandsnaam…', diff --git a/src/client/locales-pl.ts b/src/client/locales-pl.ts index 966a08a1..0462380b 100644 --- a/src/client/locales-pl.ts +++ b/src/client/locales-pl.ts @@ -51,6 +51,11 @@ export const pl: Record = { editorExplorerMergedDesc: 'Pliki przełączają się w miejscu w tym samym oknie; nowe okna zaczynają z rozwiniętym drzewem', editorExplorerSplit: 'Osobne', editorExplorerSplitDesc: 'Okna bez ścieżki to samodzielny eksplorator (tylko drzewo); każdy plik otwiera własne okno (drzewo zadokowane, domyślnie zwinięte)', + explorerExclude: 'Wzorce wykluczania', + explorerExcludeDesc: 'Całkowicie usuwa pasujące wpisy z drzewa plików i wyszukiwania (obsługuje * i ?, prefiks **/ pasuje na każdej głębokości); wykluczone wpisy nigdy nie blokują zwijania nawigacji', + explorerExcludePlaceholder: 'Dodaj wzorzec, np. node_modules, *.log, **/.git', + explorerExcludeAdd: 'Dodaj', + explorerExcludeRemove: 'Usuń', editorTreeToggle: 'Panel drzewa plików', editorPathPlaceholder: 'Ścieżka pliku (względna do katalogu sesji lub bezwzględna), Enter, aby otworzyć', editorSearchPlaceholder: 'Szukaj po nazwie pliku…', diff --git a/src/client/locales-pt.ts b/src/client/locales-pt.ts index e99bff66..a2bfe512 100644 --- a/src/client/locales-pt.ts +++ b/src/client/locales-pt.ts @@ -32,6 +32,11 @@ export const pt: Record = { editorExplorerMergedDesc: 'Arquivos alternam no mesmo lugar na mesma janela; novas janelas começam com a árvore de arquivos aberta', editorExplorerSplit: 'Separado', editorExplorerSplitDesc: 'Janelas sem caminho são o explorador independente (somente árvore de arquivos); cada arquivo abre sua própria janela (com árvore encaixada, fechada por padrão)', + explorerExclude: 'Padrões de exclusão', + explorerExcludeDesc: 'Remove totalmente as entradas correspondentes da árvore de ficheiros e da pesquisa (suporta * e ?, um prefixo **/ corresponde a qualquer profundidade); as entradas excluídas nunca bloqueiam a dobra da trilha', + explorerExcludePlaceholder: 'Adicionar padrão, ex.: node_modules, *.log, **/.git', + explorerExcludeAdd: 'Adicionar', + explorerExcludeRemove: 'Remover', editorTreeToggle: 'Painel da árvore de arquivos', editorPathPlaceholder: 'Caminho do arquivo (relativo ao diretório da sessão ou absoluto), Enter para abrir', editorSearchPlaceholder: 'Pesquisar arquivos por nome…', diff --git a/src/client/locales-ru.ts b/src/client/locales-ru.ts index e8a13e15..1aeb2fa4 100644 --- a/src/client/locales-ru.ts +++ b/src/client/locales-ru.ts @@ -45,6 +45,11 @@ export const ru: Record = { editorExplorerMergedDesc: 'Файлы переключаются в том же окне; новые окна открываются с развёрнутым деревом', editorExplorerSplit: 'Раздельный', editorExplorerSplitDesc: 'Окно без пути — отдельный проводник (только дерево); каждый файл открывается в новом окне (с деревом, по умолчанию свёрнутым)', + explorerExclude: 'Шаблоны исключения', + explorerExcludeDesc: 'Полностью убирает совпадающие записи из дерева файлов и поиска (поддерживаются * и ?, префикс **/ совпадает на любой глубине); исключённые записи никогда не блокируют свёртывание хлебных крошек', + explorerExcludePlaceholder: 'Добавьте шаблон, напр. node_modules, *.log, **/.git', + explorerExcludeAdd: 'Добавить', + explorerExcludeRemove: 'Убрать', editorTreeToggle: 'Панель дерева файлов', editorPathPlaceholder: 'Введите путь к файлу (относительно каталога сессии или абсолютный), Enter, чтобы открыть', editorSearchPlaceholder: 'Поиск по имени файла…', diff --git a/src/client/locales-sv.ts b/src/client/locales-sv.ts index 662d3f9f..e931f55c 100644 --- a/src/client/locales-sv.ts +++ b/src/client/locales-sv.ts @@ -32,6 +32,11 @@ export const sv: Record = { editorExplorerMergedDesc: 'Filer växlas på plats i samma fönster; nya fönster startar med trädet öppet', editorExplorerSplit: 'Separat', editorExplorerSplitDesc: 'Fönster utan sökväg är den fristående utforskaren (endast träd); varje fil öppnar ett eget fönster (träd dockat, stängt som standard)', + explorerExclude: 'Undantagsmönster', + explorerExcludeDesc: 'Tar bort matchande poster helt från filträdet och sökningen (stöder * och ?, ett **/-prefix matchar alla djup); undantagna poster blockerar aldrig brödsmulefällningen', + explorerExcludePlaceholder: 'Lägg till mönster, t.ex. node_modules, *.log, **/.git', + explorerExcludeAdd: 'Lägg till', + explorerExcludeRemove: 'Ta bort', editorTreeToggle: 'Filträdspanel', editorPathPlaceholder: 'Filsökväg (relativ sessionskatalogen eller absolut), Enter för att öppna', editorSearchPlaceholder: 'Sök filer efter namn…', diff --git a/src/client/locales-th.ts b/src/client/locales-th.ts index d8ab894a..27f2de6c 100644 --- a/src/client/locales-th.ts +++ b/src/client/locales-th.ts @@ -49,6 +49,11 @@ export const th: Record = { editorExplorerMergedDesc: 'ไฟล์สลับในตำแหน่งเดิมในหน้าต่างเดียวกัน; หน้าต่างใหม่เริ่มต้นด้วยต้นไม้ไฟล์ที่เปิดอยู่', editorExplorerSplit: 'แยก', editorExplorerSplitDesc: 'หน้าต่างที่ไม่มีพาธคือตัวสำรวจแบบสแตนด์อโลน (ต้นไม้ไฟล์เท่านั้น); แต่ละไฟล์เปิดหน้าต่างของตัวเอง (ต้นไม้ไฟล์ docked, ปิดเป็นค่าเริ่มต้น)', + explorerExclude: 'รูปแบบการยกเว้น', + explorerExcludeDesc: 'ลบรายการที่ตรงกันออกจากแผนผังไฟล์และการค้นหาทั้งหมด (รองรับ * และ ? ส่วนหัว **/ จับคู่ทุกระดับความลึก) รายการที่ยกเว้นจะไม่ขัดขวางการพับ breadcrumb เลย', + explorerExcludePlaceholder: 'เพิ่มรูปแบบ เช่น node_modules, *.log, **/.git', + explorerExcludeAdd: 'เพิ่ม', + explorerExcludeRemove: 'ลบ', editorTreeToggle: 'พาเนลต้นไม้ไฟล์', editorPathPlaceholder: 'พาธไฟล์ (สัมพันธ์กับไดเรกทอรีเซสชันหรือแบบ absolute), Enter เพื่อเปิด', editorSearchPlaceholder: 'ค้นหาไฟล์ตามชื่อ…', diff --git a/src/client/locales-tr.ts b/src/client/locales-tr.ts index d67b1c61..ea8fce8e 100644 --- a/src/client/locales-tr.ts +++ b/src/client/locales-tr.ts @@ -49,6 +49,11 @@ export const tr: Record = { editorExplorerMergedDesc: 'Dosyalar aynı pencerede yerinde geçer; yeni pencereler ağaç açık başlar', editorExplorerSplit: 'Ayrı', editorExplorerSplitDesc: 'Yolsuz pencere tek başına gezgindir (yalnızca ağaç); her dosya kendi penceresini açar (ağaç yuvalanmış, varsayılan kapalı)', + explorerExclude: 'Hariç tutma desenleri', + explorerExcludeDesc: 'Eşleşen girdileri dosya ağacından ve aramadan tamamen kaldırır (* ve ? destekler, **/ öneki her derinlikte eşleşir); hariç tutulan girdiler breadcrumb katlamasını asla engellemez', + explorerExcludePlaceholder: 'Desen ekleyin, örn. node_modules, *.log, **/.git', + explorerExcludeAdd: 'Ekle', + explorerExcludeRemove: 'Kaldır', editorTreeToggle: 'Dosya ağacı paneli', editorPathPlaceholder: 'Dosya yolu (oturum dizinine göreli veya mutlak), Enter ile aç', editorSearchPlaceholder: 'Dosya adına göre ara…', diff --git a/src/client/locales-vi.ts b/src/client/locales-vi.ts index 93041e85..20c24c34 100644 --- a/src/client/locales-vi.ts +++ b/src/client/locales-vi.ts @@ -49,6 +49,11 @@ export const vi: Record = { editorExplorerMergedDesc: 'Tệp chuyển tại chỗ trong cùng cửa sổ; cửa sổ mới mặc định mở cây tệp', editorExplorerSplit: 'Riêng biệt', editorExplorerSplitDesc: 'Cửa sổ không đường dẫn là trình khám phá (chỉ cây tệp); mỗi tệp mở cửa sổ riêng (có cây tệp, mặc định thu gọn)', + explorerExclude: 'Mẫu loại trừ', + explorerExcludeDesc: 'Loại bỏ hoàn toàn các mục khớp khỏi cây tệp và tìm kiếm (hỗ trợ * và ?, tiền tố **/ khớp mọi độ sâu); mục bị loại trừ không bao giờ chặn việc gập breadcrumb', + explorerExcludePlaceholder: 'Thêm mẫu, vd. node_modules, *.log, **/.git', + explorerExcludeAdd: 'Thêm', + explorerExcludeRemove: 'Xóa', editorTreeToggle: 'Panel cây tệp', editorPathPlaceholder: 'Nhập đường dẫn tệp (tương đối thư mục phiên hoặc tuyệt đối), Enter để mở', editorSearchPlaceholder: 'Tìm theo tên tệp…', diff --git a/src/client/locales-zh-HK.ts b/src/client/locales-zh-HK.ts index 56c76d2f..1031c371 100644 --- a/src/client/locales-zh-HK.ts +++ b/src/client/locales-zh-HK.ts @@ -64,6 +64,11 @@ export const zhHK: Record = { editorExplorerMergedDesc: '檔案在同一視窗內原地切換;新視窗預設展開檔案樹', editorExplorerSplit: '獨立', editorExplorerSplitDesc: '無路徑視窗即檔案總管(僅檔案樹);檔案各自新開視窗(帶檔案樹,預設收起)', + explorerExclude: '排除模式', + explorerExcludeDesc: '從檔案樹與搜尋中徹底移除符合條目(支援 * 與 ?,雙星斜槓開頭符合任意深度);符合項不阻塞麵包屑摺疊', + explorerExcludePlaceholder: '新增模式,如 node_modules、*.log、**/.git', + explorerExcludeAdd: '新增', + explorerExcludeRemove: '移除', editorTreeToggle: '檔案樹面板', editorPathPlaceholder: '輸入檔案路徑(相對工作階段目錄或絕對路徑),Enter 開啟', editorSearchPlaceholder: '按檔案名稱搜尋…', diff --git a/src/client/locales-zh-MO.ts b/src/client/locales-zh-MO.ts index ba2712a2..1ae6c856 100644 --- a/src/client/locales-zh-MO.ts +++ b/src/client/locales-zh-MO.ts @@ -64,6 +64,11 @@ export const zhMO: Record = { editorExplorerMergedDesc: '檔案在同一視窗內原地切換;新視窗預設展開檔案樹', editorExplorerSplit: '獨立', editorExplorerSplitDesc: '無路徑視窗即檔案總管(僅檔案樹);檔案各自新開視窗(帶檔案樹,預設收起)', + explorerExclude: '排除模式', + explorerExcludeDesc: '從檔案樹與搜尋中徹底移除符合條目(支援 * 與 ?,雙星斜槓開頭符合任意深度);符合項不阻塞麵包屑摺疊', + explorerExcludePlaceholder: '新增模式,如 node_modules、*.log、**/.git', + explorerExcludeAdd: '新增', + explorerExcludeRemove: '移除', editorTreeToggle: '檔案樹面板', editorPathPlaceholder: '輸入檔案路徑(相對工作階段目錄或絕對路徑),Enter 開啟', editorSearchPlaceholder: '按檔案名稱搜尋…', diff --git a/src/client/locales-zh-TW.ts b/src/client/locales-zh-TW.ts index d7d0f505..f1841407 100644 --- a/src/client/locales-zh-TW.ts +++ b/src/client/locales-zh-TW.ts @@ -64,6 +64,11 @@ export const zhTW: Record = { editorExplorerMergedDesc: '檔案在同一視窗內原地切換;新視窗預設展開檔案樹', editorExplorerSplit: '獨立', editorExplorerSplitDesc: '無路徑視窗即檔案總管(僅檔案樹);檔案各自新開視窗(帶檔案樹,預設收起)', + explorerExclude: '排除模式', + explorerExcludeDesc: '從檔案樹與搜尋中徹底移除符合條目(支援 * 與 ?,雙星斜線開頭符合任意深度);符合項不會阻礙麵包屑摺疊', + explorerExcludePlaceholder: '新增模式,如 node_modules、*.log、**/.git', + explorerExcludeAdd: '新增', + explorerExcludeRemove: '移除', editorTreeToggle: '檔案樹面板', editorPathPlaceholder: '輸入檔案路徑(相對工作階段目錄或絕對路徑),Enter 開啟', editorSearchPlaceholder: '按檔案名稱搜尋…', diff --git a/src/client/locales.ts b/src/client/locales.ts index f39512f4..4964ee2d 100644 --- a/src/client/locales.ts +++ b/src/client/locales.ts @@ -61,6 +61,11 @@ export const zh = { editorExplorerMergedDesc: '文件在同一窗口内原地切换;新窗口默认展开文件树', editorExplorerSplit: '独立', editorExplorerSplitDesc: '无路径窗口即资源管理器(仅文件树);文件各自新开窗口(带文件树,默认收起)', + explorerExclude: '排除模式', + explorerExcludeDesc: '从文件树与搜索中彻底移除匹配条目(支持 * 与 ?,双星杠头匹配任意深度);匹配项不阻塞面包屑折叠', + explorerExcludePlaceholder: '添加模式,如 node_modules、*.log、**/.git', + explorerExcludeAdd: '添加', + explorerExcludeRemove: '移除', editorTreeToggle: '文件树面板', editorPathPlaceholder: '输入文件路径(相对会话目录或绝对路径),Enter 打开', editorSearchPlaceholder: '按文件名搜索…', @@ -602,6 +607,11 @@ export const en: Record = { editorExplorerMergedDesc: 'Files switch in place in the same window; new windows start with the tree open', editorExplorerSplit: 'Separate', editorExplorerSplitDesc: 'Path-less windows are the standalone explorer (tree only); each file opens its own window (tree docked, closed by default)', + explorerExclude: 'Exclude patterns', + explorerExcludeDesc: 'Remove matching entries from the file tree and search entirely (VS Code files.exclude style; * and ? wildcards, a doublestar-slash head matches any depth); excluded entries never block the breadcrumb fold', + explorerExcludePlaceholder: 'Add a pattern, e.g. node_modules, *.log, **/.git', + explorerExcludeAdd: 'Add', + explorerExcludeRemove: 'Remove', editorTreeToggle: 'File tree panel', editorPathPlaceholder: 'File path (relative to the session directory or absolute), Enter to open', editorSearchPlaceholder: 'Search files by name…', diff --git a/src/client/prefs.ts b/src/client/prefs.ts index 9bb9bd9c..b2d19deb 100644 --- a/src/client/prefs.ts +++ b/src/client/prefs.ts @@ -11,6 +11,7 @@ import type { api } from './api.ts' import { clampTitleBarStrip, + EXPLORER_EXCLUDE_DEFAULTS, SIDEBAR_PREFS_DEFAULTS, TITLE_BAR_SCHEMES, TITLE_BAR_STRIP_DEFAULT, @@ -19,6 +20,7 @@ import { } from '../prefs-shared.ts' export { + EXPLORER_EXCLUDE_DEFAULTS, SIDEBAR_PREFS_DEFAULTS, TITLE_BAR_SCHEMES, TITLE_BAR_STRIP_DEFAULT, @@ -60,6 +62,7 @@ export function parsePrefs(value: unknown): SidebarPrefs { editorExplorer: typeof record.editorExplorer === 'boolean' ? record.editorExplorer : SIDEBAR_PREFS_DEFAULTS.editorExplorer, + explorerExclude: stringArrayOf(record.explorerExclude), // The title-bar scheme (auto | web | preset | custom). The schema // declares the field WITHOUT a default, so documents written by older // plugin versions resolve without it — migrate from the legacy fields: @@ -111,6 +114,23 @@ function pluginSettingsMapOf(value: unknown): Record = z.object({ mobileDefaultTree: z.boolean().default(true), agentOpenTools: z.boolean().default(false), editorExplorer: z.boolean().default(false), + explorerExclude: z.array(z.string()).default([...EXPLORER_EXCLUDE_DEFAULTS]), titleBarScheme: z.union([z.const('auto'), z.const('web'), z.const('preset'), z.const('custom')]), titleBarPresetId: z.string(), customCss: z.string(), diff --git a/src/exclude-patterns.ts b/src/exclude-patterns.ts new file mode 100644 index 00000000..a77ff959 --- /dev/null +++ b/src/exclude-patterns.ts @@ -0,0 +1,163 @@ +/** + * Glob-style exclude patterns for the explorer tree and name search — the + * VS Code `files.exclude` lineage. One compiled matcher serves BOTH host + * consumption points (the `fs.tree` level listing and the `fs.search` walk) + * so a pattern can never disagree between the two surfaces. + * + * Pattern grammar (a deliberate subset of VS Code's globs): + * - `name` matches that base NAME at any depth (`Thumbs.db`); + * - `dir/name` path-anchored at the session cwd (`build/out`); + * - doublestar-slash head (`**` + `/name`) matches at any depth (the head strips away); + * - `*` / `?` wildcards within one segment; `**` spans segments. + * Matching is case-sensitive on POSIX and case-insensitive on Windows (the + * filesystem's own notion). Invalid shapes (empty, overlong, over the count + * cap) are dropped silently — a malformed pattern must never break the tree. + */ +import { relative, sep } from 'node:path' + +/** Hard cap on how many patterns one request may carry (extras dropped). */ +export const EXCLUDE_PATTERN_LIMIT = 64 +/** Hard cap on one pattern's length (longer ones dropped). */ +export const EXCLUDE_PATTERN_MAX_LENGTH = 256 + +/** One entry probe: the entry's absolute path and its base name. */ +export type ExcludeTest = (entryPath: string, name: string) => boolean + +/** + * A compiled probe plus the canonical identity of the pattern set it was + * built from. The identity exists so a caller can key a cache on the + * FILTERING, not just on the directory: the host's level cache stores rows + * already filtered, so serving a listing compiled from one pattern list to a + * request carrying another would keep showing rows the user just excluded + * (and hide rows just un-excluded) for the rest of the TTL. Two calls that + * normalized to the same patterns share a key, so the cache still absorbs + * repeat listings of an unchanged list. + */ +export interface ExcludeMatcher extends ExcludeTest { + /** Canonical identity of the compiled pattern set ('' when nothing valid). */ + readonly key: string +} + +/** One compiled pattern and the surface it claims. */ +interface CompiledPattern { + /** 'name' tests the base name anywhere; 'path' tests the cwd-relative + * path anchored at the root; 'suffix' (a doublestar-slash head shape) tests + * the name + * OR any trailing segment run of the relative path. */ + kind: 'name' | 'path' | 'suffix' + regex: RegExp +} + +/** + * Normalize one raw pattern (accepts unknown wire values): trim, unify + * separators, drop the doublestar-slash head (remembered as a suffix kind) and the + * `./` and trailing-/ decorations. Returns undefined for empty/invalid input. + */ +function normalizePattern(raw: unknown): { kind: CompiledPattern['kind']; body: string } | undefined { + if (typeof raw !== 'string') return undefined + let pattern = raw.trim().replace(/\\/g, '/') + if (pattern.length > EXCLUDE_PATTERN_MAX_LENGTH) return undefined + while (pattern.startsWith('./')) pattern = pattern.slice(2) + while (pattern.startsWith('/')) pattern = pattern.slice(1) + while (pattern.endsWith('/')) pattern = pattern.slice(0, -1) + let kind: CompiledPattern['kind'] = 'name' + if (pattern.startsWith('**/')) { + kind = 'suffix' + pattern = pattern.slice(3) + } + if (pattern === '' || pattern === '**') { + // A bare `**` (or one that stripped to nothing) would swallow the whole + // tree — refuse it instead of hiding everything. + return undefined + } + if (kind === 'name' && pattern.includes('/')) kind = 'path' + return { kind, body: pattern } +} + +/** Compile one normalized glob body to an anchored RegExp. */ +function globToRegExp(body: string, insensitive: boolean): RegExp { + let out = '' + for (let i = 0; i < body.length; i += 1) { + const char = body[i]! + if (char === '*') { + if (body[i + 1] === '*') { + out += '.*' + i += 1 + } else { + out += '[^/]*' + } + continue + } + if (char === '?') { + out += '[^/]' + continue + } + out += char.replace(/[.+^${}()|[\]\\]/g, '\\$&') + } + return new RegExp(`^${out}$`, insensitive ? 'i' : undefined) +} + +/** The cwd-relative '/' path of `entryPath` (undefined when outside `root`). */ +function relativeToRoot(root: string, entryPath: string): string | undefined { + const rel = relative(root, entryPath).split(sep).join('/') + return rel.startsWith('..') ? undefined : rel +} + +/** + * Compile the wire patterns into one entry probe. + * @param raw - the request payload's `exclude` field (anything; validated). + * @param root - the session cwd the path-anchored patterns resolve against. + * @param platform - case-folding semantics (`'win32'` matches insensitively). + * @returns the probe (with its {@link ExcludeMatcher.key}), or undefined when + * nothing valid was declared (callers skip filtering entirely then — the + * no-pattern fast path). + */ +export function compileExcludePatterns( + raw: unknown, + root: string, + platform: NodeJS.Platform | 'posix' = process.platform, +): ExcludeMatcher | undefined { + if (!Array.isArray(raw)) return undefined + const compiled: CompiledPattern[] = [] + for (const item of raw) { + if (compiled.length >= EXCLUDE_PATTERN_LIMIT) break + const normalized = normalizePattern(item) + if (normalized === undefined) continue + compiled.push({ kind: normalized.kind, regex: globToRegExp(normalized.body, platform === 'win32') }) + } + if (compiled.length === 0) return undefined + const needsRel = compiled.some(pattern => pattern.kind !== 'name') + const probe = (entryPath: string, name: string): boolean => { + let rel: string | undefined + for (const pattern of compiled) { + if (pattern.kind === 'name') { + if (pattern.regex.test(name)) return true + continue + } + if (rel === undefined) { + if (!needsRel) continue + rel = relativeToRoot(root, entryPath) ?? '' + } + if (pattern.kind === 'path') { + if (rel !== '' && pattern.regex.test(rel)) return true + continue + } + // Suffix kind: the name itself or any trailing segment run of rel. + if (pattern.regex.test(name)) return true + if (rel !== '') { + const segments = rel.split('/') + for (let start = 0; start < segments.length - 1; start += 1) { + if (pattern.regex.test(segments.slice(start).join('/'))) return true + } + } + } + return false + } + // The identity covers everything the probe reads: the compiled kinds and + // their regexes (case-folding included) plus the root the path-anchored + // kinds resolve against — two sessions with the same patterns but different + // cwds match a given directory differently, so they must not share a cache + // entry. NUL joins because no pattern body can contain one. + const key = `${root}\0${compiled.map(pattern => `${pattern.kind}:${pattern.regex.source}:${pattern.regex.flags}`).join('\0')}` + return Object.assign(probe, { key }) +} diff --git a/src/fs-search.ts b/src/fs-search.ts index ee9cf2c3..2d02acc4 100644 --- a/src/fs-search.ts +++ b/src/fs-search.ts @@ -19,6 +19,7 @@ import type { Dirent } from 'node:fs' import { opendir, stat } from 'node:fs/promises' import { join, relative, sep } from 'node:path' +import type { ExcludeTest } from './exclude-patterns.ts' /** One search: the relative paths of the matching entries (dirs included so * the client can hint where matches live) plus the truncation flag. */ @@ -38,6 +39,10 @@ export interface FsSearchOptions { maxMatches?: number /** Total entries visited before the walk gives up (default 100_000). */ maxVisited?: number + /** Compiled exclude-pattern probe (the explorerExclude pref): matched + * entries never match AND are never descended — the search surface stays + * in lockstep with the tree listing. */ + exclude?: ExcludeTest } const DEFAULT_MAX_MATCHES = 200 @@ -118,6 +123,9 @@ export async function searchFiles(root: string, query: string, opts: FsSearchOpt // Dependency / VCS / build-output forests: never matched, never descended. if (dirent.isDirectory() && SEARCH_SKIP_DIRS.has(dirent.name.toLowerCase())) continue 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) diff --git a/src/fs-tree.ts b/src/fs-tree.ts index c794b5cd..bc8356a4 100644 --- a/src/fs-tree.ts +++ b/src/fs-tree.ts @@ -12,11 +12,15 @@ * Row semantics are unchanged: directories first, case-insensitive name order * with a deterministic tie-break, POSIX-hidden entries flagged for dimming, * symlinks stat'ed once so a link to a directory expands like a directory and - * a dangling one is flagged broken. + * a dangling one is flagged broken. Directory rows additionally get one + * bounded read of their own level to mark singleton-dir chains (`compact`) + * for the explorer's breadcrumb folding. */ -import { readdir, stat } from 'node:fs/promises' +import { opendir, readdir, stat } from 'node:fs/promises' +import type { Dir, Dirent } from 'node:fs' import { basename, dirname, isAbsolute, resolve, sep } from 'node:path' import { SidebarError } from './wire.ts' +import type { ExcludeMatcher } from './exclude-patterns.ts' /** One explorer row. */ export interface SidebarFsEntry { @@ -28,6 +32,14 @@ export interface SidebarFsEntry { isSymlink: boolean /** For symlinks: the target is missing or unreadable (stat failed). */ broken: boolean + /** + * Directory rows only: the contents are EXACTLY one child — the explorer + * folds such singleton chains into one breadcrumb row (VSCode's "compact + * folders"). The terminal link (sole child is a FILE) is marked too, so + * the row label never shifts when the chain expands. Symlink children + * never qualify: a self-referential link would otherwise fold forever. + */ + compact?: boolean } /** One listed level. */ @@ -66,19 +78,25 @@ const SYMLINK_PROBE_CONCURRENCY = 32 export const DIRECTORY_CACHE_TTL_MS = 1_500 /** - * The level cache, keyed by `"\0"`. + * The level cache, keyed by `"\0\0"`. * * Keyed by ABSOLUTE PATH, not by session: a listing is a pure function of the - * path plus the cap, and its rows already carry absolute paths, so sharing an - * entry between two sessions that read the same directory is correct (and - * desirable — one directory read serves both). Nothing session-scoped is - * stored, so no session's data can leak into another's listing. + * path plus the cap AND the exclude pattern set, and its rows already carry + * absolute paths, so sharing an entry between two sessions that read the same + * directory is correct (and desirable — one directory read serves both). + * Nothing session-scoped is stored, so no session's data can leak into + * another's listing. + * + * The exclude set is part of the key, never ambient host state: a listing + * filtered by one pattern list must never be served to a request carrying + * another (the user's edit must show up on the next read, and the pattern list + * travels WITH the request — see {@link ExcludeMatcher.key}). */ const directoryCache = new Map() /** Cache key of one level read. */ -function cacheKey(path: string, maxEntries: number): string { - return `${path}\0${maxEntries}` +function cacheKey(path: string, maxEntries: number, exclude?: ExcludeMatcher): string { + return `${path}\0${maxEntries}\0${exclude?.key ?? ''}` } /** @@ -106,12 +124,12 @@ export function invalidateDirectoryCache(path?: string): void { const DIRECTORY_CACHE_MAX = 512 /** Read one level through the cache when it is fresh. */ -async function listDirectoryCached(path: string, maxEntries: number): Promise { - const key = cacheKey(path, maxEntries) +async function listDirectoryCached(path: string, maxEntries: number, exclude?: ExcludeMatcher): Promise { + const key = cacheKey(path, maxEntries, exclude) const now = Date.now() const hit = directoryCache.get(key) if (hit !== undefined && now - hit.at < DIRECTORY_CACHE_TTL_MS) return hit.listing - const listing = await readDirectory(path, maxEntries) + const listing = await readDirectory(path, maxEntries, exclude) // Bounded: a deep walk of many directories must not grow this map without // limit (entries are tiny, but an unbounded map in a long-lived host is a // leak). Map iteration order is insertion order, so the first key is oldest. @@ -127,15 +145,18 @@ async function listDirectoryCached(path: string, maxEntries: number): Promise { - return await listDirectoryCached(path, maxEntries) +export async function listDirectory(path: string, maxEntries = 1000, exclude?: ExcludeMatcher): Promise { + return await listDirectoryCached(path, maxEntries, exclude) } /** Read one level straight from the filesystem (the cache's slow path). */ -async function readDirectory(path: string, maxEntries: number): Promise { +async function readDirectory(path: string, maxEntries: number, exclude?: ExcludeMatcher): Promise { let dirents try { // One syscall batch instead of an `opendir` stream: `readdir` with types is @@ -145,12 +166,19 @@ async function readDirectory(path: string, maxEntries: number): Promise maxEntries + const prefix = path.endsWith(sep) ? path : `${path}${sep}` + // The user's exclude list removes matched rows entirely (VS Code's + // files.exclude semantics) — BEFORE the cap, so an excluded entry never + // consumes a row of the level's budget, and the same compiled matcher + // filters the singleton fold probe below. + const visible = exclude === undefined + ? dirents + : dirents.filter(dirent => !exclude(`${prefix}${dirent.name}`, dirent.name)) + const truncated = visible.length > maxEntries // Build rows ONLY for the rows that survive the cap: composing a row costs // ~0.3µs (path concat + three flags), so an uncapped 10k level would spend // ~3ms on rows nobody will see. - const kept = truncated ? dirents.slice(0, maxEntries) : dirents - const prefix = path.endsWith(sep) ? path : `${path}${sep}` + const kept = truncated ? visible.slice(0, maxEntries) : visible const rows: SidebarFsEntry[] = new Array(kept.length) for (let index = 0; index < kept.length; index += 1) { const dirent = kept[index]! @@ -170,6 +198,10 @@ async function readDirectory(path: string, maxEntries: number): Promise { + let next = 0 + const workers = Array.from({ length: Math.min(concurrency, rows.length) }, async () => { + for (;;) { + const index = next + next += 1 + if (index >= rows.length) return + const row = rows[index]! + if (!row.isDir || row.broken) continue + if (await hasSingletonChild(row.path, exclude)) row.compact = true + } + }) + await Promise.all(workers) +} + +/** + * Whether `dir` holds exactly one EFFECTIVE entry (POSIX-hidden entries — + * dot-prefixed, e.g. macOS's `.DS_Store` — don't count, and neither do + * entries the user's exclude list removes) and that entry is NOT a symlink. + * Symlink children never qualify: the client's fold chain follows `compact` + * links eagerly, and a self-referential link would otherwise fold forever. + * Hidden/excluded entries never qualify either: the client walks chains + * with the same filters, so a fold never hides a visible row — the user's + * "show hidden files" switch only affects rendering, never the fold itself. + */ +async function hasSingletonChild(dir: string, exclude?: ExcludeMatcher): Promise { + let level: Dir | undefined + try { + level = await opendir(dir) + let only: Dirent | null = null + for (;;) { + const entry = await level.read() + if (entry === null) break + if (entry.name.startsWith('.')) continue + if (exclude !== undefined && exclude(`${dir}${sep}${entry.name}`, entry.name)) continue + if (only !== null) return false + only = entry + } + // A dirent's isSymbolicLink() never follows targets — exactly the + // exclusion we want here (see above). + return only !== null && !only.isSymbolicLink() + } catch { + return false + } finally { + await level?.close().catch(() => undefined) + } +} + /** The root row label of a listing: the last path segment (or the full path at the filesystem root). */ export function rootLabel(path: string): string { const base = basename(path) diff --git a/src/index.ts b/src/index.ts index 6ad91a95..478e9a94 100644 --- a/src/index.ts +++ b/src/index.ts @@ -34,6 +34,7 @@ import { resolveSessionPath } from './session-path.ts' import { mkdirWorkspaceEntry, renameWorkspaceEntry, removeWorkspaceEntry, writeWorkspaceUpload } from './fs-operations.ts' import { ensureWorkspacePath, ensureWorkspaceWritePath } from './path-security.ts' import { searchFiles } from './fs-search.ts' +import { compileExcludePatterns } from './exclude-patterns.ts' import { decodeHtmlUrl } from './html-route.ts' import { isTrustedApiRequest } from './trust-fence.ts' import { registerBundleRoute } from './bundle-route.ts' @@ -338,9 +339,12 @@ function buildApi( }, 'fs.tree': async (payload) => { const { cwd } = await cwdOf(payload) - const record = payload as { path?: unknown } + const record = payload as { path?: unknown; exclude?: unknown } const target = record.path === undefined ? cwd : await ensureWorkspacePath(cwd, requireString(payload, 'path')) - return listDirectory(target, resolved.listLimit) + // The client's explorerExclude pref rides the request (compiled here so + // the listing and the singleton fold probe share one matcher). + const exclude = compileExcludePatterns(record.exclude, cwd) + return listDirectory(target, resolved.listLimit, exclude) }, // Batch listing: one request for every level the tree has expanded, so a // mount/refresh costs one round trip instead of N. Each path rides the @@ -349,7 +353,7 @@ function buildApi( // in place — the other levels still render. 'fs.trees': async (payload) => { const { cwd } = await cwdOf(payload) - const record = payload as { paths?: unknown } | null + const record = payload as { paths?: unknown; exclude?: unknown } | null const paths = Array.isArray(record?.paths) ? record.paths.filter((value): value is string => typeof value === 'string' && value !== '') : [] @@ -357,6 +361,10 @@ function buildApi( if (paths.length > FS_TREES_MAX_PATHS) { throw new SidebarError('bad-request', `too many paths (max ${FS_TREES_MAX_PATHS})`) } + // The file tree's REAL entry (a mount/expand costs one POST): the + // explorerExclude pref has to be compiled here too, or the exclude list + // would simply not reach the only surface the explorer reads. + const exclude = compileExcludePatterns(record?.exclude, cwd) const levels = await Promise.all(paths.map(async (raw): Promise => { // A session-relative path is accepted here (the tree already carries // cwd-relative paths); `fs.tree` itself keeps requiring absolute @@ -366,7 +374,7 @@ function buildApi( const homeRelative = raw === '~' || raw.startsWith('~/') || raw.startsWith('~\\') const requested = isAbsolute(raw) || homeRelative ? raw : `${cwd}${sep}${raw}` try { - return await listDirectory(await ensureWorkspacePath(cwd, requested), resolved.listLimit) + return await listDirectory(await ensureWorkspacePath(cwd, requested), resolved.listLimit, exclude) } catch (error) { // Per-level failure: the batch itself stays a success (one unreadable // directory must not blank the whole tree). @@ -380,8 +388,9 @@ function buildApi( // cwd (not caller-targetable — the walk is unbounded by design and // must never escape the workspace), budgeted inside searchFiles. const { cwd } = await cwdOf(payload) + const record = payload as { exclude?: unknown } const query = requireString(payload, 'query') - return searchFiles(cwd, query) + return searchFiles(cwd, query, { exclude: compileExcludePatterns(record.exclude, cwd) }) }, 'fs.read': async (payload) => { const { cwd } = await cwdOf(payload) diff --git a/src/prefs-shared.ts b/src/prefs-shared.ts index 0409ee99..89b8c9d0 100644 --- a/src/prefs-shared.ts +++ b/src/prefs-shared.ts @@ -61,6 +61,18 @@ export interface SidebarPrefs { * Side card settings; off restores the pre-merge editor exactly. */ editorExplorer: boolean + /** + * VS Code `files.exclude`-style glob patterns (the editor card's gear + * popup manages the list): matched entries are REMOVED from the file tree + * and the name search entirely — dot-prefixed rows otherwise render + * dimmed as usual. Supported shapes: a bare name + * (`Thumbs.db`) at any depth, a cwd-anchored path (`build/out`), a + * doublestar head for any depth (doublestar + slash + name), and `*` / + * `?` wildcards. + * Excluded entries never block the breadcrumb fold either (the host probe + * and the listing share the one compiled matcher). + */ + explorerExclude: string[] /** * Title-bar / shell compatibility scheme (the "位置兼容模式" setting): * - `auto` (default): CONSERVATIVE — only the standard Window Controls @@ -151,6 +163,9 @@ export const TITLE_BAR_STRIP_MIN = 0 export const TITLE_BAR_STRIP_MAX = 120 export const TITLE_BAR_STRIP_DEFAULT = 40 +/** The stock exclude list (VS Code ships a similar files.exclude default). */ +export const EXPLORER_EXCLUDE_DEFAULTS: readonly string[] = ['.DS_Store', 'Thumbs.db'] + /** The title-bar / shell compatibility schemes (see {@link SidebarPrefs.titleBarScheme}). */ export const TITLE_BAR_SCHEMES = ['auto', 'web', 'preset', 'custom'] as const export type TitleBarScheme = typeof TITLE_BAR_SCHEMES[number] @@ -166,6 +181,7 @@ export const SIDEBAR_PREFS_DEFAULTS: SidebarPrefs = { mobileDefaultTree: true, agentOpenTools: false, editorExplorer: false, + explorerExclude: [...EXPLORER_EXCLUDE_DEFAULTS], titleBarScheme: 'auto', titleBarPresetId: '', customCss: '', diff --git a/tests/builtins.spec.ts b/tests/builtins.spec.ts index 8839b5dc..54237e07 100644 --- a/tests/builtins.spec.ts +++ b/tests/builtins.spec.ts @@ -140,11 +140,11 @@ describe('built-in tab registrations', () => { expect((viewMode?.options ?? []).map(o => o.value)).toEqual(['graph', 'tree']) }) - it('the editor tab declares its merged-mode (embedded file tree) setting', () => { + it('the editor tab declares its merged-mode (embedded file tree) and exclude-pattern settings', () => { const { service } = setup() const toggles = service.getTab('editor')?.settings?.toggles ?? [] // The workspace-fence switch is gone with the fence itself. - expect(toggles.map(t => t.key)).toEqual(['editorExplorer']) + expect(toggles.map(t => t.key)).toEqual(['editorExplorer', 'explorerExclude']) expect(toggles[0]?.title).toBeDefined() expect(toggles[0]?.desc).toBeDefined() // The merged mode is an iconed select (merged vs separate), not a switch. @@ -152,6 +152,12 @@ describe('built-in tab registrations', () => { const options = toggles[0]?.options ?? [] expect(options.map(o => o.value)).toEqual([true, false]) expect(options.every(o => o.icon !== undefined && o.title !== undefined)).toBe(true) + // The exclude list is a patterns row (editable string list): title/desc + // plus the add-input placeholder the shared row renderer reads. + expect(toggles[1]?.type).toBe('patterns') + expect(toggles[1]?.title).toBeDefined() + expect(toggles[1]?.desc).toBeDefined() + expect(toggles[1]?.patternsPlaceholder).toBeDefined() // The open-with configuration (SSH host + custom editors) is the custom // panel rendered below the declarative rows. expect(service.getTab('editor')?.settings?.render).toBeDefined() diff --git a/tests/exclude-patterns.spec.ts b/tests/exclude-patterns.spec.ts new file mode 100644 index 00000000..4a038180 --- /dev/null +++ b/tests/exclude-patterns.spec.ts @@ -0,0 +1,121 @@ +/** + * Unit tests for the explorer's VS Code-style exclude pattern compiler + * (src/exclude-patterns.ts): the one matcher both host surfaces (fs.trees + * listing and fs.search walk) share, plus the {@link ExcludeMatcher.key} the + * host's level cache keys filtered listings on. + */ +import { describe, expect, it } from 'vitest' +import { compileExcludePatterns, EXCLUDE_PATTERN_LIMIT, EXCLUDE_PATTERN_MAX_LENGTH } from '../src/exclude-patterns.ts' + +const ROOT = '/work/project' +const test = (patterns: unknown[], path: string, name = path.split('/').pop()!) => + compileExcludePatterns(patterns, ROOT, 'posix')?.(path, name) ?? false + +describe('compileExcludePatterns', () => { + it('returns undefined for missing / empty / non-array input (no-pattern fast path)', () => { + expect(compileExcludePatterns(undefined, ROOT, 'posix')).toBeUndefined() + expect(compileExcludePatterns([], ROOT, 'posix')).toBeUndefined() + expect(compileExcludePatterns('node_modules', ROOT, 'posix')).toBeUndefined() + expect(compileExcludePatterns(['', ' ', '**'], ROOT, 'posix')).toBeUndefined() + }) + + it('matches plain names at any depth', () => { + const patterns = ['Thumbs.db', 'node_modules'] + expect(test(patterns, `${ROOT}/Thumbs.db`)).toBe(true) + expect(test(patterns, `${ROOT}/deep/dir/Thumbs.db`)).toBe(true) + expect(test(patterns, `${ROOT}/node_modules`)).toBe(true) + expect(test(patterns, `${ROOT}/keep.txt`)).toBe(false) + // A name pattern is anchored: a substring or superstring does not match. + expect(test(patterns, `${ROOT}/Thumbs.db2`)).toBe(false) + expect(test(patterns, `${ROOT}/my-node_modules-x`)).toBe(false) + }) + + it('supports * and ? wildcards within one segment', () => { + expect(test(['*.log'], `${ROOT}/app.log`)).toBe(true) + expect(test(['*.log'], `${ROOT}/deep/app.log`)).toBe(true) + // `*` never crosses a segment boundary (the rel path stays unmatchable). + expect(test(['*.log'], `${ROOT}/log`)).toBe(false) + expect(test(['temp-?'], `${ROOT}/temp-1`)).toBe(true) + expect(test(['temp-?'], `${ROOT}/temp-12`)).toBe(false) + }) + + it('matches path patterns anchored at the session cwd', () => { + expect(test(['build/out'], `${ROOT}/build/out`)).toBe(true) + expect(test(['build/out'], `${ROOT}/src/build/out`)).toBe(false) + expect(test(['build/*'], `${ROOT}/build/main.o`)).toBe(true) + expect(test(['build/*'], `${ROOT}/build/sub/main.o`)).toBe(false) + expect(test(['build/**'], `${ROOT}/build/sub/main.o`)).toBe(true) + }) + + it('matches a doublestar-slash head at any depth (name and segment runs)', () => { + expect(test(['**/.git'], `${ROOT}/.git`)).toBe(true) + expect(test(['**/.git'], `${ROOT}/deep/.git`)).toBe(true) + expect(test(['**/cache/tmp'], `${ROOT}/cache/tmp`)).toBe(true) + expect(test(['**/cache/tmp'], `${ROOT}/deep/cache/tmp`)).toBe(true) + expect(test(['**/cache/tmp'], `${ROOT}/deep/cache/other`)).toBe(false) + }) + + it('normalizes decorations: backslashes, ./, leading and trailing slashes', () => { + expect(test(['node_modules\\'], `${ROOT}/node_modules`)).toBe(true) + expect(test(['./dist/'], `${ROOT}/dist`)).toBe(true) + expect(test(['/dist'], `${ROOT}/dist`)).toBe(true) + expect(test(['build\\out'], `${ROOT}/build/out`)).toBe(true) + }) + + it('escapes regex specials literally', () => { + expect(test(['a.b'], `${ROOT}/a.b`)).toBe(true) + expect(test(['a.b'], `${ROOT}/axb`)).toBe(false) + expect(test(['(x)'], `${ROOT}/(x)`)).toBe(true) + }) + + it('matches case-insensitively on win32 only', () => { + const win = compileExcludePatterns(['Thumbs.db'], 'C:\\work', 'win32')! + expect(win('C:\\work\\thumbs.db', 'thumbs.db')).toBe(true) + expect(test(['Thumbs.db'], `${ROOT}/thumbs.db`)).toBe(false) + }) + + it('drops malformed entries without breaking the rest', () => { + const patterns = ['', 3, null, '**', ' ', '*.tmp'] as unknown[] + const matcher = compileExcludePatterns(patterns, ROOT, 'posix')! + expect(matcher(`${ROOT}/scratch.tmp`, 'scratch.tmp')).toBe(true) + expect(matcher(`${ROOT}/keep.txt`, 'keep.txt')).toBe(false) + }) + + it('caps pattern count and length', () => { + const many = Array.from({ length: EXCLUDE_PATTERN_LIMIT + 5 }, (_, i) => `file-${i}`) + const matcher = compileExcludePatterns(many, ROOT, 'posix')! + expect(matcher(`${ROOT}/file-0`, 'file-0')).toBe(true) + expect(matcher(`${ROOT}/file-${EXCLUDE_PATTERN_LIMIT + 1}`, `file-${EXCLUDE_PATTERN_LIMIT + 1}`)).toBe(false) + const long = 'x'.repeat(EXCLUDE_PATTERN_MAX_LENGTH + 1) + expect(compileExcludePatterns([long], ROOT, 'posix')).toBeUndefined() + }) + + // The host's level cache keys listings on this identity, so a matcher that + // lied about its patterns would serve rows filtered by somebody else's list. + describe('the matcher key (the host cache dimension)', () => { + it('is equal for pattern sets that normalize alike', () => { + const a = compileExcludePatterns(['dist/', './dist'], ROOT, 'posix')! + const b = compileExcludePatterns(['/dist', 'dist'], ROOT, 'posix')! + expect(a.key).toBe(b.key) + // The key is derived from the normalized list, not deduplicated: a + // repeated pattern splits the key. That direction is safe — an + // over-split costs one cache miss, never a wrongly filtered listing. + expect(a.key).not.toBe(compileExcludePatterns(['dist'], ROOT, 'posix')!.key) + }) + + it('differs when the patterns differ, and when the anchor root differs', () => { + const base = compileExcludePatterns(['*.log'], ROOT, 'posix')! + expect(base.key).not.toBe(compileExcludePatterns(['*.tmp'], ROOT, 'posix')!.key) + // Path-anchored kinds resolve against the root, so two sessions with the + // same patterns but different cwds match one directory differently. + expect(base.key).not.toBe(compileExcludePatterns(['*.log'], '/other', 'posix')!.key) + // Case-folding is part of the compiled regex, hence part of the identity. + expect(compileExcludePatterns(['a'], '/x', 'posix')!.key) + .not.toBe(compileExcludePatterns(['a'], '/x', 'win32')!.key) + }) + + it('gives malformed-only input the undefined fast path (never an empty key)', () => { + expect(compileExcludePatterns(['', ' ', '**'], ROOT, 'posix')).toBeUndefined() + }) + }) +}) diff --git a/tests/file-tree-compact-fold.spec.tsx b/tests/file-tree-compact-fold.spec.tsx new file mode 100644 index 00000000..e6788a86 --- /dev/null +++ b/tests/file-tree-compact-fold.spec.tsx @@ -0,0 +1,253 @@ +/** + * Explorer breadcrumb folding in the real tree (VSCode "compact folders"). + * + * The host marks a directory row `compact` when its contents are exactly one + * effective child; this spec drives the CLIENT half against the level cache the + * batch route fills: + * - a chain of singleton dirs renders as ONE `a/b/c` row, and the collapsed + * links' levels are PRELOADED (otherwise the label would grow a segment at + * a time as the user clicks); + * - a plain click toggles the WHOLE chain, so the row opens and closes as one + * (only ever toggling the head would strand an earlier-expanded link open); + * - the open row descends into the chain TAIL, not the head; + * - the exclude list is carried on every `fs.trees` request and a changed list + * wipes the level cache (the host filters, so cached rows are stale). + */ +// @vitest-environment jsdom +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' +import { createElement } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { act } from 'react-dom/test-utils' +import { FileTree } from '../src/client/FileTree.tsx' + +import { setupReactAct } from './test-utils.ts' +setupReactAct() + +// vitest 4.1.11+ follows the OS locale; pin en-US so the copy is English. +beforeAll(() => { + Object.defineProperty(window.navigator, 'language', { value: 'en-US', configurable: true }) +}) + +const fsTrees = vi.hoisted(() => vi.fn()) + +vi.mock('../src/client/api.ts', () => ({ + api: { + fsTree: vi.fn(), + fsTrees: (...args: unknown[]) => fsTrees(...args), + gitStatus: async () => ({ isRepo: false, entries: [] }), + }, + downloadUrl: () => '/sidebar/file', + isOutsideWorkspaceMessage: () => false, +})) + +/** A directory row; `compact` is the host's singleton mark. */ +function dir(path: string, compact = false): { + name: string; path: string; isDir: boolean; hidden: boolean; isSymlink: boolean; broken: boolean; compact?: boolean +} { + const name = path.slice(path.lastIndexOf('/') + 1) + return { + name, + path, + isDir: true, + hidden: name.startsWith('.'), + isSymlink: false, + broken: false, + ...(compact ? { compact: true } : {}), + } +} + +/** A file row. */ +function file(path: string): { + name: string; path: string; isDir: boolean; hidden: boolean; isSymlink: boolean; broken: boolean +} { + const name = path.slice(path.lastIndexOf('/') + 1) + return { name, path, isDir: false, hidden: name.startsWith('.'), isSymlink: false, broken: false } +} + +/** + * `/tmp` → `a`, then a/b, then a/b/c, then a real file. Every directory on the + * chain is a singleton, so `a` folds all the way to `a/b/c`. + */ +function levelOf(path: string): { + path: string; entries: unknown[]; truncated: boolean +} { + switch (path) { + case '/tmp': + return { path, entries: [dir('/tmp/a', true), file('/tmp/readme.md')], truncated: false } + case '/tmp/a': + return { path, entries: [dir('/tmp/a/b', true)], truncated: false } + case '/tmp/a/b': + return { path, entries: [dir('/tmp/a/b/c', true)], truncated: false } + default: + return { path, entries: [file(`${path}/leaf.txt`)], truncated: false } + } +} + +/** The smallest WebSocket the directory watcher talks to. */ +class FakeSocket { + static readonly OPEN = 1 + static readonly CONNECTING = 0 + readyState = FakeSocket.CONNECTING + onopen: (() => void) | null = null + onmessage: ((event: { data: string }) => void) | null = null + onclose: (() => void) | null = null + constructor(readonly url: string) {} + send(): void {} + close(): void { this.readyState = 3 } +} + +interface Harness { + container: HTMLDivElement + toggled: string[] + rerender: (expanded: string[], exclude?: readonly string[]) => void + unmount: () => void +} + +function mountTree(expanded: string[] = [], exclude?: readonly string[]): Harness { + const container = document.createElement('div') + document.body.append(container) + const root: Root = createRoot(container) + const toggled: string[] = [] + const render = (dirs: string[], patterns: readonly string[] | undefined): void => { + root.render(createElement(FileTree, { + sessionId: 's1', + cwd: '/tmp', + expanded: dirs, + revealed: [], + onToggle: (path: string) => { toggled.push(path) }, + onOpenFile: () => {}, + onReferenceFile: () => {}, + ...(patterns === undefined ? {} : { exclude: patterns }), + refreshTick: 0, + onUploadRequest: () => {}, + busy: false, + })) + } + act(() => { render(expanded, exclude) }) + return { + container, + toggled, + rerender: (dirs: string[], patterns?: readonly string[]) => { + act(() => { render(dirs, patterns ?? exclude) }) + }, + unmount: () => { act(() => { root.unmount() }); container.remove() }, + } +} + +/** Flush the batch promise chain. */ +async function flush(): Promise { + await act(async () => { + await Promise.resolve() + await Promise.resolve() + await Promise.resolve() + await Promise.resolve() + }) +} + +/** The directory rows' rendered labels, in document order. */ +function rowLabels(container: HTMLElement): string[] { + return [...container.querySelectorAll('[role="button"]')] + .map(row => row.textContent ?? '') +} + +/** The row whose label is exactly `label`. */ +function rowByLabel(container: HTMLElement, label: string): HTMLElement { + const row = [...container.querySelectorAll('[role="button"]')] + .find(candidate => (candidate.textContent ?? '').startsWith(label)) + if (row === undefined) throw new Error(`no row "${label}" in ${JSON.stringify(rowLabels(container))}`) + return row +} + +/** Every path the tree has asked for, across all batches. */ +function requestedPaths(): string[] { + return fsTrees.mock.calls.flatMap(call => call[1] as string[]) +} + +let harness: Harness +beforeEach(() => { + vi.stubGlobal('WebSocket', FakeSocket) + fsTrees.mockReset() + fsTrees.mockImplementation(async (_scope: unknown, paths: readonly string[]) => ({ + levels: paths.map(path => levelOf(path)), + })) +}) + +afterEach(() => { + harness.unmount() + document.body.innerHTML = '' + vi.unstubAllGlobals() +}) + +describe('FileTree breadcrumb folding', () => { + it('folds a singleton chain into ONE a/b/c row and preloads the collapsed links', async () => { + harness = mountTree() + await flush() + + // The chain renders as one row carrying the full breadcrumb… + const labels = rowLabels(harness.container) + expect(labels.some(label => label.startsWith('a/b/c'))).toBe(true) + // …and NOT as the three nested rows it would be unfolded. + expect(labels.filter(label => /^a\/?b?\/?c?/.test(label))).toHaveLength(1) + // The collapsed links' levels were loaded ahead of any expansion: without + // them the label would grow a segment per click. + expect(requestedPaths().sort()).toEqual(['/tmp', '/tmp/a', '/tmp/a/b', '/tmp/a/b/c'].sort()) + // The sibling file is untouched by the fold. + expect(harness.container.textContent).toContain('readme.md') + }) + + it('toggles the WHOLE chain on a plain click, so the row closes as one', async () => { + // The head was expanded by an earlier interaction (before the fold formed): + // closing the row must collapse every link, not just the head. + harness = mountTree(['/tmp/a']) + await flush() + act(() => { rowByLabel(harness.container, 'a/b/c').click() }) + expect(harness.toggled).toEqual(['/tmp/a']) + }) + + it('expands every link of the chain when the row is closed', async () => { + harness = mountTree() + await flush() + act(() => { rowByLabel(harness.container, 'a/b/c').click() }) + // Closed → open: every link that is not expanded yet gets toggled, which is + // what makes the tail's children render. + expect(harness.toggled.sort()).toEqual(['/tmp/a', '/tmp/a/b', '/tmp/a/b/c'].sort()) + }) + + it('descends into the chain TAIL when open, not the head', async () => { + harness = mountTree(['/tmp/a/b/c']) + await flush() + // The folded row shows the tail's contents (the chain's end), never a/b's. + expect(harness.container.textContent).toContain('leaf.txt') + expect(rowLabels(harness.container).some(label => label.startsWith('a/b/c'))).toBe(true) + }) + + it('carries the exclude list on every request, and a changed list wipes the cache', async () => { + harness = mountTree([], ['node_modules']) + await flush() + // Every batch carries the patterns as its third argument. + for (const call of fsTrees.mock.calls) { + expect(call[2]).toEqual(['node_modules']) + } + expect(requestedPaths()).toContain('/tmp') + fsTrees.mockClear() + // A changed list must re-list the visible set: the HOST filters the rows, + // so what is cached was filtered by the previous list. + harness.rerender([], ['.DS_Store', 'node_modules']) + await flush() + expect(requestedPaths()).toContain('/tmp') + for (const call of fsTrees.mock.calls) { + expect(call[2]).toEqual(['.DS_Store', 'node_modules']) + } + }) + + it('does not re-list when a value-equal exclude list changes identity', async () => { + harness = mountTree([], ['node_modules']) + await flush() + fsTrees.mockClear() + // A fresh array with the same content: the cache and the effect key on the + // VALUE, so a re-render must not cost another listing. + harness.rerender([], ['node_modules']) + await flush() + expect(fsTrees).not.toHaveBeenCalled() + }) +}) diff --git a/tests/file-tree-compact.spec.ts b/tests/file-tree-compact.spec.ts new file mode 100644 index 00000000..30e378f4 --- /dev/null +++ b/tests/file-tree-compact.spec.ts @@ -0,0 +1,143 @@ +/** + * Explorer breadcrumb folding logic: the fold chain walks successive sole + * directory children while each link's level is loaded and healthy, and the + * load-target scan finds the collapsed singleton dirs whose levels must load + * ahead of expansion so chains can extend. + */ +import { describe, expect, it } from 'vitest' +import type { FsEntry } from '../src/client/api.ts' +import { MAX_COMPACT_DEPTH, compactChain, compactLoadTargets, type CompactLevel } from '../src/client/file-tree-compact.ts' + +/** A directory row; `compact` marks a singleton-dir level (host flag). + * `hidden` mirrors the host: dot-prefixed names are hidden rows. */ +function dir(path: string, compact = false): FsEntry { + const name = path.split('/').pop()! + return { + name, + path, + isDir: true, + hidden: name.startsWith('.'), + isSymlink: false, + broken: false, + ...(compact ? { compact: true } : {}), + } +} + +/** A file row. */ +function file(path: string): FsEntry { + const name = path.split('/').pop()! + return { name, path, isDir: false, hidden: name.startsWith('.'), isSymlink: false, broken: false } +} + +describe('compactChain', () => { + it('walks a loaded singleton chain to its end', () => { + // The terminal link carries the host mark too (sole FILE child), but the + // chain only extends through directory links. + const levels: Record = { + '/a': { entries: [dir('/a/b', true)] }, + '/a/b': { entries: [dir('/a/b/c', true)] }, + '/a/b/c': { entries: [file('/a/b/c/leaf.txt')] }, + } + const chain = compactChain(dir('/a', true), path => levels[path]) + expect(chain.map(entry => entry.path)).toEqual(['/a', '/a/b', '/a/b/c']) + }) + + it('pauses at an unloaded link (the caller keeps loading)', () => { + const levels: Record = { + '/a': { entries: [dir('/a/b', true)] }, + } + const chain = compactChain(dir('/a', true), path => levels[path]) + expect(chain.map(entry => entry.path)).toEqual(['/a', '/a/b']) + }) + + it('pauses at a failed level', () => { + const levels: Record = { + '/a': { entries: [dir('/a/b', true)] }, + '/a/b': { error: 'cannot list' }, + } + const chain = compactChain(dir('/a', true), path => levels[path]) + expect(chain.map(entry => entry.path)).toEqual(['/a', '/a/b']) + }) + + it('ignores hidden entries (macOS .DS_Store & co.) beside the sole child', () => { + // The host marked `compact` with the same filter: hidden rows beside the + // sole directory child must not snap the chain open on the client either. + const levels: Record = { + '/a': { entries: [file('/a/.DS_Store'), dir('/a/b', true)] }, + '/a/b': { entries: [dir('/a/b/c'), file('/a/b/.DS_Store'), file('/a/b/.gitignore')] }, + '/a/b/c': { entries: [file('/a/b/c/leaf.txt')] }, + } + const chain = compactChain(dir('/a', true), path => levels[path]) + expect(chain.map(entry => entry.path)).toEqual(['/a', '/a/b', '/a/b/c']) + }) + + it('does not extend through a hidden sole child', () => { + // A dir whose only non-hidden view is a hidden dir is never compact on + // the host; a stale mark must stop at the hidden child anyway. + const levels: Record = { + '/a': { entries: [dir('/a/.git', true)] }, + } + expect(compactChain(dir('/a', true), path => levels[path]).map(entry => entry.path)).toEqual(['/a']) + }) + + it('stops when a stale compact flag meets a multi-entry level', () => { + const levels: Record = { + '/a': { entries: [dir('/a/b'), file('/a/late.txt')] }, + } + const chain = compactChain(dir('/a', true), path => levels[path]) + expect(chain.map(entry => entry.path)).toEqual(['/a']) + }) + + it('refuses broken or file-shaped sole children', () => { + const broken: Record = { '/a': { entries: [{ ...dir('/a/b'), broken: true }] } } + expect(compactChain(dir('/a', true), path => broken[path])).toHaveLength(1) + const fileOnly: Record = { '/a': { entries: [file('/a/b.txt')] } } + expect(compactChain(dir('/a', true), path => fileOnly[path])).toHaveLength(1) + }) + + it('never revisits a path (stale-cache cycle guard)', () => { + const levels: Record = { + '/a': { entries: [dir('/a', true)] }, + } + const chain = compactChain(dir('/a', true), path => levels[path]) + expect(chain.map(entry => entry.path)).toEqual(['/a']) + }) + + it('bounds one chain at the depth cap', () => { + // A synthetic chain longer than the cap: every link loaded and compact. + const levels: Record = {} + for (let index = 0; index < MAX_COMPACT_DEPTH + 8; index += 1) { + levels[`/${'x'.repeat(index + 1)}`] = { entries: [dir(`/${'x'.repeat(index + 2)}`, true)] } + } + const chain = compactChain(dir('/x', true), path => levels[path]) + expect(chain).toHaveLength(MAX_COMPACT_DEPTH) + }) + + it('returns a non-compact entry unchanged', () => { + const chain = compactChain(dir('/a'), () => ({ entries: [dir('/a/b', true)] })) + expect(chain.map(entry => entry.path)).toEqual(['/a']) + }) +}) + +describe('compactLoadTargets', () => { + it('collects unloaded compact dir entries across loaded levels', () => { + const levels: Record = { + '/root': { entries: [dir('/root/a', true), file('/root/readme.md'), dir('/root/normal')] }, + '/root/a': { entries: [dir('/root/a/b', true), dir('/root/a/c', true)] }, + // Already in flight (FileTree stores {} while loading): not collected again. + '/root/a/b': {}, + } + // Only marked, not-yet-loaded dirs qualify: files and plain dirs never do. + expect(compactLoadTargets(levels)).toEqual(['/root/a/c']) + }) + + it('skips already-loaded paths and dedupes repeat appearances', () => { + const row = dir('/root/a', true) + const levels: Record = { + '/root': { entries: [row] }, + '/alt': { entries: [row] }, + '/root/a': { entries: [] }, + } + expect(compactLoadTargets(levels)).toEqual([]) + }) +}) diff --git a/tests/fs-search.spec.ts b/tests/fs-search.spec.ts index 515bdfe2..6173443b 100644 --- a/tests/fs-search.spec.ts +++ b/tests/fs-search.spec.ts @@ -10,6 +10,7 @@ import { 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 { compileExcludePatterns } from '../src/exclude-patterns.ts' import { searchFiles } from '../src/fs-search.ts' /** @@ -92,6 +93,30 @@ describe('fs-search', () => { } }) + it('the exclude probe removes entries and stops descent (in lockstep with the tree)', async () => { + const dir = mkdtempSync(join(tmpdir(), 'dsh-sidebar-search-exclude-')) + try { + mkdirSync(join(dir, 'third_party', 'pkg'), { recursive: true }) + mkdirSync(join(dir, 'src')) + writeFileSync(join(dir, 'third_party', 'pkg', 'index.ts'), 'dep') + writeFileSync(join(dir, 'third_party', 'index.ts'), 'dep') + writeFileSync(join(dir, 'src', 'index.ts'), 'code') + writeFileSync(join(dir, 'debug.log'), 'log') + const exclude = compileExcludePatterns(['third_party', '*.log'], dir) + // Excluded names never match AND their subtrees are never walked. + expect((await searchFiles(dir, 'index', { exclude })).matches).toEqual(['src/index.ts']) + expect((await searchFiles(dir, 'log', { exclude })).matches).toEqual([]) + // A directory hit disappears with the exclusion (no dangling nav row). + expect((await searchFiles(dir, 'third_party', { exclude })).dirs).toEqual([]) + // Without the probe the junk level matches and is descended. + expect((await searchFiles(dir, 'index')).matches) + .toEqual(['src/index.ts', 'third_party/index.ts', 'third_party/pkg/index.ts']) + expect((await searchFiles(dir, 'third_party')).dirs).toEqual(['third_party']) + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + it('never descends into node_modules or other noise directories', async () => { const dir = makeFixture() try { diff --git a/tests/fs-tree-compact.spec.ts b/tests/fs-tree-compact.spec.ts new file mode 100644 index 00000000..4d5a3c0e --- /dev/null +++ b/tests/fs-tree-compact.spec.ts @@ -0,0 +1,127 @@ +/** + * fs-tree compact marking: a directory row whose contents are EXACTLY one + * real directory child gets `compact` so the explorer can fold singleton + * chains into one breadcrumb row. Mixed/empty/file-only levels and + * symlink-only children stay unmarked (a self-referential link would + * otherwise fold forever). + */ +import { 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 { listDirectory } from '../src/fs-tree.ts' + +/** Mirror of the symlink spec's capability probe (symlinks need privileges on Windows). */ +const canSymlink = (() => { + const dir = mkdtempSync(join(tmpdir(), 'dsh-sidebar-compact-probe-')) + try { + symlinkSync('target', join(dir, 'link')) + return true + } catch { + return false + } finally { + rmSync(dir, { recursive: true, force: true }) + } +})() + +/** A scratch level covering every compact/not-compact shape. */ +function makeFixture(): string { + const dir = mkdtempSync(join(tmpdir(), 'dsh-sidebar-compact-')) + // Singleton chain a/b/c ending in a real file. + mkdirSync(join(dir, 'a', 'b', 'c'), { recursive: true }) + writeFileSync(join(dir, 'a', 'b', 'c', 'leaf.txt'), 'leaf') + // Dir + file together: not a singleton. + mkdirSync(join(dir, 'mixed', 'child'), { recursive: true }) + writeFileSync(join(dir, 'mixed', 'note.txt'), 'note') + // Empty dir: not a singleton. + mkdirSync(join(dir, 'empty')) + // Lone FILE child: not a directory singleton. + mkdirSync(join(dir, 'lone-file')) + writeFileSync(join(dir, 'lone-file', 'only.txt'), 'only') + return dir +} + +describe('fs-tree compact marking', () => { + it('marks every link of a singleton directory chain', async () => { + const dir = makeFixture() + try { + const root = await listDirectory(dir) + expect(root.entries.find(entry => entry.name === 'a')).toMatchObject({ isDir: true, compact: true }) + const levelA = await listDirectory(join(dir, 'a')) + expect(levelA.entries.find(entry => entry.name === 'b')).toMatchObject({ isDir: true, compact: true }) + const levelB = await listDirectory(join(dir, 'a', 'b')) + expect(levelB.entries.find(entry => entry.name === 'c')).toMatchObject({ isDir: true, compact: true }) + // The chain ends where the level stops being a dir singleton. + const levelC = await listDirectory(join(dir, 'a', 'b', 'c')) + expect(levelC.entries.find(entry => entry.name === 'leaf.txt')?.compact).toBeUndefined() + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + + it('leaves mixed and empty levels unmarked; marks the terminal singleton', async () => { + const dir = makeFixture() + try { + const root = await listDirectory(dir) + for (const name of ['mixed', 'empty']) { + expect(root.entries.find(entry => entry.name === name)?.compact, name).toBeUndefined() + } + // The terminal link (sole FILE child) is marked too: the client + // preloads it so the fold label never shifts on expansion. + expect(root.entries.find(entry => entry.name === 'lone-file')).toMatchObject({ isDir: true, compact: true }) + // File rows never carry the mark. + const mixed = await listDirectory(join(dir, 'mixed')) + expect(mixed.entries.find(entry => entry.name === 'note.txt')?.compact).toBeUndefined() + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + + it.skipIf(!canSymlink)('never marks a dir whose only child is a symlink', async () => { + const dir = mkdtempSync(join(tmpdir(), 'dsh-sidebar-compact-link-')) + try { + mkdirSync(join(dir, 'wrapper')) + mkdirSync(join(dir, 'target')) + symlinkSync(join(dir, 'target'), join(dir, 'wrapper', 'link')) + const listing = await listDirectory(join(dir, 'wrapper')) + expect(listing.entries.find(entry => entry.name === 'link')).toMatchObject({ isDir: true, isSymlink: true }) + expect(listing.entries.find(entry => entry.name === 'link')?.compact).toBeUndefined() + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + + it('ignores hidden (dot-prefixed) entries when counting children', async () => { + const dir = mkdtempSync(join(tmpdir(), 'dsh-sidebar-compact-hidden-')) + try { + // Finder junk beside the sole dir child: still a fold singleton. + mkdirSync(join(dir, 'chain', 'inner'), { recursive: true }) + writeFileSync(join(dir, 'chain', '.DS_Store'), 'junk') + // Any hidden file beside the sole FILE child (terminal link): marked. + mkdirSync(join(dir, 'terminal')) + writeFileSync(join(dir, 'terminal', 'only.txt'), 'only') + writeFileSync(join(dir, 'terminal', '.gitignore'), 'ignored') + // Hidden DIR children never count either. + mkdirSync(join(dir, 'hidden-dir', 'child'), { recursive: true }) + mkdirSync(join(dir, 'hidden-dir', '.cache')) + // Hidden beside TWO real entries: not a singleton. + mkdirSync(join(dir, 'crowded', 'child'), { recursive: true }) + writeFileSync(join(dir, 'crowded', 'note.txt'), 'note') + writeFileSync(join(dir, 'crowded', '.DS_Store'), 'junk') + // Hidden alone is NOT a singleton (zero effective children). + mkdirSync(join(dir, 'hidden-only')) + writeFileSync(join(dir, 'hidden-only', '.DS_Store'), 'junk') + const listing = await listDirectory(dir) + expect(listing.entries.find(entry => entry.name === 'chain')).toMatchObject({ isDir: true, compact: true }) + expect(listing.entries.find(entry => entry.name === 'terminal')).toMatchObject({ isDir: true, compact: true }) + expect(listing.entries.find(entry => entry.name === 'hidden-dir')).toMatchObject({ isDir: true, compact: true }) + expect(listing.entries.find(entry => entry.name === 'crowded')?.compact).toBeUndefined() + expect(listing.entries.find(entry => entry.name === 'hidden-only')?.compact).toBeUndefined() + // Hidden rows themselves still list (dimmed) and never carry the mark. + const chain = await listDirectory(join(dir, 'chain')) + expect(chain.entries.find(entry => entry.name === '.DS_Store')).toMatchObject({ isDir: false, hidden: true }) + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) +}) diff --git a/tests/fs-tree-exclude.spec.ts b/tests/fs-tree-exclude.spec.ts new file mode 100644 index 00000000..25a28766 --- /dev/null +++ b/tests/fs-tree-exclude.spec.ts @@ -0,0 +1,155 @@ +/** + * fs-tree exclude filtering: the explorerExclude pref compiles into a probe + * that listDirectory and the singleton-fold probe share. Matched entries + * vanish from the listing (VS Code files.exclude semantics), never occupy a + * row or an overflow slot, and never block a breadcrumb fold. + */ +import { describe, expect, it } from 'vitest' +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { compileExcludePatterns } from '../src/exclude-patterns.ts' +import { listDirectory } from '../src/fs-tree.ts' + +/** A scratch tree exercising name, path-anchored and deep patterns. */ +function makeFixture(): string { + const dir = mkdtempSync(join(tmpdir(), 'dsh-sidebar-exclude-')) + writeFileSync(join(dir, '.DS_Store'), 'junk') + writeFileSync(join(dir, 'keep.txt'), 'keep') + mkdirSync(join(dir, 'node_modules', 'pkg'), { recursive: true }) + writeFileSync(join(dir, 'node_modules', 'pkg', 'index.js'), 'dep') + mkdirSync(join(dir, 'build', 'out'), { recursive: true }) + writeFileSync(join(dir, 'build', 'out', 'app.js'), 'artifact') + writeFileSync(join(dir, 'build', 'main.ts'), 'source') + mkdirSync(join(dir, 'src', 'out'), { recursive: true }) + writeFileSync(join(dir, 'src', 'out', 'gen.ts'), 'generated') + // Singleton chain with excluded junk beside the sole child. + mkdirSync(join(dir, 'chain', 'inner'), { recursive: true }) + mkdirSync(join(dir, 'chain', 'node_modules'), { recursive: true }) + // Terminal link with an excluded file beside the sole FILE child. + mkdirSync(join(dir, 'terminal')) + writeFileSync(join(dir, 'terminal', 'only.txt'), 'only') + writeFileSync(join(dir, 'terminal', 'debug.log'), 'log') + return dir +} + +describe('fs-tree exclude filtering', () => { + it('drops matched entries from the listing (bare names at any depth)', async () => { + const dir = makeFixture() + try { + const exclude = compileExcludePatterns(['.DS_Store', 'node_modules'], dir) + const root = await listDirectory(dir, 1000, exclude) + const names = root.entries.map(entry => entry.name) + expect(names).not.toContain('.DS_Store') + expect(names).not.toContain('node_modules') + expect(names).toContain('keep.txt') + expect(names).toContain('build') + // The same bare name vanishes wherever it appears. + const chain = await listDirectory(join(dir, 'chain'), 1000, exclude) + expect(chain.entries.map(entry => entry.name)).toEqual(['inner']) + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + + it('path-anchored patterns match the full cwd-relative path only', async () => { + const dir = makeFixture() + try { + const exclude = compileExcludePatterns(['build/out'], dir) + // The anchored level: `build/out` drops as one row, its sibling stays. + const root = await listDirectory(dir, 1000, exclude) + expect(root.entries.map(entry => entry.name)).toContain('build') + const build = await listDirectory(join(dir, 'build'), 1000, exclude) + expect(build.entries.map(entry => entry.name)).toEqual(['main.ts']) + // The same tail shape elsewhere is NOT excluded (no anchor match). + const src = await listDirectory(join(dir, 'src'), 1000, exclude) + expect(src.entries.map(entry => entry.name)).toEqual(['out']) + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + + it('a doublestar-slash pattern matches at any depth', async () => { + const dir = mkdtempSync(join(tmpdir(), 'dsh-sidebar-exclude-deep-')) + try { + mkdirSync(join(dir, 'logs')) + mkdirSync(join(dir, 'nested', 'logs'), { recursive: true }) + writeFileSync(join(dir, 'nested', 'keep.txt'), 'keep') + const exclude = compileExcludePatterns(['**/logs'], dir) + expect((await listDirectory(dir, 1000, exclude)).entries.map(entry => entry.name)).toEqual(['nested']) + const nested = await listDirectory(join(dir, 'nested'), 1000, exclude) + expect(nested.entries.map(entry => entry.name)).toEqual(['keep.txt']) + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + + it('excluded entries never block the singleton fold probe', async () => { + const dir = makeFixture() + try { + const exclude = compileExcludePatterns(['node_modules', '*.log'], dir) + const root = await listDirectory(dir, 1000, exclude) + // Excluded dir beside the sole child: still a fold singleton. + expect(root.entries.find(entry => entry.name === 'chain')).toMatchObject({ isDir: true, compact: true }) + // Excluded file beside the sole FILE child (terminal link): marked. + expect(root.entries.find(entry => entry.name === 'terminal')).toMatchObject({ isDir: true, compact: true }) + // Without the probe the junk entries break the fold. + const unfiltered = await listDirectory(dir) + expect(unfiltered.entries.find(entry => entry.name === 'chain')?.compact).toBeUndefined() + expect(unfiltered.entries.find(entry => entry.name === 'terminal')?.compact).toBeUndefined() + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + + it('excluded rows neither render nor count toward the level cap', async () => { + const dir = mkdtempSync(join(tmpdir(), 'dsh-sidebar-exclude-cap-')) + try { + writeFileSync(join(dir, 'a.txt'), 'a') + writeFileSync(join(dir, 'b.txt'), 'b') + writeFileSync(join(dir, 'junk.log'), 'junk') + const exclude = compileExcludePatterns(['*.log'], dir) + const result = await listDirectory(dir, 2, exclude) + expect(result.truncated).toBe(false) + expect(result.entries.map(entry => entry.name)).toEqual(['a.txt', 'b.txt']) + // Same level without the probe: the cap trips. + expect((await listDirectory(dir, 2)).truncated).toBe(true) + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + + it('an undefined probe leaves the listing untouched', async () => { + const dir = makeFixture() + try { + const names = (await listDirectory(dir)).entries.map(entry => entry.name) + expect(names).toContain('.DS_Store') + expect(names).toContain('node_modules') + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + + // The host keeps listings in a TTL cache, so the pattern set MUST be part of + // the cache identity: a listing filtered by one list can never be served to a + // request carrying another. There is no pref-change invalidation hook to ride + // (the patterns travel WITH each request), so the key is the whole defence — + // it is also what makes the user's edit visible on the very next read. + it('never serves a level cached under a different pattern set', async () => { + const dir = makeFixture() + try { + // Warm the cache with the junk visible… + const unfiltered = await listDirectory(dir, 1000) + expect(unfiltered.entries.map(entry => entry.name)).toContain('node_modules') + // …then re-list the SAME level through a filter, inside the TTL. + const filtered = await listDirectory(dir, 1000, compileExcludePatterns(['node_modules'], dir)) + expect(filtered.entries.map(entry => entry.name)).not.toContain('node_modules') + // A value-equal pattern list still hits the cache (no needless re-read). + expect(await listDirectory(dir, 1000, compileExcludePatterns(['node_modules'], dir))).toBe(filtered) + // And the unfiltered level stays reachable under its own key. + expect(await listDirectory(dir, 1000)).toBe(unfiltered) + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) +}) diff --git a/tests/prefs.spec.ts b/tests/prefs.spec.ts index f38dc58b..c1210463 100644 --- a/tests/prefs.spec.ts +++ b/tests/prefs.spec.ts @@ -39,6 +39,7 @@ describe('side card preferences', () => { mobileDefaultTree: true, agentOpenTools: true, editorExplorer: false, + explorerExclude: ['.DS_Store', 'Thumbs.db'], titleBarScheme: 'auto', titleBarPresetId: '', customCss: '', @@ -62,6 +63,7 @@ describe('side card preferences', () => { mobileDefaultTree: true, agentOpenTools: false, editorExplorer: false, + explorerExclude: ['.DS_Store', 'Thumbs.db'], titleBarScheme: 'auto', titleBarPresetId: '', customCss: '', @@ -85,6 +87,7 @@ describe('side card preferences', () => { mobileDefaultTree: true, agentOpenTools: false, editorExplorer: false, + explorerExclude: ['.DS_Store', 'Thumbs.db'], titleBarScheme: 'auto', titleBarPresetId: '', customCss: '', @@ -125,6 +128,18 @@ describe('side card preferences', () => { } }) + it('defaults explorerExclude to the stock junk list; only a valid string array overrides it', async () => { + // Absent or malformed → the stock list. + expect((await loadPrefs(wire({}))).explorerExclude).toEqual(['.DS_Store', 'Thumbs.db']) + expect((await loadPrefs(wire({ explorerExclude: 'node_modules' }))).explorerExclude).toEqual(['.DS_Store', 'Thumbs.db']) + expect((await loadPrefs(wire({ explorerExclude: { a: 1 } }))).explorerExclude).toEqual(['.DS_Store', 'Thumbs.db']) + // Non-string entries drop out; blanks drop out; entries trim. + expect((await loadPrefs(wire({ explorerExclude: ['node_modules', 42, ' *.log ', '', null] }))).explorerExclude) + .toEqual(['node_modules', '*.log']) + // An explicit empty array means "exclude nothing" and survives verbatim. + expect((await loadPrefs(wire({ explorerExclude: [] }))).explorerExclude).toEqual([]) + }) + it('defaults editorExplorer to false; only an explicit true enables the merged editor-explorer', async () => { // Absent or malformed → off (separate file windows are the default). expect((await loadPrefs(wire({}))).editorExplorer).toBe(false) diff --git a/tests/side-card-section.spec.tsx b/tests/side-card-section.spec.tsx index 7c906fc8..77cac81e 100644 --- a/tests/side-card-section.spec.tsx +++ b/tests/side-card-section.spec.tsx @@ -392,9 +392,11 @@ describe('SettingsBody rows + custom render panel (open-with seam)', () => { onToggle: () => {}, onCommit: () => '', onSelectValue: () => {}, + onPatterns: () => {}, onPluginToggle: () => {}, onPluginCommit: () => '', onPluginSelectValue: () => {}, + onPluginPatterns: () => {}, onPluginWrite: () => {}, onClose: () => {}, })) @@ -422,9 +424,11 @@ describe('SettingsBody rows + custom render panel (open-with seam)', () => { onToggle: () => {}, onCommit: () => '', onSelectValue: () => {}, + onPatterns: () => {}, onPluginToggle: () => {}, onPluginCommit: () => '', onPluginSelectValue: () => {}, + onPluginPatterns: () => {}, onPluginWrite: () => {}, onClose: () => {}, })) diff --git a/tests/smoke.spec.ts b/tests/smoke.spec.ts index 03446bd8..0ec6076a 100644 --- a/tests/smoke.spec.ts +++ b/tests/smoke.spec.ts @@ -1009,6 +1009,43 @@ describe('session cwd resolution over the API route', () => { } }) + it('fs.trees and fs.search apply the request exclude patterns', async () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-fs-exclude-')) + const workspace = join(root, 'workspace') + mkdirSync(join(workspace, 'src'), { recursive: true }) + mkdirSync(join(workspace, 'third_party', 'pkg'), { recursive: true }) + writeFileSync(join(workspace, '.DS_Store'), 'junk') + writeFileSync(join(workspace, 'src', 'index.ts'), 'code') + writeFileSync(join(workspace, 'third_party', 'index.ts'), 'dep') + try { + const route = mount({ sessions: { get: () => ({ header: { cwd: workspace } }) } }) + // `fs.trees` is the file tree's REAL entry (one POST per mount/expand): + // the exclude list has to reach this route or the pref does nothing. + const batch = await invoke(route, 'fs.trees', { + sessionId: 's-tree', + paths: [workspace], + exclude: ['.DS_Store', 'third_party'], + }) + expect(batch.ok).toBe(true) + const levels = (batch.value as unknown as { levels: Array<{ entries: Array<{ name: string }> }> }).levels + expect(levels[0]!.entries.map(entry => entry.name)).toEqual(['src']) + // The search shares the one compiled matcher: excluded names never match + // and are never descended (a directory hit disappears with them). + const search = await invoke(route, 'fs.search', { + sessionId: 's-tree', + query: 'index', + exclude: ['third_party'], + }) + expect((search.value as unknown as { matches: string[] }).matches).toEqual(['src/index.ts']) + // No exclude on the request → the unfiltered fast path, unchanged. + const plain = await invoke(route, 'fs.trees', { sessionId: 's-tree', paths: [workspace] }) + const plainLevels = (plain.value as unknown as { levels: Array<{ entries: Array<{ name: string }> }> }).levels + expect(plainLevels[0]!.entries.map(entry => entry.name)).toEqual(['src', 'third_party', '.DS_Store']) + } 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')