diff --git a/external_plugins/batch-file-renamer/.zcode-plugin/plugin.json b/external_plugins/batch-file-renamer/.zcode-plugin/plugin.json new file mode 100644 index 00000000..fb3e31c7 --- /dev/null +++ b/external_plugins/batch-file-renamer/.zcode-plugin/plugin.json @@ -0,0 +1,56 @@ +{ + "name": "batch-file-renamer", + "version": "0.1.0", + "description": "Rename a whole folder of files by rules — find/replace or regex, name templates with numbering, dates and folder names, case and space clean-up, lower-case extensions and per-file manual names. See old → new for every file and every clash before anything changes, rename safely (swaps and case-only changes work), keep a log, and undo the last rename. Runs locally; no API keys.", + "description_i18n": { + "en": "Rename a whole folder of files by rules — find/replace or regex, name templates with numbering, dates and folder names, case and space clean-up, lower-case extensions and per-file manual names. See old → new for every file and every clash before anything changes, rename safely (swaps and case-only changes work), keep a log, and undo the last rename. Runs locally; no API keys.", + "zh-CN": "按规则批量重命名整个文件夹:查找替换或正则、带序号/日期/文件夹名的命名模板、大小写和空格整理、扩展名统一小写,也可逐个手动指定新名。改名前就能看到每个文件的“原名 → 新名”和所有冲突,安全执行(互换名字、只改大小写也没问题),留下改名记录,还能撤销上一次改名。在本地运行,无需 API 密钥。" + }, + "author": { + "name": "Penova", + "url": "https://github.com/ppppp2005-p" + }, + "license": "MIT", + "keywords": [ + "rename", + "batch rename", + "file names", + "regex", + "numbering", + "批量重命名", + "改名", + "文件名", + "序号", + "正则" + ], + "skills": "skills", + "mcpServers": { + "batch-file-renamer": { + "type": "stdio", + "command": "node", + "args": [ + "${ZCODE_PLUGIN_ROOT}/dist/server.mjs" + ], + "cwd": "${ZCODE_PROJECT_DIR}", + "timeoutMs": 900000, + "env": { + "ZCODE_WORKSPACE_ROOT": "${ZCODE_PROJECT_DIR}" + } + } + }, + "ui": { + "surfaces": [ + { + "id": "editor", + "title": { + "zh-CN": "批量重命名", + "en-US": "Batch File Renamer" + }, + "icon": "text-cursor-input", + "server": "batch-file-renamer", + "resourceUri": "ui://batch-file-renamer/panel.html", + "availability": "session" + } + ] + } +} diff --git a/external_plugins/batch-file-renamer/LICENSE b/external_plugins/batch-file-renamer/LICENSE new file mode 100644 index 00000000..67e98093 --- /dev/null +++ b/external_plugins/batch-file-renamer/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Penova + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/external_plugins/batch-file-renamer/README.md b/external_plugins/batch-file-renamer/README.md new file mode 100644 index 00000000..9cf31c9a --- /dev/null +++ b/external_plugins/batch-file-renamer/README.md @@ -0,0 +1,52 @@ +# Batch File Renamer + +Rename a whole folder of files by rules — find/replace or regex, name templates with numbering, dates and folder names, case and space clean-up, lower-case extensions and per-file manual names. See old → new for every file and every clash before anything changes, rename safely (swaps and case-only changes work), keep a log, and undo the last rename. Runs locally; no API keys. + +## Features + +- **Rules**: find/replace (plain or regex with $1), a name template with {name} {n} {date} {parent} {ext}, numbering start and digits, numbering by name or modified time. +- **Clean-up**: lower/UPPER/Title case, spaces to - or _ or removed, runs of spaces collapsed, extensions lower-cased, illegal characters (\ / : * ? " < > |) replaced. +- **Manual names**: type a new name for any file in the table; the extension is kept if you leave it out. +- **Safety**: duplicate targets, names that already belong to other files and broken regexes are errors and block the rename; renaming is two-step so swaps and case-only changes work, and it rolls back if something fails. +- **Undo**: the last rename is logged and can be reverted with the “Undo” button (it is never part of “Export all”). +- **Panel**: pick input files, adjust settings, see problems, edit any cell in the table, preview the result and export — all in the ZCode side panel. Edits are saved in `batch-file-renamer/.project.json` and kept until you re-open the inputs. + +## Usage + +Ask the agent in ZCode Desktop: + +- "Rename the photos in 相册/ to 杭州-001.jpg, 杭州-002.jpg … in date order" +- "In 扫描件/, replace “scan_” with “合同-” and make extensions lower-case" +- "Undo the last rename" + +## Tools + +| Tool | Purpose | +|---|---| +| `rename_open` | List the files in a workspace folder and preview their new names. Opens the panel | +| `rename_edit` | Change settings, edit cells by row, add or remove rows | +| `rename_status` | Show the current rows, issues and summary | +| `rename_export` | Write rename-plan.csv, rename the files on disk (with rename-log-*.csv), or undo the last rename | + +Output goes to `batch-file-renamer//` in the workspace. + +## Scope (v0.1) + +- Renames files only, not folders, inside the workspace; hidden files are skipped. +- Up to 5 folders and 5,000 files per project; subfolders are optional. +- Reading EXIF dates for photo names is a separate plugin (Photo Date Organizer). + +## Privacy, network and files + +- **Everything runs locally.** No network, no uploads, no API keys or accounts. +- Reads only the files you choose. Writes only the `batch-file-renamer/` folder in the workspace; it also renames files inside the folder you pick, but only when you click “Rename files” (or “Undo last rename”). No hooks. + +## Build and test (developers) + +- Source: `ui-plugins/batch-file-renamer/`. +- Build: `pnpm install --frozen-lockfile && pnpm build`, then add `dist/local-marketplace` as a local source. +- Tests: `pnpm --filter @penova/plugin-batch-file-renamer test` and `test:e2e` (needs Chrome; sample files in `test/samples/`). + +## Third-party components and licenses + +MIT licensed (author: Penova). Bundled: MCP SDK and ext-apps (MIT), zod (MIT); the full list is in `dist/THIRD_PARTY_NOTICES.txt`. diff --git a/external_plugins/batch-file-renamer/README_CN.md b/external_plugins/batch-file-renamer/README_CN.md new file mode 100644 index 00000000..5cb06e9d --- /dev/null +++ b/external_plugins/batch-file-renamer/README_CN.md @@ -0,0 +1,52 @@ +# 批量重命名 + +按规则批量重命名整个文件夹:查找替换或正则、带序号/日期/文件夹名的命名模板、大小写和空格整理、扩展名统一小写,也可逐个手动指定新名。改名前就能看到每个文件的“原名 → 新名”和所有冲突,安全执行(互换名字、只改大小写也没问题),留下改名记录,还能撤销上一次改名。在本地运行,无需 API 密钥。 + +## 功能 + +- **规则**:查找替换(普通文本或正则,可用 $1)、命名模板 {name} {n} {date} {parent} {ext}、起始序号和位数,按文件名或修改时间编号。 +- **整理**:全小写/全大写/首字母大写,空格改成 - 或 _ 或去掉,合并连续空格,扩展名统一小写,非法字符(\ / : * ? " < > |)自动替换。 +- **手动改名**:在表格里给任意文件填新名字,不写扩展名就保留原扩展名。 +- **安全**:新名字重复、和其他文件撞名、正则写错都会报错并阻止改名;改名分两步,互换名字和只改大小写都能正确处理,中途出错会自动还原。 +- **撤销**:上一次改名有记录,可用“撤销上次改名”按钮还原(“全部导出”不会触发撤销)。 +- **面板**:在 ZCode 侧栏里选择输入文件、调整设置、查看问题、直接修改表格里的任意单元格、预览成品并导出。修改保存在 `batch-file-renamer/<项目>.project.json`,重新打开输入文件前一直保留。 + +## 使用方法 + +在 ZCode 桌面端对助手说: + +- “把 相册/ 里的照片按时间顺序改成 杭州-001.jpg、杭州-002.jpg……” +- “扫描件/ 里把“scan_”换成“合同-”,扩展名统一小写” +- “撤销刚才的改名” + +## 工具 + +| 工具 | 作用 | +|---|---| +| `rename_open` | 列出工作区文件夹里的文件并预览新文件名,并打开面板 | +| `rename_edit` | 修改设置、按行修改单元格、新增或删除行 | +| `rename_status` | 查看当前数据、问题和汇总 | +| `rename_export` | 导出改名清单 rename-plan.csv、实际改名(附 rename-log-*.csv),或撤销上次改名 | + +导出文件写到工作区的 `batch-file-renamer/<项目>/` 文件夹。 + +## 范围(v0.1) + +- 只改文件名、不改文件夹名,范围限于工作区;隐藏文件会跳过。 +- 每个项目最多 5 个文件夹、5,000 个文件;子文件夹可选。 +- 按照片 EXIF 拍摄日期命名请用另一个插件(照片按日期整理)。 + +## 隐私、网络与文件 + +- **全部在本地运行。** 不联网、不上传,不需要 API 密钥或账号。 +- 只读取你选择的文件,只写入工作区的 `batch-file-renamer/` 文件夹;另外只有在你点“执行改名”(或“撤销上次改名”)时,才会重命名你所选文件夹里的文件。没有 Hook。 + +## 构建与测试(开发者) + +- 源码:`ui-plugins/batch-file-renamer/`。 +- 构建:`pnpm install --frozen-lockfile && pnpm build`,然后把 `dist/local-marketplace` 添加为本地来源。 +- 测试:`pnpm --filter @penova/plugin-batch-file-renamer test` 和 `test:e2e`(需要 Chrome;样例文件在 `test/samples/`)。 + +## 第三方组件与许可证 + +MIT 许可(作者:Penova)。打包的组件:MCP SDK 与 ext-apps(MIT)、zod(MIT);完整列表见 `dist/THIRD_PARTY_NOTICES.txt`。 diff --git a/external_plugins/batch-file-renamer/skills/batch-file-renamer/SKILL.md b/external_plugins/batch-file-renamer/skills/batch-file-renamer/SKILL.md new file mode 100644 index 00000000..eeee16f9 --- /dev/null +++ b/external_plugins/batch-file-renamer/skills/batch-file-renamer/SKILL.md @@ -0,0 +1,15 @@ +--- +name: batch-file-renamer +description: 按规则批量重命名整个文件夹:查找替换或正则、带序号/日期/文件夹名的命名模板、大小写和空格整理、扩展名统一小写,也可逐个手动指定新名。改名前就能看到每个文件的“原名 → 新名”和所有冲突,安全执行(互换名字、只改大小写也没问题),留下改名记录,还能撤销上一次改名。在本地运行,无需 API 密钥。 用户提到“批量改名 / 重命名 / 改文件名 / 文件名加序号 / 撤销改名”时使用。 +--- + +# 批量重命名 + +1. `rename_open(inputs, settings?, project?)`:列出工作区文件夹里的文件并预览新文件名。inputs 是工作区相对路径。 + - 结果里有汇总、问题列表(错误 / 提醒)和前几行数据,每行有编号 `#n`。 + - inputs 传文件夹路径;只改某类文件用 settings.only(如 "jpg,png");要子文件夹设 recursive: true。 +2. 向用户简要说明结果,先说错误和需要确认的地方,不要逐行念。 +3. 用户要改时调用 `rename_edit(project, settings?, set?: [{row, values}], add?, remove?)`。 + - 规则写在 settings(find/replace/regex/template/start/pad/case/spaces/extCase/sort);单个文件用 `set: [{row, values: {override: "新名"}}]`。 +4. `rename_export(project, formats?)`:导出改名清单 rename-plan.csv、实际改名(附 rename-log-*.csv),或撤销上次改名。把文件路径告诉用户。 +5. 先 `rename_export` 用 formats ["plan"] 给用户看清单;用户确认后再 formats ["rename"]。撤销用 formats ["undo"]。有 error 时不要尝试改名。 diff --git a/marketplace.json b/marketplace.json index 32e8c8ef..9a4f21a6 100644 --- a/marketplace.json +++ b/marketplace.json @@ -1673,6 +1673,54 @@ "把上一个 Hi3D 任务生成的模型按角色拆分成部件" ] } + }, + { + "name": "batch-file-renamer", + "componentTypes": [ + "ui" + ], + "source": "./external_plugins/batch-file-renamer", + "displayName": "Batch File Renamer", + "displayName_i18n": { + "en": "Batch File Renamer", + "zh-CN": "批量重命名" + }, + "description": "Rename a whole folder of files by rules — find/replace or regex, name templates with numbering, dates and folder names, case and space clean-up, lower-case extensions and per-file manual names. See old → new for every file and every clash before anything changes, rename safely (swaps and case-only changes work), keep a log, and undo the last rename. Runs locally; no API keys.", + "description_i18n": { + "en": "Rename a whole folder of files by rules — find/replace or regex, name templates with numbering, dates and folder names, case and space clean-up, lower-case extensions and per-file manual names. See old → new for every file and every clash before anything changes, rename safely (swaps and case-only changes work), keep a log, and undo the last rename. Runs locally; no API keys.", + "zh-CN": "按规则批量重命名整个文件夹:查找替换或正则、带序号/日期/文件夹名的命名模板、大小写和空格整理、扩展名统一小写,也可逐个手动指定新名。改名前就能看到每个文件的“原名 → 新名”和所有冲突,安全执行(互换名字、只改大小写也没问题),留下改名记录,还能撤销上一次改名。在本地运行,无需 API 密钥。" + }, + "version": "0.1.0", + "author": { + "name": "Penova", + "url": "https://github.com/ppppp2005-p" + }, + "license": "MIT", + "category": "productivity", + "keywords": [ + "rename", + "batch rename", + "file names", + "regex", + "numbering", + "批量重命名", + "改名", + "文件名", + "序号", + "正则" + ], + "examplePrompts": [ + "Rename the photos in 相册/ to 杭州-001.jpg, 杭州-002.jpg … in date order", + "In 扫描件/, replace “scan_” with “合同-” and make extensions lower-case", + "Undo the last rename" + ], + "examplePrompts_i18n": { + "zh-CN": [ + "把 相册/ 里的照片按时间顺序改成 杭州-001.jpg、杭州-002.jpg……", + "扫描件/ 里把“scan_”换成“合同-”,扩展名统一小写", + "撤销刚才的改名" + ] + } } ] } \ No newline at end of file diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 14b35f76..98dc042d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -42,6 +42,37 @@ importers: specifier: 4.6.5 version: 4.6.5 + ui-plugins/batch-file-renamer: + dependencies: + '@modelcontextprotocol/sdk': + specifier: 1.29.0 + version: 1.29.0(zod@4.6.5) + zod: + specifier: ^4.6.5 + version: 4.6.5 + devDependencies: + '@modelcontextprotocol/core': + specifier: 2.0.0 + version: 2.0.0 + '@modelcontextprotocol/ext-apps': + specifier: 2.0.0 + version: 2.0.0(@modelcontextprotocol/client@2.2.0)(@modelcontextprotocol/core@2.0.0)(@modelcontextprotocol/server@2.0.0)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.5) + '@types/node': + specifier: 25.5.0 + version: 25.5.0 + esbuild: + specifier: ^0.25.12 + version: 0.25.12 + playwright-core: + specifier: 1.59.1 + version: 1.59.1 + typescript: + specifier: 6.0.2 + version: 6.0.2 + vitest: + specifier: 4.1.4 + version: 4.1.4(@opentelemetry/api@1.9.1)(@types/node@25.5.0)(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.0)) + ui-plugins/cadcraft: {} ui-plugins/craft-runtime: {} @@ -2475,10 +2506,6 @@ packages: resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==} engines: {node: '>= 0.6'} - eventsource-parser@3.1.0: - resolution: {integrity: sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg==} - engines: {node: '>=18.0.0'} - eventsource-parser@3.1.1: resolution: {integrity: sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==} engines: {node: '>=18.0.0'} @@ -2714,9 +2741,6 @@ packages: jose@6.2.12: resolution: {integrity: sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==} - jose@6.2.2: - resolution: {integrity: sha512-d7kPDd34KO/YnzaDOlikGpOurfF0ByC2sEV4cANCtdqLlTfBlw2p14O/5d/zv40gJPbIQxfES3nSx1/oYNyuZQ==} - jotai-scope@0.7.2: resolution: {integrity: sha512-Gwed97f3dDObrO43++2lRcgOqw4O2sdr4JCjP/7eHK1oPACDJ7xKHGScpJX9XaflU+KBHXF+VhwECnzcaQiShg==} peerDependencies: @@ -3068,10 +3092,6 @@ packages: resolution: {integrity: sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==} engines: {node: '>=8.6'} - picomatch@4.0.4: - resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==} - engines: {node: '>=12'} - picomatch@4.0.7: resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} engines: {node: '>=12'} @@ -3383,18 +3403,10 @@ packages: tinybench@2.9.0: resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} - tinyexec@1.1.1: - resolution: {integrity: sha512-VKS/ZaQhhkKFMANmAOhhXVoIfBXblQxGX1myCQ2faQrfmobMftXeJPcZGp0gS07ocvGJWDLZGyOZDadDBqYIJg==} - engines: {node: '>=18'} - tinyexec@1.3.1: resolution: {integrity: sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==} engines: {node: '>=18'} - tinyglobby@0.2.16: - resolution: {integrity: sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==} - engines: {node: '>=12.0.0'} - tinyglobby@0.2.17: resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} engines: {node: '>=12.0.0'} @@ -3742,7 +3754,7 @@ snapshots: '@antfu/install-pkg@1.1.0': dependencies: package-manager-detector: 1.6.0 - tinyexec: 1.1.1 + tinyexec: 1.3.1 '@atlaskit/pragmatic-drag-and-drop-hitbox@1.2.0': dependencies: @@ -4285,11 +4297,11 @@ snapshots: cors: 2.8.6 cross-spawn: 7.0.6 eventsource: 3.0.7 - eventsource-parser: 3.1.0 + eventsource-parser: 3.1.1 express: 5.2.1 express-rate-limit: 8.3.2(express@5.2.1) hono: 4.12.12 - jose: 6.2.2 + jose: 6.2.12 json-schema-typed: 8.0.2 pkce-challenge: 5.0.1 raw-body: 3.0.2 @@ -5809,13 +5821,11 @@ snapshots: etag@1.8.1: {} - eventsource-parser@3.1.0: {} - eventsource-parser@3.1.1: {} eventsource@3.0.7: dependencies: - eventsource-parser: 3.1.0 + eventsource-parser: 3.1.1 expect-type@1.4.0: {} @@ -5869,10 +5879,6 @@ snapshots: fast-uri@3.1.0: {} - fdir@6.5.0(picomatch@4.0.4): - optionalDependencies: - picomatch: 4.0.4 - fdir@6.5.0(picomatch@4.0.7): optionalDependencies: picomatch: 4.0.7 @@ -6048,8 +6054,6 @@ snapshots: jose@6.2.12: {} - jose@6.2.2: {} - jotai-scope@0.7.2(jotai@2.11.0(@types/react@19.2.14)(react@19.2.7))(react@19.2.7): dependencies: jotai: 2.11.0(@types/react@19.2.14)(react@19.2.7) @@ -6406,8 +6410,6 @@ snapshots: picomatch@2.3.2: {} - picomatch@4.0.4: {} - picomatch@4.0.7: {} pirates@4.0.7: {} @@ -6745,7 +6747,7 @@ snapshots: lines-and-columns: 1.2.4 mz: 2.7.0 pirates: 4.0.7 - tinyglobby: 0.2.16 + tinyglobby: 0.2.17 ts-interface-checker: 0.1.13 svg-pathdata@6.0.3: @@ -6779,15 +6781,8 @@ snapshots: tinybench@2.9.0: {} - tinyexec@1.1.1: {} - tinyexec@1.3.1: {} - tinyglobby@0.2.16: - dependencies: - fdir: 6.5.0(picomatch@4.0.4) - picomatch: 4.0.4 - tinyglobby@0.2.17: dependencies: fdir: 6.5.0(picomatch@4.0.7) diff --git a/ui-plugins/batch-file-renamer/package.json b/ui-plugins/batch-file-renamer/package.json new file mode 100644 index 00000000..e6442129 --- /dev/null +++ b/ui-plugins/batch-file-renamer/package.json @@ -0,0 +1,32 @@ +{ + "name": "@penova/plugin-batch-file-renamer", + "version": "0.1.0", + "private": true, + "license": "MIT", + "type": "module", + "scripts": { + "build": "node scripts/build.mjs", + "typecheck": "tsc -p tsconfig.json --noEmit", + "test": "vitest run", + "test:e2e": "node --experimental-strip-types scripts/e2e.mts" + }, + "zcode": { + "title": "Batch File Renamer" + }, + "engines": { + "node": ">=22.0.0" + }, + "dependencies": { + "@modelcontextprotocol/sdk": "1.29.0", + "zod": "^4.6.5" + }, + "devDependencies": { + "@modelcontextprotocol/core": "2.0.0", + "@modelcontextprotocol/ext-apps": "2.0.0", + "@types/node": "25.5.0", + "esbuild": "^0.25.12", + "playwright-core": "1.59.1", + "typescript": "6.0.2", + "vitest": "4.1.4" + } +} diff --git a/ui-plugins/batch-file-renamer/scripts/build.mjs b/ui-plugins/batch-file-renamer/scripts/build.mjs new file mode 100644 index 00000000..02ff90d4 --- /dev/null +++ b/ui-plugins/batch-file-renamer/scripts/build.mjs @@ -0,0 +1,74 @@ +import { build } from "esbuild"; +import { copyFile, cp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { createRequire } from "node:module"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { writeNotices } from "./licenses.mjs"; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const dist = join(root, "dist"); +const pkg = JSON.parse(await readFile(join(root, "package.json"), "utf8")); +await rm(dist, { recursive: true, force: true }); +await mkdir(join(dist, "ui"), { recursive: true }); + +// 宿主只提供 HTML 本身,JS 与 CSS 全部内联到一个页面里。 +const ui = await build({ + metafile: true, + entryPoints: [join(root, "ui/main.ts")], + bundle: true, + format: "iife", + platform: "browser", + target: "es2022", + minify: true, + write: false, + outdir: join(dist, "ui"), + legalComments: "none", + loader: { ".css": "text" }, +}); +const js = ui.outputFiles.find((file) => file.path.endsWith(".js")).text; +const escape = (text) => text.replace(/<\/script/gi, "<\\/script"); +const html = `${pkg.zcode?.title ?? pkg.name}
`; +const htmlBytes = Buffer.byteLength(html); +if (htmlBytes > 4 * 1024 * 1024 - 64 * 1024) throw new Error(`panel.html is ${Math.round(htmlBytes / 1024)} KiB; keep it below 4 MiB`); +await writeFile(join(dist, "ui/panel.html"), html); + +// 用不到、且许可证不明的可选依赖(package.json 的 zcode.stub)替换为空模块。 +const stubs = pkg.zcode?.stub ?? []; +const stubPlugin = { + name: "stub", + setup(b) { + if (!stubs.length) return; + const filter = new RegExp(`^(${stubs.map((s) => s.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")).join("|")})$`); + b.onResolve({ filter }, (args) => ({ path: args.path, namespace: "stub" })); + b.onLoad({ filter: /.*/, namespace: "stub" }, () => ({ contents: "module.exports = {};", loader: "js" })); + }, +}; + +const server = await build({ + plugins: [stubPlugin], + metafile: true, + entryPoints: [join(root, "src/main.ts")], + outfile: join(dist, "server.mjs"), + bundle: true, + platform: "node", + format: "esm", + target: "node22", + legalComments: "none", + banner: { + js: 'import { createRequire as __createRequire } from "node:module"; const require=__createRequire(import.meta.url);', + }, +}); + +// 运行时需要的 wasm 等文件(package.json 的 zcode.assets:{ 包内路径: 输出文件名 })。 +const require = createRequire(join(root, "package.json")); +for (const [from, to] of Object.entries(pkg.zcode?.assets ?? {})) await copyFile(require.resolve(from), join(dist, to)); + +// 整个目录(package.json 的 zcode.dirs:{ "包名:子目录": 输出目录 }),例如 pdf.js 的 CMap。 +for (const [spec, to] of Object.entries(pkg.zcode?.dirs ?? {})) { + const [name, sub] = spec.split(":"); + const base = dirname(require.resolve(`${name}/package.json`)); + await cp(join(base, sub), join(dist, to), { recursive: true, filter: (path) => !/(_nowasm_fallback\.js|quickjs-eval\.(js|wasm))$/.test(path) }); +} + +await writeNotices([ui.metafile, server.metafile], join(dist, "THIRD_PARTY_NOTICES.txt"), Object.keys(pkg.zcode?.assets ?? {})); +process.stdout.write(`${pkg.name}: panel ${Math.round(htmlBytes / 1024)} KiB, server ${Math.round((await readFile(join(dist, "server.mjs"))).length / 1024)} KiB\n`); diff --git a/ui-plugins/batch-file-renamer/scripts/e2e.mts b/ui-plugins/batch-file-renamer/scripts/e2e.mts new file mode 100644 index 00000000..918c9e73 --- /dev/null +++ b/ui-plugins/batch-file-renamer/scripts/e2e.mts @@ -0,0 +1,79 @@ +// 浏览器端到端测试:真实打包的 server + 官方 AppBridge 宿主 + 隔离 iframe 中的面板。需要 Chrome。 +// 场景写在 test/e2e.json:用户在面板里选文件打开 → Agent 修改 → 用户在表格里改一格 → 导出。 +import assert from "node:assert/strict"; +import { cp, mkdir, mkdtemp, readFile, stat } from "node:fs/promises"; +import { existsSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { startHarness } from "./harness.mjs"; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const pkg = JSON.parse(await readFile(join(root, "package.json"), "utf8")); +const name = pkg.name.replace("@penova/plugin-", ""); +const spec = JSON.parse(await readFile(join(root, "test/e2e.json"), "utf8")); +const shots = process.env.E2E_SHOTS ?? join(tmpdir(), `${name}-shots`); +await mkdir(shots, { recursive: true }); +const workspace = await mkdtemp(join(tmpdir(), `${name}-e2e-`)); +const samples = process.env.SAMPLES ?? join(root, "test/samples"); +if (existsSync(samples)) await cp(samples, join(workspace, spec.folder ?? "samples"), { recursive: true }); + +const harness = await startHarness({ workspace }); +const step = (text: string) => process.stdout.write(`• ${text}\n`); +let failShot: (() => Promise) | undefined; +try { + const { outer, frame } = await harness.open("?locale=zh-CN", { width: 1400, height: 950 }); + failShot = () => outer.screenshot({ path: join(shots, "failed.png") }); + step("user picks the sample in the panel and opens it"); + await frame.locator(".start").waitFor(); + for (const pick of spec.pick ?? []) await frame.locator("label.file", { hasText: pick }).first().click(); + for (const [key, value] of Object.entries(spec.startSettings ?? {})) { + const el = frame.locator(`.settings [data-key="${key}"]`); + if (typeof value === "boolean") await el.setChecked(value); + else if ((await el.evaluate((e) => e.tagName)) === "SELECT") await el.selectOption(String(value)); + else await el.fill(String(value)); + } + await frame.locator("button.open").click(); + await frame.locator(".project .summary").waitFor(); + const project = (await frame.locator(".pname").textContent())!.trim(); + if (spec.edit) { + step("agent edits the project"); + await harness.agent(outer, `${spec.prefix}_edit`, { project, ...spec.edit }); + } + if (spec.uiEdit) { + step("user edits a cell in the table"); + const input = frame.locator(`tr[data-row="${spec.uiEdit.row}"] td[data-key="${spec.uiEdit.key}"] input`); + await input.fill(String(spec.uiEdit.value)); + await input.press("Enter"); + await input.blur(); + await frame.waitForTimeout(800); + } + if (spec.expectText) await frame.locator("#root", { hasText: spec.expectText }).waitFor(); + await frame.waitForTimeout(400); + await outer.screenshot({ path: join(shots, "01-panel.png") }); + step("user exports"); + const all = frame.locator("button.expall"); + if (await all.count()) await all.click(); + else await frame.locator("button.exp").first().click(); + await frame.locator(".exported li").first().waitFor({ timeout: 300_000 }); + await frame.waitForTimeout(300); + await outer.screenshot({ path: join(shots, "02-exported.png") }); + const files = await frame.locator(".exported li").allTextContents(); + for (const f of files) assert.ok((await stat(join(workspace, f.trim()))).size > 0, `${f} is empty`); + for (const pattern of spec.expectFiles ?? []) assert.ok(files.some((f) => new RegExp(pattern).test(f)), `expected an exported file matching ${pattern}; got ${files.join(", ")}`); + + step("English panel"); + const en = await harness.open("?locale=en-US&theme=dark", { width: 1400, height: 950 }); + await harness.agent(en.outer, `${spec.prefix}_status`, { project }); + await en.frame.locator(".project .summary").waitFor(); + await en.frame.waitForTimeout(400); + await en.outer.screenshot({ path: join(shots, "03-en-dark.png") }); + assert.deepEqual(harness.errors, []); + step(`ok — ${files.length} file(s) exported; screenshots in ${shots}`); +} catch (error) { + await failShot?.().catch(() => undefined); + console.error("page errors:", harness.errors, harness.stderr.join("")); + throw error; +} finally { + await harness.close(); +} diff --git a/ui-plugins/batch-file-renamer/scripts/harness.mjs b/ui-plugins/batch-file-renamer/scripts/harness.mjs new file mode 100644 index 00000000..a45e6e41 --- /dev/null +++ b/ui-plugins/batch-file-renamer/scripts/harness.mjs @@ -0,0 +1,162 @@ +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import { readFile } from "node:fs/promises"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { build } from "esbuild"; +import { chromium } from "playwright-core"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; +import { ResourceUpdatedNotificationSchema } from "@modelcontextprotocol/sdk/types.js"; + +/** + * 浏览器测试宿主:真实打包的 server(stdio)+ 官方 AppBridge 宿主页 + 隔离 iframe 中的面板。 + * 宿主页用与 ZCode 相同的 CSP 约束面板。测试脚本同时扮演 Agent:经同一个 MCP 连接调用工具, + * 并像宿主一样把结果推给页面。 + */ +const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); + +// 与 ZCode 给 MCP App 页面的限制一致:没有网络,允许 wasm(声明了 zcode/csp.wasmUnsafeEval)。 +export const PANEL_CSP = + "default-src 'none'; script-src 'self' 'unsafe-inline' blob: data: 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; media-src 'self' data: blob:; worker-src 'self' blob:; connect-src 'none'; frame-src 'none'; base-uri 'self'; form-action 'none'"; + +/** server:要运行的 server 入口(默认真实打包的 dist/server.mjs)。 */ +export async function startHarness({ env = {}, workspace, server = join(root, "dist/server.mjs") }) { + const client = new Client({ name: "kit-harness", version: "1" }); + const sseClients = new Set(); + client.setNotificationHandler(ResourceUpdatedNotificationSchema, (notification) => { + for (const response of sseClients) response.write(`data: ${JSON.stringify(notification.params)}\n\n`); + }); + const stderr = []; + const transport = new StdioClientTransport({ + command: process.execPath, + args: [server], + cwd: workspace, + env: { ...process.env, ZCODE_WORKSPACE_ROOT: workspace, ...env }, + stderr: "pipe", + }); + transport.stderr?.on("data", (chunk) => stderr.push(String(chunk))); + await client.connect(transport); + const html = await readFile(join(root, "dist/ui/panel.html"), "utf8"); + const hostJs = await build({ + stdin: { + contents: ` +import { AppBridge, PostMessageTransport } from "@modelcontextprotocol/ext-apps/app-bridge"; +import { z } from "zod"; +const WidgetState = z.object({ method: z.literal('ui/set-widget-state'), params: z.object({ widgetState: z.unknown() }) }); +const rpc = async (method, args) => { + const response = await fetch('/rpc', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({method,args})}); + const result = await response.json(); if (!response.ok) throw Error(result.error); return result; +}; +const params = new URLSearchParams(location.search); +const context = { theme: params.get('theme') || 'light', locale: params.get('locale') || 'en-US', displayMode: params.get('mode') || 'fullscreen' }; +const bridge = new AppBridge(null, {name:"kit-harness",version:"1"}, { + serverTools:{}, serverResources:{ listChanged: true }, message:{text:{}}, updateModelContext:{text:{}, structuredContent:{}}, openLinks:{}, + experimental: params.get('nosub') ? { "zcode/widgetState": {} } : { "zcode/resourceSubscribe": {}, "zcode/widgetState": {} }, +}, {hostContext:{...context, "zcode/widgetState": JSON.parse(sessionStorage.getItem('widgetState') || 'null')}}); +window.__messages = []; +window.__context = []; +window.__links = []; +window.__calls = []; +window.__initializations = 0; +bridge.oncalltool = (args) => { window.__calls.push(args.name); return rpc('callTool', args); }; +bridge.onreadresource = (args) => rpc('readResource', args); +bridge.onmessage = async (params) => { window.__messages.push(params.content[0].text); return {}; }; +bridge.onupdatemodelcontext = async (params) => { window.__context.push(params); return {}; }; +bridge.onopenlink = async (params) => { window.__links.push(params.url); return {}; }; +bridge.setRequestHandler('resources/subscribe', async (request) => { await rpc('subscribe', { uri: request.params.uri }); return {}; }); +bridge.setRequestHandler('resources/unsubscribe', async (request) => { await rpc('unsubscribe', { uri: request.params.uri }); return {}; }); +bridge.setRequestHandler(WidgetState, async (request) => { sessionStorage.setItem('widgetState', JSON.stringify(request.params.widgetState)); return {}; }); +bridge.oninitialized = () => { window.__initializations++; }; +window.__sendToolResult = (result) => bridge.sendToolResult(result); +window.__setContext = (patch) => bridge.setHostContext({ ...context, ...patch }); +new EventSource('/events').onmessage = (event) => { + bridge.notification({ method: 'notifications/resources/updated', params: JSON.parse(event.data) }); +}; +const frame = document.querySelector('iframe'); +await bridge.connect(new PostMessageTransport(frame.contentWindow, frame.contentWindow)); +frame.src = '/panel'; +`, + resolveDir: root, + sourcefile: "browser-host.mjs", + }, + bundle: true, + format: "esm", + platform: "browser", + write: false, + }); + const http = createServer(async (request, response) => { + try { + const url = new URL(request.url, "http://localhost"); + if (url.pathname === "/") { + response.setHeader("Content-Type", "text/html; charset=utf-8"); + response.end( + '', + ); + } else if (url.pathname === "/host.js") { + response.setHeader("Content-Type", "text/javascript"); + response.end(hostJs.outputFiles[0].text); + } else if (url.pathname === "/panel") { + response.setHeader("Content-Type", "text/html; charset=utf-8"); + response.setHeader("Content-Security-Policy", PANEL_CSP); + response.end(html); + } else if (url.pathname === "/events") { + response.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" }); + response.write(": connected\n\n"); + sseClients.add(response); + request.on("close", () => sseClients.delete(response)); + } else if (request.method === "POST" && url.pathname === "/rpc") { + let body = ""; + for await (const chunk of request) body += chunk; + const { method, args } = JSON.parse(body); + const result = + method === "readResource" + ? await client.readResource(args) + : method === "subscribe" + ? await client.subscribeResource(args) + : method === "unsubscribe" + ? await client.unsubscribeResource(args) + : await client.callTool(args, undefined, { timeout: 300_000 }); + response.setHeader("Content-Type", "application/json"); + response.end(JSON.stringify(result ?? {})); + } else if (url.pathname === "/favicon.ico") response.writeHead(204).end(); + else response.writeHead(404).end(); + } catch (error) { + response.writeHead(500, { "Content-Type": "application/json" }).end(JSON.stringify({ error: String(error) })); + } + }); + await new Promise((done) => http.listen(0, "127.0.0.1", done)); + const base = `http://127.0.0.1:${http.address().port}`; + const browser = await chromium.launch(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : { channel: "chrome" }); + const errors = []; + const contexts = []; + + const open = async (query = "", viewport = { width: 720, height: 900 }) => { + const context = await browser.newContext({ viewport, deviceScaleFactor: 2 }); + contexts.push(context); + const outer = await context.newPage(); + outer.on("pageerror", (error) => errors.push(String(error))); + outer.on("console", (message) => { + if (message.type() === "error" && !/favicon/.test(message.text())) errors.push(message.text()); + }); + await outer.goto(`${base}/${query}`); + await outer.waitForFunction(() => window.__initializations === 1); + const frame = outer.frames().find((item) => item !== outer.mainFrame()); + assert.ok(frame, "official App iframe exists"); + return { outer, frame, context }; + }; + /** 扮演 Agent:调用工具,再像宿主一样把结果推给页面。 */ + const agent = async (outer, name, args, { expectError = false } = {}) => { + const result = await client.callTool({ name, arguments: args }, undefined, { timeout: 300_000 }); + if (expectError) assert.ok(result.isError, `${name} should fail`); + else assert.ok(!result.isError, `${name}: ${JSON.stringify(result.content)}`); + if (outer) await outer.evaluate((value) => window.__sendToolResult(value), result); + return result; + }; + const close = async () => { + await browser.close().catch(() => undefined); + await client.close().catch(() => undefined); + http.close(); + }; + return { client, open, agent, close, errors, stderr, base, contexts: () => contexts.filter((context) => context.pages().length) }; +} diff --git a/ui-plugins/batch-file-renamer/scripts/licenses.mjs b/ui-plugins/batch-file-renamer/scripts/licenses.mjs new file mode 100644 index 00000000..5107fe7c --- /dev/null +++ b/ui-plugins/batch-file-renamer/scripts/licenses.mjs @@ -0,0 +1,43 @@ +import { readFile, readdir, writeFile } from "node:fs/promises"; +import { dirname, join, resolve } from "node:path"; + +// 从实际参与打包的模块收集许可证,避免只列直接依赖而漏掉 Canvas/SDK 的传递依赖。 +export async function writeNotices(metafiles, destination, extra = []) { + const packages = new Map(); + const { createRequire } = await import("node:module"); + const require = createRequire(resolve("package.json")); + const extraInputs = extra.map((spec) => require.resolve(spec)); + for (const input of [...metafiles.flatMap((meta) => Object.keys(meta.inputs)), ...extraInputs]) { + if (!input.includes("node_modules/")) continue; + let directory = dirname(resolve(input)); + while (directory.includes("node_modules")) { + try { + const pkg = JSON.parse(await readFile(join(directory, "package.json"), "utf8")); + if (pkg.name && pkg.version) { + packages.set(directory, pkg); + break; + } + } catch (error) { + if (error.code !== "ENOENT") throw error; + } + directory = dirname(directory); + } + } + const notices = []; + const seen = new Set(); + for (const [directory, pkg] of [...packages].sort((a, b) => a[1].name.localeCompare(b[1].name))) { + const key = `${pkg.name}@${pkg.version}`; + if (seen.has(key)) continue; + seen.add(key); + const files = (await readdir(directory)).filter((name) => + /^(license|copying|notice)([.-]|$)/i.test(name), + ); + const texts = await Promise.all(files.map((file) => readFile(join(directory, file), "utf8"))); + if (!texts.length && !pkg.license) throw new Error(`Missing license for bundled dependency ${key}`); + if (!texts.length) texts.push(`(No license file is shipped in this package; its package.json declares the ${pkg.license} license.)`); + notices.push( + `${key} — ${typeof pkg.license === "string" ? pkg.license : JSON.stringify(pkg.license)}\n${texts.join("\n\n")}`, + ); + } + await writeFile(destination, notices.join("\n\n----------------------------------------\n\n")); +} diff --git a/ui-plugins/batch-file-renamer/src/kit/app.ts b/ui-plugins/batch-file-renamer/src/kit/app.ts new file mode 100644 index 00000000..b3acd847 --- /dev/null +++ b/ui-plugins/batch-file-renamer/src/kit/app.ts @@ -0,0 +1,395 @@ +import { readFile } from "node:fs/promises"; +import { join } from "node:path"; +import { z } from "zod"; +import { createKitServer } from "./server-kit.ts"; +import { KitError, safeFileName, Workspace } from "./workspace.ts"; + +/** 双语文案:[中文, English]。 */ +export type L = [string, string]; +export type Row = Record; + +export interface Field { + key: string; + label: L; + type: "text" | "number" | "bool" | "select" | "color" | "textarea" | "date"; + options?: { value: string; label: L }[]; + default?: unknown; + help?: L; + min?: number; + max?: number; + /** 改了需要重新读取输入文件。 */ + reload?: boolean; +} + +export interface Column { + key: string; + label: L; + type?: "text" | "number" | "bool" | "select" | "date"; + options?: string[]; + readOnly?: boolean; + wide?: boolean; +} + +export interface Issue { + level: "error" | "warn" | "info"; + message: string; + row?: number; + key?: string; +} + +export interface Project { + name: string; + inputs: string[]; + settings: Record; + rows: Row[]; + meta: Record; + exported?: string[]; + created: string; + updated: string; +} + +export interface Computed { + /** 与 project.rows 一一对应(同顺序),可附加只读的计算列。 */ + rows?: Row[]; + issues?: Issue[]; + summary: string; + /** 面板预览:由插件生成、已转义的 HTML(可含 data: 图片)。 */ + preview?: string; + stats?: Record; +} + +export interface AppCtx { + ws: Workspace; + assetRoot: string; + log: (line: string) => void; +} + +export interface ExportCtx extends AppCtx { + project: Project; + computed: Computed; + outDir: string; + /** 写入导出目录下的文件,返回工作区相对路径。 */ + write: (name: string, data: Uint8Array | string) => Promise; +} + +export interface ExportDef { + id: string; + label: L; + description: string; + run: (ctx: ExportCtx) => Promise; + /** 不包含在“全部导出”里,只有点名时才运行(例如撤销)。 */ + manual?: boolean; +} + +export interface AppDef { + name: string; + version: string; + /** 工具名前缀,例如 "invoice" → invoice_open。 */ + prefix: string; + title: L; + /** invoice_open 的说明(给 Agent 看)。 */ + openDescription: string; + inputs: { exts: string[]; min: number; max: number; label: L; folders?: boolean }; + settings: Field[]; + columns: (project: Project) => Column[]; + load: (ctx: AppCtx & { files: string[]; settings: Record }) => Promise<{ rows: Row[]; meta?: Record }>; + compute: (project: Project, ctx: AppCtx) => Promise | Computed; + exports: ExportDef[]; + /** 允许在面板 / 工具里新增行时的空白行。 */ + newRow?: (project: Project) => Row; + /** 行描述(给 Agent 的文字列表),默认取前几列。 */ + describeRow?: (row: Row, index: number) => string; +} + +const MAX_ROWS_PANEL = 3000; + +export function coerceSettings(fields: Field[], input: Record | undefined, base: Record = {}) { + const out: Record = {}; + for (const field of fields) { + let value = input && field.key in input ? input[field.key] : field.key in base ? base[field.key] : field.default; + if (value === undefined || value === null) { + if (field.default !== undefined) out[field.key] = field.default; + continue; + } + if (field.type === "number") { + const n = typeof value === "number" ? value : Number(String(value).trim()); + if (!Number.isFinite(n)) throw new KitError("bad_setting", `${field.key} must be a number (got ${JSON.stringify(value)}).`); + value = Math.min(field.max ?? Infinity, Math.max(field.min ?? -Infinity, n)); + } else if (field.type === "bool") value = value === true || value === "true" || value === 1 || value === "1" || value === "yes"; + else if (field.type === "select") { + value = String(value); + if (field.options && !field.options.some((o) => o.value === value)) throw new KitError("bad_setting", `${field.key} must be one of ${field.options.map((o) => o.value).join(", ")} (got ${value}).`); + } else value = String(value); + out[field.key] = value; + } + return out; +} + +export function coerceCell(column: Column | undefined, value: unknown): unknown { + if (!column) return value; + if (column.type === "number") { + if (value === "" || value === null || value === undefined) return ""; + const n = typeof value === "number" ? value : Number(String(value).replace(/[,,\s]/g, "")); + return Number.isFinite(n) ? n : String(value); + } + if (column.type === "bool") return value === true || value === "true" || value === 1 || value === "1" || value === "yes"; + return value === null || value === undefined ? "" : String(value); +} + +const stem = (path: string) => (path.split("/").pop() ?? path).replace(/\.[^.]+$/, ""); + +export function createApp(def: AppDef, options: { workspaceRoot: string; assetRoot: string; log?: (line: string) => void }) { + const ws = new Workspace(options.workspaceRoot); + const log = options.log ?? (() => undefined); + const ctx: AppCtx = { ws, assetRoot: options.assetRoot, log }; + const PANEL_URI = `ui://${def.name}/panel.html`; + const { server, tool } = createKitServer({ + name: def.name, + version: def.version, + panelUri: PANEL_URI, + surface: "editor", + panelHtml: () => readFile(join(options.assetRoot, "ui/panel.html"), "utf8"), + log, + }); + const P = def.prefix; + const projectPath = (name: string) => `${def.name}/${safeFileName(name, "project")}.project.json`; + let queue: Promise = Promise.resolve(); + const serial = (work: () => Promise): Promise => { + const job = queue.catch(() => undefined).then(work); + queue = job; + return job; + }; + + async function loadProject(name: string): Promise { + if (!name) throw new KitError("missing_project", "Pass `project` (from the open result)."); + const path = projectPath(name); + if (!(await ws.exists(path))) throw new KitError("no_project", `No project named "${name}". Open input files first with ${P}_open.`); + return JSON.parse(await ws.readText(path)) as Project; + } + async function saveProject(project: Project) { + project.updated = new Date().toISOString(); + await ws.write(projectPath(project.name), JSON.stringify(project, null, 1) + "\n"); + } + async function listProjects() { + const files = await ws.list({ dir: def.name, exts: [".json"], recursive: false, limit: 500 }).catch(() => []); + return files.map((f) => f.path).filter((p) => p.endsWith(".project.json")).map((p) => p.split("/").pop()!.replace(/\.project\.json$/, "")); + } + + async function view(project: Project, extra: Record = {}) { + const computed = await def.compute(project, ctx); + const columns = def.columns(project); + const rows = computed.rows ?? project.rows; + return { + computed, + structured: { + kind: "project", + app: def.name, + project: project.name, + inputs: project.inputs, + settings: project.settings, + columns, + rows: rows.slice(0, MAX_ROWS_PANEL), + totalRows: rows.length, + canAdd: !!def.newRow, + issues: (computed.issues ?? []).slice(0, 500), + summary: computed.summary, + stats: computed.stats ?? {}, + preview: computed.preview ?? "", + exported: project.exported ?? [], + ...extra, + }, + }; + } + function describe(project: Project, computed: Computed, limit = 25) { + const rows = computed.rows ?? project.rows; + const cols = def.columns(project); + const line = def.describeRow ?? ((row: Row, i: number) => `#${i} ` + cols.slice(0, 5).map((c) => `${c.key}=${String(row[c.key] ?? "").slice(0, 40)}`).join(" · ")); + const issues = computed.issues ?? []; + return [ + `Project "${project.name}" (${project.inputs.join(", ") || "no input files"}): ${computed.summary}`, + issues.length ? `Issues (${issues.length}):\n` + issues.slice(0, 30).map((x) => `- [${x.level}]${x.row !== undefined ? ` row #${x.row}` : ""}${x.key ? ` ${x.key}` : ""}: ${x.message}`).join("\n") + (issues.length > 30 ? `\n… ${issues.length - 30} more in the panel.` : "") : "No issues found.", + rows.length ? `Rows (${rows.length}):\n` + rows.slice(0, limit).map((r, i) => line(r, i)).join("\n") + (rows.length > limit ? `\n… ${rows.length - limit} more rows in the panel.` : "") : "", + `Exports: ${def.exports.map((e) => `${e.id} (${e.description})`).join("; ")}. Edit with ${P}_edit, export with ${P}_export.`, + ].filter(Boolean).join("\n\n"); + } + + const settingsDoc = def.settings.map((f) => `${f.key} (${f.type}${f.options ? `: ${f.options.map((o) => o.value).join("|")}` : ""}${f.default !== undefined ? `, default ${JSON.stringify(f.default)}` : ""})${f.help ? ` — ${f.help[1]}` : ""}`).join("; "); + + tool( + `${P}_open`, + { + description: `${def.openDescription} Opens the editing panel. Settings: ${settingsDoc || "none"}. Re-opening the same project name replaces its rows with a fresh read of the inputs.`, + input: { + inputs: z.array(z.string()).describe(`Workspace-relative input paths (${def.inputs.exts.join(", ")}${def.inputs.folders ? " or folders" : ""}); ${def.inputs.min}–${def.inputs.max} item(s).`), + settings: z.record(z.string(), z.unknown()).optional(), + project: z.string().optional().describe("Project name (default: first input's file name)."), + }, + openPanel: true, + timeoutMs: 600_000, + }, + (args) => + serial(async () => { + const inputs: string[] = args.inputs ?? []; + if (inputs.length < def.inputs.min) throw new KitError("missing_input", `Pass at least ${def.inputs.min} input file(s) (${def.inputs.exts.join(", ")}).`); + if (inputs.length > def.inputs.max) throw new KitError("too_many_inputs", `At most ${def.inputs.max} input(s).`); + for (const i of inputs) ws.resolve(i); + const name = safeFileName(args.project || (inputs[0] ? stem(inputs[0]) : def.name), "project"); + const settings = coerceSettings(def.settings, args.settings); + const loaded = await def.load({ ...ctx, files: inputs, settings }); + const now = new Date().toISOString(); + const project: Project = { name, inputs, settings, rows: loaded.rows, meta: loaded.meta ?? {}, created: now, updated: now }; + await saveProject(project); + const v = await view(project); + return { text: describe(project, v.computed), structured: v.structured }; + }), + ); + + tool( + `${P}_edit`, + { + description: `Change a ${def.name} project: update settings, set cell values by row index (from ${P}_open / ${P}_status), add rows${def.newRow ? "" : " (not supported here)"} or remove rows. Changes are saved; returns the updated summary and issues.`, + input: { + project: z.string(), + settings: z.record(z.string(), z.unknown()).optional(), + set: z.array(z.object({ row: z.number().int().min(0), values: z.record(z.string(), z.unknown()) })).optional(), + add: z.array(z.record(z.string(), z.unknown())).optional(), + remove: z.array(z.number().int().min(0)).optional(), + }, + timeoutMs: 600_000, + }, + (args) => + serial(async () => { + const project = await loadProject(args.project); + const notes: string[] = []; + if (args.settings) { + const next = coerceSettings(def.settings, args.settings, project.settings); + const reload = def.settings.some((f) => f.reload && JSON.stringify(next[f.key]) !== JSON.stringify(project.settings[f.key])); + project.settings = next; + if (reload) { + const loaded = await def.load({ ...ctx, files: project.inputs, settings: next }); + project.rows = loaded.rows; + project.meta = loaded.meta ?? project.meta; + notes.push("Inputs re-read with the new settings (row edits were reset)."); + } + } + const cols = def.columns(project); + const byKey = new Map(cols.map((c) => [c.key, c])); + for (const s of args.set ?? []) { + const row = project.rows[s.row]; + if (!row) { notes.push(`Row #${s.row} does not exist.`); continue; } + for (const [k, v] of Object.entries(s.values)) { + const c = byKey.get(k); + if (c?.readOnly) { notes.push(`${k} is calculated and cannot be edited.`); continue; } + row[k] = coerceCell(c, v); + } + } + if (args.add?.length) { + if (!def.newRow) throw new KitError("no_add", "This tool does not support adding rows."); + for (const a of args.add) { + const row = def.newRow(project); + for (const [k, v] of Object.entries(a)) row[k] = coerceCell(byKey.get(k), v); + project.rows.push(row); + } + } + if (args.remove?.length) { + const drop = new Set(args.remove); + project.rows = project.rows.filter((_, i) => !drop.has(i)); + } + await saveProject(project); + const v = await view(project); + return { text: [notes.join(" "), describe(project, v.computed, 10)].filter(Boolean).join("\n\n"), structured: v.structured }; + }), + ); + + tool( + `${P}_status`, + { description: `Show a ${def.name} project's rows, issues and summary (no changes).`, input: { project: z.string(), limit: z.number().int().min(1).max(500).optional() }, readOnly: true }, + async (args) => { + const project = await loadProject(args.project); + const v = await view(project); + return { text: describe(project, v.computed, args.limit ?? 50), structured: v.structured }; + }, + ); + + tool( + `${P}_export`, + { + description: `Write the finished files for a ${def.name} project into ${def.name}// in the workspace. Formats: ${def.exports.map((e) => `"${e.id}" — ${e.description}`).join("; ")}.`, + input: { project: z.string(), formats: z.array(z.enum(def.exports.map((e) => e.id) as [string, ...string[]])).optional().describe("Default: all formats except manual ones (e.g. undo).") }, + timeoutMs: 900_000, + }, + (args) => + serial(async () => { + const project = await loadProject(args.project); + const computed = await def.compute(project, ctx); + if ((computed.issues ?? []).some((i) => i.level === "error") && !def.exports.length) throw new KitError("has_errors", "Fix the errors first."); + const outDir = `${def.name}/${safeFileName(project.name, "project")}`; + const ids = args.formats?.length ? args.formats : def.exports.filter((e) => !e.manual).map((e) => e.id); + const files: string[] = []; + const notes: string[] = []; + for (const id of ids) { + const ex = def.exports.find((e) => e.id === id)!; + const result = await ex.run({ ...ctx, project, computed, outDir, write: (n, d) => ws.write(`${outDir}/${n}`, d) }); + if (Array.isArray(result)) files.push(...result); + else { files.push(...result.files); if (result.note) notes.push(result.note); } + } + project.exported = files; + await saveProject(project); + const v = await view(project, { justExported: files }); + const errors = (computed.issues ?? []).filter((i) => i.level === "error").length; + return { + text: `Exported ${files.length} file(s):\n${files.map((f) => `- ${f}`).join("\n")}${notes.length ? `\n${notes.join("\n")}` : ""}${errors ? `\nNote: ${errors} error(s) are still open in the project.` : ""}`, + structured: v.structured, + }; + }), + ); + + tool( + "app_info", + { description: "Panel bootstrap: tool definition, workspace files and saved projects.", input: {}, visibility: ["app"], readOnly: true }, + async () => { + const files = (await ws.list({ exts: def.inputs.exts, limit: 3000 })).map((f) => f.path).filter((p) => !p.startsWith(`${def.name}/`)); + const folders = def.inputs.folders ? [...new Set(files.map((f) => f.split("/").slice(0, -1).join("/") || "."))].sort() : []; + return { + text: "", + structured: { + kind: "info", + app: def.name, + prefix: P, + title: def.title, + inputs: def.inputs, + settings: def.settings, + exports: def.exports.map((e) => ({ id: e.id, label: e.label, description: e.description })), + files, + folders, + projects: await listProjects(), + }, + }; + }, + ); + + return { server, ws, PANEL_URI }; +} + +/** HTML 转义。 */ +export const esc = (value: unknown) => + String(value ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]!); + +/** 简单 HTML 表格(用于预览与报告)。 */ +export function htmlTable(headers: string[], rows: unknown[][], cls = "data") { + return `${headers.map((h) => ``).join("")}${rows.map((r) => `${r.map((c) => ``).join("")}`).join("")}
${esc(h)}
${esc(c)}
`; +} + +/** 独立 HTML 报告页。 */ +export function htmlPage(title: string, body: string, extraCss = "") { + return `${esc(title)}${body}`; +} + +/** CSV(带 BOM,Excel 打开中文不乱码)。 */ +export function toCsv(headers: string[], rows: unknown[][]) { + const cell = (v: unknown) => { + const s = String(v ?? ""); + return /[",\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; + }; + return "\uFEFF" + [headers, ...rows].map((r) => r.map(cell).join(",")).join("\r\n") + "\r\n"; +} diff --git a/ui-plugins/batch-file-renamer/src/kit/columns.ts b/ui-plugins/batch-file-renamer/src/kit/columns.ts new file mode 100644 index 00000000..4cb79023 --- /dev/null +++ b/ui-plugins/batch-file-renamer/src/kit/columns.ts @@ -0,0 +1,53 @@ +/** 表头别名匹配:把用户表格里的中英文列名对应到插件字段。 */ +const norm = (s: string) => s.toLowerCase().replace(/[\s_\-::()().#]/g, ""); + +export function mapHeaders(headers: string[], aliases: Record): Record { + const out: Record = {}; + const used = new Set(); + const nh = headers.map((h) => [h, norm(h)] as const); + for (const [key, names] of Object.entries(aliases)) { + const wanted = [key, ...names].map(norm); + let hit = nh.find(([h, n]) => !used.has(h) && wanted.includes(n)); + hit ??= nh.find(([h, n]) => !used.has(h) && wanted.some((w) => w.length >= 2 && n.includes(w))); + if (hit) { out[key] = hit[0]; used.add(hit[0]); } + } + return out; +} + +/** 解析金额 / 数字:"¥1,234.50"、"12%"、"(3)"、全角数字。失败返回 NaN。 */ +export function num(value: unknown): number { + if (typeof value === "number") return value; + let s = String(value ?? "").trim().replace(/[0-9.-]/g, (c) => String.fromCharCode(c.charCodeAt(0) - 0xfee0)); + if (!s) return NaN; + let neg = false; + if (/^\(.*\)$|^(.*)$/.test(s)) { neg = true; s = s.slice(1, -1); } + s = s.replace(/[¥¥$€£,,\s元]|RMB|CNY|USD|EUR/gi, ""); + if (s.endsWith("%")) s = s.slice(0, -1); + const n = Number(s); + return neg ? -n : n; +} + +export const round2 = (n: number) => Math.round((n + Number.EPSILON) * 100) / 100; + +/** 解析日期:2026-11-25、2026/11/25、2026年11月25日、11/25/2026、Excel 序号。返回 YYYY-MM-DD 或 ""。 */ +export function parseDate(value: unknown): string { + if (value instanceof Date && !isNaN(+value)) return value.toISOString().slice(0, 10); + const s = String(value ?? "").trim(); + if (!s) return ""; + let m = /^(\d{4})[-/.年](\d{1,2})[-/.月](\d{1,2})日?/.exec(s); + if (m) return `${m[1]}-${m[2].padStart(2, "0")}-${m[3].padStart(2, "0")}`; + m = /^(\d{1,2})\/(\d{1,2})\/(\d{4})/.exec(s); + if (m) return `${m[3]}-${m[1].padStart(2, "0")}-${m[2].padStart(2, "0")}`; + if (/^\d{5}(\.\d+)?$/.test(s)) { + const d = new Date(Date.UTC(1899, 11, 30) + Number(s) * 86400000); + return d.toISOString().slice(0, 10); + } + const d = new Date(s); + return isNaN(+d) ? "" : d.toISOString().slice(0, 10); +} + +export function addDays(date: string, days: number) { + const d = new Date(`${date}T00:00:00Z`); + d.setUTCDate(d.getUTCDate() + days); + return d.toISOString().slice(0, 10); +} diff --git a/ui-plugins/batch-file-renamer/src/kit/console.ts b/ui-plugins/batch-file-renamer/src/kit/console.ts new file mode 100644 index 00000000..f6817656 --- /dev/null +++ b/ui-plugins/batch-file-renamer/src/kit/console.ts @@ -0,0 +1,5 @@ +// stdout 只留给 MCP 协议;依赖库的日志改写到 stderr。 +console.log = (...args: unknown[]) => process.stderr.write(`${args.map(String).join(" ")}\n`); +console.info = console.log; +console.warn = console.log; +console.debug = console.log; diff --git a/ui-plugins/batch-file-renamer/src/kit/server-kit.ts b/ui-plugins/batch-file-renamer/src/kit/server-kit.ts new file mode 100644 index 00000000..6bc31594 --- /dev/null +++ b/ui-plugins/batch-file-renamer/src/kit/server-kit.ts @@ -0,0 +1,84 @@ +import { readFile } from "node:fs/promises"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { z } from "zod"; +import { KitError } from "./workspace.ts"; + +export const HTML_MIME = "text/html;profile=mcp-app"; +type Visibility = ("model" | "app")[]; +type Content = { type: "text"; text: string } | { type: "image"; data: string; mimeType: string }; + +export interface ToolOutput { + text: string; + structured?: Record; + images?: { data: string; mimeType: string }[]; +} + +export interface KitServerOptions { + name: string; + version: string; + panelUri: string; + surface: string; + panelHtml: () => Promise; + log?: (line: string) => void; + /** 页面资源的额外 _meta,例如 { "zcode/csp": { wasmUnsafeEval: true } }。 */ + panelMeta?: Record; +} + +/** 统一的工具注册:所有工具都关联同一个侧栏面板,错误带 code 返回给 Agent 与页面。 */ +export function createKitServer(options: KitServerOptions) { + const log = options.log ?? (() => undefined); + const server = new McpServer({ name: options.name, version: options.version }, { capabilities: { logging: {} } }); + const panelMeta = { ui: { prefersBorder: false }, ...options.panelMeta }; + server.registerResource("panel", options.panelUri, { mimeType: HTML_MIME, _meta: panelMeta }, async () => ({ + contents: [{ uri: options.panelUri, mimeType: HTML_MIME, _meta: panelMeta, text: await options.panelHtml() }], + })); + + const tool = ( + name: string, + config: { + description: string; + input: Record; + visibility?: Visibility; + openPanel?: boolean; + readOnly?: boolean; + timeoutMs?: number; + }, + run: (input: any) => Promise, + ) => { + server.registerTool( + name, + { + description: config.description, + inputSchema: config.input, + annotations: { readOnlyHint: !!config.readOnly, ...(config.readOnly ? {} : { destructiveHint: false }), openWorldHint: false }, + _meta: { + ui: { resourceUri: options.panelUri, surface: options.surface, visibility: config.visibility ?? ["model", "app"] }, + ...(config.timeoutMs ? { timeoutMs: config.timeoutMs } : {}), + ...(config.openPanel ? { "openai/ui": { preferredModelDisplayMode: "fullscreen" } } : {}), + }, + }, + async (input: unknown) => { + try { + const output = await run(input); + const content: Content[] = [{ type: "text", text: output.text }]; + for (const image of output.images ?? []) content.push({ type: "image", ...image }); + return { content, ...(output.structured ? { structuredContent: output.structured } : {}) }; + } catch (error) { + const code = error instanceof KitError ? error.code : "internal_error"; + const message = error instanceof Error ? error.message : String(error); + if (!(error instanceof KitError)) log(`${name} failed: ${error instanceof Error ? error.stack : message}`); + return { + isError: true, + content: [{ type: "text" as const, text: `[${code}] ${message}` }], + structuredContent: { error: { code, message } }, + }; + } + }, + ); + }; + return { server, tool }; +} + +export async function readPanel(path: string) { + return readFile(path, "utf8"); +} diff --git a/ui-plugins/batch-file-renamer/src/kit/testing.ts b/ui-plugins/batch-file-renamer/src/kit/testing.ts new file mode 100644 index 00000000..0d8dc72e --- /dev/null +++ b/ui-plugins/batch-file-renamer/src/kit/testing.ts @@ -0,0 +1,16 @@ +// 仅测试使用:通过内存传输连接 server,像 Agent 一样调用工具。 +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; + +export async function connect(server: McpServer) { + const [a, b] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: "test", version: "1" }); + await Promise.all([server.connect(a), client.connect(b)]); + const call = async (name: string, args: Record = {}) => { + const r = (await client.callTool({ name, arguments: args }, undefined, { timeout: 300_000 })) as any; + if (r.isError) throw Object.assign(new Error(r.content?.[0]?.text ?? "tool error"), { code: r.structuredContent?.error?.code }); + return { text: r.content?.[0]?.text as string, data: r.structuredContent as any }; + }; + return { client, call }; +} diff --git a/ui-plugins/batch-file-renamer/src/kit/workspace.ts b/ui-plugins/batch-file-renamer/src/kit/workspace.ts new file mode 100644 index 00000000..7326158b --- /dev/null +++ b/ui-plugins/batch-file-renamer/src/kit/workspace.ts @@ -0,0 +1,170 @@ +import { lstatSync, readlinkSync, realpathSync } from "node:fs"; +import { mkdir, readFile, readdir, rename, stat, writeFile } from "node:fs/promises"; +import { dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path"; + +export class KitError extends Error { + readonly code: string; + constructor(code: string, message: string) { + super(message); + this.code = code; + this.name = "KitError"; + } +} + +const SKIP = new Set(["node_modules", ".git", "dist", "build", ".next", ".cache", "__pycache__"]); + +/** 只允许读写当前工作区内的文件;所有路径都相对工作区根目录。 */ +export class Workspace { + readonly root: string; + constructor(root: string) { + this.root = resolve(root); + } + + resolve(path: string): string { + if (typeof path !== "string" || !path.trim()) throw new KitError("bad_path", "Path is empty."); + const absolute = resolve(this.root, path); + const rel = relative(this.root, absolute); + if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) + throw new KitError("outside_workspace", `Path is outside the workspace: ${path}`); + this.assertRealInside(absolute, path); + return absolute; + } + + private realRoot?: string; + + /** + * 符号链接不能把读写带出工作区:从目标往上找到第一个已存在的路径,取它的真实路径, + * 必须仍在工作区根目录的真实路径之下。还不存在的写入目标按其已存在的上级目录判断; + * 指向不存在位置的悬空链接一律拒绝(否则 writeFile 会顺着它在外部建文件)。 + */ + private assertRealInside(absolute: string, path: string) { + let realRoot: string; + try { + realRoot = this.realRoot ??= realpathSync(this.root); + } catch { + return; // 根目录本身不存在时,没有可逃出的链接 + } + const outside = (real: string) => { + const rel = relative(realRoot, real); + return rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel); + }; + let probe = absolute; + for (;;) { + let real: string | undefined; + try { + real = realpathSync(probe); + } catch { + let link = false; + try { + link = lstatSync(probe).isSymbolicLink(); + } catch {} + if (link) { + const target = resolve(dirname(probe), readlinkSync(probe)); + throw new KitError("outside_workspace", outside(target) ? `Path leaves the workspace through a link: ${path}` : `Path goes through a broken link: ${path}`); + } + } + if (real !== undefined) { + if (outside(real)) throw new KitError("outside_workspace", `Path leaves the workspace through a link: ${path}`); + return; + } + const parent = dirname(probe); + if (parent === probe) return; + probe = parent; + } + } + + rel(absolute: string): string { + return relative(this.root, absolute).split(sep).join("/") || "."; + } + + async exists(path: string): Promise { + try { + await stat(this.resolve(path)); + return true; + } catch { + return false; + } + } + + async read(path: string, maxBytes = 200 * 1024 * 1024): Promise { + const absolute = this.resolve(path); + let info; + try { + info = await stat(absolute); + } catch { + throw new KitError("not_found", `File not found: ${path}`); + } + if (!info.isFile()) throw new KitError("not_a_file", `Not a file: ${path}`); + if (info.size > maxBytes) throw new KitError("too_large", `File is larger than ${Math.round(maxBytes / 1048576)} MB: ${path}`); + return readFile(absolute); + } + + async readText(path: string): Promise { + return (await this.read(path, 20 * 1024 * 1024)).toString("utf8"); + } + + async write(path: string, data: Uint8Array | string): Promise { + const absolute = this.resolve(path); + await mkdir(dirname(absolute), { recursive: true }); + await writeFile(absolute, data); + return this.rel(absolute); + } + + /** 在工作区内移动 / 重命名文件;目标已存在时拒绝,不覆盖。 */ + async move(from: string, to: string): Promise { + const source = this.resolve(from); + const target = this.resolve(to); + if (!(await this.exists(from))) throw new KitError("not_found", `File not found: ${from}`); + if (await this.exists(to)) throw new KitError("exists", `Target already exists: ${to}`); + await mkdir(dirname(target), { recursive: true }); + await rename(source, target); + return this.rel(target); + } + + async size(path: string): Promise { + return (await stat(this.resolve(path))).size; + } + + async mtime(path: string): Promise { + return (await stat(this.resolve(path))).mtime; + } + + /** 列出文件(默认递归、跳过依赖与构建目录),按路径排序。 */ + async list({ dir = ".", exts, recursive = true, limit = 2000 }: { dir?: string; exts?: string[]; recursive?: boolean; limit?: number } = {}) { + const wanted = exts?.map((ext) => ext.toLowerCase()); + const out: { path: string; size: number }[] = []; + const walk = async (absolute: string, depth: number) => { + if (out.length >= limit || depth > 8) return; + let entries; + try { + entries = await readdir(absolute, { withFileTypes: true }); + } catch { + return; + } + entries.sort((a, b) => a.name.localeCompare(b.name, "en", { numeric: true })); + for (const entry of entries) { + if (out.length >= limit) return; + if (entry.name.startsWith(".") && entry.name !== ".") continue; + const child = join(absolute, entry.name); + if (entry.isDirectory()) { + if (recursive && !SKIP.has(entry.name)) await walk(child, depth + 1); + } else if (entry.isFile() && (!wanted?.length || wanted.includes(extname(entry.name).toLowerCase()))) { + out.push({ path: this.rel(child), size: (await stat(child)).size }); + } + } + }; + await walk(this.resolve(dir), 0); + return out; + } +} + +/** 把文件名中不适合的字符替换掉,保留中文。 */ +export function safeFileName(name: string, fallback = "file"): string { + const cleaned = name + .replace(/[\\/:*?"<>|]+/g, "_") + .replace(/\p{Cc}+/gu, "_") + .replace(/\s+/g, " ") + .trim() + .replace(/^\.+/, ""); + return (cleaned || fallback).slice(0, 120); +} diff --git a/ui-plugins/batch-file-renamer/src/main.ts b/ui-plugins/batch-file-renamer/src/main.ts new file mode 100644 index 00000000..33df0c93 --- /dev/null +++ b/ui-plugins/batch-file-renamer/src/main.ts @@ -0,0 +1,14 @@ +import "./kit/console.ts"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { createServer } from "./server.ts"; + +const here = dirname(fileURLToPath(import.meta.url)); +const server = createServer({ + workspaceRoot: resolve(process.env.ZCODE_WORKSPACE_ROOT || process.cwd()), + assetRoot: here, + log: (line) => process.stderr.write(`[batch-file-renamer] ${line}\n`), +}); +process.stdin.once("end", () => process.exit(0)); +await server.connect(new StdioServerTransport()); diff --git a/ui-plugins/batch-file-renamer/src/rename.ts b/ui-plugins/batch-file-renamer/src/rename.ts new file mode 100644 index 00000000..1746c9a0 --- /dev/null +++ b/ui-plugins/batch-file-renamer/src/rename.ts @@ -0,0 +1,62 @@ +import { extname } from "node:path"; + +export interface Rules { + find: string; replace: string; regex: boolean; template: string; start: number; pad: number; + case: "keep" | "lower" | "upper" | "title"; extCase: "keep" | "lower"; spaces: "keep" | "dash" | "underscore" | "remove"; sort: "name" | "mtime"; +} +export interface FileInfo { path: string; mtime: string; override?: string } + +const ILLEGAL = /[\\/:*?"<>|\u0000-\u001f]/g; +const title = (s: string) => s.replace(/(^|[\s_-])(\p{Ll})/gu, (_, a: string, b: string) => a + b.toUpperCase()); + +/** 按规则算出新文件名(不含目录)。 */ +export function newName(f: FileInfo, index: number, r: Rules): { name: string; error?: string } { + const base = f.path.split("/").pop()!; + const ext = extname(base); + let stem = base.slice(0, base.length - ext.length); + if (r.find) { + if (r.regex) { + let re: RegExp; + try { re = new RegExp(r.find, "g"); } catch (e) { return { name: base, error: `Bad regular expression: ${(e as Error).message}` }; } + stem = stem.replace(re, r.replace); + } else stem = stem.split(r.find).join(r.replace); + } + const parent = f.path.split("/").slice(-2, -1)[0] ?? ""; + const n = String(r.start + index).padStart(r.pad, "0"); + let out = (r.template || "{name}").replace(/\{name\}/g, stem).replace(/\{n\}/g, n).replace(/\{date\}/g, f.mtime.slice(0, 10)).replace(/\{parent\}/g, parent).replace(/\{ext\}/g, ext.slice(1)); + if (r.spaces === "dash") out = out.replace(/\s+/g, "-"); + else if (r.spaces === "underscore") out = out.replace(/\s+/g, "_"); + else if (r.spaces === "remove") out = out.replace(/\s+/g, ""); + else out = out.replace(/\s{2,}/g, " "); + if (r.case === "lower") out = out.toLowerCase(); + else if (r.case === "upper") out = out.toUpperCase(); + else if (r.case === "title") out = title(out.toLowerCase()); + out = out.replace(ILLEGAL, "_").trim().replace(/^\.+/, ""); + if (f.override?.trim()) { + const o = f.override.trim().replace(ILLEGAL, "_"); + return { name: extname(o) ? o : o + (r.extCase === "lower" ? ext.toLowerCase() : ext) }; + } + if (!out) return { name: base, error: "The rules produce an empty name" }; + return { name: out + (r.extCase === "lower" ? ext.toLowerCase() : ext) }; +} + +export interface Planned { from: string; to: string; changed: boolean; error?: string } + +export function plan(files: FileInfo[], r: Rules, exists: (p: string) => boolean): Planned[] { + const order = files.map((f, i) => ({ f, i })).sort((a, b) => (r.sort === "mtime" ? a.f.mtime.localeCompare(b.f.mtime) : 0) || a.f.path.localeCompare(b.f.path, "en", { numeric: true })); + const rank = new Map(order.map((o, k) => [o.i, k])); + const out = files.map((f, i) => { + const { name, error } = newName(f, rank.get(i)!, r); + const dir = f.path.includes("/") ? f.path.slice(0, f.path.lastIndexOf("/") + 1) : ""; + return { from: f.path, to: dir + name, changed: dir + name !== f.path, error }; + }); + const sources = new Set(files.map((f) => f.path.toLowerCase())); + const count = new Map(); + for (const p of out) count.set(p.to.toLowerCase(), (count.get(p.to.toLowerCase()) ?? 0) + 1); + for (const p of out) { + if (p.error) continue; + if ((count.get(p.to.toLowerCase()) ?? 0) > 1) p.error = `Two files would get the same name: ${p.to.split("/").pop()} (add {n})`; + else if (p.changed && !sources.has(p.to.toLowerCase()) && exists(p.to)) p.error = `A different file already has this name: ${p.to}`; + } + return out; +} diff --git a/ui-plugins/batch-file-renamer/src/server.ts b/ui-plugins/batch-file-renamer/src/server.ts new file mode 100644 index 00000000..adde7b7d --- /dev/null +++ b/ui-plugins/batch-file-renamer/src/server.ts @@ -0,0 +1,147 @@ +import { createApp, htmlTable, toCsv, type AppDef, type Issue, type Project } from "./kit/app.ts"; +import { KitError, type Workspace } from "./kit/workspace.ts"; +import { plan, type Rules } from "./rename.ts"; + +export const NAME = "batch-file-renamer"; +export const VERSION = "0.1.0"; + +const rulesOf = (p: Project): Rules => ({ + find: String(p.settings.find ?? ""), replace: String(p.settings.replace ?? ""), regex: Boolean(p.settings.regex), template: String(p.settings.template || "{name}"), + start: Number(p.settings.start ?? 1), pad: Number(p.settings.pad ?? 3), case: (p.settings.case as Rules["case"]) ?? "keep", extCase: (p.settings.extCase as Rules["extCase"]) ?? "lower", + spaces: (p.settings.spaces as Rules["spaces"]) ?? "keep", sort: (p.settings.sort as Rules["sort"]) ?? "name", +}); +const filesOf = (p: Project) => p.rows.map((r) => ({ path: String(r.path), mtime: String(r.mtime ?? ""), override: String(r.override ?? "") })); +const existsSync = (p: Project) => new Set((p.meta.others as string[] | undefined ?? []).map((x) => x.toLowerCase())); + +const NEUTRAL = { find: "", replace: "", regex: false, template: "{name}", case: "keep", spaces: "keep" }; +interface Move { from: string; to: string } +async function moveAll(ws: Workspace, moves: Move[]) { + const sources = new Set(moves.map((m) => m.from.toLowerCase())); + for (const m of moves) if (!sources.has(m.to.toLowerCase()) && (await ws.exists(m.to))) throw new KitError("exists", `Target already exists: ${m.to}. Nothing was renamed.`); + const tag = Date.now().toString(36); + const staged: (Move & { orig: string })[] = []; + // 两步改名:先全部改成临时名,避免 a→b、b→a 互换或仅大小写变化时冲突 + for (const [i, m] of moves.entries()) { + const dir = m.from.includes("/") ? m.from.slice(0, m.from.lastIndexOf("/") + 1) : ""; + const tmp = `${dir}.rename-${tag}-${i}`; + await ws.move(m.from, tmp); + staged.push({ from: tmp, to: m.to, orig: m.from }); + } + const done: (Move & { orig: string })[] = []; + try { + for (const m of staged) { await ws.move(m.from, m.to); done.push(m); } + } catch (e) { + // 出错时尽量全部还原成原名 + for (const m of done) await ws.move(m.to, m.from).catch(() => undefined); + for (const m of staged) await ws.move(m.from, m.orig).catch(() => undefined); + throw e; + } +} + +const def: AppDef = { + name: NAME, + version: VERSION, + prefix: "rename", + title: ["批量重命名", "Batch File Renamer"], + openDescription: + "Rename many files in a workspace folder with rules: find/replace (optionally regex), a name template with {name} {n} {date} {parent} {ext}, numbering with start and padding, upper/lower/title case, spaces to dashes/underscores, lower-case extensions, and per-file manual names. Shows old → new for every file, flags duplicate targets, names that clash with other files and illegal characters before anything changes. Export “rename” applies it (two-step, safe for swaps and case-only changes) and writes a log; “undo” reverts the last rename.", + inputs: { exts: [], min: 1, max: 5, folders: true, label: ["选择要重命名的文件夹", "Pick the folder whose files to rename"] }, + settings: [ + { key: "recursive", label: ["包含子文件夹", "Include subfolders"], type: "bool", default: false, reload: true }, + { key: "only", label: ["只改这些扩展名(逗号分隔,留空=全部)", "Only these extensions (comma-separated, empty = all)"], type: "text", default: "", reload: true }, + { key: "find", label: ["查找", "Find"], type: "text", default: "" }, + { key: "replace", label: ["替换为", "Replace with"], type: "text", default: "" }, + { key: "regex", label: ["用正则表达式", "Regular expression"], type: "bool", default: false, help: ["替换里可用 $1、$2", "Use $1, $2 in the replacement"] }, + { key: "template", label: ["新文件名模板", "Name template"], type: "text", default: "{name}", help: ["{name} 原名(已替换) {n} 序号 {date} 修改日期 {parent} 所在文件夹 {ext} 扩展名", "{name} old name (after replace) {n} number {date} modified date {parent} folder {ext} extension"] }, + { key: "start", label: ["起始序号", "Start number"], type: "number", default: 1, min: 0 }, + { key: "pad", label: ["序号位数", "Number digits"], type: "number", default: 3, min: 1, max: 8 }, + { key: "sort", label: ["编号顺序", "Number in order of"], type: "select", default: "name", options: [{ value: "name", label: ["文件名", "File name"] }, { value: "mtime", label: ["修改时间", "Modified time"] }] }, + { key: "case", label: ["大小写", "Case"], type: "select", default: "keep", options: [{ value: "keep", label: ["不变", "Keep"] }, { value: "lower", label: ["全小写", "lower"] }, { value: "upper", label: ["全大写", "UPPER"] }, { value: "title", label: ["首字母大写", "Title Case"] }] }, + { key: "spaces", label: ["空格", "Spaces"], type: "select", default: "keep", options: [{ value: "keep", label: ["保留(合并连续空格)", "Keep (collapse runs)"] }, { value: "dash", label: ["改成 -", "To -"] }, { value: "underscore", label: ["改成 _", "To _"] }, { value: "remove", label: ["去掉", "Remove"] }] }, + { key: "extCase", label: ["扩展名", "Extension"], type: "select", default: "lower", options: [{ value: "lower", label: ["统一小写", "lower-case"] }, { value: "keep", label: ["不变", "Keep"] }] }, + ], + columns: () => [ + { key: "path", label: ["当前文件", "Current file"], readOnly: true, wide: true }, + { key: "override", label: ["手动指定新名", "Manual new name"] }, + { key: "_to", label: ["新文件名", "New name"], readOnly: true, wide: true }, + { key: "_state", label: ["状态", "State"], readOnly: true }, + ], + async load({ ws, files, settings }) { + const only = String(settings.only ?? "").split(/[,,\s]+/).filter(Boolean).map((e) => (e.startsWith(".") ? e : "." + e).toLowerCase()); + const rows = []; + const others: string[] = []; + for (const dir of files) { + const list = await ws.list({ dir, recursive: Boolean(settings.recursive), limit: 5000 }).catch(() => { throw new KitError("not_found", `Folder not found: ${dir}`); }); + for (const f of list) { + if (f.path.startsWith(`${NAME}/`)) continue; + const ext = f.path.slice(f.path.lastIndexOf(".")).toLowerCase(); + if (only.length && !only.includes(ext)) { others.push(f.path); continue; } + rows.push({ path: f.path, mtime: (await ws.mtime(f.path)).toISOString(), override: "" }); + } + } + if (!rows.length) throw new KitError("empty", "No files to rename in that folder."); + return { rows, meta: { others } }; + }, + compute(p) { + const others = existsSync(p); + const planned = plan(filesOf(p), rulesOf(p), (x) => others.has(x.toLowerCase())); + const issues: Issue[] = []; + planned.forEach((x, i) => { if (x.error) issues.push({ level: "error", row: i, message: x.error }); }); + const changed = planned.filter((x) => x.changed && !x.error).length; + const rows = p.rows.map((r, i) => ({ ...r, _to: planned[i].to.split("/").pop(), _state: planned[i].error ? "✗" : planned[i].changed ? "→" : "=" })); + const last = p.meta.lastRename as Move[] | undefined; + const preview = + `

${changed} / ${planned.length} files will be renamed${last?.length ? ` · last rename: ${last.length} files (undo available)` : ""}

` + + htmlTable(["Before / 原名", "After / 新名"], planned.filter((x) => x.changed).slice(0, 200).map((x) => [x.from.split("/").pop()!, x.to.split("/").pop()!])); + return { rows, issues, preview, summary: `${planned.length} files, ${changed} to rename${issues.length ? `, ${issues.length} problem(s)` : ""}`, stats: { files: planned.length, rename: changed, problems: issues.length } }; + }, + exports: [ + { + id: "plan", label: ["改名清单 CSV", "Plan CSV"], description: "rename-plan.csv with old and new names (changes nothing)", + async run({ project, write }) { + const others = existsSync(project); + const planned = plan(filesOf(project), rulesOf(project), (x) => others.has(x.toLowerCase())); + return [await write("rename-plan.csv", toCsv(["from", "to", "problem"], planned.map((x) => [x.from, x.to, x.error ?? ""])))]; + }, + }, + { + id: "rename", label: ["执行改名", "Rename files"], description: "rename the files on disk and write rename-log.csv (undo reverts it)", + async run({ ws, project, write }) { + const others = existsSync(project); + const planned = plan(filesOf(project), rulesOf(project), (x) => others.has(x.toLowerCase())); + const bad = planned.filter((x) => x.error); + if (bad.length) throw new KitError("has_errors", `Fix ${bad.length} problem(s) first, e.g. ${bad[0].from}: ${bad[0].error}`); + const moves = planned.filter((x) => x.changed).map((x) => ({ from: x.from, to: x.to })); + if (!moves.length) return { files: [], note: "Nothing to rename — every file already has its new name." }; + for (const m of moves) if (!(await ws.exists(m.from))) throw new KitError("not_found", `File moved or deleted since opening: ${m.from}. Reopen the folder.`); + await moveAll(ws, moves); + const to = new Map(moves.map((m) => [m.from, m.to])); + project.rows = project.rows.map((r) => ({ ...r, path: to.get(String(r.path)) ?? r.path, override: "" })); + project.meta.lastRename = moves; + // 改完后把规则复位,避免再次套用模板(例如 {n} 重新编号) + Object.assign(project.settings, NEUTRAL); + const log = await write(`rename-log-${new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19)}.csv`, toCsv(["from", "to"], moves.map((m) => [m.from, m.to]))); + return { files: [log], note: `Renamed ${moves.length} file(s). The rules were reset so the new names stay as they are.` }; + }, + }, + { + id: "undo", manual: true, label: ["撤销上次改名", "Undo last rename"], description: "rename the files from the last “rename” back to their old names", + async run({ ws, project, write }) { + const last = project.meta.lastRename as Move[] | undefined; + if (!last?.length) throw new KitError("nothing_to_undo", "No rename to undo in this project."); + const back = last.map((m) => ({ from: m.to, to: m.from })); + for (const m of back) if (!(await ws.exists(m.from))) throw new KitError("not_found", `Can't undo: ${m.from} is gone or was renamed again.`); + await moveAll(ws, back); + const to = new Map(back.map((m) => [m.from, m.to])); + project.rows = project.rows.map((r) => ({ ...r, path: to.get(String(r.path)) ?? r.path })); + delete project.meta.lastRename; + Object.assign(project.settings, NEUTRAL); + return { files: [await write("undo-log.csv", toCsv(["from", "to"], back.map((m) => [m.from, m.to])))], note: `Restored ${back.length} file name(s).` }; + }, + }, + ], +}; + +export function createServer(options: { workspaceRoot: string; assetRoot: string; log?: (line: string) => void }) { + return createApp(def, options).server; +} diff --git a/ui-plugins/batch-file-renamer/test/e2e.json b/ui-plugins/batch-file-renamer/test/e2e.json new file mode 100644 index 00000000..75aa125e --- /dev/null +++ b/ui-plugins/batch-file-renamer/test/e2e.json @@ -0,0 +1,2 @@ +{ "prefix": "rename", "folder": "相册", "pick": ["photos"], "startSettings": { "template": "杭州-{n}" }, + "uiEdit": { "row": 7, "key": "override", "value": "微信图片" }, "expectText": "杭州-001.jpg", "expectFiles": ["rename-plan\\.csv$", "rename-log-.*\\.csv$"] } diff --git a/ui-plugins/batch-file-renamer/test/rename.test.ts b/ui-plugins/batch-file-renamer/test/rename.test.ts new file mode 100644 index 00000000..dca21f68 --- /dev/null +++ b/ui-plugins/batch-file-renamer/test/rename.test.ts @@ -0,0 +1,59 @@ +import { cp, mkdtemp, readdir, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { describe, expect, it } from "vitest"; +import { newName, plan, type Rules } from "../src/rename.ts"; +import { connect } from "../src/kit/testing.ts"; +import { createServer } from "../src/server.ts"; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const R: Rules = { find: "", replace: "", regex: false, template: "{name}", start: 1, pad: 3, case: "keep", extCase: "lower", spaces: "keep", sort: "name" }; + +describe("rules", () => { + it("applies replace, template, case and spaces", () => { + const f = { path: "a/IMG_20261103_101522.JPG", mtime: "2026-11-03T10:15:22Z" }; + expect(newName(f, 0, R).name).toBe("IMG_20261103_101522.jpg"); + expect(newName(f, 4, { ...R, regex: true, find: "^IMG_(\\d{4})(\\d{2})(\\d{2})_.*$", replace: "$1-$2-$3", template: "{name} 杭州 {n}" }).name).toBe("2026-11-03 杭州 005.jpg"); + expect(newName({ path: "notes draft FINAL.txt", mtime: "" }, 0, { ...R, case: "title", spaces: "dash" }).name).toBe("Notes-Draft-Final.txt"); + expect(newName(f, 0, { ...R, template: "{parent}-{date}" }).name).toBe("a-2026-11-03.jpg"); + expect(newName(f, 0, { ...R, find: "/", replace: "x" }).name).toBe("IMG_20261103_101522.jpg"); + expect(newName(f, 0, { ...R, template: "a:b" }).name).toBe("a_b.jpg"); + expect(newName(f, 0, { ...R, regex: true, find: "(" }).error).toMatch(/regular expression/); + expect(newName({ ...f, override: "封面" }, 0, R).name).toBe("封面.jpg"); + }); + it("flags duplicates and clashes, allows swaps", () => { + const files = [{ path: "x/a.txt", mtime: "" }, { path: "x/b.txt", mtime: "" }]; + expect(plan(files, { ...R, template: "same" }, () => false).every((p) => /same name/.test(p.error ?? ""))).toBe(true); + expect(plan(files, { ...R, template: "c" , find: "", }, () => false)[0].error).toMatch(/same name/); + const swap = plan([{ path: "x/a.txt", mtime: "", override: "b" }, { path: "x/b.txt", mtime: "", override: "a" }], R, () => true); + expect(swap.map((p) => [p.to, p.error])).toEqual([["x/b.txt", undefined], ["x/a.txt", undefined]]); + expect(plan([files[0]], { ...R, template: "z" }, (p) => p === "x/z.txt")[0].error).toMatch(/already has/); + }); +}); + +describe("rename tools", () => { + it("renames, logs and undoes on disk", async () => { + const root = await mkdtemp(join(tmpdir(), "rename-")); + await cp(join(HERE, "samples/photos"), join(root, "相册"), { recursive: true }); + await writeFile(join(root, "相册/keep.md"), "x"); + const c = await connect(createServer({ workspaceRoot: root, assetRoot: root })); + const o = await c.call("rename_open", { inputs: ["相册"], project: "trip", settings: { only: "jpg, png" } }); + expect(o.data.stats).toMatchObject({ files: 5, rename: 2 }); + const e = await c.call("rename_edit", { project: "trip", settings: { template: "杭州-{n}", sort: "name" } }); + expect(e.data.rows.map((r: { _to: string }) => r._to)).toEqual(["IMG_20261103_101522.jpg".replace(/.*/, "杭州-001.jpg"), "杭州-002.jpg", "杭州-003.jpg", "杭州-004.png", "杭州-005.jpg"]); + await c.call("rename_edit", { project: "trip", set: [{ row: 4, values: { override: "keep.md" } }] }); + const bad = await c.call("rename_status", { project: "trip" }); + expect(bad.data.issues[0].message).toMatch(/already has/); + await c.call("rename_edit", { project: "trip", set: [{ row: 4, values: { override: "微信图片" } }] }); + const x = await c.call("rename_export", { project: "trip" }); + expect(x.text).toMatch(/Renamed 5/); + const names = (await readdir(join(root, "相册"))).sort(); + expect(names).toEqual(["keep.md", "notes draft FINAL.txt", "微信图片.jpg", "报价单 (1).pdf", "报价单 (2).pdf", "杭州-001.jpg", "杭州-002.jpg", "杭州-003.jpg", "杭州-004.png"].sort()); + const again = await c.call("rename_status", { project: "trip" }); + expect(again.data.stats.rename).toBe(0); + await c.call("rename_export", { project: "trip", formats: ["undo"] }); + expect((await readdir(join(root, "相册"))).sort()).toContain("IMG_20261103_101522.JPG"); + expect((await readdir(join(root, "相册"))).sort()).toContain("WeChat Image_20261106.jpg"); + }); +}); diff --git a/ui-plugins/batch-file-renamer/test/samples/photos/IMG_20261103_101522.JPG b/ui-plugins/batch-file-renamer/test/samples/photos/IMG_20261103_101522.JPG new file mode 100644 index 00000000..72035e10 --- /dev/null +++ b/ui-plugins/batch-file-renamer/test/samples/photos/IMG_20261103_101522.JPG @@ -0,0 +1 @@ +xxxxxxxxxx \ No newline at end of file diff --git a/ui-plugins/batch-file-renamer/test/samples/photos/IMG_20261103_101530.JPG b/ui-plugins/batch-file-renamer/test/samples/photos/IMG_20261103_101530.JPG new file mode 100644 index 00000000..72035e10 --- /dev/null +++ b/ui-plugins/batch-file-renamer/test/samples/photos/IMG_20261103_101530.JPG @@ -0,0 +1 @@ +xxxxxxxxxx \ No newline at end of file diff --git a/ui-plugins/batch-file-renamer/test/samples/photos/IMG_20261104_090001.jpg b/ui-plugins/batch-file-renamer/test/samples/photos/IMG_20261104_090001.jpg new file mode 100644 index 00000000..72035e10 --- /dev/null +++ b/ui-plugins/batch-file-renamer/test/samples/photos/IMG_20261104_090001.jpg @@ -0,0 +1 @@ +xxxxxxxxxx \ No newline at end of file diff --git a/ui-plugins/batch-file-renamer/test/samples/photos/Screenshot 2026-11-05 at 10.22.31.png b/ui-plugins/batch-file-renamer/test/samples/photos/Screenshot 2026-11-05 at 10.22.31.png new file mode 100644 index 00000000..72035e10 --- /dev/null +++ b/ui-plugins/batch-file-renamer/test/samples/photos/Screenshot 2026-11-05 at 10.22.31.png @@ -0,0 +1 @@ +xxxxxxxxxx \ No newline at end of file diff --git a/ui-plugins/batch-file-renamer/test/samples/photos/WeChat Image_20261106.jpg b/ui-plugins/batch-file-renamer/test/samples/photos/WeChat Image_20261106.jpg new file mode 100644 index 00000000..72035e10 --- /dev/null +++ b/ui-plugins/batch-file-renamer/test/samples/photos/WeChat Image_20261106.jpg @@ -0,0 +1 @@ +xxxxxxxxxx \ No newline at end of file diff --git a/ui-plugins/batch-file-renamer/test/samples/photos/notes draft FINAL.txt b/ui-plugins/batch-file-renamer/test/samples/photos/notes draft FINAL.txt new file mode 100644 index 00000000..72035e10 --- /dev/null +++ b/ui-plugins/batch-file-renamer/test/samples/photos/notes draft FINAL.txt @@ -0,0 +1 @@ +xxxxxxxxxx \ No newline at end of file diff --git "a/ui-plugins/batch-file-renamer/test/samples/photos/\346\212\245\344\273\267\345\215\225 (1).pdf" "b/ui-plugins/batch-file-renamer/test/samples/photos/\346\212\245\344\273\267\345\215\225 (1).pdf" new file mode 100644 index 00000000..72035e10 Binary files /dev/null and "b/ui-plugins/batch-file-renamer/test/samples/photos/\346\212\245\344\273\267\345\215\225 (1).pdf" differ diff --git "a/ui-plugins/batch-file-renamer/test/samples/photos/\346\212\245\344\273\267\345\215\225 (2).pdf" "b/ui-plugins/batch-file-renamer/test/samples/photos/\346\212\245\344\273\267\345\215\225 (2).pdf" new file mode 100644 index 00000000..72035e10 Binary files /dev/null and "b/ui-plugins/batch-file-renamer/test/samples/photos/\346\212\245\344\273\267\345\215\225 (2).pdf" differ diff --git a/ui-plugins/batch-file-renamer/test/workspace-links.test.ts b/ui-plugins/batch-file-renamer/test/workspace-links.test.ts new file mode 100644 index 00000000..f3dae538 --- /dev/null +++ b/ui-plugins/batch-file-renamer/test/workspace-links.test.ts @@ -0,0 +1,43 @@ +import { existsSync, mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { Workspace } from "../src/kit/workspace.ts"; + +// 回归测试:工作区里的符号链接不能把读写带到工作区之外(TEST-FINDINGS #2) +describe("workspace symlink containment", () => { + const base = mkdtempSync(join(tmpdir(), "wslinks-")); + const root = join(base, "项目 ws"), outside = join(base, "outside"); + mkdirSync(join(root, "inner"), { recursive: true }); + mkdirSync(outside, { recursive: true }); + writeFileSync(join(outside, "secret.txt"), "SECRET"); + writeFileSync(join(root, "inner", "ok.txt"), "ok"); + symlinkSync(outside, join(root, "out-link")); + symlinkSync(join(outside, "secret.txt"), join(root, "secret-link.txt")); + symlinkSync(join(outside, "new-file.txt"), join(root, "dangling.txt")); + symlinkSync(join(root, "inner"), join(root, "inner-link")); + symlinkSync(root, join(base, "root-link")); + const ws = new Workspace(root); + + it("refuses to read through a link to outside (directory and file links)", async () => { + await expect(ws.read("out-link/secret.txt")).rejects.toMatchObject({ code: "outside_workspace" }); + await expect(ws.read("secret-link.txt")).rejects.toMatchObject({ code: "outside_workspace" }); + expect(await ws.exists("out-link/secret.txt")).toBe(false); + }); + it("refuses to write through a link, including to targets that do not exist yet", async () => { + await expect(ws.write("out-link/a/b/new.txt", "x")).rejects.toMatchObject({ code: "outside_workspace" }); + await expect(ws.write("dangling.txt", "x")).rejects.toMatchObject({ code: "outside_workspace" }); + expect(existsSync(join(outside, "a"))).toBe(false); + expect(existsSync(join(outside, "new-file.txt"))).toBe(false); + }); + it("still allows normal paths, new nested files and links that stay inside", async () => { + expect(await ws.write("新 目录/子/文件.txt", "中文")).toBe("新 目录/子/文件.txt"); + expect((await ws.read("inner-link/ok.txt")).toString()).toBe("ok"); + await expect(ws.read("../outside/secret.txt")).rejects.toMatchObject({ code: "outside_workspace" }); + }); + it("works when the workspace root itself is reached through a link", async () => { + const viaLink = new Workspace(join(base, "root-link")); + expect((await viaLink.read("inner/ok.txt")).toString()).toBe("ok"); + await expect(viaLink.read("out-link/secret.txt")).rejects.toMatchObject({ code: "outside_workspace" }); + }); +}); diff --git a/ui-plugins/batch-file-renamer/tsconfig.json b/ui-plugins/batch-file-renamer/tsconfig.json new file mode 100644 index 00000000..39f7ab60 --- /dev/null +++ b/ui-plugins/batch-file-renamer/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "lib": ["ES2023", "DOM", "DOM.Iterable"], + "strict": true, + "skipLibCheck": true, + "noEmit": true, + "allowImportingTsExtensions": true, + "types": ["node"] + }, + "include": ["src/**/*.ts", "ui/**/*.ts", "test/**/*.ts"] +} diff --git a/ui-plugins/batch-file-renamer/ui/app.css b/ui-plugins/batch-file-renamer/ui/app.css new file mode 100644 index 00000000..19894635 --- /dev/null +++ b/ui-plugins/batch-file-renamer/ui/app.css @@ -0,0 +1,39 @@ +.top { display:flex; align-items:baseline; gap:10px; } +.files { max-height: 260px; overflow:auto; border:1px solid var(--line); border-radius:6px; padding:4px; background:var(--bg); } +.file { padding:2px 4px; font-size:12px; word-break: break-all; } +.filter { width:100%; margin-bottom:6px; } +.settings { display:grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap:6px 12px; } +.set { justify-content: space-between; } +.set span { color: var(--muted); } +.set input[type=text], .set input[type=number], .set select, .set textarea, .set input[type=date] { width: 60%; } +.set-textarea { grid-column: 1 / -1; align-items: flex-start; } +.set-textarea textarea { width: 80%; } +.head .pname { font-weight:600; } +.summary { margin:8px 0 4px; } +.chips { display:flex; flex-wrap:wrap; gap:6px; margin:4px 0 8px; } +.chip { background:var(--panel); border:1px solid var(--line); border-radius:12px; padding:1px 8px; font-size:12px; } +.issues { margin:6px 0; } +.issues ul { margin:4px 0; padding-left:18px; max-height:180px; overflow:auto; } +.issues li { cursor:pointer; } +.lvl-error { color: var(--bad); } .lvl-warn { color: var(--warn); } +.split2 { display:grid; grid-template-columns: minmax(0, 3fr) minmax(0, 2fr); gap:10px; align-items:start; } +.split2 .previewcol:empty { display:none; } +.split2:has(.previewcol:empty) { grid-template-columns: 1fr; } +@media (max-width: 900px) { .split2 { grid-template-columns: 1fr; } } +.tablewrap { overflow:auto; max-height: 60vh; border:1px solid var(--line); border-radius:6px; } +table.edit { font-size:12px; } +table.edit td { padding:1px 2px; } +table.edit th { position: sticky; top: 0; z-index: 1; white-space: nowrap; } +table.edit td input[type=text], table.edit td select { width:100%; min-width:70px; border-color: transparent; background: transparent; padding:2px 4px; } +table.edit td input:focus, table.edit td select:focus { border-color: var(--accent); background: var(--bg); } +table.edit td.wide input { min-width: 200px; } +table.edit td.ro { color: var(--muted); padding: 2px 6px; white-space: nowrap; } +table.edit .num { text-align: right; } +table.edit td.idx { color: var(--muted); text-align: right; padding: 2px 4px; } +table.edit tr.warn td.idx { background: var(--warnbg); } +table.edit tr.err td.idx { background: var(--badbg); color: var(--bad); } +table.edit tr.focus td { outline: 1px solid var(--accent); } +button.del { padding: 0 6px; } +.preview { border:1px solid var(--line); border-radius:6px; padding:8px; background: var(--bg); overflow:auto; max-height: 75vh; } +.preview img, .preview svg { max-width: 100%; height: auto; } +.exported ul { margin: 4px 0; padding-left: 18px; font-size: 12px; } diff --git a/ui-plugins/batch-file-renamer/ui/app.ts b/ui-plugins/batch-file-renamer/ui/app.ts new file mode 100644 index 00000000..dba63195 --- /dev/null +++ b/ui-plugins/batch-file-renamer/ui/app.ts @@ -0,0 +1,236 @@ +import css from "./kit.css"; +import appCss from "./app.css"; +import { applyTheme, call, h, initHost, locale, onHostContext, onToolResult, put, toast, updateContext } from "./kit.ts"; + +type L = [string, string]; +interface Field { key: string; label: L; type: string; options?: { value: string; label: L }[]; default?: unknown; help?: L; min?: number; max?: number } +interface Column { key: string; label: L; type?: string; options?: string[]; readOnly?: boolean; wide?: boolean } +interface Issue { level: string; message: string; row?: number; key?: string } +interface Info { app: string; prefix: string; title: L; inputs: { exts: string[]; min: number; max: number; label: L; folders?: boolean }; settings: Field[]; exports: { id: string; label: L; description: string }[]; files: string[]; folders: string[]; projects: string[] } +interface View { project: string; inputs: string[]; settings: Record; columns: Column[]; rows: Record[]; totalRows: number; canAdd: boolean; issues: Issue[]; summary: string; stats: Record; preview: string; exported: string[]; justExported?: string[] } + +const T = (l: L | undefined) => (l ? (locale() === "zh" ? l[0] : l[1]) : ""); +const t = (zh: string, en: string) => (locale() === "zh" ? zh : en); +const PAGE = 100; + +export function startApp(name: string, version: string) { + const style = document.createElement("style"); + style.textContent = css + appCss; + document.head.append(style); + const root = document.getElementById("root")!; + const state: { info?: Info; view?: View; picked: Set; filter: string; page: number; startSettings: Record; focusRow?: number; mode: "start" | "project" } = { picked: new Set(), filter: "", page: 0, startSettings: {}, mode: "start" }; + + async function busy(work: () => Promise, label: string): Promise { + root.classList.add("busy"); + const st = document.getElementById("status"); + if (st) st.textContent = label; + try { + return await work(); + } catch (error) { + toast(error instanceof Error ? error.message : String(error), "error"); + return undefined; + } finally { + root.classList.remove("busy"); + const s2 = document.getElementById("status"); + if (s2) s2.textContent = ""; + } + } + const P = () => state.info?.prefix ?? name; + function show(v: Record) { + const prev = state.view?.project; + state.view = v as unknown as View; + state.mode = "project"; + if (prev !== state.view.project) state.page = 0; + render(); + } + onToolResult((v) => { + if (v?.kind === "project" && v.app === name) show(v); + }); + + async function refreshInfo() { + const info = await call("app_info", {}); + state.info = info; + render(); + } + + function fieldInput(f: Field, value: unknown, onChange: (v: unknown) => void) { + const v = value ?? f.default ?? ""; + if (f.type === "bool") return h("input", { type: "checkbox", checked: !!v, "data-key": f.key, onchange: (e: Event) => onChange((e.target as HTMLInputElement).checked) }); + if (f.type === "select") + return h("select", { "data-key": f.key, onchange: (e: Event) => onChange((e.target as HTMLSelectElement).value) }, ...(f.options ?? []).map((o) => h("option", { value: o.value, selected: String(v) === o.value }, T(o.label)))); + if (f.type === "textarea") return h("textarea", { rows: 3, "data-key": f.key, value: String(v), onchange: (e: Event) => onChange((e.target as HTMLTextAreaElement).value) }); + return h("input", { + type: f.type === "number" ? "number" : f.type === "color" ? "color" : f.type === "date" ? "date" : "text", + "data-key": f.key, + value: String(v), + min: f.min, + max: f.max, + step: f.type === "number" ? "any" : undefined, + onchange: (e: Event) => onChange(f.type === "number" ? Number((e.target as HTMLInputElement).value) : (e.target as HTMLInputElement).value), + }); + } + function settingsForm(values: Record, onChange: (key: string, v: unknown) => void) { + const fields = state.info?.settings ?? []; + if (!fields.length) return null; + return h("div", { class: "settings" }, ...fields.map((f) => h("label", { class: `set set-${f.type}`, title: T(f.help) }, h("span", {}, T(f.label)), fieldInput(f, values[f.key], (v) => onChange(f.key, v))))); + } + + function renderStart() { + const info = state.info; + if (!info) return h("div", { class: "empty" }, t("正在连接…", "Connecting…")); + const list = info.inputs.folders ? info.folders : info.files; + const shown = list.filter((f) => !state.filter || f.toLowerCase().includes(state.filter.toLowerCase())).slice(0, 400); + const needs = info.inputs.min; + const open = () => + busy(async () => { + const r = await call(`${P()}_open`, { inputs: [...state.picked], settings: state.startSettings }); + show(r); + }, t("正在读取…", "Reading…")); + return h( + "div", + { class: "start" }, + h("div", { class: "card" }, + h("h2", {}, T(info.inputs.label)), + needs === 0 && !list.length ? h("p", { class: "muted" }, t("这个工具不需要输入文件,直接点“开始”。", "No input file needed — just press Start.")) : null, + list.length > 8 ? h("input", { class: "filter", placeholder: t("筛选文件…", "Filter files…"), value: state.filter, oninput: (e: Event) => { state.filter = (e.target as HTMLInputElement).value; render(); } }) : null, + list.length + ? h("div", { class: "files" }, ...shown.map((f) => h("label", { class: "file" }, h("input", { type: info.inputs.max === 1 ? "radio" : "checkbox", name: "pick", checked: state.picked.has(f), onchange: (e: Event) => { if (info.inputs.max === 1) state.picked.clear(); if ((e.target as HTMLInputElement).checked) state.picked.add(f); else state.picked.delete(f); render(); } }), h("span", {}, f)))) + : needs > 0 ? h("div", { class: "empty" }, t(`工作区里没有 ${info.inputs.exts.join(" / ")} 文件。把文件放进项目文件夹,或让助手帮你处理。`, `No ${info.inputs.exts.join(" / ")} files in the workspace yet. Add some to the project folder or ask the assistant.`)) : null, + ), + info.settings.length ? h("div", { class: "card" }, h("h2", {}, t("设置", "Settings")), settingsForm(state.startSettings, (k, v) => { state.startSettings[k] = v; })) : null, + h("div", { class: "row" }, + h("button", { class: "primary open", disabled: state.picked.size < needs || state.picked.size > info.inputs.max, onclick: open }, needs === 0 && !state.picked.size ? t("开始", "Start") : t(`打开(${state.picked.size})`, `Open (${state.picked.size})`)), + h("button", { onclick: () => busy(refreshInfo, "") }, t("刷新文件列表", "Refresh files")), + ), + info.projects.length + ? h("div", { class: "card" }, h("h2", {}, t("已保存的项目", "Saved projects")), h("div", { class: "row" }, ...info.projects.map((p) => h("button", { class: "proj", onclick: () => busy(async () => show(await call(`${P()}_status`, { project: p })), "") }, p)))) + : null, + ); + } + + let editQueue: Promise = Promise.resolve(); + function edit(args: Record) { + const v = state.view!; + editQueue = editQueue + .then(async () => { + const r = await call(`${P()}_edit`, { project: v.project, ...args }); + state.view = r as unknown as View; + renderProjectParts(); + }) + .catch((e) => toast(String((e as Error)?.message ?? e), "error")); + return editQueue; + } + + function cell(c: Column, row: Record, index: number) { + const value = row[c.key]; + if (c.readOnly) return h("td", { "data-key": c.key, class: `ro ${c.type === "number" ? "num" : ""}` }, typeof value === "number" ? fmtNum(value) : String(value ?? "")); + const onChange = (v: unknown) => edit({ set: [{ row: index, values: { [c.key]: v } }] }); + let input: HTMLElement; + if (c.type === "bool") input = h("input", { type: "checkbox", checked: !!value, onchange: (e: Event) => onChange((e.target as HTMLInputElement).checked) }); + else if (c.type === "select") input = h("select", { onchange: (e: Event) => onChange((e.target as HTMLSelectElement).value) }, ...[...new Set([String(value ?? ""), ...(c.options ?? [])])].map((o) => h("option", { value: o, selected: o === String(value ?? "") }, o))); + else input = h("input", { type: "text", class: c.type === "number" ? "num" : "", value: String(value ?? ""), onchange: (e: Event) => onChange((e.target as HTMLInputElement).value) }); + return h("td", { "data-key": c.key, class: c.wide ? "wide" : "" }, input); + } + const fmtNum = (n: number) => (Number.isInteger(n) ? String(n) : n.toFixed(2)); + + function tableEl() { + const v = state.view!; + const issuesByRow = new Map(); + for (const i of v.issues) if (i.row !== undefined) issuesByRow.set(i.row, [...(issuesByRow.get(i.row) ?? []), i]); + const pages = Math.max(1, Math.ceil(v.rows.length / PAGE)); + state.page = Math.min(state.page, pages - 1); + const start = state.page * PAGE; + const slice = v.rows.slice(start, start + PAGE); + if (!v.rows.length) return h("div", { class: "empty" }, t("没有数据行。", "No rows.")); + return h("div", {}, + h("div", { class: "tablewrap" }, + h("table", { class: "data edit" }, + h("thead", {}, h("tr", {}, h("th", {}, "#"), ...v.columns.map((c) => h("th", { class: c.readOnly ? "ro" : "" }, T(c.label))), v.canAdd ? h("th", {}, "") : null)), + h("tbody", {}, ...slice.map((row, k) => { + const index = start + k; + const iss = issuesByRow.get(index); + return h("tr", { class: `${iss?.some((i) => i.level === "error") ? "err" : iss ? "warn" : ""} ${state.focusRow === index ? "focus" : ""}`, "data-row": index, title: iss?.map((i) => i.message).join("\n") }, + h("td", { class: "idx" }, String(index)), ...v.columns.map((c) => cell(c, row, index)), + v.canAdd ? h("td", {}, h("button", { class: "del", title: t("删除这一行", "Delete row"), onclick: () => edit({ remove: [index] }) }, "×")) : null); + })), + ), + ), + h("div", { class: "row" }, + pages > 1 ? h("span", { class: "pager" }, h("button", { disabled: state.page === 0, onclick: () => { state.page--; renderProjectParts(); } }, "‹"), ` ${state.page + 1} / ${pages} `, h("button", { disabled: state.page >= pages - 1, onclick: () => { state.page++; renderProjectParts(); } }, "›")) : null, + v.totalRows > v.rows.length ? h("span", { class: "muted" }, t(`面板显示前 ${v.rows.length} 行,共 ${v.totalRows} 行`, `Showing ${v.rows.length} of ${v.totalRows} rows`)) : null, + v.canAdd ? h("button", { class: "add", onclick: () => edit({ add: [{}] }) }, t("+ 新增一行", "+ Add row")) : null, + ), + ); + } + + function issuesEl() { + const v = state.view!; + if (!v.issues.length) return h("div", { class: "issues ok" }, h("span", { class: "badge ok" }, t("没有发现问题", "No issues"))); + const counts = { error: 0, warn: 0, info: 0 } as Record; + for (const i of v.issues) counts[i.level] = (counts[i.level] ?? 0) + 1; + return h("details", { class: "issues", open: v.issues.length <= 12 }, + h("summary", {}, counts.error ? h("span", { class: "badge bad" }, t(`${counts.error} 个错误`, `${counts.error} error(s)`)) : null, " ", counts.warn ? h("span", { class: "badge" }, t(`${counts.warn} 个提醒`, `${counts.warn} warning(s)`)) : null, " ", counts.info ? h("span", { class: "badge ok" }, t(`${counts.info} 条说明`, `${counts.info} note(s)`)) : null), + h("ul", {}, ...v.issues.slice(0, 200).map((i) => h("li", { class: `lvl-${i.level}`, onclick: () => { if (i.row !== undefined) { state.focusRow = i.row; state.page = Math.floor(i.row / PAGE); renderProjectParts(); document.querySelector(`tr[data-row="${i.row}"]`)?.scrollIntoView({ block: "center" }); } } }, i.row !== undefined ? h("b", {}, `#${i.row} `) : null, i.key ? h("code", {}, i.key) : null, " ", i.message))), + ); + } + + function exportsEl() { + const v = state.view!; + const info = state.info; + const run = (formats?: string[]) => + busy(async () => { + const r = await call(`${P()}_export`, { project: v.project, ...(formats ? { formats } : {}) }, 900_000); + state.view = r as unknown as View; + renderProjectParts(); + toast(t(`已导出 ${state.view.exported.length} 个文件`, `Exported ${state.view.exported.length} file(s)`)); + updateContext(`User exported ${v.project}: ${state.view.exported.join(", ")}`).catch(() => undefined); + }, t("正在导出…", "Exporting…")); + return h("div", { class: "card exports" }, + h("h2", {}, t("导出", "Export")), + h("div", { class: "row" }, ...(info?.exports ?? []).map((e) => h("button", { class: "exp", title: e.description, "data-id": e.id, onclick: () => run([e.id]) }, T(e.label))), (info?.exports.length ?? 0) > 1 ? h("button", { class: "primary expall", onclick: () => run() }, t("全部导出", "Export all")) : null), + v.exported.length ? h("div", { class: "exported" }, h("div", { class: "muted" }, t("已导出:", "Exported:")), h("ul", {}, ...v.exported.map((f) => h("li", {}, h("code", {}, f))))) : null, + ); + } + + function renderProjectParts() { + const v = state.view; + if (!v) return; + const parts: Record Node | null> = { + summary: () => h("div", {}, h("div", { class: "summary" }, v.summary), Object.keys(v.stats).length ? h("div", { class: "chips" }, ...Object.entries(v.stats).map(([k, s]) => h("span", { class: "chip" }, h("b", {}, String(s)), " ", k))) : null), + issues: issuesEl, + table: tableEl, + preview: () => (v.preview ? (() => { const d = h("div", { class: "preview" }); d.innerHTML = v.preview; return d; })() : null), + exports: exportsEl, + }; + for (const [id, make] of Object.entries(parts)) { + const el = document.getElementById(`part-${id}`); + if (el) put(el, make()); + } + } + + function renderProject() { + const v = state.view!; + return h("div", { class: "project" }, + h("div", { class: "row head" }, + h("span", { class: "pname" }, v.project), + v.inputs.length ? h("span", { class: "muted" }, v.inputs.length > 3 ? t(`${v.inputs.length} 个输入`, `${v.inputs.length} inputs`) : v.inputs.join(" · ")) : null, + h("button", { class: "back", onclick: () => { state.mode = "start"; busy(refreshInfo, ""); } }, t("← 换文件", "← Other files")), + ), + state.info?.settings.length ? h("details", { class: "card", open: true }, h("summary", {}, t("设置", "Settings")), settingsForm(v.settings, (k, val) => edit({ settings: { [k]: val } }))) : null, + h("div", { id: "part-summary" }), + h("div", { id: "part-issues" }), + h("div", { class: "split2" }, h("div", { id: "part-table", class: "tablecol" }), h("div", { id: "part-preview", class: "previewcol" })), + h("div", { id: "part-exports" }), + ); + } + + function render() { + const title = state.info ? T(state.info.title) : name; + put(root, h("div", { class: "top" }, h("h1", {}, title), h("span", { id: "status", class: "muted" })), state.mode === "project" && state.view ? renderProject() : renderStart()); + if (state.mode === "project") renderProjectParts(); + } + + onHostContext(() => { applyTheme(); render(); }); + render(); + initHost(name, version).then(() => { applyTheme(); refreshInfo().catch((e) => toast(String(e?.message ?? e), "error")); }); +} diff --git a/ui-plugins/batch-file-renamer/ui/env.d.ts b/ui-plugins/batch-file-renamer/ui/env.d.ts new file mode 100644 index 00000000..4210a464 --- /dev/null +++ b/ui-plugins/batch-file-renamer/ui/env.d.ts @@ -0,0 +1,4 @@ +declare module "*.css" { + const text: string; + export default text; +} diff --git a/ui-plugins/batch-file-renamer/ui/kit.css b/ui-plugins/batch-file-renamer/ui/kit.css new file mode 100644 index 00000000..398bc83a --- /dev/null +++ b/ui-plugins/batch-file-renamer/ui/kit.css @@ -0,0 +1,34 @@ +:root { --bg:#fff; --fg:#1d1f23; --muted:#6b7280; --line:#e5e7eb; --panel:#f7f7f8; --accent:#2563eb; --warn:#b45309; --warnbg:#fef3c7; --bad:#b91c1c; --badbg:#fee2e2; --okbg:#dcfce7; --ok:#15803d; } +[data-theme="dark"] { --bg:#18191b; --fg:#e8e8ea; --muted:#9ca3af; --line:#2e3035; --panel:#222327; --accent:#60a5fa; --warn:#fbbf24; --warnbg:#3b2f10; --bad:#f87171; --badbg:#3b1717; --okbg:#12301d; --ok:#4ade80; } +* { box-sizing: border-box; } +html, body { margin:0; background:var(--bg); color:var(--fg); font:13px/1.45 -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif; } +#root { padding: 12px; } +h1 { font-size: 15px; margin: 0 0 8px; } +h2 { font-size: 13px; margin: 14px 0 6px; color: var(--muted); font-weight: 600; text-transform: none; } +button { font: inherit; border:1px solid var(--line); background:var(--panel); color:var(--fg); border-radius:6px; padding:5px 10px; cursor:pointer; } +button.primary { background:var(--accent); border-color:var(--accent); color:#fff; } +button:disabled { opacity:.5; cursor:default; } +input, select, textarea { font: inherit; color: var(--fg); background: var(--bg); border:1px solid var(--line); border-radius:5px; padding:4px 6px; } +input[type="color"] { padding: 0; width: 32px; height: 26px; } +input[type="range"] { padding: 0; } +label { display:flex; gap:6px; align-items:center; } +.row { display:flex; gap:8px; align-items:center; flex-wrap:wrap; margin: 6px 0; } +.muted { color: var(--muted); } +.card { border:1px solid var(--line); border-radius:8px; padding:10px; background:var(--panel); margin: 8px 0; } +.grid { display:grid; grid-template-columns:repeat(auto-fill, minmax(150px, 1fr)); gap:8px; } +.thumb { border:1px solid var(--line); border-radius:6px; overflow:hidden; background: var(--bg); cursor:pointer; position:relative; } +.thumb img { width:100%; display:block; aspect-ratio:1; object-fit:contain; background: repeating-conic-gradient(#ddd 0 25%, #fff 0 50%) 50% / 16px 16px; } +.thumb .cap { padding:4px 6px; font-size:12px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; } +.thumb.selected { outline: 2px solid var(--accent); } +.badge { display:inline-block; font-size:11px; padding:1px 6px; border-radius:10px; background:var(--warnbg); color:var(--warn); } +.badge.bad { background: var(--badbg); color: var(--bad); } +.badge.ok { background: var(--okbg); color: var(--ok); } +table.data { border-collapse: collapse; width: 100%; } +table.data td, table.data th { border:1px solid var(--line); padding:3px 6px; text-align:left; vertical-align:top; } +table.data th { background: var(--panel); } +.toast { position: fixed; right: 12px; bottom: 12px; padding: 8px 12px; border-radius: 6px; background: var(--okbg); color: var(--ok); z-index: 10; max-width: 80%; } +.toast.error { background: var(--badbg); color: var(--bad); } +.empty { padding: 24px; text-align:center; color: var(--muted); border: 1px dashed var(--line); border-radius: 8px; } +.busy { opacity:.6; pointer-events:none; } +.split { display:grid; grid-template-columns: minmax(0,1fr) minmax(0,1fr); gap: 10px; } +@media (max-width: 640px) { .split { grid-template-columns: 1fr; } } diff --git a/ui-plugins/batch-file-renamer/ui/kit.ts b/ui-plugins/batch-file-renamer/ui/kit.ts new file mode 100644 index 00000000..b0646f25 --- /dev/null +++ b/ui-plugins/batch-file-renamer/ui/kit.ts @@ -0,0 +1,133 @@ +import { App } from "@modelcontextprotocol/ext-apps"; + +export class ToolError extends Error { + readonly code: string; + constructor(code: string, message: string) { + super(message); + this.code = code; + } +} + +let app: App | undefined; +let connection: Promise | undefined; +let created!: () => void; +const appCreated = new Promise((resolve) => (created = resolve)); +const resultListeners = new Set<(value: Record | undefined, tool?: string) => void>(); +const contextListeners = new Set<() => void>(); + +export function initHost(name: string, version: string) { + app = new App({ name, version }, { availableDisplayModes: ["inline", "fullscreen"] }); + app.ontoolresult = (result) => { + const content = result.structuredContent as Record | undefined; + resultListeners.forEach((listener) => listener(content)); + }; + app.onhostcontextchanged = () => contextListeners.forEach((listener) => listener()); + created(); + return ready(); +} + +export function ready(): Promise { + if (!app) return appCreated.then(() => ready()); + return (connection ??= app.connect().then(() => contextListeners.forEach((listener) => listener()))); +} + +export function onToolResult(listener: (value: Record | undefined) => void) { + resultListeners.add(listener); +} + +export function onHostContext(listener: () => void) { + contextListeners.add(listener); +} + +export function hostContext() { + return app?.getHostContext(); +} + +export function locale(): "zh" | "en" { + const fromHost = (app?.getHostContext()?.locale as string | undefined) ?? navigator.language ?? "en"; + return /^zh/i.test(fromHost) ? "zh" : "en"; +} + +export async function call>(name: string, args: Record = {}, timeout = 300_000): Promise { + await ready(); + let result; + try { + result = await app!.callServerTool({ name, arguments: args }, { timeout }); + } catch (error) { + throw new ToolError("host_error", error instanceof Error ? error.message : String(error)); + } + const content = result.structuredContent as Record | undefined; + const error = content?.error as { code?: string; message?: string } | undefined; + if (result.isError || error) { + const text = (result.content?.[0] as { text?: string } | undefined)?.text; + throw new ToolError(error?.code ?? "tool_error", error?.message ?? text ?? "The tool failed."); + } + return (content ?? {}) as T; +} + +/** 读取插件资源(二进制)。 */ +export async function readBlob(uri: string): Promise { + await ready(); + const result = await app!.readServerResource({ uri }); + const first = result.contents[0] as { blob?: string; text?: string } | undefined; + if (typeof first?.blob !== "string") throw new ToolError("host_error", first?.text?.slice(0, 300) ?? `Empty resource ${uri}`); + return base64ToBytes(first.blob); +} + +export function base64ToBytes(base64: string): Uint8Array { + const binary = atob(base64); + const bytes = new Uint8Array(binary.length); + for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index); + return bytes; +} + +/** 由用户点击触发:把一句话发到对话里交给 Agent。 */ +export async function sendMessage(text: string) { + await ready(); + return app!.sendMessage({ role: "user", content: [{ type: "text", text }] }); +} + +export async function updateContext(text: string) { + await ready(); + return app!.updateModelContext({ content: [{ type: "text", text }] }); +} + +type Child = Node | string | number | null | undefined | false; +/** 极简 DOM 构建器。 */ +export function h( + tag: K, + props: Record = {}, + ...children: (Child | Child[])[] +): HTMLElementTagNameMap[K] { + const element = document.createElement(tag); + for (const [key, value] of Object.entries(props)) { + if (value === undefined || value === null || value === false) continue; + if (key.startsWith("on") && typeof value === "function") element.addEventListener(key.slice(2).toLowerCase(), value as EventListener); + else if (key === "class") element.className = String(value); + else if (key === "style" && typeof value === "object") Object.assign(element.style, value); + else if (key === "value" || (key in element && typeof value !== "string")) (element as any)[key] = value; + else element.setAttribute(key, value === true ? "" : String(value)); + } + for (const child of children.flat()) { + if (child === null || child === undefined || child === false) continue; + element.append(child instanceof Node ? child : String(child)); + } + return element; +} + +export function toast(message: string, kind: "ok" | "error" = "ok") { + const node = h("div", { class: `toast ${kind}`, role: "status" }, message); + document.body.append(node); + setTimeout(() => node.remove(), kind === "error" ? 6000 : 3000); +} + +/** 主题:跟随宿主的浅色 / 深色。 */ +export function applyTheme() { + const theme = (app?.getHostContext()?.theme as string | undefined) ?? "light"; + document.documentElement.dataset.theme = theme === "dark" ? "dark" : "light"; +} + +/** replaceChildren,跳过 null / false。 */ +export function put(element: Element, ...children: (Node | string | null | undefined | false)[]) { + element.replaceChildren(...(children.filter((c) => c !== null && c !== undefined && c !== false) as (Node | string)[])); +} diff --git a/ui-plugins/batch-file-renamer/ui/main.ts b/ui-plugins/batch-file-renamer/ui/main.ts new file mode 100644 index 00000000..1a659cf2 --- /dev/null +++ b/ui-plugins/batch-file-renamer/ui/main.ts @@ -0,0 +1,3 @@ +import { startApp } from "./app.ts"; + +startApp("batch-file-renamer", "0.1.0"); diff --git a/ui-plugins/batch-file-renamer/vitest.config.ts b/ui-plugins/batch-file-renamer/vitest.config.ts new file mode 100644 index 00000000..27153a26 --- /dev/null +++ b/ui-plugins/batch-file-renamer/vitest.config.ts @@ -0,0 +1,2 @@ +import { defineConfig } from "vitest/config"; +export default defineConfig({ test: { include: ["src/**/*.test.ts", "test/**/*.test.ts"], testTimeout: 120000, hookTimeout: 120000 } });