feat(explorer): 资源管理器补「新建文件」+ 排序三档(#132)
第一部分:新建文件(移植贡献者 PR #832 的交互语义,写路径改落服务端) - 新增路由 fs.createFile → fs-operations.ts 的 createWorkspaceFile:单段名、 已存在即拒(fs-error 409,同一句 "x" already exists,绝不截断同名文件, 落盘用 wx)、拒绝 Windows 非法字符(< > : " | ? * 与控制字符)与保留设备名 (CON / PRN / AUX / NUL / COM1-9 / LPT1-9,带不带扩展名都拒)、路径穿越 (..、a/b、a\b)与空名一律 bad-request 400 - src/client/api.ts 镜像 fsCreateFile;FileTree 目录行右键「新建文件」与 「新建文件夹」并列,复用同一套行内输入(Enter 提交 / Escape 取消 / 失焦提交 / IME 保护,图标跟随输入名),两者互斥;客户端先在已加载层做大小写不敏感的 占用检查(newFileExists),服务端仍是最终裁决 - 词条 newFile / newFilePlaceholder / newFileInvalid / newFileExists 进入 locales.ts 的 zh/en 与 19 份第三语言词典(ja 为真日文) 第二部分:排序三档(名称 / 类型 / 文件夹优先开关) - 新增 src/client/file-tree-sort.ts:对 level.entries 的副本排序,不改服务端、 不原地重排共享目录缓存;默认(名称 + 文件夹优先)与宿主 fs-tree.ts 的 compareEntries 逐元素一致 - 控件落在文件树头部既有工具区(TreePanel 搜索行的刷新按钮旁):IconButton + Menu(名称 / 类型打勾 + 文件夹优先独立开关),沿用既有控件样式与可访问名 - 「按修改时间」不在本批范围 测试:tests/fs-create-file.spec.ts(11)、tests/file-tree-new-file.spec.tsx(11)、 tests/file-tree-sort.spec.tsx(12),并修 tests/file-tree-hover-title.spec.tsx 的 夹具顺序(原夹具不是任何宿主会返回的目录序) Co-authored-by: finley08 <fazhang08@163.com>
This commit is contained in:
1 parent
f0a038a1f5
commit
0655b88629
33 files changed
+1389
-24
No files matched your search
@@ -4,6 +4,10 @@
|
||||
|
||||
### Unreleased
|
||||
|
||||
- 🗂️ **资源管理器补「新建文件」**([#132](https://github.com/omdsh-dev/DSH-better-sidebar/issues/132),移植贡献者 PR [#832](https://github.com/omdsh-dev/DSH-better-sidebar/pull/832) 的交互语义):目录行右键「新建文件夹」旁新增「**新建文件**」,在该层顶部插入同款行内输入(Enter 提交 / Escape 取消 / 失焦提交 / IME 保护,图标跟随输入的文件名),与「新建文件夹」**互斥**(开一个即关另一个)。与 PR 的差别是**写路径落在服务端**:新增路由 `fs.createFile` → `fs-operations.ts` 的 `createWorkspaceFile`,复用既有 rename/mkdir 的单段名与「已存在即拒」规则(`fs-error` 409,同一句 `"x" already exists`),并额外拒绝 Windows 非法字符(`< > : " | ? *` 与控制字符)与保留设备名(CON / PRN / AUX / NUL / COM1-9 / LPT1-9,带不带扩展名都拒);落盘用 `wx`,**同名文件绝不被截断**;客户端在已加载的那一层先做一次大小写不敏感的占用检查(`newFileExists`),服务端仍是最终裁决。词条 `newFile` / `newFilePlaceholder` / `newFileInvalid` / `newFileExists` 同批进入 `locales.ts` 的 zh/en 与 19 份第三语言词典。
|
||||
- ↕️ **资源管理器排序三档**([#132](https://github.com/omdsh-dev/DSH-better-sidebar/issues/132)):文件树头部工具区(刷新 / 上传按钮旁)新增排序菜单——**按名称 / 按类型**二选一(打勾)+ **文件夹优先**独立开关。排序作用于 `level.entries` 的**副本**,不改服务端、不原地重排共享的目录缓存;**默认(名称 + 文件夹优先)与宿主原有顺序逐元素一致**(`tests/file-tree-sort.spec.tsx` 直接拿 `fs-tree.ts` 的 `compareEntries` 当基准)。「按修改时间」不在本批范围(维护者另立 issue)。
|
||||
- 🧪 测试:`tests/fs-create-file.spec.ts`(11 例:成功 / 根目录为父 / 空名·`.`·`..`·分隔符·`../escape` 路径穿越 / 全部 Windows 非法字符 / 保留名与近似名 / 已存在且内容不被截断 / 同名为目录 / 不可写父目录 / 工作区外父目录 / 路由 200·409·400 三态),`tests/file-tree-new-file.spec.tsx`(11 例:菜单只在目录行、根层与子层提交、Escape、非法名、占用名、服务端拒绝进错误条、失焦提交、两种创建器互斥),`tests/file-tree-sort.spec.tsx`(12 例:三档顺序、文件夹优先两种取值、默认等于宿主顺序、不原地排序、`typeOf`,以及 FileTree 渲染与 TreePanel 头部控件端到端切档)。
|
||||
|
||||
- 📑 **Tab 右键菜单补两项**([#109](https://github.com/omdsh-dev/DSH-better-sidebar/issues/109)):「**关闭全部页签**」与「**在资源管理器中定位**」。前者作用域与相邻三项一致——**右键所在的那个标签组**(分栏各管各的),含右键的那个页签本身(这是它与「关闭其他页签」的区别),逐条走既有单页签关闭路径(descriptor `onClose` 生命周期 + 终端 pty 释放 + 会话作用域),页签在滚动视口外也能关;菜单只从页签上打开,所以该项恒可用。后者对页签关联的文件(`tab.path`,即编辑器/文件夹窗口)调用宿主 **open-in-app** 的 reveal——与资源管理器行右键「在文件管理器中显示」**同一个适配器**(`createOpenInApp` → `ctx.remote.session.openWorkspacePath({ action: 'reveal' })`),不新增任何宿主调用;变更 / 任务 / 侧边对话 / diff 页签没有可定位的文件(diff 的 ref 是仓库相对路径,不是宿主能定位的路径),该项置灰,无 resolver 时同样置灰。词条 `closeAllTabs` / `revealTabInFileManager` 同批进入 `locales.ts` 的 zh/en 与 19 份第三语言词典。
|
||||
- 🧪 测试:`tests/tab-bar-context-menu.spec.tsx` 把菜单整份钉到 **6 项**(标签序 + 每行 disabled 数组),新增「关闭全部」「定位」「无关联文件置灰」「无 resolver 置灰」用例,并新增一条 Workbench 用例钉住 reveal resolver 穿到**分栏后每个 pane 的** tab 条(回退任一层传递即红)。
|
||||
- 🔍 **文件搜索优先走本机原生引擎(fd / ripgrep),缺失或失败自动回退 JS 遍历**([#203](https://github.com/omdsh-dev/DSH-better-sidebar/issues/203),PR [#303](https://github.com/omdsh-dev/DSH-better-sidebar/pull/303) 重写落地):`fs.search` 之前是纯 JS 递归遍历,十万级目录秒级、10 万条访问预算一顶就静默截断。现在启动后惰性探测一次(每个候选二进制 `--version` 500ms 内验证通过才用,进程内缓存),探到就用引擎,探不到/运行失败回退原遍历;rg 优先用 DSH 自己捆绑的 `@vscode/ripgrep`(agent 侧搜索工具同一个二进制,从 CLI 入口的依赖树推导候选路径),fd 走 `--fixed-strings` 字面量匹配。噪声目录排除名单单源化到 `SKIP_DIR_NAMES`(18 项,walk 与两条 argv 共用),引擎输出统一归一化成 walk 契约(根相对、`/` 分隔、大小写不敏感),**路由与客户端零改动**。**目录命中按 #801 的契约同时产出 `dirs`**:fd 用 `--type d` 直接列目录,rg 由文件路径倒推匹配的目录段(`deriveRgMatches`)——唯一残留差异是**空目录在 rg 下不可见**(已记录)。运行失败禁用该引擎(坏二进制不该拖慢后续搜索),**超时只降级本次**(树太大不等于二进制坏)。调试插桩 `DSH_SEARCH_DEBUG=1` 写 `$DSH_HOME/search-debug.log`,默认完全静默。Windows 侧由 `ci-windows` lane 承载:`choco install fd ripgrep` + `pnpm check:engines` 对插件自己的 argv 做字节级断言(不得含 `\`/CR、非 ASCII 文件名必须命中)。
|
||||
|
||||
@@ -48,7 +48,7 @@
|
||||
相比 DSH 官方侧边栏,本插件补上的关键能力:
|
||||
|
||||
- **🖥️ 可编辑的代码编辑器**:官方文档预览是**只读**的 → 插件保留**可编辑**的 CodeMirror 编辑器(保存、语法高亮、预览切换);Markdown / HTML 也走插件自有渲染(Mermaid 图表安全渲染 + 点击放大、README 级内嵌 HTML、浮动目录大纲、HTML 沙箱预览)
|
||||
- **🗂️ 增强文件树**:接管内置「文件」页——懒加载目录树、**展开的目录实时 watch 自动刷新**、软链接识别、全局文件名搜索、拖拽上传、悬浮 `@文件` 一键引用进输入框;**Ctrl/Cmd 多选 + Shift 连选**(批量复制路径 / 批量删除)、**Git 变更着色 + 状态字母**(VS Code 同款)、**新建文件夹**、**多选右键「压缩并打包下载」**(服务端流式打 ZIP,无第三方依赖);右键「打开方式」= **DSH 自带 open-in-app**(宿主探测到的本机关联应用 + 文件管理器显示)**+ 插件自研打开方式**(资源管理器 / VS Code / Cursor / Zed / 自定义编辑器 URL 模板、SSH 远端、固定到菜单)两者并存
|
||||
- **🗂️ 增强文件树**:接管内置「文件」页——懒加载目录树、**展开的目录实时 watch 自动刷新**、软链接识别、全局文件名搜索、拖拽上传、悬浮 `@文件` 一键引用进输入框;**Ctrl/Cmd 多选 + Shift 连选**(批量复制路径 / 批量删除)、**Git 变更着色 + 状态字母**(VS Code 同款)、**新建文件夹 / 新建文件**(行内输入;服务端拒绝非法名、Windows 保留设备名与已存在的目标,绝不截断同名文件)、**排序**(名称 / 类型 + 文件夹优先开关,默认与宿主原有顺序一致)、**多选右键「压缩并打包下载」**(服务端流式打 ZIP,无第三方依赖);右键「打开方式」= **DSH 自带 open-in-app**(宿主探测到的本机关联应用 + 文件管理器显示)**+ 插件自研打开方式**(资源管理器 / VS Code / Cursor / Zed / 自定义编辑器 URL 模板、SSH 远端、固定到菜单)两者并存
|
||||
- **🌿 文件变动**(官方侧栏没有 Git 面板):Git 视角(暂存 / 提交 / 历史 / 工作树与子仓库)+ 本轮 AI 改动视角双合一,统一 diff 渲染(行内字符级高亮、语法着色、敏感内容脱敏);两视角共用一套 28px 行、单一空态/错误通道与吸底提交条
|
||||
- **🧩 任务管理**(官方没有):子代理拓扑实时预览 + 后台任务清单(退出码 / 实时输出 / 强制终止)
|
||||
- **💬 侧边对话**(官方没有,beta):Codex 风格侧边线程——继承主会话完整上下文独立运行,可持续追问,一键提升为顶层会话
|
||||
@@ -172,7 +172,7 @@ dsh registry enable dsh-external/dsh-better-sidebar
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **🗂️ 文件工作台:资源管理器**<br/><sub>支持两种格式的资源管理器:内嵌在文件预览中 / 独立显示文件树。懒加载目录树、**展开的目录由宿主按目录 watch、改动后自动重列**、软链接按目标类型展示(目录软链接可展开、失效链接标红)、全局文件名搜索、上传文件/文件夹与拖放上传、右键菜单(在新 Tab 打开 / 在侧边打开 / 新建文件夹 / 打开方式:**宿主探测到的系统关联应用**(open-in-app)+ **插件自研目标**(资源管理器 / VS Code / Cursor / Zed / 自定义编辑器,支持 SSH 远端与固定到菜单)/ 复制路径 / 重命名 / 删除)、**Ctrl/Cmd 多选与 Shift 连选**(批量复制路径 / 批量删除 / **压缩并下载**)、**Git 变更按状态着色并带 M/A/D/U 字母**、悬浮 `@文件` 一键引用进输入框。</sub><br/><div align="center"><img width="420" alt="文件资源管理器" src="https://github.com/user-attachments/assets/a410bfd2-a8ba-43e6-873e-22417756e94d" /></div> | **📝 Markdown · HTML 内联预览**<br/><sub>Markdown 预览支持 **Mermaid 图表**(`securityLevel: 'strict'` 安全渲染 + 二次清洗;点击图表弹窗放大、滚轮缩放、拖拽平移)、**README 级内嵌 HTML**(徽章墙 `<div align=center>`、`<details>` 折叠块内嵌 markdown、表格单元格内联标签——DOMPurify 白名单消毒真实渲染,`<script>` 等活性内容剥除,本地图片经会话媒体路由重写)与**浮动目录大纲**(≥3 标题出现,点击平滑跳转、自动展开折叠块);HTML 走插件自带的**沙箱预览**,并带 `htmlViewerNoSandbox` / `htmlViewerDefaultUnsafe` 两个宿主没有的逃生门开关。**图片 / PDF / 表格 / Office 不再是插件能力**——那些格式由 DSH 自己的文档预览渲染。</sub><br/><div align="center"><img width="420" alt="Markdown + Mermaid 预览" src="https://github.com/user-attachments/assets/fe0e5182-55bb-45cc-b98b-a2877c2bdd38" /></div> |
|
||||
| **🗂️ 文件工作台:资源管理器**<br/><sub>支持两种格式的资源管理器:内嵌在文件预览中 / 独立显示文件树。懒加载目录树、**展开的目录由宿主按目录 watch、改动后自动重列**、软链接按目标类型展示(目录软链接可展开、失效链接标红)、全局文件名搜索、上传文件/文件夹与拖放上传、右键菜单(在新 Tab 打开 / 在侧边打开 / 新建文件夹 / 新建文件 / 打开方式:**宿主探测到的系统关联应用**(open-in-app)+ **插件自研目标**(资源管理器 / VS Code / Cursor / Zed / 自定义编辑器,支持 SSH 远端与固定到菜单)/ 复制路径 / 重命名 / 删除)、**Ctrl/Cmd 多选与 Shift 连选**(批量复制路径 / 批量删除 / **压缩并下载**)、**Git 变更按状态着色并带 M/A/D/U 字母**、头部工具区可切**名称 / 类型排序 + 文件夹优先开关**(默认即宿主原顺序)、悬浮 `@文件` 一键引用进输入框。</sub><br/><div align="center"><img width="420" alt="文件资源管理器" src="https://github.com/user-attachments/assets/a410bfd2-a8ba-43e6-873e-22417756e94d" /></div> | **📝 Markdown · HTML 内联预览**<br/><sub>Markdown 预览支持 **Mermaid 图表**(`securityLevel: 'strict'` 安全渲染 + 二次清洗;点击图表弹窗放大、滚轮缩放、拖拽平移)、**README 级内嵌 HTML**(徽章墙 `<div align=center>`、`<details>` 折叠块内嵌 markdown、表格单元格内联标签——DOMPurify 白名单消毒真实渲染,`<script>` 等活性内容剥除,本地图片经会话媒体路由重写)与**浮动目录大纲**(≥3 标题出现,点击平滑跳转、自动展开折叠块);HTML 走插件自带的**沙箱预览**,并带 `htmlViewerNoSandbox` / `htmlViewerDefaultUnsafe` 两个宿主没有的逃生门开关。**图片 / PDF / 表格 / Office 不再是插件能力**——那些格式由 DSH 自己的文档预览渲染。</sub><br/><div align="center"><img width="420" alt="Markdown + Mermaid 预览" src="https://github.com/user-attachments/assets/fe0e5182-55bb-45cc-b98b-a2877c2bdd38" /></div> |
|
||||
| **🖥️ CodeMirror 代码编辑器**<br/><sub>**可编辑**的文本 / 代码编辑器(保存、语法高亮、预览切换)——宿主自己的文档预览是**只读**的,这是插件保留 catch-all viewer 的理由。</sub><br/><div align="center"><img width="420" alt="CodeMirror 代码编辑器" src="https://github.com/user-attachments/assets/b44b488e-568c-4ee0-b96c-e9c906598a77" /></div> | **🖼️ 图片 / PDF / 表格 / Office 预览(由 DSH 内置提供)**<br/><sub>这些只读格式由 DSH 自己的 `ui-sidebar-documentpreview` 渲染:宿主侧 Office→PDF 转换、电子表格 worker 表格、图片 / PDF 缩放视口,并**按目录自动刷新**。插件已删除自己的 image / pdf / 下载兜底 viewer,也不再认领这些扩展名。</sub><br/><div align="center"><img width="420" alt="图片内联预览" src="https://github.com/user-attachments/assets/f9a58c30-5b7a-48b5-9e22-37d7e071f593" /></div> |
|
||||
| **💻 终端(由 DSH 内置提供)**<br/><sub>右侧栏终端由 DSH 自己的 `ui-sidebar-terminal` 提供:shell 选择、双击重命名、断线重连、刷新后恢复、主题与对比度跟随。插件不再自带终端实现。<br/><br/>⚠️ **模型侧提示**:插件原来自带的 8 个 `terminal_*` 工具(默认关)是模型唯一的**跨调用持久**终端;上游等价物 `@deepseek-ai/dsh-tool-terminal` 未被任何内置 bundle 默认挂载,若你需要该能力,请在 profile 的 `cordis.patch.yml` 里自行插入一行 `tool-terminal`。</sub><br/><div align="center"><img width="420" alt="真实终端" src="https://github.com/user-attachments/assets/0dad6ad3-ff3f-4b5a-86d2-f832ce65323e" /></div> | **🌿 文件变动:Git 视角 + 本轮文件**<br/><sub>双视角合一:**Git 视角**保留完整源代码管理(暂存 / 取消暂存 / 提交(`Ctrl+Enter`)/ 还原、历史、worktree 与子仓库选择);**本轮文件视角**实时折叠会话事件日志,记录模型读 / 写 / 编辑的每个文件(按文件分组、按类型筛选、操作数角标)。点击任意改动在底部**可拖拽预览面板**查看统一 diff——删红 / 增绿 / 改蓝配对 + 行内字符级高亮 + 语法着色 + 上下文折叠——也可一键展开为 VSCode 式独立 diff tab(同一渲染栈)。两个视角共用 36px 头(宿主 SegmentedControl 切换)、28px 行、单一空态与吸底提交条;**Git 视角按目录层级(树)展示变更**——单子目录链压缩成一行、目录行可折叠并带下级变更数、文件行带状态字母与文件图标;git 状态与文件树共享同一份快照,暂存/提交后文件树着色同步刷新。</sub><br/><div align="center"><img width="420" alt="文件变动" src="https://github.com/user-attachments/assets/e7fc1220-305f-4bca-8583-e77ab4f4fa78" /></div> |
|
||||
| **🌐 外链接管(浏览器视图由 DSH 提供)**<br/><sub>网页 tab 是 DSH 自己的 `ui-sidebar-browser`(多开 / 后退前进刷新 / 地址栏 / 沙箱 iframe),**0.1.7 起只在 desktop profile 挂载**——Web profile 里没有这个 kind。插件保留宿主没有的那一半:**只认领有 tab 类型通过 `urlTarget` 明确声明的链接**(Ctrl/Cmd 点击始终放行),**其余一律放行给宿主**(正文链接的去向由宿主的用户设置 `linkOpening` 决定);按协议分流的三个外链接管设置项已删除,认领成功但目标类型此刻不可用时兜底到 `window.open`。</sub><br/><div align="center"><img width="420" alt="内嵌浏览器" src="https://github.com/user-attachments/assets/9bc6b65a-64fc-4942-a685-76e391e55606" /></div> | **🧩 任务页:子代理拓扑 + 后台任务**<br/><sub>子代理树实时拓扑(运行状态、批量实时预览)+ 后台任务清单(退出码 / 实时输出 / 强制终止);新子代理 / 新任务可自动激活任务页,宽屏同时展开侧边栏,窄屏不强制展开全屏抽屉(可关)。</sub><br/><div align="center"><img width="420" alt="任务页:子代理拓扑" src="https://github.com/user-attachments/assets/dcd8ed2f-59fa-405b-937b-2d250f5034dd" /></div> |
|
||||
|
||||
+2
-2
@@ -48,7 +48,7 @@
|
||||
What this plugin adds on top of DSH's stock sidebar:
|
||||
|
||||
- **✏️ Editable editor**: the host's document preview is **read-only** → the plugin keeps an **editable** CodeMirror editor (save, syntax highlighting, preview toggle); Markdown / HTML also render through the plugin's own pipeline (Mermaid diagrams with safe rendering + click-to-zoom, README-level inline HTML, floating table of contents, sandboxed HTML preview)
|
||||
- **🗂️ Enhanced file tree**: takes over the built-in Files page — lazy-loading tree, **expanded directories watched live and auto-refreshed**, symlink awareness, global filename search, drag-and-drop upload, hover `@file` to drop a reference into the input box; **Ctrl/Cmd multi-select and Shift range-select** (copy or delete a batch), **VS Code-style git status colors + M/A/D/U letters**, **new folder**, **multi-select “Zip and download”** (the host streams a ZIP built with no third-party dependency), and an “Open with” menu that COMBINES DSH’s own open-in-app (the host’s probed OS handlers + file-manager reveal) with the plugin’s own targets (file manager / VS Code / Cursor / Zed / custom editor URL templates, SSH remotes, pin-to-menu)
|
||||
- **🗂️ Enhanced file tree**: takes over the built-in Files page — lazy-loading tree, **expanded directories watched live and auto-refreshed**, symlink awareness, global filename search, drag-and-drop upload, hover `@file` to drop a reference into the input box; **Ctrl/Cmd multi-select and Shift range-select** (copy or delete a batch), **VS Code-style git status colors + M/A/D/U letters**, **new folder / new file** (inline editor; the server refuses illegal names, Windows reserved device names and an existing destination — a same-named file is never truncated), **sorting** (by name / by type, plus a folders-first switch; the default is the host's own order), **multi-select “Zip and download”** (the host streams a ZIP built with no third-party dependency), and an “Open with” menu that COMBINES DSH’s own open-in-app (the host’s probed OS handlers + file-manager reveal) with the plugin’s own targets (file manager / VS Code / Cursor / Zed / custom editor URL templates, SSH remotes, pin-to-menu)
|
||||
- **🌿 Changes** (no Git panel in the stock sidebar): two lenses in one tab — **Git** (diff / history / stage·commit·revert) and **This Session** (every file the model touched) — with a unified diff renderer (intra-line character highlights, syntax coloring, secret redaction); the two lenses now share one 36px header (host SegmentedControl), 28px rows, a single empty state and a sticky commit bar, and the git snapshot is shared with the file tree so staging recolors the tree too
|
||||
- **🧩 Background Tasks** (absent upstream): agent topology preview + background task list (exit codes / live output / force-kill)
|
||||
- **💬 Side Chat** (absent upstream, beta): Codex-style side threads — inheriting the full parent context, running independently, promotable to a top-level session
|
||||
@@ -172,7 +172,7 @@ Update: `git pull && pnpm install && pnpm build` → `node scripts/package-regis
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **🗂️ File Workbench: Explorer**<br/><sub>Two explorer modes: embedded in the file preview / standalone file tree. Lazy-loading directory tree whose **expanded directories the host watches per directory and re-lists on change**, symlinks classified by target kind (directory links expand, dangling links flagged), global filename search, file/folder upload buttons plus drag-drop upload, context menu (open in new tab / open to the side / new folder / Open with — the host’s probed OS handlers PLUS the plugin’s own targets (file manager / VS Code / Cursor / Zed / custom editors, SSH remotes, pin-to-menu) / copy paths / rename / delete), **Ctrl/Cmd multi-select with Shift range-select** (batch copy paths, batch delete, **zip and download**), **git changes colored by status with M/A/D/U letters**, and a hover `@file` button that references a file straight into the composer.</sub><br/><div align="center"><img width="420" alt="File explorer" src="https://github.com/user-attachments/assets/a410bfd2-a8ba-43e6-873e-22417756e94d" /></div> | **📝 Inline Preview: Markdown · HTML**<br/><sub>The Markdown preview renders **Mermaid diagrams** (strict-mode safe rendering + a second sanitize pass; click a diagram for a zoom modal with wheel-zoom and drag-pan), **README-level inline HTML** (badge walls `<div align=center>`, `<details>` blocks nesting markdown, inline tags in table cells — DOMPurify-sanitized, `<script>` stripped, local media rewritten to the session media route) and a floating **table of contents** (appears with ≥3 headings, smooth-scroll jumping, auto-expanding folded blocks); HTML uses the plugin's own **sandboxed preview** with the two escape hatches the host does not have (`htmlViewerNoSandbox` / `htmlViewerDefaultUnsafe`). **Images / PDF / spreadsheets / Office are no longer a plugin capability** — the host's own document preview renders those formats.</sub><br/><div align="center"><img width="420" alt="Markdown + Mermaid preview" src="https://github.com/user-attachments/assets/fe0e5182-55bb-45cc-b98b-a2877c2bdd38" /></div> |
|
||||
| **🗂️ File Workbench: Explorer**<br/><sub>Two explorer modes: embedded in the file preview / standalone file tree. Lazy-loading directory tree whose **expanded directories the host watches per directory and re-lists on change**, symlinks classified by target kind (directory links expand, dangling links flagged), global filename search, file/folder upload buttons plus drag-drop upload, context menu (open in new tab / open to the side / new folder / new file / Open with — the host’s probed OS handlers PLUS the plugin’s own targets (file manager / VS Code / Cursor / Zed / custom editors, SSH remotes, pin-to-menu) / copy paths / rename / delete), **Ctrl/Cmd multi-select with Shift range-select** (batch copy paths, batch delete, **zip and download**), **git changes colored by status with M/A/D/U letters**, a header control to **sort by name / by type with a folders-first switch** (the default is the host's own order), and a hover `@file` button that references a file straight into the composer.</sub><br/><div align="center"><img width="420" alt="File explorer" src="https://github.com/user-attachments/assets/a410bfd2-a8ba-43e6-873e-22417756e94d" /></div> | **📝 Inline Preview: Markdown · HTML**<br/><sub>The Markdown preview renders **Mermaid diagrams** (strict-mode safe rendering + a second sanitize pass; click a diagram for a zoom modal with wheel-zoom and drag-pan), **README-level inline HTML** (badge walls `<div align=center>`, `<details>` blocks nesting markdown, inline tags in table cells — DOMPurify-sanitized, `<script>` stripped, local media rewritten to the session media route) and a floating **table of contents** (appears with ≥3 headings, smooth-scroll jumping, auto-expanding folded blocks); HTML uses the plugin's own **sandboxed preview** with the two escape hatches the host does not have (`htmlViewerNoSandbox` / `htmlViewerDefaultUnsafe`). **Images / PDF / spreadsheets / Office are no longer a plugin capability** — the host's own document preview renders those formats.</sub><br/><div align="center"><img width="420" alt="Markdown + Mermaid preview" src="https://github.com/user-attachments/assets/fe0e5182-55bb-45cc-b98b-a2877c2bdd38" /></div> |
|
||||
| **🖥️ CodeMirror editor**<br/><sub>An **editable** text / code editor (save, syntax highlighting, preview toggle) — the host's own document preview is **read-only**, which is exactly why the plugin keeps its catch-all viewer.</sub><br/><div align="center"><img width="420" alt="CodeMirror editor" src="https://github.com/user-attachments/assets/b44b488e-568c-4ee0-b96c-e9c906598a77" /></div> | **🖼️ Images / PDF / spreadsheets / Office (provided by DSH)**<br/><sub>These read-only formats render in DSH's own `ui-sidebar-documentpreview`: host-side Office→PDF conversion, worker-backed spreadsheet tables, image / PDF zoom viewports, and **per-directory auto-refresh**. The plugin deleted its own image / pdf / download-fallback viewers and no longer claims those extensions.</sub><br/><div align="center"><img width="420" alt="Inline image preview" src="https://github.com/user-attachments/assets/f9a58c30-5b7a-48b5-9e22-37d7e071f593" /></div> |
|
||||
| **💻 Terminal (provided by DSH)**<br/><sub>The right-Sidebar terminal is provided by DSH's own `ui-sidebar-terminal`: shell picker, double-click rename, reconnect, restore after reload, theme and contrast following. The plugin no longer ships xterm + node-pty.<br/><br/>⚠️ **Model-side caveat**: the plugin's own 8 `terminal_*` tools (off by default) were the model's only **cross-call persistent** terminal; the upstream equivalent `@deepseek-ai/dsh-tool-terminal` is not mounted by any shipped bundle, so if you need that capability, add a `tool-terminal` row to your profile's `cordis.patch.yml` yourself.</sub><br/><div align="center"><img width="420" alt="Terminal" src="https://github.com/user-attachments/assets/0dad6ad3-ff3f-4b5a-86d2-f832ce65323e" /></div> | **🌿 Changes: Git lens + This-Session lens**<br/><sub>Two lenses on "what changed?": the **Git lens** keeps the full source-control surface (stage / unstage / commit (`Ctrl+Enter`) / revert, history, worktree and child-repo selectors); the **This Session** lens folds the session event log live, recording every file the model read / wrote / edited (grouped by file, kind-filtered, op-count badge). Both lenses now share one 36px header, 28px rows, a single empty state and a sticky commit bar; the **Git lens lists changes as a directory tree** (single-child chains collapsed into one row, collapsible folders with descendant counts, status letters and file icons on the leaves); the git snapshot is shared with the file tree, so staging recolors the tree as well. Clicking any change previews it in the **draggable bottom pane** with the unified diff — del red / add green / mod-blue pairing + intra-line character highlights + syntax coloring + context folding — or expands into a VSCode-style dedicated diff tab (same rendering stack).</sub><br/><div align="center"><img width="420" alt="Changes" src="https://github.com/user-attachments/assets/e7fc1220-305f-4bca-8583-e77ab4f4fa78" /></div> |
|
||||
| **🌐 External-link takeover (browser view provided by DSH)**<br/><sub>Web tabs are DSH's own `ui-sidebar-browser` (multiple tabs / back-forward-reload / address bar / sandboxed iframe), mounted **only in the desktop profile since 0.1.7** — the Web profile has no such kind. The plugin keeps the half the host does not provide: it takes over **only links a tab type explicitly claims through `urlTarget`** (Ctrl/Cmd-clicks always pass through) and **lets everything else through to the host** (whose `linkOpening` user setting decides where prose links go); the three protocol-routing settings are gone, and a claim whose target type is unavailable at open time falls back to `window.open`.</sub><br/><div align="center"><img width="420" alt="Browser" src="https://github.com/user-attachments/assets/9bc6b65a-64fc-4942-a685-76e391e55606" /></div> | **🧩 Tasks: Agent Topology + Background Jobs**<br/><sub>Live subagent-tree topology (run states, batched live previews) plus the background-jobs list (exit codes / live output / force-kill); new subagents / jobs can auto-activate the Tasks page, expanding the sidebar on wide viewports without forcing narrow full-screen drawers open (configurable).</sub><br/><div align="center"><img width="420" alt="Tasks: subagent topology" src="https://github.com/user-attachments/assets/dcd8ed2f-59fa-405b-937b-2d250f5034dd" /></div> |
|
||||
|
||||
+140
-5
@@ -27,8 +27,9 @@
|
||||
* context menu: file rows offer the caller's open escapes (new tab / to the
|
||||
* side, only when the callbacks exist), the host's "open in app" section and
|
||||
* a download action (the host serves raw bytes, binary-safe); directory rows
|
||||
* offer "upload here" and "new folder" (an inline editor at the top of that
|
||||
* level); every row can copy the relative or absolute path (with a brief
|
||||
* offer "upload here", "new folder" and "new file" (an inline editor at the
|
||||
* top of that level; the two creators are mutually exclusive); every row can
|
||||
* copy the relative or absolute path (with a brief
|
||||
* "copied" label replacing the button after a successful write).
|
||||
*
|
||||
* Rows are memoized components (FileRow / DirRow) fed by stable callbacks and
|
||||
@@ -53,6 +54,7 @@ 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 { DEFAULT_FILE_TREE_SORT, sortEntries, type FileTreeSort } from './file-tree-sort.ts'
|
||||
import { FS_TREES_MAX_PATHS } from '../fs-batch.ts'
|
||||
import { builtinFileIcon, builtinFolderIcon } from './file-icons.tsx'
|
||||
import { IconUploadOutline16, IconVscode16 } from './icons.tsx'
|
||||
@@ -92,6 +94,25 @@ function parentOf(path: string): string {
|
||||
return at <= 0 ? path : path.slice(0, at)
|
||||
}
|
||||
|
||||
/** A direct child path of one tree level (row paths may use either separator;
|
||||
* node:fs accepts the mixed form on Windows, where this runs). */
|
||||
export function joinChild(dir: string, name: string): string {
|
||||
return `${dir.replace(/[\\/]+$/, '')}/${name}`
|
||||
}
|
||||
|
||||
/** Client-side collision guard for the inline new-file editor: the typed name
|
||||
* must not already be taken in the level being edited. The SERVER refuses a
|
||||
* taken destination too — this is the same rule answered from the rows the
|
||||
* user is looking at, so the refusal arrives before a round trip (and on a
|
||||
* level whose listing is stale the server still has the last word).
|
||||
* Case-insensitive: the primary platforms (Windows/macOS) resolve names
|
||||
* that way, and on case-sensitive ones a refusal is merely conservative. */
|
||||
export function nameTaken(entries: readonly { name: string }[] | undefined, name: string): boolean {
|
||||
if (entries === undefined) return false
|
||||
const want = name.toLowerCase()
|
||||
return entries.some((entry) => entry.name.toLowerCase() === want)
|
||||
}
|
||||
|
||||
/** Only OS file drags belong to the upload surface; in-app drags (tab reorder,
|
||||
* split zones) must pass through untouched to the pane's tab-drop handling
|
||||
* (mirror of Sidebar.tsx's panel-host shield gate). */
|
||||
@@ -500,6 +521,12 @@ export function FileTree(props: {
|
||||
* the `openWithPluginTargets` plugin setting and passes it down.
|
||||
*/
|
||||
openWithShowPluginTargets?: boolean
|
||||
/**
|
||||
* The explorer's row order (the header control's choice). Absent → the
|
||||
* server's own order, which {@link DEFAULT_FILE_TREE_SORT} reproduces, so an
|
||||
* older caller renders exactly what it rendered before the control existed.
|
||||
*/
|
||||
sort?: FileTreeSort
|
||||
/**
|
||||
* The sidebar registry service: when present, externally registered file
|
||||
* icons (`registerFileIcon`) outrank the host's file-type artwork on file rows.
|
||||
@@ -516,6 +543,7 @@ export function FileTree(props: {
|
||||
openWithShowPluginTargets, exclude,
|
||||
onPathRenamed, onPathDeleted, refreshTick, onUploadRequest, busy, hidden, visible, service,
|
||||
} = props
|
||||
const sort = props.sort ?? DEFAULT_FILE_TREE_SORT
|
||||
/** The live props for the stable callbacks below (identity churns per render). */
|
||||
const propsRef = useRef(props)
|
||||
propsRef.current = props
|
||||
@@ -551,6 +579,8 @@ export function FileTree(props: {
|
||||
const [renaming, setRenaming] = useState<{ path: string; value: string } | null>(null)
|
||||
/** The inline new-folder editor: the directory it inserts into plus the buffer. */
|
||||
const [newFolder, setNewFolder] = useState<{ dir: string; value: string } | null>(null)
|
||||
/** The inline new-file editor: the directory it inserts into plus the buffer. */
|
||||
const [newFile, setNewFile] = useState<{ dir: string; value: string } | null>(null)
|
||||
/** The delete awaiting the confirmation modal's yes (single row). */
|
||||
const [confirmDelete, setConfirmDelete] = useState<{ path: string; isDir: boolean; name: string } | null>(null)
|
||||
/** The batch delete awaiting the confirmation modal's yes. */
|
||||
@@ -1069,6 +1099,7 @@ export function FileTree(props: {
|
||||
const startNewFolder = (dir: string): void => {
|
||||
const live = propsRef.current
|
||||
if (live.cwd !== undefined && dir !== live.cwd && !expandedSetRef.current.has(dir)) live.onToggle(dir)
|
||||
setNewFile(null)
|
||||
setNewFolder({ dir, value: '' })
|
||||
}
|
||||
|
||||
@@ -1104,6 +1135,57 @@ export function FileTree(props: {
|
||||
setNewFolder(null)
|
||||
}
|
||||
|
||||
// ── New file ───────────────────────────────────────────────────────────
|
||||
const newFileRef = useRef(newFile)
|
||||
newFileRef.current = newFile
|
||||
|
||||
/** Open the inline editor at the TOP of `dir`'s level (expanding it first). */
|
||||
const startNewFile = (dir: string): void => {
|
||||
const live = propsRef.current
|
||||
if (live.cwd !== undefined && dir !== live.cwd && !expandedSetRef.current.has(dir)) live.onToggle(dir)
|
||||
setNewFolder(null)
|
||||
setNewFile({ dir, value: '' })
|
||||
}
|
||||
|
||||
/**
|
||||
* Commit the inline new-file name: Enter, blur, or the editor's own cancel
|
||||
* path. The ref guard makes the commit idempotent — a blur that lands after
|
||||
* Enter must not fire a second create. Creates an EMPTY file through
|
||||
* `fs.createFile` (the server refuses a taken destination without truncating
|
||||
* it); a name the level already lists is refused here first, so the two
|
||||
* obvious mistakes never cost a round trip.
|
||||
*/
|
||||
const commitNewFile = (dir: string, raw: string): void => {
|
||||
if (newFileRef.current === null) return
|
||||
newFileRef.current = null
|
||||
setNewFile(null)
|
||||
const name = raw.trim()
|
||||
const live = propsRef.current
|
||||
if (live.cwd === undefined) return
|
||||
if (!validName(name)) {
|
||||
setActionError(t('newFileInvalid'))
|
||||
return
|
||||
}
|
||||
if (nameTaken(dataRef.current[dir]?.entries, name)) {
|
||||
setActionError(t('newFileExists'))
|
||||
return
|
||||
}
|
||||
api.fsCreateFile({ sessionId: live.sessionId, cwd: live.cwd }, dir, name)
|
||||
.then(() => {
|
||||
setActionError(null)
|
||||
if (dir !== live.cwd && !expandedSetRef.current.has(dir)) live.onToggle(dir)
|
||||
retryDir(dir)
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
setActionError(error instanceof Error ? error.message : String(error))
|
||||
})
|
||||
}
|
||||
|
||||
const cancelNewFile = (): void => {
|
||||
newFileRef.current = null
|
||||
setNewFile(null)
|
||||
}
|
||||
|
||||
// ── Batch delete ───────────────────────────────────────────────────────
|
||||
/**
|
||||
* Delete every selected row, ONE AT A TIME (the host refuses nothing here,
|
||||
@@ -1685,9 +1767,52 @@ export function FileTree(props: {
|
||||
</div>
|
||||
)
|
||||
|
||||
/**
|
||||
* The inline new-file editor at the top of one level: the same interaction
|
||||
* contract as the new-folder editor (Enter commits, Escape cancels, blur
|
||||
* commits, conservatively IME-guarded). The glyph follows the typed name, so
|
||||
* the extension's icon updates while typing (an empty buffer probes with a
|
||||
* neutral carrier name).
|
||||
*/
|
||||
const renderNewFileRow = (dir: string, depth: number): ReactNode => {
|
||||
const typed = newFile?.value.trim() ?? ''
|
||||
const probe = joinChild(dir, typed === '' ? 'untitled' : typed)
|
||||
return (
|
||||
<div className={clsx(css.explorerRow, css.explorerRenaming)} style={{ paddingLeft: depth * 22 + 6 }}>
|
||||
{service !== undefined ? service.fileIcon(probe, 14) : builtinFileIcon(probe, 14)}
|
||||
<input
|
||||
ref={renameInputRef}
|
||||
className={css.explorerRenameInput}
|
||||
value={newFile?.value ?? ''}
|
||||
placeholder={t('newFilePlaceholder')}
|
||||
aria-label={t('newFile')}
|
||||
spellCheck={false}
|
||||
onChange={(event) => {
|
||||
setNewFile(prev => prev === null ? prev : { ...prev, value: event.target.value })
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (isLikelyImeKey(event)) return
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault()
|
||||
commitNewFile(dir, newFile?.value ?? '')
|
||||
} else if (event.key === 'Escape') {
|
||||
event.preventDefault()
|
||||
cancelNewFile()
|
||||
}
|
||||
}}
|
||||
onBlur={() => { commitNewFile(dir, newFile?.value ?? '') }}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const renderLevel = (dir: string, depth: number): ReactNode => {
|
||||
const level = data[dir]
|
||||
const head = newFolder?.dir === dir ? renderNewFolderRow(dir, depth) : null
|
||||
// Only ONE inline creator is open at a time (each start closes the other),
|
||||
// so the two are tested in a fixed order rather than merged.
|
||||
const head = newFolder?.dir === dir
|
||||
? renderNewFolderRow(dir, depth)
|
||||
: newFile?.dir === dir ? renderNewFileRow(dir, depth) : null
|
||||
// Both the not-yet-requested level (`undefined`) and the in-flight marker
|
||||
// `loadLevels` stores (`{}` — no entries, no error yet) draw the loading
|
||||
// row. Without the second half the marker fell into `entries ?? []` and
|
||||
@@ -1716,7 +1841,9 @@ export function FileTree(props: {
|
||||
</>
|
||||
)
|
||||
}
|
||||
const entries = level.entries ?? []
|
||||
// The ORDER is the caller's choice (the header's sort control); the level
|
||||
// cache keeps the host's own order and is never reordered in place.
|
||||
const entries = sortEntries(level.entries ?? [], sort)
|
||||
return (
|
||||
<>
|
||||
{head}
|
||||
@@ -1952,6 +2079,9 @@ export function FileTree(props: {
|
||||
...(rowMenu?.isDir === true
|
||||
? [{ id: 'new-folder', label: t('newFolder'), icon: <IconPlusOutlineRegular size={14} /> }]
|
||||
: []),
|
||||
...(rowMenu?.isDir === true
|
||||
? [{ id: 'new-file', label: t('newFile'), icon: <IconCodeOutlineRegular size={14} /> }]
|
||||
: []),
|
||||
// 5: ZIP of the current selection (≥2 rows, or one lone directory).
|
||||
...(rowMenu === null ? [] : zipEntries(rowMenu)),
|
||||
// 6: copy, then the mutations (never on the workspace root row).
|
||||
@@ -2011,7 +2141,12 @@ export function FileTree(props: {
|
||||
if (id === 'new-folder') {
|
||||
startNewFolder(target.path)
|
||||
return
|
||||
} if (id === 'rename') {
|
||||
}
|
||||
if (id === 'new-file') {
|
||||
startNewFile(target.path)
|
||||
return
|
||||
}
|
||||
if (id === 'rename') {
|
||||
setRenaming({ path: target.path, value: baseName(target.path) })
|
||||
return
|
||||
}
|
||||
|
||||
@@ -6,9 +6,10 @@
|
||||
* search is free — the tree keeps its level cache and the live directory
|
||||
* watcher (the old conditional render dropped both and refetched the whole
|
||||
* visible set on every query change). Owns its refresh tick: the icon next to
|
||||
* the search input clears the tree cache. EditorHost docks it as the tab's
|
||||
* right panel (wrapped in a drag-resize handle) and provides the file
|
||||
* context-menu open escapes.
|
||||
* the search input clears the tree cache, and the sort menu beside it owns the
|
||||
* tree's row order (passed down; the default is the host's own order).
|
||||
* EditorHost docks it as the tab's right panel (wrapped in a drag-resize
|
||||
* handle) and provides the file context-menu open escapes.
|
||||
*
|
||||
* Uploads (header pickers, the tree's drag-drop and "upload here" menu)
|
||||
* all funnel through here: one session at a time, shown in a full-window
|
||||
@@ -20,11 +21,12 @@
|
||||
*/
|
||||
import { useEffect, useRef, useState, type InputHTMLAttributes } from 'react'
|
||||
import clsx from 'clsx'
|
||||
import { IconFolderOpenRegular, IconRefreshOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import { IconChevronsUpDownOutlineRegular, IconFolderOpenRegular, IconRefreshOutlineRegular, Menu } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import { api } from './api.ts'
|
||||
import type { BetterSidebarService } from './service.ts'
|
||||
import { ancestorDirs } from './state.ts'
|
||||
import { FileTree } from './FileTree.tsx'
|
||||
import { DEFAULT_FILE_TREE_SORT, type FileTreeSort } from './file-tree-sort.ts'
|
||||
import { IconUploadOutline16 } from './icons.tsx'
|
||||
import type { OpenInApp } from './open-in-app.ts'
|
||||
import type { OpenWithTarget } from './open-with.ts'
|
||||
@@ -101,6 +103,13 @@ export function TreePanel(props: {
|
||||
const [results, setResults] = useState<{ matches: string[]; dirs: string[]; truncated: boolean } | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [refreshTick, setRefreshTick] = useState(0)
|
||||
/**
|
||||
* The explorer's row order (the header's sort control). Starts at the
|
||||
* default — name order, folders first — which is the order the host already
|
||||
* returns, so the tree looks exactly as it did before the control existed.
|
||||
*/
|
||||
const [sort, setSort] = useState<FileTreeSort>(DEFAULT_FILE_TREE_SORT)
|
||||
const [sortOpen, setSortOpen] = useState(false)
|
||||
|
||||
// The tree caches loaded directories per refresh tick, so content changed
|
||||
// outside DSH (another editor, a sync tool) stays stale until the manual
|
||||
@@ -244,6 +253,41 @@ export function TreePanel(props: {
|
||||
icon={<IconRefreshOutlineRegular size={14} />}
|
||||
onClick={() => { setRefreshTick(tick => tick + 1) }}
|
||||
/>
|
||||
{/* Row order: the two keys are one choice (check mark), the
|
||||
folders-first switch is independent — the same two-group menu the
|
||||
host's own menus use. Picking a row closes the menu like every
|
||||
other menu in the plugin. */}
|
||||
<Menu
|
||||
open={sortOpen}
|
||||
onClose={() => { setSortOpen(false) }}
|
||||
onSelect={(id) => {
|
||||
setSort((current) => {
|
||||
if (id === 'sort-name') return { ...current, key: 'name' }
|
||||
if (id === 'sort-type') return { ...current, key: 'type' }
|
||||
return { ...current, dirsFirst: !current.dirsFirst }
|
||||
})
|
||||
setSortOpen(false)
|
||||
}}
|
||||
items={[
|
||||
{ id: 'sort-name', label: t('sortByName'), icon: <IconChevronsUpDownOutlineRegular size={14} /> },
|
||||
{ id: 'sort-type', label: t('sortByType'), icon: <IconChevronsUpDownOutlineRegular size={14} /> },
|
||||
{ type: 'separator', id: 'sort-sep' },
|
||||
{ id: 'sort-folders-first', label: t('sortFoldersFirst') },
|
||||
]}
|
||||
selectedIds={[
|
||||
sort.key === 'name' ? 'sort-name' : 'sort-type',
|
||||
...(sort.dirsFirst ? ['sort-folders-first'] : []),
|
||||
]}
|
||||
align="end"
|
||||
compact
|
||||
anchor={(
|
||||
<IconButton
|
||||
label={t('sort')}
|
||||
icon={<IconChevronsUpDownOutlineRegular size={14} />}
|
||||
onClick={() => { setSortOpen(open => !open) }}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<IconButton
|
||||
label={t('uploadFiles')}
|
||||
icon={<IconUploadOutline16 size={14} />}
|
||||
@@ -347,6 +391,7 @@ export function TreePanel(props: {
|
||||
busy={busy}
|
||||
hidden={searching}
|
||||
visible={visible !== false}
|
||||
sort={sort}
|
||||
service={service}
|
||||
/>
|
||||
{upload !== null && (
|
||||
|
||||
@@ -391,6 +391,11 @@ export const api = {
|
||||
* is armed — anything resolving outside the workspace). */
|
||||
fsMkdir: (scope: SessionScope, path: string, name: string) =>
|
||||
call<{ path: string }>('fs.mkdir', scopePayload(scope, { path, name })),
|
||||
/** Create one EMPTY file row inside `path` (single-segment name; the server
|
||||
* refuses existing destinations — without truncating them — plus the
|
||||
* characters and Windows device names a file name may not use). */
|
||||
fsCreateFile: (scope: SessionScope, path: string, name: string) =>
|
||||
call<{ path: string }>('fs.createFile', scopePayload(scope, { path, name })),
|
||||
/** Upload one file's raw bytes into `dir` (keeps the folder tree via
|
||||
* `relativePath`); the host streams it under the session workspace. */
|
||||
uploadFile: (scope: SessionScope, dir: string, relativePath: string, body: Blob, signal?: AbortSignal) =>
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* Explorer row ordering: the client-side sort behind the tree header's sort
|
||||
* control.
|
||||
*
|
||||
* The host already returns every level directory-first, case-insensitively by
|
||||
* name (`fs-tree.ts`'s `compareEntries`), and {@link DEFAULT_FILE_TREE_SORT}
|
||||
* reproduces exactly that order — so the control's out-of-the-box state is
|
||||
* indistinguishable from having no control at all. "Type" groups by extension
|
||||
* (the part after the last dot, lowercased), the way VS Code's "Sort by Type"
|
||||
* does; a directory has no extension, so with "folders first" off it lands
|
||||
* with the extension-less files and both fall back to the name order.
|
||||
*
|
||||
* Sorting runs on a COPY: the level cache is shared per absolute path (two
|
||||
* sessions reading one directory share an entry), so a cached listing must
|
||||
* never be reordered in place.
|
||||
*/
|
||||
|
||||
/** The two orderings the control offers ("by modified time" is a separate issue). */
|
||||
export type FileTreeSortKey = 'name' | 'type'
|
||||
|
||||
/** One explorer sort choice: the key plus the folders-first switch. */
|
||||
export interface FileTreeSort {
|
||||
key: FileTreeSortKey
|
||||
/** Directories before files, whatever the key says. */
|
||||
dirsFirst: boolean
|
||||
}
|
||||
|
||||
/** The default choice — byte-for-byte the order the host listing arrives in. */
|
||||
export const DEFAULT_FILE_TREE_SORT: FileTreeSort = { key: 'name', dirsFirst: true }
|
||||
|
||||
/**
|
||||
* The extension shown as a row's "type": the text after the LAST dot,
|
||||
* lowercased, `''` for a directory or a dot-less name (a leading dot is a
|
||||
* hidden file's marker, not an extension, so `.gitignore` has none).
|
||||
*/
|
||||
export function typeOf(name: string, isDir: boolean): string {
|
||||
if (isDir) return ''
|
||||
const at = name.lastIndexOf('.')
|
||||
return at <= 0 ? '' : name.slice(at + 1).toLowerCase()
|
||||
}
|
||||
|
||||
/**
|
||||
* Case-insensitive name order with the host's deterministic tie-break: names
|
||||
* that only differ in case keep their original code-point order (`A` before
|
||||
* `a`), so the order is total and stable.
|
||||
*/
|
||||
function compareName(a: { name: string }, b: { name: string }): number {
|
||||
const la = a.name.toLowerCase()
|
||||
const lb = b.name.toLowerCase()
|
||||
if (la !== lb) return la < lb ? -1 : 1
|
||||
if (a.name === b.name) return 0
|
||||
return a.name < b.name ? -1 : 1
|
||||
}
|
||||
|
||||
/**
|
||||
* Order one level's rows for display. The input is never mutated (the level
|
||||
* cache is shared), and with {@link DEFAULT_FILE_TREE_SORT} the result equals
|
||||
* `fs-tree.ts`'s server order for every input.
|
||||
*
|
||||
* @param entries - the level's rows, in host order.
|
||||
* @param sort - the caller's choice (key + folders-first switch).
|
||||
* @returns a new array; the rows themselves are the same objects.
|
||||
*/
|
||||
export function sortEntries<T extends { name: string; isDir: boolean }>(
|
||||
entries: readonly T[],
|
||||
sort: FileTreeSort,
|
||||
): T[] {
|
||||
return [...entries].sort((a, b) => {
|
||||
if (sort.dirsFirst && a.isDir !== b.isDir) return a.isDir ? -1 : 1
|
||||
if (sort.key === 'type') {
|
||||
const ta = typeOf(a.name, a.isDir)
|
||||
const tb = typeOf(b.name, b.isDir)
|
||||
if (ta !== tb) return ta < tb ? -1 : 1
|
||||
}
|
||||
return compareName(a, b)
|
||||
})
|
||||
}
|
||||
@@ -102,6 +102,14 @@ export const ar: Record<string, string> = {
|
||||
newFolder: 'مجلد جديد',
|
||||
newFolderPlaceholder: 'اسم المجلد',
|
||||
newFolderInvalid: 'اسم المجلد غير صالح',
|
||||
newFile: 'ملف جديد',
|
||||
newFilePlaceholder: 'اسم الملف',
|
||||
newFileInvalid: 'اسم الملف غير صالح',
|
||||
newFileExists: 'يوجد ملف بهذا الاسم بالفعل',
|
||||
sort: 'فرز',
|
||||
sortByName: 'الفرز حسب الاسم',
|
||||
sortByType: 'الفرز حسب النوع',
|
||||
sortFoldersFirst: 'المجلدات أولاً',
|
||||
filesTruncated: 'يحتوي هذا المجلد على عناصر كثيرة جداً؛ تُعرض العناصر الأولى فقط',
|
||||
gitStatusModified: 'معدّل',
|
||||
gitStatusAdded: 'مضاف',
|
||||
|
||||
@@ -87,6 +87,14 @@ export const de: Record<string, string> = {
|
||||
newFolder: 'Neuer Ordner',
|
||||
newFolderPlaceholder: 'Ordnername',
|
||||
newFolderInvalid: 'Ungültiger Ordnername',
|
||||
newFile: 'Neue Datei',
|
||||
newFilePlaceholder: 'Dateiname',
|
||||
newFileInvalid: 'Ungültiger Dateiname',
|
||||
newFileExists: 'Eine Datei mit diesem Namen existiert bereits',
|
||||
sort: 'Sortieren',
|
||||
sortByName: 'Nach Name sortieren',
|
||||
sortByType: 'Nach Typ sortieren',
|
||||
sortFoldersFirst: 'Ordner zuerst',
|
||||
filesTruncated: 'Dieser Ordner enthält zu viele Einträge; nur die ersten werden angezeigt',
|
||||
gitStatusModified: 'Geändert',
|
||||
gitStatusAdded: 'Hinzugefügt',
|
||||
|
||||
@@ -94,6 +94,14 @@ export const fr: Record<string, string> = {
|
||||
newFolder: 'Nouveau dossier',
|
||||
newFolderPlaceholder: 'Nom du dossier',
|
||||
newFolderInvalid: 'Nom de dossier invalide',
|
||||
newFile: 'Nouveau fichier',
|
||||
newFilePlaceholder: 'Nom du fichier',
|
||||
newFileInvalid: 'Nom de fichier invalide',
|
||||
newFileExists: 'Un fichier portant ce nom existe déjà',
|
||||
sort: 'Trier',
|
||||
sortByName: 'Trier par nom',
|
||||
sortByType: 'Trier par type',
|
||||
sortFoldersFirst: 'Dossiers en premier',
|
||||
filesTruncated: 'Ce dossier contient trop d’éléments ; seuls les premiers sont affichés',
|
||||
gitStatusModified: 'Modifié',
|
||||
gitStatusAdded: 'Ajouté',
|
||||
|
||||
@@ -101,6 +101,14 @@ export const hi: Record<string, string> = {
|
||||
newFolder: 'नया फ़ोल्डर',
|
||||
newFolderPlaceholder: 'फ़ोल्डर नाम',
|
||||
newFolderInvalid: 'फ़ोल्डर नाम अमान्य है',
|
||||
newFile: 'नई फ़ाइल',
|
||||
newFilePlaceholder: 'फ़ाइल नाम',
|
||||
newFileInvalid: 'फ़ाइल नाम अमान्य है',
|
||||
newFileExists: 'इस नाम की फ़ाइल पहले से मौजूद है',
|
||||
sort: 'क्रमबद्ध करें',
|
||||
sortByName: 'नाम से क्रमबद्ध करें',
|
||||
sortByType: 'प्रकार से क्रमबद्ध करें',
|
||||
sortFoldersFirst: 'फ़ोल्डर पहले',
|
||||
filesTruncated: 'इस फ़ोल्डर में बहुत अधिक प्रविष्टियाँ हैं; केवल शुरुआती कुछ दिखाई जा रही हैं',
|
||||
gitStatusModified: 'संशोधित',
|
||||
gitStatusAdded: 'जोड़ा गया',
|
||||
|
||||
@@ -99,6 +99,14 @@ export const id: Record<string, string> = {
|
||||
newFolder: 'Folder baru',
|
||||
newFolderPlaceholder: 'Nama folder',
|
||||
newFolderInvalid: 'Nama folder tidak valid',
|
||||
newFile: 'File baru',
|
||||
newFilePlaceholder: 'Nama file',
|
||||
newFileInvalid: 'Nama file tidak valid',
|
||||
newFileExists: 'File dengan nama ini sudah ada',
|
||||
sort: 'Urutkan',
|
||||
sortByName: 'Urutkan menurut nama',
|
||||
sortByType: 'Urutkan menurut jenis',
|
||||
sortFoldersFirst: 'Folder lebih dulu',
|
||||
filesTruncated: 'Folder ini berisi terlalu banyak entri; hanya sebagian awal yang ditampilkan',
|
||||
gitStatusModified: 'Dimodifikasi',
|
||||
gitStatusAdded: 'Ditambahkan',
|
||||
|
||||
@@ -92,6 +92,14 @@ export const it: Record<string, string> = {
|
||||
newFolder: 'Nuova cartella',
|
||||
newFolderPlaceholder: 'Nome cartella',
|
||||
newFolderInvalid: 'Nome cartella non valido',
|
||||
newFile: 'Nuovo file',
|
||||
newFilePlaceholder: 'Nome file',
|
||||
newFileInvalid: 'Nome file non valido',
|
||||
newFileExists: 'Esiste già un file con questo nome',
|
||||
sort: 'Ordina',
|
||||
sortByName: 'Ordina per nome',
|
||||
sortByType: 'Ordina per tipo',
|
||||
sortFoldersFirst: 'Cartelle per prime',
|
||||
filesTruncated: 'Questa cartella contiene troppe voci; vengono mostrate solo le prime',
|
||||
gitStatusModified: 'Modificato',
|
||||
gitStatusAdded: 'Aggiunto',
|
||||
|
||||
@@ -101,6 +101,14 @@ export const ja: Record<string, string> = {
|
||||
newFolder: '新しいフォルダー',
|
||||
newFolderPlaceholder: 'フォルダー名',
|
||||
newFolderInvalid: 'フォルダー名が無効です',
|
||||
newFile: '新しいファイル',
|
||||
newFilePlaceholder: 'ファイル名',
|
||||
newFileInvalid: 'ファイル名が無効です',
|
||||
newFileExists: '同じ名前のファイルが既に存在します',
|
||||
sort: '並べ替え',
|
||||
sortByName: '名前で並べ替え',
|
||||
sortByType: '種類で並べ替え',
|
||||
sortFoldersFirst: 'フォルダーを先に表示',
|
||||
filesTruncated: 'このフォルダーの項目が多すぎるため、先頭の一部のみ表示しています',
|
||||
gitStatusModified: '変更あり',
|
||||
gitStatusAdded: '追加',
|
||||
|
||||
@@ -93,6 +93,14 @@ export const ko: Record<string, string> = {
|
||||
newFolder: '새 폴더',
|
||||
newFolderPlaceholder: '폴더 이름',
|
||||
newFolderInvalid: '폴더 이름이 올바르지 않습니다',
|
||||
newFile: '새 파일',
|
||||
newFilePlaceholder: '파일 이름',
|
||||
newFileInvalid: '파일 이름이 올바르지 않습니다',
|
||||
newFileExists: '같은 이름의 파일이 이미 있습니다',
|
||||
sort: '정렬',
|
||||
sortByName: '이름순 정렬',
|
||||
sortByType: '종류순 정렬',
|
||||
sortFoldersFirst: '폴더 먼저',
|
||||
filesTruncated: '이 폴더에 항목이 너무 많아 앞부분만 표시합니다',
|
||||
gitStatusModified: '수정됨',
|
||||
gitStatusAdded: '추가됨',
|
||||
|
||||
@@ -99,6 +99,14 @@ export const nl: Record<string, string> = {
|
||||
newFolder: 'Nieuwe map',
|
||||
newFolderPlaceholder: 'Mapnaam',
|
||||
newFolderInvalid: 'Ongeldige mapnaam',
|
||||
newFile: 'Nieuw bestand',
|
||||
newFilePlaceholder: 'Bestandsnaam',
|
||||
newFileInvalid: 'Ongeldige bestandsnaam',
|
||||
newFileExists: 'Er bestaat al een bestand met deze naam',
|
||||
sort: 'Sorteren',
|
||||
sortByName: 'Sorteren op naam',
|
||||
sortByType: 'Sorteren op type',
|
||||
sortFoldersFirst: 'Mappen eerst',
|
||||
filesTruncated: 'Deze map bevat te veel items; alleen de eerste worden getoond',
|
||||
gitStatusModified: 'Gewijzigd',
|
||||
gitStatusAdded: 'Toegevoegd',
|
||||
|
||||
@@ -103,6 +103,14 @@ export const pl: Record<string, string> = {
|
||||
newFolder: 'Nowy folder',
|
||||
newFolderPlaceholder: 'Nazwa folderu',
|
||||
newFolderInvalid: 'Nieprawidłowa nazwa folderu',
|
||||
newFile: 'Nowy plik',
|
||||
newFilePlaceholder: 'Nazwa pliku',
|
||||
newFileInvalid: 'Nieprawidłowa nazwa pliku',
|
||||
newFileExists: 'Plik o tej nazwie już istnieje',
|
||||
sort: 'Sortuj',
|
||||
sortByName: 'Sortuj według nazwy',
|
||||
sortByType: 'Sortuj według typu',
|
||||
sortFoldersFirst: 'Najpierw foldery',
|
||||
filesTruncated: 'Ten folder zawiera zbyt wiele pozycji; wyświetlane są tylko pierwsze',
|
||||
gitStatusModified: 'Zmodyfikowany',
|
||||
gitStatusAdded: 'Dodany',
|
||||
|
||||
@@ -84,6 +84,14 @@ export const pt: Record<string, string> = {
|
||||
newFolder: 'Nova pasta',
|
||||
newFolderPlaceholder: 'Nome da pasta',
|
||||
newFolderInvalid: 'Nome de pasta inválido',
|
||||
newFile: 'Novo arquivo',
|
||||
newFilePlaceholder: 'Nome do arquivo',
|
||||
newFileInvalid: 'Nome de arquivo inválido',
|
||||
newFileExists: 'Já existe um arquivo com este nome',
|
||||
sort: 'Ordenar',
|
||||
sortByName: 'Ordenar por nome',
|
||||
sortByType: 'Ordenar por tipo',
|
||||
sortFoldersFirst: 'Pastas primeiro',
|
||||
filesTruncated: 'Esta pasta tem entradas demais; apenas as primeiras são exibidas',
|
||||
gitStatusModified: 'Modificado',
|
||||
gitStatusAdded: 'Adicionado',
|
||||
|
||||
@@ -97,6 +97,14 @@ export const ru: Record<string, string> = {
|
||||
newFolder: 'Новая папка',
|
||||
newFolderPlaceholder: 'Имя папки',
|
||||
newFolderInvalid: 'Недопустимое имя папки',
|
||||
newFile: 'Новый файл',
|
||||
newFilePlaceholder: 'Имя файла',
|
||||
newFileInvalid: 'Недопустимое имя файла',
|
||||
newFileExists: 'Файл с таким именем уже существует',
|
||||
sort: 'Сортировка',
|
||||
sortByName: 'Сортировать по имени',
|
||||
sortByType: 'Сортировать по типу',
|
||||
sortFoldersFirst: 'Сначала папки',
|
||||
filesTruncated: 'В этой папке слишком много элементов; показаны только первые',
|
||||
gitStatusModified: 'Изменён',
|
||||
gitStatusAdded: 'Добавлен',
|
||||
|
||||
@@ -84,6 +84,14 @@ export const sv: Record<string, string> = {
|
||||
newFolder: 'Ny mapp',
|
||||
newFolderPlaceholder: 'Mappnamn',
|
||||
newFolderInvalid: 'Ogiltigt mappnamn',
|
||||
newFile: 'Ny fil',
|
||||
newFilePlaceholder: 'Filnamn',
|
||||
newFileInvalid: 'Ogiltigt filnamn',
|
||||
newFileExists: 'En fil med det här namnet finns redan',
|
||||
sort: 'Sortera',
|
||||
sortByName: 'Sortera efter namn',
|
||||
sortByType: 'Sortera efter typ',
|
||||
sortFoldersFirst: 'Mappar först',
|
||||
filesTruncated: 'Mappen har för många poster; bara de första visas',
|
||||
gitStatusModified: 'Ändrad',
|
||||
gitStatusAdded: 'Tillagd',
|
||||
|
||||
@@ -101,6 +101,14 @@ export const th: Record<string, string> = {
|
||||
newFolder: 'โฟลเดอร์ใหม่',
|
||||
newFolderPlaceholder: 'ชื่อโฟลเดอร์',
|
||||
newFolderInvalid: 'ชื่อโฟลเดอร์ไม่ถูกต้อง',
|
||||
newFile: 'ไฟล์ใหม่',
|
||||
newFilePlaceholder: 'ชื่อไฟล์',
|
||||
newFileInvalid: 'ชื่อไฟล์ไม่ถูกต้อง',
|
||||
newFileExists: 'มีไฟล์ชื่อนี้อยู่แล้ว',
|
||||
sort: 'เรียงลำดับ',
|
||||
sortByName: 'เรียงตามชื่อ',
|
||||
sortByType: 'เรียงตามชนิด',
|
||||
sortFoldersFirst: 'โฟลเดอร์ก่อน',
|
||||
filesTruncated: 'โฟลเดอร์นี้มีรายการมากเกินไป จึงแสดงเฉพาะส่วนแรก',
|
||||
gitStatusModified: 'แก้ไขแล้ว',
|
||||
gitStatusAdded: 'เพิ่มแล้ว',
|
||||
|
||||
@@ -101,6 +101,14 @@ export const tr: Record<string, string> = {
|
||||
newFolder: 'Yeni klasör',
|
||||
newFolderPlaceholder: 'Klasör adı',
|
||||
newFolderInvalid: 'Klasör adı geçersiz',
|
||||
newFile: 'Yeni dosya',
|
||||
newFilePlaceholder: 'Dosya adı',
|
||||
newFileInvalid: 'Dosya adı geçersiz',
|
||||
newFileExists: 'Bu adda bir dosya zaten var',
|
||||
sort: 'Sırala',
|
||||
sortByName: 'Ada göre sırala',
|
||||
sortByType: 'Türe göre sırala',
|
||||
sortFoldersFirst: 'Önce klasörler',
|
||||
filesTruncated: 'Bu klasörde çok fazla öğe var; yalnızca ilk kısmı gösteriliyor',
|
||||
gitStatusModified: 'Değiştirildi',
|
||||
gitStatusAdded: 'Eklendi',
|
||||
|
||||
@@ -101,6 +101,14 @@ export const vi: Record<string, string> = {
|
||||
newFolder: 'Thư mục mới',
|
||||
newFolderPlaceholder: 'Tên thư mục',
|
||||
newFolderInvalid: 'Tên thư mục không hợp lệ',
|
||||
newFile: 'Tệp mới',
|
||||
newFilePlaceholder: 'Tên tệp',
|
||||
newFileInvalid: 'Tên tệp không hợp lệ',
|
||||
newFileExists: 'Đã tồn tại tệp có tên này',
|
||||
sort: 'Sắp xếp',
|
||||
sortByName: 'Sắp xếp theo tên',
|
||||
sortByType: 'Sắp xếp theo loại',
|
||||
sortFoldersFirst: 'Thư mục trước',
|
||||
filesTruncated: 'Thư mục này có quá nhiều mục; chỉ hiển thị phần đầu',
|
||||
gitStatusModified: 'Đã sửa',
|
||||
gitStatusAdded: 'Đã thêm',
|
||||
|
||||
@@ -116,6 +116,14 @@ export const zhHK: Record<string, string> = {
|
||||
newFolder: '新增資料夾',
|
||||
newFolderPlaceholder: '資料夾名稱',
|
||||
newFolderInvalid: '資料夾名稱無效',
|
||||
newFile: '新增檔案',
|
||||
newFilePlaceholder: '檔案名稱',
|
||||
newFileInvalid: '檔案名稱無效',
|
||||
newFileExists: '同名檔案已存在',
|
||||
sort: '排序',
|
||||
sortByName: '按名稱排序',
|
||||
sortByType: '按類型排序',
|
||||
sortFoldersFirst: '資料夾優先',
|
||||
filesTruncated: '此目錄項目過多,僅顯示前一部分',
|
||||
gitStatusModified: '已修改',
|
||||
gitStatusAdded: '新增',
|
||||
|
||||
@@ -116,6 +116,14 @@ export const zhMO: Record<string, string> = {
|
||||
newFolder: '新增資料夾',
|
||||
newFolderPlaceholder: '資料夾名稱',
|
||||
newFolderInvalid: '資料夾名稱無效',
|
||||
newFile: '新增檔案',
|
||||
newFilePlaceholder: '檔案名稱',
|
||||
newFileInvalid: '檔案名稱無效',
|
||||
newFileExists: '同名檔案已存在',
|
||||
sort: '排序',
|
||||
sortByName: '按名稱排序',
|
||||
sortByType: '按類型排序',
|
||||
sortFoldersFirst: '資料夾優先',
|
||||
filesTruncated: '此目錄項目過多,僅顯示前一部分',
|
||||
gitStatusModified: '已修改',
|
||||
gitStatusAdded: '新增',
|
||||
|
||||
@@ -116,6 +116,14 @@ export const zhTW: Record<string, string> = {
|
||||
newFolder: '新增資料夾',
|
||||
newFolderPlaceholder: '資料夾名稱',
|
||||
newFolderInvalid: '資料夾名稱無效',
|
||||
newFile: '新增檔案',
|
||||
newFilePlaceholder: '檔案名稱',
|
||||
newFileInvalid: '檔案名稱無效',
|
||||
newFileExists: '同名檔案已存在',
|
||||
sort: '排序',
|
||||
sortByName: '按名稱排序',
|
||||
sortByType: '按類型排序',
|
||||
sortFoldersFirst: '資料夾優先',
|
||||
filesTruncated: '此目錄項目過多,僅顯示前一部分',
|
||||
gitStatusModified: '已修改',
|
||||
gitStatusAdded: '新增',
|
||||
|
||||
@@ -113,6 +113,14 @@ export const zh = {
|
||||
newFolder: '新建文件夹',
|
||||
newFolderPlaceholder: '文件夹名称',
|
||||
newFolderInvalid: '文件夹名称无效',
|
||||
newFile: '新建文件',
|
||||
newFilePlaceholder: '文件名称',
|
||||
newFileInvalid: '文件名称无效',
|
||||
newFileExists: '同名文件已存在',
|
||||
sort: '排序',
|
||||
sortByName: '按名称排序',
|
||||
sortByType: '按类型排序',
|
||||
sortFoldersFirst: '文件夹优先',
|
||||
filesTruncated: '该目录条目过多,仅显示前一部分',
|
||||
gitStatusModified: '已修改',
|
||||
gitStatusAdded: '新增',
|
||||
@@ -684,6 +692,14 @@ export const en: Record<keyof typeof zh, string> = {
|
||||
newFolder: 'New folder',
|
||||
newFolderPlaceholder: 'Folder name',
|
||||
newFolderInvalid: 'Invalid folder name',
|
||||
newFile: 'New file',
|
||||
newFilePlaceholder: 'File name',
|
||||
newFileInvalid: 'Invalid file name',
|
||||
newFileExists: 'A file with this name already exists',
|
||||
sort: 'Sort',
|
||||
sortByName: 'Sort by name',
|
||||
sortByType: 'Sort by type',
|
||||
sortFoldersFirst: 'Folders first',
|
||||
filesTruncated: 'This folder has too many entries; only the first ones are shown',
|
||||
gitStatusModified: 'Modified',
|
||||
gitStatusAdded: 'Added',
|
||||
|
||||
+109
-6
@@ -6,11 +6,13 @@
|
||||
* user's request, so these operations reach whatever the HOST USER can reach.
|
||||
* What is still enforced is the SHAPE of a request: the relative upload path
|
||||
* is sanitized (absolute paths, '.', '..' and empty segments are refused), a
|
||||
* rename/mkdir name must be one path segment, an existing destination is
|
||||
* refused instead of clobbered, and the session workspace root itself is never
|
||||
* renamable or removable. Bytes stream from the request body to a uniquely
|
||||
* named temp sibling and are renamed into place, so a failed, aborted, or
|
||||
* oversized upload never leaves a partial file at the target path.
|
||||
* rename/mkdir name must be one path segment, a new FILE's name is additionally
|
||||
* checked against the characters and device names Windows cannot store, an
|
||||
* existing destination is refused instead of clobbered, and the session
|
||||
* workspace root itself is never renamable or removable. Bytes stream from the
|
||||
* request body to a uniquely named temp sibling and are renamed into place, so
|
||||
* a failed, aborted, or oversized upload never leaves a partial file at the
|
||||
* target path.
|
||||
*
|
||||
* The tree's rename/delete are link-aware: they address the LEXICAL row path
|
||||
* (lstat decides), so renaming or deleting a symlink row renames/unlinks the
|
||||
@@ -21,7 +23,7 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { once } from 'node:events'
|
||||
import { createWriteStream } from 'node:fs'
|
||||
import { access, lstat, mkdir, rename, rm, stat, unlink } from 'node:fs/promises'
|
||||
import { access, lstat, mkdir, rename, rm, stat, unlink, writeFile } from 'node:fs/promises'
|
||||
import { basename, dirname, join } from 'node:path'
|
||||
import { invalidateDirectoryCache, requireAbsolute } from './fs-tree.ts'
|
||||
import { ensureWorkspaceWritePath, resolveTarget } from './path-security.ts'
|
||||
@@ -223,6 +225,107 @@ export async function mkdirWorkspaceEntry(input: WorkspaceMkdirInput): Promise<{
|
||||
return { path: destination }
|
||||
}
|
||||
|
||||
/**
|
||||
* Characters Windows refuses in a file NAME (control characters — U+0000 to
|
||||
* U+001F — are refused beside these, see {@link firstIllegalNameChar}).
|
||||
* Checked on every platform: a tree row the plugin happily creates on macOS
|
||||
* must not become un-openable (or un-checkout-able) on the Windows host the
|
||||
* same workspace is later opened on.
|
||||
*/
|
||||
const ILLEGAL_FILE_NAME_CHARS = /[<>:"|?*]/
|
||||
|
||||
/**
|
||||
* The first character of one file name that Windows cannot store, or undefined
|
||||
* when the name is storable there. Iterating the string (not indexing it) keeps
|
||||
* astral characters whole, so a valid emoji name is never mistaken for two
|
||||
* illegal halves.
|
||||
*/
|
||||
function firstIllegalNameChar(name: string): string | undefined {
|
||||
for (const char of name) {
|
||||
if (ILLEGAL_FILE_NAME_CHARS.test(char) || (char.codePointAt(0) ?? 0) < 0x20) return char
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Windows device names, reserved in EVERY directory with or without an
|
||||
* extension (`NUL.txt` and `NUL.tar.gz` both name the device, so the check is
|
||||
* on the segment before the FIRST dot).
|
||||
*/
|
||||
const RESERVED_FILE_NAMES = new Set([
|
||||
'con', 'prn', 'aux', 'nul',
|
||||
...Array.from({ length: 9 }, (_, index) => `com${index + 1}`),
|
||||
...Array.from({ length: 9 }, (_, index) => `lpt${index + 1}`),
|
||||
])
|
||||
|
||||
/**
|
||||
* The NEW FILE name rule: one path segment (the shared rename/mkdir rule) plus
|
||||
* the two Windows-only refusals — illegal characters and reserved device
|
||||
* names. Refusing them HERE, as a shape error, is what lets the inline editor
|
||||
* say which rule was broken instead of surfacing a bare `EPERM` from the
|
||||
* filesystem on one platform and nothing at all on the others.
|
||||
*
|
||||
* @throws SidebarError with a wire code of `bad-request` for every refusal.
|
||||
*/
|
||||
function assertCreatableFileName(name: string): void {
|
||||
if (name === '' || name === '.' || name === '..' || name.includes('/') || name.includes('\\')) {
|
||||
throw new SidebarError('bad-request', 'name must be a single path segment', 400)
|
||||
}
|
||||
const illegal = firstIllegalNameChar(name)
|
||||
if (illegal !== undefined) {
|
||||
throw new SidebarError('bad-request', `name contains a character that is not allowed in a file name: ${JSON.stringify(illegal)}`, 400)
|
||||
}
|
||||
if (RESERVED_FILE_NAMES.has(name.split('.')[0]!.toLowerCase())) {
|
||||
throw new SidebarError('bad-request', `"${name}" is a reserved device name on Windows`, 400)
|
||||
}
|
||||
}
|
||||
|
||||
/** Inputs of one new file row. */
|
||||
export interface WorkspaceCreateFileInput {
|
||||
/** The session workspace root (the base of session-relative targets). */
|
||||
cwd: string
|
||||
/** Absolute path of the PARENT row as the tree displays it (a directory). */
|
||||
path: string
|
||||
/** The new file's base name (single segment — creating never nests). */
|
||||
name: string
|
||||
/** @deprecated IGNORED — containment was removed. Do not pass it. */
|
||||
fence?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Create one EMPTY file inside an existing tree row: `<path>/<name>`.
|
||||
* The name must be one path segment and must survive a Windows host
|
||||
* ({@link assertCreatableFileName}); an existing destination — file OR
|
||||
* directory — is refused with the same "already exists" sentence rename and
|
||||
* mkdir use, and is never truncated (the write itself is `wx`, so a name that
|
||||
* appears between the check and the write is refused too, never clobbered);
|
||||
* the parent row may be any directory the host user can write (an unwritable
|
||||
* one surfaces the filesystem's own refusal text).
|
||||
*
|
||||
* @throws SidebarError with a wire code for shape, existence and write
|
||||
* failures.
|
||||
*/
|
||||
export async function createWorkspaceFile(input: WorkspaceCreateFileInput): Promise<{ path: string }> {
|
||||
const { cwd, path, name } = input
|
||||
assertCreatableFileName(name)
|
||||
const { absolute } = await resolveEntry(cwd, path)
|
||||
const destination = await ensureWorkspaceWritePath(cwd, join(absolute, name))
|
||||
if (await pathExists(destination)) {
|
||||
throw new SidebarError('fs-error', `"${name}" already exists`, 409)
|
||||
}
|
||||
try {
|
||||
await writeFile(destination, '', { flag: 'wx', encoding: 'utf8' })
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'EEXIST') {
|
||||
throw new SidebarError('fs-error', `"${name}" already exists`, 409)
|
||||
}
|
||||
throw new SidebarError('fs-error', `cannot create "${name}": ${error instanceof Error ? error.message : String(error)}`, 400)
|
||||
}
|
||||
// The PARENT level gained a row; the new file is a leaf.
|
||||
invalidateDirectoryCache(absolute)
|
||||
return { path: destination }
|
||||
}
|
||||
|
||||
/** Inputs of one tree-row delete. */
|
||||
export interface WorkspaceRemoveInput {
|
||||
/** The session workspace root (the base of session-relative targets). */
|
||||
|
||||
+13
-1
@@ -31,7 +31,7 @@ import {
|
||||
} from './config.ts'
|
||||
import { invalidateDirectoryCache, listDirectory, messageOf, parentOf, requireAbsolute, rootLabel, type SidebarFsEntry } from './fs-tree.ts'
|
||||
import { resolveSessionPath } from './session-path.ts'
|
||||
import { mkdirWorkspaceEntry, renameWorkspaceEntry, removeWorkspaceEntry, writeWorkspaceUpload } from './fs-operations.ts'
|
||||
import { createWorkspaceFile, 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'
|
||||
@@ -657,6 +657,18 @@ function buildApi(
|
||||
name: requireString(payload, 'name'),
|
||||
})
|
||||
},
|
||||
// The tree's "new file": one EMPTY file inside an existing row. Same
|
||||
// single-segment/existence rules as mkdir, plus the Windows-illegal and
|
||||
// reserved-device-name refusals a file name has to survive (fs-operations.ts
|
||||
// owns both), and a destination that is never truncated.
|
||||
'fs.createFile': async (payload) => {
|
||||
const { cwd } = await cwdOf(payload)
|
||||
return createWorkspaceFile({
|
||||
cwd,
|
||||
path: requireString(payload, 'path'),
|
||||
name: requireString(payload, 'name'),
|
||||
})
|
||||
},
|
||||
// The tree row's delete (permanent — the host has no trash): recursive
|
||||
// for directories, unlinks a symlink row without touching its target.
|
||||
'fs.remove': async (payload) => {
|
||||
|
||||
@@ -74,15 +74,20 @@ function file(path: string, broken = false): Row {
|
||||
* `ws/` holds a PLAIN directory (chain of one — the row that used to render no
|
||||
* title), a singleton chain `a` → `a/b` (folded into one breadcrumb row), a
|
||||
* regular file and a broken symlink (the file row's conditional wording).
|
||||
*
|
||||
* The rows arrive in the order a host really lists them (directories first,
|
||||
* then case-insensitive by name): the tree re-sorts each level for display
|
||||
* (file-tree-sort.ts), so a fixture in any other order describes a listing no
|
||||
* host ever produces.
|
||||
*/
|
||||
function levelOf(path: string): { path: string; entries: Row[]; truncated: boolean } {
|
||||
switch (path) {
|
||||
case ROOT:
|
||||
return { path, entries: [
|
||||
dir('/tmp/ws/plain'),
|
||||
dir('/tmp/ws/a', true),
|
||||
file('/tmp/ws/readme.md'),
|
||||
dir('/tmp/ws/plain'),
|
||||
file('/tmp/ws/dangling', true),
|
||||
file('/tmp/ws/readme.md'),
|
||||
], truncated: false }
|
||||
case '/tmp/ws/a':
|
||||
return { path, entries: [dir('/tmp/ws/a/b', true)], truncated: false }
|
||||
@@ -224,10 +229,10 @@ describe('FileTree row hover titles', () => {
|
||||
.map(row => `${labelOf(row)} → ${row.getAttribute('title') ?? '<none>'}`)
|
||||
expect(titled).toEqual([
|
||||
'ws → /tmp/ws',
|
||||
'plain → /tmp/ws/plain',
|
||||
'a/b → /tmp/ws/a/b',
|
||||
'readme.md → /tmp/ws/readme.md',
|
||||
'plain → /tmp/ws/plain',
|
||||
'dangling → /tmp/ws/dangling — Broken symlink',
|
||||
'readme.md → /tmp/ws/readme.md',
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,319 @@
|
||||
/**
|
||||
* FileTree "new file": the directory rows (and the workspace root row) offer
|
||||
* it in the context menu beside "New folder"; choosing it inserts the inline
|
||||
* editor at the TOP of that level (expanding a collapsed directory first), and
|
||||
* the editor follows the rename contract — Enter commits through
|
||||
* `api.fsCreateFile` with the parent directory + single-segment name, Escape
|
||||
* cancels, blur commits, an invalid name reports `newFileInvalid`, a name the
|
||||
* level already lists is refused client-side with `newFileExists`, and any
|
||||
* other server refusal lands in the dismissable strip. The two inline creators
|
||||
* (folder / file) are mutually exclusive.
|
||||
*/
|
||||
// @vitest-environment jsdom
|
||||
import { beforeAll, afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createElement, useState, type ReactNode } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { act } from 'react-dom/test-utils'
|
||||
import { FileTree, joinChild, nameTaken } from '../src/client/FileTree.tsx'
|
||||
|
||||
import { setupReactAct } from './test-utils.ts'
|
||||
setupReactAct()
|
||||
|
||||
// vitest 4.1.11+ follows the OS locale; pin en-US so menu copy is English.
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(window.navigator, 'language', { value: 'en-US', configurable: true })
|
||||
})
|
||||
|
||||
const { fsCreateFile, fsMkdir, fsTrees } = vi.hoisted(() => ({
|
||||
fsCreateFile: vi.fn(async (_scope: unknown, _path: string, name: string) => ({ path: `/tmp/${name}` })),
|
||||
fsMkdir: vi.fn(async (_scope: unknown, _path: string, name: string) => ({ path: `/tmp/${name}` })),
|
||||
// `listingFor` is a hoisted function declaration, so the factory may
|
||||
// reference it; it only runs when the mock is called (after module init).
|
||||
fsTrees: vi.fn(async (_scope: unknown, paths: readonly string[]) => ({ levels: paths.map(path => listingFor(path)) })),
|
||||
}))
|
||||
|
||||
vi.mock('../src/client/api.ts', () => ({
|
||||
api: {
|
||||
fsTrees,
|
||||
fsCreateFile,
|
||||
fsMkdir,
|
||||
// The tree reads the shared git-status store; a non-repo answer keeps
|
||||
// every row plain (this spec is about file creation).
|
||||
gitStatus: async () => ({ isRepo: false, entries: [] }),
|
||||
},
|
||||
downloadUrl: () => '/sidebar/file',
|
||||
isOutsideWorkspaceMessage: () => false,
|
||||
}))
|
||||
|
||||
const ROOT_ENTRIES = [
|
||||
{ name: 'sub', path: '/tmp/sub', isDir: true },
|
||||
{ name: 'a.ts', path: '/tmp/a.ts', isDir: false },
|
||||
]
|
||||
|
||||
/** Per-directory listings: /tmp/sub must NOT list itself (a real host never
|
||||
* returns a directory inside its own listing). */
|
||||
function listingFor(path: string): { path: string; entries: typeof ROOT_ENTRIES; truncated: boolean } {
|
||||
return {
|
||||
path,
|
||||
entries: path === '/tmp/sub' ? [{ name: 'inner.txt', path: '/tmp/sub/inner.txt', isDir: false }] : ROOT_ENTRIES,
|
||||
truncated: false,
|
||||
}
|
||||
}
|
||||
|
||||
interface Harness {
|
||||
container: HTMLDivElement
|
||||
/** Directories the tree asked the caller to expand/collapse. */
|
||||
toggled: string[]
|
||||
unmount: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* The real caller owns the expansion set (EditorHost holds it in the store),
|
||||
* so the harness does too: a toggle really expands the tree and loads the
|
||||
* level beneath it.
|
||||
*/
|
||||
function mountTree(initialExpanded: string[] = []): Harness {
|
||||
const container = document.createElement('div')
|
||||
document.body.append(container)
|
||||
const root: Root = createRoot(container)
|
||||
const toggled: string[] = []
|
||||
function Host(): ReactNode {
|
||||
const [expanded, setExpanded] = useState<string[]>(initialExpanded)
|
||||
return createElement(FileTree, {
|
||||
sessionId: 's1',
|
||||
cwd: '/tmp',
|
||||
expanded,
|
||||
revealed: [],
|
||||
onToggle: (path: string) => {
|
||||
toggled.push(path)
|
||||
setExpanded(current => current.includes(path) ? current.filter(item => item !== path) : [...current, path])
|
||||
},
|
||||
onOpenFile: () => {},
|
||||
onReferenceFile: () => {},
|
||||
refreshTick: 0,
|
||||
onUploadRequest: () => {},
|
||||
busy: false,
|
||||
})
|
||||
}
|
||||
act(() => { root.render(createElement(Host)) })
|
||||
return {
|
||||
container,
|
||||
toggled,
|
||||
unmount: () => { act(() => { root.unmount() }); container.remove() },
|
||||
}
|
||||
}
|
||||
|
||||
/** One tree row by its displayed name (the root row included). */
|
||||
function rowByName(container: HTMLElement, name: string): HTMLElement {
|
||||
const row = [...container.querySelectorAll<HTMLElement>('[class*="explorerRow"]')]
|
||||
.find(el => el.querySelector('[class*="explorerName"]')?.textContent === name)
|
||||
if (row === undefined) throw new Error(`row not found: ${name}`)
|
||||
return row
|
||||
}
|
||||
|
||||
function openMenu(container: HTMLElement, name: string): void {
|
||||
const event = new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 20, clientY: 30 })
|
||||
act(() => { rowByName(container, name).dispatchEvent(event) })
|
||||
}
|
||||
|
||||
function menuLabels(): string[] {
|
||||
return [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].map(el => el.textContent ?? '')
|
||||
}
|
||||
|
||||
function clickMenuitem(label: string): void {
|
||||
const item = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')]
|
||||
.find(el => el.textContent === label)
|
||||
if (item === undefined) throw new Error(`menuitem not found: ${label}`)
|
||||
act(() => { item.click() })
|
||||
}
|
||||
|
||||
/** Set a controlled input's value the React way (native setter + input). */
|
||||
function setNativeValue(el: HTMLInputElement, value: string): void {
|
||||
const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')?.set
|
||||
if (setter === undefined) throw new Error('no native value setter')
|
||||
setter.call(el, value)
|
||||
el.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
}
|
||||
|
||||
function pressKey(el: HTMLElement, key: string): void {
|
||||
el.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }))
|
||||
}
|
||||
|
||||
/** Every inline editor input currently rendered (folder and file alike). */
|
||||
function editorInputs(container: HTMLElement): HTMLInputElement[] {
|
||||
return [...container.querySelectorAll<HTMLInputElement>('input[class*="explorerRenameInput"]')]
|
||||
}
|
||||
|
||||
function editorInput(container: HTMLElement): HTMLInputElement {
|
||||
const input = editorInputs(container)[0]
|
||||
if (input === undefined) throw new Error('inline editor not rendered')
|
||||
return input
|
||||
}
|
||||
|
||||
/** The editor row's indent (depth * 22 + 6) — proof of WHICH level hosts it. */
|
||||
function editorIndent(container: HTMLElement): string {
|
||||
return editorInput(container).closest<HTMLElement>('[class*="explorerRow"]')?.style.paddingLeft ?? ''
|
||||
}
|
||||
|
||||
let harness: Harness
|
||||
afterEach(() => {
|
||||
// The pure-helper cases never mount a tree; every other case assigns first.
|
||||
const tree: Harness | undefined = harness
|
||||
tree?.unmount()
|
||||
document.body.innerHTML = ''
|
||||
fsCreateFile.mockReset()
|
||||
fsCreateFile.mockImplementation(async (_scope: unknown, _path: string, name: string) => ({ path: `/tmp/${name}` }))
|
||||
fsMkdir.mockReset()
|
||||
fsMkdir.mockImplementation(async (_scope: unknown, _path: string, name: string) => ({ path: `/tmp/${name}` }))
|
||||
fsTrees.mockReset()
|
||||
fsTrees.mockImplementation(async (_scope: unknown, paths: readonly string[]) => ({ levels: paths.map(path => listingFor(path)) }))
|
||||
})
|
||||
|
||||
describe('FileTree new file helpers', () => {
|
||||
it('joinChild appends one segment without doubling the separator', () => {
|
||||
expect(joinChild('/tmp', 'a.ts')).toBe('/tmp/a.ts')
|
||||
expect(joinChild('/tmp/', 'a.ts')).toBe('/tmp/a.ts')
|
||||
expect(joinChild('C:\\tmp\\', 'a.ts')).toBe('C:\\tmp/a.ts')
|
||||
})
|
||||
|
||||
it('nameTaken compares case-insensitively and answers false for an unloaded level', () => {
|
||||
const entries = [{ name: 'a.ts' }, { name: 'Sub' }]
|
||||
expect(nameTaken(entries, 'a.ts')).toBe(true)
|
||||
expect(nameTaken(entries, 'A.TS')).toBe(true)
|
||||
expect(nameTaken(entries, 'sub')).toBe(true)
|
||||
expect(nameTaken(entries, 'b.ts')).toBe(false)
|
||||
expect(nameTaken(undefined, 'a.ts')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('FileTree new file', () => {
|
||||
it('offers the entry on directory rows (the root included, never on files)', async () => {
|
||||
harness = mountTree()
|
||||
await act(async () => {})
|
||||
openMenu(harness.container, 'sub')
|
||||
expect(menuLabels()).toContain('New file')
|
||||
openMenu(harness.container, 'tmp')
|
||||
expect(menuLabels()).toContain('New file')
|
||||
openMenu(harness.container, 'a.ts')
|
||||
expect(menuLabels()).not.toContain('New file')
|
||||
})
|
||||
|
||||
it('inserts the editor at the root level and commits through api.fsCreateFile', async () => {
|
||||
harness = mountTree()
|
||||
await act(async () => {})
|
||||
openMenu(harness.container, 'tmp')
|
||||
clickMenuitem('New file')
|
||||
const input = editorInput(harness.container)
|
||||
expect(input.placeholder).toBe('File name')
|
||||
// The root level's rows sit at depth 1 (22 + 6); the editor replaces the
|
||||
// level's first row.
|
||||
expect(editorIndent(harness.container)).toBe('28px')
|
||||
setNativeValue(input, 'fresh.ts')
|
||||
const listings = fsTrees.mock.calls.length
|
||||
await act(async () => { pressKey(input, 'Enter') })
|
||||
expect(fsCreateFile).toHaveBeenCalledWith({ sessionId: 's1', cwd: '/tmp' }, '/tmp', 'fresh.ts')
|
||||
expect(editorInputs(harness.container)).toHaveLength(0)
|
||||
// The level was dropped and re-listed, so the new file shows up.
|
||||
expect(fsTrees.mock.calls.length).toBeGreaterThan(listings)
|
||||
})
|
||||
|
||||
it('expands a collapsed directory, edits at ITS level, and creates there', async () => {
|
||||
harness = mountTree()
|
||||
await act(async () => {})
|
||||
openMenu(harness.container, 'sub')
|
||||
clickMenuitem('New file')
|
||||
// The collapsed directory is expanded so its level can host the editor.
|
||||
expect(harness.toggled).toEqual(['/tmp/sub'])
|
||||
expect(editorIndent(harness.container)).toBe('50px')
|
||||
setNativeValue(editorInput(harness.container), 'inner2.txt')
|
||||
await act(async () => { pressKey(editorInput(harness.container), 'Enter') })
|
||||
expect(fsCreateFile).toHaveBeenCalledWith({ sessionId: 's1', cwd: '/tmp' }, '/tmp/sub', 'inner2.txt')
|
||||
})
|
||||
|
||||
it('Escape cancels without touching the API', async () => {
|
||||
harness = mountTree()
|
||||
await act(async () => {})
|
||||
openMenu(harness.container, 'tmp')
|
||||
clickMenuitem('New file')
|
||||
const input = editorInput(harness.container)
|
||||
setNativeValue(input, 'fresh.ts')
|
||||
await act(async () => { pressKey(input, 'Escape') })
|
||||
expect(fsCreateFile).not.toHaveBeenCalled()
|
||||
expect(editorInputs(harness.container)).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('rejects an invalid name client-side with the strip, no API call', async () => {
|
||||
harness = mountTree()
|
||||
await act(async () => {})
|
||||
openMenu(harness.container, 'tmp')
|
||||
clickMenuitem('New file')
|
||||
const input = editorInput(harness.container)
|
||||
setNativeValue(input, 'a/b')
|
||||
await act(async () => { pressKey(input, 'Enter') })
|
||||
expect(fsCreateFile).not.toHaveBeenCalled()
|
||||
expect(harness.container.querySelector('[role="alert"]')?.textContent).toContain('Invalid file name')
|
||||
})
|
||||
|
||||
it('refuses a name the level already lists (case-insensitively) without a round trip', async () => {
|
||||
harness = mountTree()
|
||||
await act(async () => {})
|
||||
openMenu(harness.container, 'tmp')
|
||||
clickMenuitem('New file')
|
||||
const input = editorInput(harness.container)
|
||||
setNativeValue(input, 'A.TS')
|
||||
await act(async () => { pressKey(input, 'Enter') })
|
||||
expect(fsCreateFile).not.toHaveBeenCalled()
|
||||
expect(harness.container.querySelector('[role="alert"]')?.textContent).toContain('A file with this name already exists')
|
||||
})
|
||||
|
||||
it('lands a server refusal in the dismissable strip', async () => {
|
||||
fsCreateFile.mockRejectedValueOnce(new Error('boom: reserved'))
|
||||
harness = mountTree()
|
||||
await act(async () => {})
|
||||
openMenu(harness.container, 'tmp')
|
||||
clickMenuitem('New file')
|
||||
const input = editorInput(harness.container)
|
||||
setNativeValue(input, 'CON')
|
||||
await act(async () => { pressKey(input, 'Enter') })
|
||||
expect(fsCreateFile).toHaveBeenCalledTimes(1)
|
||||
expect(harness.container.querySelector('[role="alert"]')?.textContent).toContain('boom: reserved')
|
||||
})
|
||||
|
||||
it('commits on blur (the same contract the rename editor has)', async () => {
|
||||
harness = mountTree()
|
||||
await act(async () => {})
|
||||
openMenu(harness.container, 'tmp')
|
||||
clickMenuitem('New file')
|
||||
const input = editorInput(harness.container)
|
||||
setNativeValue(input, 'blurred.ts')
|
||||
// React delegates onBlur from the native focusout event.
|
||||
await act(async () => { input.dispatchEvent(new FocusEvent('focusout', { bubbles: true })) })
|
||||
expect(fsCreateFile).toHaveBeenCalledWith({ sessionId: 's1', cwd: '/tmp' }, '/tmp', 'blurred.ts')
|
||||
})
|
||||
|
||||
it('keeps the two inline creators mutually exclusive', async () => {
|
||||
harness = mountTree()
|
||||
await act(async () => {})
|
||||
// New folder, then New file: only the file editor is left.
|
||||
openMenu(harness.container, 'tmp')
|
||||
clickMenuitem('New folder')
|
||||
expect(editorInputs(harness.container)).toHaveLength(1)
|
||||
openMenu(harness.container, 'tmp')
|
||||
clickMenuitem('New file')
|
||||
expect(editorInputs(harness.container)).toHaveLength(1)
|
||||
setNativeValue(editorInput(harness.container), 'only.ts')
|
||||
await act(async () => { pressKey(editorInput(harness.container), 'Enter') })
|
||||
expect(fsCreateFile).toHaveBeenCalledTimes(1)
|
||||
expect(fsMkdir).not.toHaveBeenCalled()
|
||||
// …and the other way around.
|
||||
openMenu(harness.container, 'tmp')
|
||||
clickMenuitem('New file')
|
||||
openMenu(harness.container, 'tmp')
|
||||
clickMenuitem('New folder')
|
||||
expect(editorInputs(harness.container)).toHaveLength(1)
|
||||
setNativeValue(editorInput(harness.container), 'only-dir')
|
||||
await act(async () => { pressKey(editorInput(harness.container), 'Enter') })
|
||||
expect(fsMkdir).toHaveBeenCalledTimes(1)
|
||||
expect(fsCreateFile).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,256 @@
|
||||
/**
|
||||
* Explorer sort control: the pure ordering (`sortEntries` / `typeOf`) plus the
|
||||
* two surfaces that consume it — FileTree's rows and the tree header's menu in
|
||||
* TreePanel.
|
||||
*
|
||||
* The contract under test: the DEFAULT choice (name + folders first) reproduces
|
||||
* the server's own order EXACTLY (`fs-tree.ts`'s `compareEntries` drives the
|
||||
* expectation, so a divergence on either side fails here), "by type" groups by
|
||||
* extension, and the folders-first switch is independent of the key (it really
|
||||
* mixes directories into the key's order when off).
|
||||
*/
|
||||
// @vitest-environment jsdom
|
||||
import { beforeAll, afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createElement, useState, type ReactNode } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { act } from 'react-dom/test-utils'
|
||||
import { compareEntries, type SidebarFsEntry } from '../src/fs-tree.ts'
|
||||
import { FileTree } from '../src/client/FileTree.tsx'
|
||||
import { TreePanel } from '../src/client/TreePanel.tsx'
|
||||
import { DEFAULT_FILE_TREE_SORT, sortEntries, typeOf } from '../src/client/file-tree-sort.ts'
|
||||
|
||||
import { setupReactAct } from './test-utils.ts'
|
||||
setupReactAct()
|
||||
|
||||
// vitest 4.1.11+ follows the OS locale; pin en-US so menu copy is English.
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(window.navigator, 'language', { value: 'en-US', configurable: true })
|
||||
})
|
||||
|
||||
/** One host-shaped row (only the fields ordering reads). */
|
||||
function row(name: string, isDir: boolean): SidebarFsEntry {
|
||||
return { name, path: `/tmp/${name}`, isDir, hidden: false, isSymlink: false, broken: false }
|
||||
}
|
||||
|
||||
/**
|
||||
* A level whose HOST order (directories first, then name) is deliberately not
|
||||
* the type order: `zdir` is a directory that sorts after two of the files by
|
||||
* name, so only the folders-first switch can move it.
|
||||
*/
|
||||
const HOST_ORDER: SidebarFsEntry[] = [
|
||||
row('zdir', true),
|
||||
row('alpha.ts', false),
|
||||
row('beta', false),
|
||||
row('Gamma.MD', false),
|
||||
]
|
||||
|
||||
const names = (entries: readonly { name: string }[]): string[] => entries.map(entry => entry.name)
|
||||
|
||||
describe('file tree sort (pure ordering)', () => {
|
||||
it('defaults to the server order: same key, folders first', () => {
|
||||
expect(DEFAULT_FILE_TREE_SORT).toEqual({ key: 'name', dirsFirst: true })
|
||||
})
|
||||
|
||||
it('reproduces compareEntries EXACTLY for the default choice', () => {
|
||||
// The host comparator is the reference: the default client order must be
|
||||
// the same listing order, element for element (the control ON with its
|
||||
// initial value changes nothing).
|
||||
expect(names(sortEntries(HOST_ORDER, DEFAULT_FILE_TREE_SORT)))
|
||||
.toEqual(names([...HOST_ORDER].sort(compareEntries)))
|
||||
// …and it is not a no-op by accident: an unsorted level comes out ordered.
|
||||
const shuffled = [HOST_ORDER[2]!, HOST_ORDER[0]!, HOST_ORDER[3]!, HOST_ORDER[1]!]
|
||||
expect(names(sortEntries(shuffled, DEFAULT_FILE_TREE_SORT))).toEqual(['zdir', 'alpha.ts', 'beta', 'Gamma.MD'])
|
||||
})
|
||||
|
||||
it('orders by name case-insensitively with the host tie-break when folders are first', () => {
|
||||
const entries = [row('b.txt', false), row('A.txt', false), row('a.txt', false), row('Dir', true)]
|
||||
expect(names(sortEntries(entries, { key: 'name', dirsFirst: true }))).toEqual(['Dir', 'A.txt', 'a.txt', 'b.txt'])
|
||||
})
|
||||
|
||||
it('mixes directories into the name order when folders first is off', () => {
|
||||
expect(names(sortEntries(HOST_ORDER, { key: 'name', dirsFirst: false })))
|
||||
.toEqual(['alpha.ts', 'beta', 'Gamma.MD', 'zdir'])
|
||||
})
|
||||
|
||||
it('orders by type (extension) with folders first', () => {
|
||||
expect(names(sortEntries(HOST_ORDER, { key: 'type', dirsFirst: true })))
|
||||
// zdir first (a directory), then extension-less `beta`, then md, then ts.
|
||||
.toEqual(['zdir', 'beta', 'Gamma.MD', 'alpha.ts'])
|
||||
})
|
||||
|
||||
it('mixes directories into the type order when folders first is off', () => {
|
||||
expect(names(sortEntries(HOST_ORDER, { key: 'type', dirsFirst: false })))
|
||||
// `zdir` has no extension, so it groups with `beta` and the name order
|
||||
// decides between them — the switch really moved the directory.
|
||||
.toEqual(['beta', 'zdir', 'Gamma.MD', 'alpha.ts'])
|
||||
})
|
||||
|
||||
it('sorts a copy: the cached level array is never reordered in place', () => {
|
||||
const before = names(HOST_ORDER)
|
||||
const sorted = sortEntries(HOST_ORDER, { key: 'type', dirsFirst: false })
|
||||
expect(sorted).not.toBe(HOST_ORDER)
|
||||
expect(names(HOST_ORDER)).toEqual(before)
|
||||
})
|
||||
|
||||
it('typeOf reads the LAST extension, nothing for dirs, dotfiles or dot-less names', () => {
|
||||
expect(typeOf('a.tar.gz', false)).toBe('gz')
|
||||
expect(typeOf('A.TS', false)).toBe('ts')
|
||||
expect(typeOf('.gitignore', false)).toBe('')
|
||||
expect(typeOf('Makefile', false)).toBe('')
|
||||
expect(typeOf('weird.', false)).toBe('')
|
||||
expect(typeOf('a.tar.gz', true)).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
const { fsTrees, fsSearch, gitStatus } = vi.hoisted(() => ({
|
||||
fsTrees: vi.fn(async (_scope: unknown, paths: readonly string[]) => ({
|
||||
levels: paths.map(path => ({ path, entries: path === '/tmp' ? HOST_ORDER_ROWS : [], truncated: false })),
|
||||
})),
|
||||
fsSearch: vi.fn(async () => ({ matches: [], dirs: [], truncated: false })),
|
||||
gitStatus: vi.fn(async () => ({ isRepo: false, entries: [] })),
|
||||
}))
|
||||
|
||||
vi.mock('../src/client/api.ts', () => ({
|
||||
api: { fsTrees, fsSearch, gitStatus },
|
||||
downloadUrl: () => '/sidebar/file',
|
||||
isOutsideWorkspaceMessage: () => false,
|
||||
}))
|
||||
|
||||
/** The fixture as the level cache stores it (plain rows, host order). */
|
||||
const HOST_ORDER_ROWS = [
|
||||
{ name: 'zdir', path: '/tmp/zdir', isDir: true },
|
||||
{ name: 'alpha.ts', path: '/tmp/alpha.ts', isDir: false },
|
||||
{ name: 'beta', path: '/tmp/beta', isDir: false },
|
||||
{ name: 'Gamma.MD', path: '/tmp/Gamma.MD', isDir: false },
|
||||
]
|
||||
|
||||
interface Harness {
|
||||
container: HTMLDivElement
|
||||
unmount: () => void
|
||||
}
|
||||
|
||||
/** Child row labels of the workspace root, in render order. */
|
||||
function rowNames(container: HTMLElement): string[] {
|
||||
return [...container.querySelectorAll<HTMLElement>('[class*="explorerRow"]')]
|
||||
.filter(el => (el.style.paddingLeft === '28px'))
|
||||
.map(el => el.querySelector('[class*="explorerName"]')?.textContent ?? '')
|
||||
}
|
||||
|
||||
let harness: Harness | undefined
|
||||
|
||||
afterEach(() => {
|
||||
harness?.unmount()
|
||||
harness = undefined
|
||||
document.body.innerHTML = ''
|
||||
fsTrees.mockClear()
|
||||
fsSearch.mockClear()
|
||||
gitStatus.mockClear()
|
||||
})
|
||||
|
||||
describe('FileTree sort prop', () => {
|
||||
function mountTree(sort?: { key: 'name' | 'type'; dirsFirst: boolean }): Harness {
|
||||
const container = document.createElement('div')
|
||||
document.body.append(container)
|
||||
const root: Root = createRoot(container)
|
||||
act(() => {
|
||||
root.render(createElement(FileTree, {
|
||||
sessionId: 's1',
|
||||
cwd: '/tmp',
|
||||
expanded: [],
|
||||
revealed: [],
|
||||
onToggle: () => {},
|
||||
onOpenFile: () => {},
|
||||
onReferenceFile: () => {},
|
||||
refreshTick: 0,
|
||||
onUploadRequest: () => {},
|
||||
busy: false,
|
||||
...(sort !== undefined ? { sort } : {}),
|
||||
}))
|
||||
})
|
||||
return { container, unmount: () => { act(() => { root.unmount() }); container.remove() } }
|
||||
}
|
||||
|
||||
it('renders the host order by default (the control is invisible until used)', async () => {
|
||||
harness = mountTree()
|
||||
await act(async () => {})
|
||||
expect(rowNames(harness.container)).toEqual(['zdir', 'alpha.ts', 'beta', 'Gamma.MD'])
|
||||
})
|
||||
|
||||
it('renders the type order when the caller asks for it', async () => {
|
||||
harness = mountTree({ key: 'type', dirsFirst: true })
|
||||
await act(async () => {})
|
||||
expect(rowNames(harness.container)).toEqual(['zdir', 'beta', 'Gamma.MD', 'alpha.ts'])
|
||||
})
|
||||
|
||||
it('interleaves directories with files once folders first is off', async () => {
|
||||
harness = mountTree({ key: 'name', dirsFirst: false })
|
||||
await act(async () => {})
|
||||
expect(rowNames(harness.container)).toEqual(['alpha.ts', 'beta', 'Gamma.MD', 'zdir'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('TreePanel sort control', () => {
|
||||
function mountPanel(): Harness {
|
||||
const container = document.createElement('div')
|
||||
document.body.append(container)
|
||||
const root: Root = createRoot(container)
|
||||
function Host(): ReactNode {
|
||||
const [expanded, setExpanded] = useState<string[]>([])
|
||||
return createElement(TreePanel, {
|
||||
sessionId: 's1',
|
||||
cwd: '/tmp',
|
||||
expanded,
|
||||
revealed: [],
|
||||
onToggle: (path: string) => { setExpanded(current => current.includes(path) ? current : [...current, path]) },
|
||||
onOpenFile: () => {},
|
||||
onReferenceFile: () => {},
|
||||
})
|
||||
}
|
||||
act(() => { root.render(createElement(Host)) })
|
||||
return { container, unmount: () => { act(() => { root.unmount() }); container.remove() } }
|
||||
}
|
||||
|
||||
function click(el: HTMLElement): void {
|
||||
act(() => { el.click() })
|
||||
}
|
||||
|
||||
function sortButton(container: HTMLElement): HTMLButtonElement {
|
||||
const button = container.querySelector<HTMLButtonElement>('button[aria-label="Sort"]')
|
||||
if (button === null) throw new Error('sort button not found')
|
||||
return button
|
||||
}
|
||||
|
||||
function menuItem(label: string): HTMLElement {
|
||||
const item = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')]
|
||||
.find(el => el.textContent === label)
|
||||
if (item === undefined) throw new Error(`menuitem not found: ${label}`)
|
||||
return item
|
||||
}
|
||||
|
||||
it('offers both keys and the folders-first switch, and applies them to the tree', async () => {
|
||||
harness = mountPanel()
|
||||
await act(async () => {})
|
||||
expect(rowNames(harness.container)).toEqual(['zdir', 'alpha.ts', 'beta', 'Gamma.MD'])
|
||||
|
||||
// The control lives in the tree header's tool row, next to refresh/upload.
|
||||
click(sortButton(harness.container))
|
||||
expect([...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].map(el => el.textContent))
|
||||
.toEqual(['Sort by name', 'Sort by type', 'Folders first'])
|
||||
|
||||
click(menuItem('Sort by type'))
|
||||
expect(rowNames(harness.container)).toEqual(['zdir', 'beta', 'Gamma.MD', 'alpha.ts'])
|
||||
|
||||
// The switch is independent of the key: turning folders first off keeps
|
||||
// the type grouping and lets the directory fall into its own group.
|
||||
click(sortButton(harness.container))
|
||||
click(menuItem('Folders first'))
|
||||
expect(rowNames(harness.container)).toEqual(['beta', 'zdir', 'Gamma.MD', 'alpha.ts'])
|
||||
|
||||
// …and back to the default pair.
|
||||
click(sortButton(harness.container))
|
||||
click(menuItem('Folders first'))
|
||||
click(sortButton(harness.container))
|
||||
click(menuItem('Sort by name'))
|
||||
expect(rowNames(harness.container)).toEqual(['zdir', 'alpha.ts', 'beta', 'Gamma.MD'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,236 @@
|
||||
/**
|
||||
* The host's "new file" mutation (`fs.createFile` route → createWorkspaceFile):
|
||||
* the happy path against a real temporary filesystem, the shared
|
||||
* single-segment/existence rules, the two Windows-only refusals a file name
|
||||
* must survive (illegal characters, reserved device names), and the promise
|
||||
* that an existing destination is REFUSED and never truncated.
|
||||
*
|
||||
* The workspace fence is GONE (like rename/mkdir): a parent outside the
|
||||
* session workspace is accepted like any other directory the host user can
|
||||
* write, and an unwritable one surfaces the filesystem's own refusal.
|
||||
*/
|
||||
import { chmod, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { createWorkspaceFile } from '../src/fs-operations.ts'
|
||||
import { apply } from '../src/index.ts'
|
||||
import type { SidebarWebRoute } from '../src/context-types.ts'
|
||||
|
||||
let root: string
|
||||
|
||||
beforeEach(async () => {
|
||||
root = await mkdtemp(join(tmpdir(), 'dsh-create-file-'))
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await chmod(root, 0o700).catch(() => {})
|
||||
await rm(root, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
/** The wire code of a rejected call (the route maps it to an HTTP status). */
|
||||
async function codeOf(run: () => Promise<unknown>): Promise<string> {
|
||||
try {
|
||||
await run()
|
||||
} catch (error) {
|
||||
return (error as { code?: string }).code ?? 'no-code'
|
||||
}
|
||||
return 'resolved'
|
||||
}
|
||||
|
||||
/** The message of a rejected call (the strip shows this text verbatim). */
|
||||
async function messageOf(run: () => Promise<unknown>): Promise<string> {
|
||||
try {
|
||||
await run()
|
||||
} catch (error) {
|
||||
return (error as Error).message
|
||||
}
|
||||
return 'resolved'
|
||||
}
|
||||
|
||||
describe('createWorkspaceFile', () => {
|
||||
it('creates one EMPTY file inside the named row and returns its absolute path', async () => {
|
||||
await mkdir(join(root, 'sub'))
|
||||
const result = await createWorkspaceFile({ cwd: root, path: join(root, 'sub'), name: 'fresh.txt' })
|
||||
// Lexical: the path comes back exactly as composed (no realpath — on macOS
|
||||
// /var would otherwise be reported as /private/var).
|
||||
expect(result.path).toBe(join(root, 'sub', 'fresh.txt'))
|
||||
expect(await readdir(join(root, 'sub'))).toEqual(['fresh.txt'])
|
||||
expect(await readFile(join(root, 'sub', 'fresh.txt'), 'utf8')).toBe('')
|
||||
})
|
||||
|
||||
it('accepts the workspace root itself as the parent', async () => {
|
||||
const result = await createWorkspaceFile({ cwd: root, path: root, name: 'top.ts' })
|
||||
expect(result.path).toBe(join(root, 'top.ts'))
|
||||
expect(await readdir(root)).toEqual(['top.ts'])
|
||||
})
|
||||
|
||||
it('refuses a name that is not a single path segment (empty, dots, separators, traversal)', async () => {
|
||||
for (const name of ['', '.', '..', 'a/b', 'a\\b', '../escape', '..\\escape', 'sub/../../escape']) {
|
||||
expect(await codeOf(() => createWorkspaceFile({ cwd: root, path: root, name })), name).toBe('bad-request')
|
||||
}
|
||||
// Nothing was created by any of the refusals.
|
||||
expect(await readdir(root)).toEqual([])
|
||||
})
|
||||
|
||||
it('refuses the characters Windows cannot store in a file name', async () => {
|
||||
for (const name of ['a:b', 'a?b', 'a*b', 'a"b', 'a<b', 'a>b', 'a|b', 'a\u0000b', 'a\u001fb', 'lead<ing']) {
|
||||
expect(await codeOf(() => createWorkspaceFile({ cwd: root, path: root, name })), JSON.stringify(name)).toBe('bad-request')
|
||||
}
|
||||
// The message names the offending character, so the strip is actionable.
|
||||
expect(await messageOf(() => createWorkspaceFile({ cwd: root, path: root, name: 'a:b' }))).toContain('":"')
|
||||
expect(await readdir(root)).toEqual([])
|
||||
})
|
||||
|
||||
it('refuses Windows device names, with or without an extension, and accepts near misses', async () => {
|
||||
for (const name of ['CON', 'con', 'Con.txt', 'NUL', 'nul.tar.gz', 'AUX', 'PRN', 'COM1', 'com9.log', 'LPT1', 'lpt9.txt']) {
|
||||
expect(await codeOf(() => createWorkspaceFile({ cwd: root, path: root, name })), name).toBe('bad-request')
|
||||
}
|
||||
expect(await messageOf(() => createWorkspaceFile({ cwd: root, path: root, name: 'CON' }))).toContain('reserved device name')
|
||||
// Names that merely START with a device name are ordinary files.
|
||||
for (const name of ['console.txt', 'conx', 'COM10', 'LPT', 'null.md', 'auxiliary']) {
|
||||
await expect(createWorkspaceFile({ cwd: root, path: root, name })).resolves.toEqual({ path: join(root, name) })
|
||||
}
|
||||
expect(await readdir(root)).toEqual(['COM10', 'LPT', 'auxiliary', 'console.txt', 'conx', 'null.md'])
|
||||
})
|
||||
|
||||
it('refuses an existing destination with the same conflict code as rename and mkdir', async () => {
|
||||
await writeFile(join(root, 'taken.txt'), 'keep me')
|
||||
expect(await codeOf(() => createWorkspaceFile({ cwd: root, path: root, name: 'taken.txt' }))).toBe('fs-error')
|
||||
expect(await messageOf(() => createWorkspaceFile({ cwd: root, path: root, name: 'taken.txt' }))).toContain('already exists')
|
||||
// ⚠️ The refusal must NOT truncate: the create uses `wx`, not `w`.
|
||||
expect(await readFile(join(root, 'taken.txt'), 'utf8')).toBe('keep me')
|
||||
})
|
||||
|
||||
it('refuses a destination that is a DIRECTORY (a row of either kind occupies the name)', async () => {
|
||||
await mkdir(join(root, 'both'))
|
||||
expect(await codeOf(() => createWorkspaceFile({ cwd: root, path: root, name: 'both' }))).toBe('fs-error')
|
||||
})
|
||||
|
||||
it('reports an unwritable parent directory as an fs-error carrying the filesystem message', async () => {
|
||||
// POSIX only: Windows has no mode bits, and root bypasses them everywhere.
|
||||
if (process.platform === 'win32' || process.getuid?.() === 0) return
|
||||
const locked = join(root, 'locked')
|
||||
await mkdir(locked)
|
||||
await chmod(locked, 0o500)
|
||||
try {
|
||||
expect(await codeOf(() => createWorkspaceFile({ cwd: root, path: locked, name: 'nope.txt' }))).toBe('fs-error')
|
||||
expect(await messageOf(() => createWorkspaceFile({ cwd: root, path: locked, name: 'nope.txt' }))).toContain('cannot create "nope.txt"')
|
||||
} finally {
|
||||
await chmod(locked, 0o700)
|
||||
}
|
||||
})
|
||||
|
||||
it('creates a file under a parent outside the workspace (fence removed)', async () => {
|
||||
const outside = await mkdtemp(join(tmpdir(), 'dsh-outside-'))
|
||||
try {
|
||||
const result = await createWorkspaceFile({ cwd: root, path: outside, name: 'allowed.txt' })
|
||||
expect(result.path).toBe(join(outside, 'allowed.txt'))
|
||||
expect(await readdir(outside)).toEqual(['allowed.txt'])
|
||||
} finally {
|
||||
await rm(outside, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* The ROUTE, not just the operation: `fs.createFile` must exist in the route
|
||||
* table, take `path`/`name` off the payload, resolve `cwd` from the session,
|
||||
* and map the two refusal classes to their HTTP statuses (409 for a taken
|
||||
* destination, 400 for a broken name) — the wire contract the client's inline
|
||||
* editor reads.
|
||||
*/
|
||||
interface FakeContext {
|
||||
webRuntime: { trustedHosts: readonly string[] }
|
||||
webServer: {
|
||||
register: (route: SidebarWebRoute) => () => void
|
||||
registerUpgrade: () => () => void
|
||||
}
|
||||
sessions: { get: (id: string) => { header: { cwd?: string } } | undefined }
|
||||
tools: { register: () => () => void }
|
||||
effect: (fn: () => void | (() => void)) => void
|
||||
inject: (deps: readonly string[], callback: (sctx: never) => void) => () => void
|
||||
on: () => () => void
|
||||
get: (key: string) => undefined
|
||||
}
|
||||
|
||||
/** Mount the plugin against a fake context whose session cwd is `workspace`. */
|
||||
function mountApi(workspace: string): SidebarWebRoute {
|
||||
const routes: SidebarWebRoute[] = []
|
||||
const ctx: FakeContext = {
|
||||
webRuntime: { trustedHosts: [] },
|
||||
webServer: { register: (route) => { routes.push(route); return () => {} }, registerUpgrade: () => () => {} },
|
||||
sessions: { get: () => ({ header: { cwd: workspace } }) },
|
||||
tools: { register: () => () => {} },
|
||||
effect: (fn) => { fn() },
|
||||
inject: () => () => {},
|
||||
on: () => () => {},
|
||||
get: () => undefined,
|
||||
}
|
||||
apply(ctx as never, {})
|
||||
return routes.find(route => route.path === '/sidebar/api')!
|
||||
}
|
||||
|
||||
interface Invoked {
|
||||
ok: boolean
|
||||
status: number
|
||||
value?: { path?: string }
|
||||
error?: { code?: string; message?: string }
|
||||
}
|
||||
|
||||
async function invoke(route: SidebarWebRoute, method: string, payload: unknown): Promise<Invoked> {
|
||||
const body = Buffer.from(JSON.stringify(payload))
|
||||
const req = {
|
||||
method: 'POST',
|
||||
url: `/sidebar/api/${method}`,
|
||||
headers: { host: '127.0.0.1:3080' },
|
||||
[Symbol.asyncIterator]: async function* () { yield body },
|
||||
} as never
|
||||
const out = { status: 200, body: '' }
|
||||
const res = {
|
||||
writeHead: (status: number) => { out.status = status },
|
||||
end: (chunk: unknown) => { out.body += String(chunk ?? '') },
|
||||
} as never
|
||||
await route.handler(req, res)
|
||||
return { ...JSON.parse(out.body) as Invoked, status: out.status }
|
||||
}
|
||||
|
||||
describe('fs.createFile route', () => {
|
||||
it('creates the empty file the payload names and answers with its path', async () => {
|
||||
const workspace = await mkdtemp(join(tmpdir(), 'dsh-create-route-'))
|
||||
try {
|
||||
const route = mountApi(workspace)
|
||||
const result = await invoke(route, 'fs.createFile', { sessionId: 's', path: workspace, name: 'made.txt' })
|
||||
expect(result.ok).toBe(true)
|
||||
expect(result.status).toBe(200)
|
||||
expect(result.value?.path).toBe(join(workspace, 'made.txt'))
|
||||
expect(await readFile(join(workspace, 'made.txt'), 'utf8')).toBe('')
|
||||
} finally {
|
||||
await rm(workspace, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('maps a taken destination to 409/fs-error and a broken name to 400/bad-request', async () => {
|
||||
const workspace = await mkdtemp(join(tmpdir(), 'dsh-create-route-'))
|
||||
try {
|
||||
const route = mountApi(workspace)
|
||||
await writeFile(join(workspace, 'taken.txt'), 'keep')
|
||||
const taken = await invoke(route, 'fs.createFile', { sessionId: 's', path: workspace, name: 'taken.txt' })
|
||||
expect(taken.status).toBe(409)
|
||||
expect(taken.error?.code).toBe('fs-error')
|
||||
expect(taken.error?.message).toContain('already exists')
|
||||
expect(await readFile(join(workspace, 'taken.txt'), 'utf8')).toBe('keep')
|
||||
|
||||
const reserved = await invoke(route, 'fs.createFile', { sessionId: 's', path: workspace, name: 'CON' })
|
||||
expect(reserved.status).toBe(400)
|
||||
expect(reserved.error?.code).toBe('bad-request')
|
||||
|
||||
const traversal = await invoke(route, 'fs.createFile', { sessionId: 's', path: workspace, name: '../escape' })
|
||||
expect(traversal.status).toBe(400)
|
||||
expect(traversal.error?.code).toBe('bad-request')
|
||||
expect(await readdir(workspace)).toEqual(['taken.txt'])
|
||||
} finally {
|
||||
await rm(workspace, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user