From 9ece0780a9873d420af5206767b9e44b89e98608 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:14:15 -0400 Subject: [PATCH 01/11] feat(ui-plugins): add Photo Date Organizer (photo-date-organizer) --- marketplace.json | 49 ++++++++++++++++++++++++++++++ pnpm-lock.yaml | 77 ++++++++++++++++++++++-------------------------- 2 files changed, 85 insertions(+), 41 deletions(-) diff --git a/marketplace.json b/marketplace.json index 32e8c8ef..b3f9321f 100644 --- a/marketplace.json +++ b/marketplace.json @@ -1673,6 +1673,55 @@ "把上一个 Hi3D 任务生成的模型按角色拆分成部件" ] } + }, + { + "name": "photo-date-organizer", + "componentTypes": [ + "ui" + ], + "source": "./external_plugins/photo-date-organizer", + "displayName": "Photo Date Organizer", + "displayName_i18n": { + "en": "Photo Date Organizer", + "zh-CN": "照片按日期整理" + }, + "description": "Sort a messy folder of phone photos, screenshots and videos into year/month folders by the date they were taken — read from EXIF, the video's creation time or a date in the file name, with the file time only as a last resort — and optionally rename them to 20261002_091500.jpg. Every file shows where its date came from, you can correct any date, and a move can be undone. Runs locally; no API keys.", + "description_i18n": { + "en": "Sort a messy folder of phone photos, screenshots and videos into year/month folders by the date they were taken — read from EXIF, the video's creation time or a date in the file name, with the file time only as a last resort — and optionally rename them to 20261002_091500.jpg. Every file shows where its date came from, you can correct any date, and a move can be undone. Runs locally; no API keys.", + "zh-CN": "把乱七八糟的手机照片、截图和视频,按拍摄日期整理进“年/月”文件夹——日期取自 EXIF、视频创建时间或文件名里的日期,最后才用文件修改时间——还可以统一改名成 20261002_091500.jpg。每个文件都标明日期来源,日期可以手动改正,移动后还能撤销。在本地运行,无需 API 密钥。" + }, + "version": "0.1.0", + "author": { + "name": "Penova", + "url": "https://github.com/ppppp2005-p" + }, + "license": "MIT", + "category": "productivity", + "keywords": [ + "photos", + "exif", + "date taken", + "organize", + "sort by date", + "screenshots", + "照片整理", + "按日期", + "拍摄时间", + "相册", + "归档" + ], + "examplePrompts": [ + "Sort 手机相册/ into year/month folders by date taken", + "Also rename them to the date, like 20261002_091500.jpg", + "Undo the last move" + ], + "examplePrompts_i18n": { + "zh-CN": [ + "把 手机相册/ 按拍摄日期整理成 年/月 文件夹", + "顺便把文件名改成日期,像 20261002_091500.jpg", + "撤销刚才的整理" + ] + } } ] } \ No newline at end of file diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 14b35f76..a775aa53 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -222,6 +222,37 @@ importers: ui-plugins/pdfcraft: {} + ui-plugins/photo-date-organizer: + 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/photocraft: {} ui-plugins/soundcraft: {} @@ -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) From 650f646c9829d718a051009a99c2c4ce2075ea9b Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:14:49 -0400 Subject: [PATCH 02/11] feat(ui-plugins): add Photo Date Organizer (photo-date-organizer) --- external_plugins/photo-date-organizer/LICENSE | 21 ++++++++ .../photo-date-organizer/README.md | 52 +++++++++++++++++++ .../photo-date-organizer/README_CN.md | 52 +++++++++++++++++++ 3 files changed, 125 insertions(+) create mode 100644 external_plugins/photo-date-organizer/LICENSE create mode 100644 external_plugins/photo-date-organizer/README.md create mode 100644 external_plugins/photo-date-organizer/README_CN.md diff --git a/external_plugins/photo-date-organizer/LICENSE b/external_plugins/photo-date-organizer/LICENSE new file mode 100644 index 00000000..67e98093 --- /dev/null +++ b/external_plugins/photo-date-organizer/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/photo-date-organizer/README.md b/external_plugins/photo-date-organizer/README.md new file mode 100644 index 00000000..7b94c10a --- /dev/null +++ b/external_plugins/photo-date-organizer/README.md @@ -0,0 +1,52 @@ +# Photo Date Organizer + +Sort a messy folder of phone photos, screenshots and videos into year/month folders by the date they were taken — read from EXIF, the video's creation time or a date in the file name, with the file time only as a last resort — and optionally rename them to 20261002_091500.jpg. Every file shows where its date came from, you can correct any date, and a move can be undone. Runs locally; no API keys. + +## Features + +- **Real dates first**: EXIF DateTimeOriginal for JPEG/HEIC/TIFF/DNG, the MP4/MOV creation time, then dates in names (IMG_20261103_101522, Screenshot 2026-11-05 at 10.22.31, 微信图片_20261106, mmexport timestamps), and only then the file time — flagged, because copying changes it. +- **Layouts**: 2026/2026-10, 2026-10, 2026/10, 2026/2026-10-02, 2026-10-02 or no folders; keep names, rename to the date, or date + original name. +- **Fix in the table**: type a date in any format like 2024-02-02 12:00 or 2024年2月2日; the source becomes “manual”. Camera make/model is shown. +- **Safe**: same-name files get -2, -3; nothing is overwritten. Move mode can be undone; copy mode writes into the plugin's output and leaves the originals alone. +- **Plan first**: organize-plan.csv lists each file, its date, the source and its destination. +- **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 `photo-date-organizer/.project.json` and kept until you re-open the inputs. + +## Usage + +Ask the agent in ZCode Desktop: + +- "Sort 手机相册/ into year/month folders by date taken" +- "Also rename them to the date, like 20261002_091500.jpg" +- "Undo the last move" + +## Tools + +| Tool | Purpose | +|---|---| +| `photos_open` | Read the date of every photo and video in a folder and plan the date folders. Opens the panel | +| `photos_edit` | Change settings, edit cells by row, add or remove rows | +| `photos_status` | Show the current rows, issues and summary | +| `photos_export` | Write organize-plan.csv, then move or copy the files into the date folders (organize-log.csv); undo moves them back | + +Output goes to `photo-date-organizer//` in the workspace. + +## Scope (v0.1) + +- Dates are the camera's local time; time zones are not converted (videos use the computer's time zone). +- No face, place or content grouping; GPS is read but not used for folders in v0.1. +- One folder (with subfolders) and up to 20,000 files per project; RAW formats other than DNG fall back to the name or file time. + +## 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 `photo-date-organizer/` folder in the workspace; in move mode it also moves the photos inside the folder you pick, but only when you click “Organize” (and back with “Undo last move”). No hooks. + +## Build and test (developers) + +- Source: `ui-plugins/photo-date-organizer/`. +- Build: `pnpm install --frozen-lockfile && pnpm build`, then add `dist/local-marketplace` as a local source. +- Tests: `pnpm --filter @penova/plugin-photo-date-organizer 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/photo-date-organizer/README_CN.md b/external_plugins/photo-date-organizer/README_CN.md new file mode 100644 index 00000000..26da08c7 --- /dev/null +++ b/external_plugins/photo-date-organizer/README_CN.md @@ -0,0 +1,52 @@ +# 照片按日期整理 + +把乱七八糟的手机照片、截图和视频,按拍摄日期整理进“年/月”文件夹——日期取自 EXIF、视频创建时间或文件名里的日期,最后才用文件修改时间——还可以统一改名成 20261002_091500.jpg。每个文件都标明日期来源,日期可以手动改正,移动后还能撤销。在本地运行,无需 API 密钥。 + +## 功能 + +- **优先用真实日期**:JPEG/HEIC/TIFF/DNG 的 EXIF 拍摄时间、MP4/MOV 的创建时间,其次是文件名里的日期(IMG_20261103_101522、Screenshot 2026-11-05 at 10.22.31、微信图片_20261106、mmexport 时间戳),最后才用文件修改时间——并会提醒,因为拷贝会改变它。 +- **文件夹结构**:2026/2026-10、2026-10、2026/10、2026/2026-10-02、2026-10-02 或不分文件夹;保留原名、改成日期,或“日期 + 原名”。 +- **表格里改正**:日期可以写成 2024-02-02 12:00 或 2024年2月2日 等格式,来源会变成“手动”。会显示相机品牌和型号。 +- **安全**:重名自动加 -2、-3,不会覆盖任何文件。移动模式可以撤销;复制模式写到插件输出文件夹,原文件不动。 +- **先看清单**:organize-plan.csv 列出每个文件的日期、来源和去向。 +- **面板**:在 ZCode 侧栏里选择输入文件、调整设置、查看问题、直接修改表格里的任意单元格、预览成品并导出。修改保存在 `photo-date-organizer/<项目>.project.json`,重新打开输入文件前一直保留。 + +## 使用方法 + +在 ZCode 桌面端对助手说: + +- “把 手机相册/ 按拍摄日期整理成 年/月 文件夹” +- “顺便把文件名改成日期,像 20261002_091500.jpg” +- “撤销刚才的整理” + +## 工具 + +| 工具 | 作用 | +|---|---| +| `photos_open` | 读取文件夹里每张照片和每个视频的日期,规划日期文件夹,并打开面板 | +| `photos_edit` | 修改设置、按行修改单元格、新增或删除行 | +| `photos_status` | 查看当前数据、问题和汇总 | +| `photos_export` | 导出 organize-plan.csv,再把文件移动或复制到日期文件夹(organize-log.csv);undo 可移回原处 | + +导出文件写到工作区的 `photo-date-organizer/<项目>/` 文件夹。 + +## 范围(v0.1) + +- 日期按相机记录的本地时间,不做时区换算(视频按电脑所在时区)。 +- 不按人脸、地点或内容分组;v0.1 会读取 GPS 但不用于分文件夹。 +- 每个项目一个文件夹(可含子文件夹),最多 20,000 个文件;DNG 以外的 RAW 格式按文件名或文件时间。 + +## 隐私、网络与文件 + +- **全部在本地运行。** 不联网、不上传,不需要 API 密钥或账号。 +- 只读取你选择的文件,只写入工作区的 `photo-date-organizer/` 文件夹;移动模式下,只有在你点“开始整理”时才会移动所选文件夹里的照片(点“撤销上次整理”可移回)。没有 Hook。 + +## 构建与测试(开发者) + +- 源码:`ui-plugins/photo-date-organizer/`。 +- 构建:`pnpm install --frozen-lockfile && pnpm build`,然后把 `dist/local-marketplace` 添加为本地来源。 +- 测试:`pnpm --filter @penova/plugin-photo-date-organizer test` 和 `test:e2e`(需要 Chrome;样例文件在 `test/samples/`)。 + +## 第三方组件与许可证 + +MIT 许可(作者:Penova)。打包的组件:MCP SDK 与 ext-apps(MIT)、zod(MIT);完整列表见 `dist/THIRD_PARTY_NOTICES.txt`。 From a5affbdd849efacd981316ca13ecc27d3b31319a Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:15:46 -0400 Subject: [PATCH 03/11] feat(ui-plugins): add Photo Date Organizer (photo-date-organizer) --- ui-plugins/photo-date-organizer/package.json | 32 +++++++++++++++++++ ui-plugins/photo-date-organizer/tsconfig.json | 14 ++++++++ .../photo-date-organizer/vitest.config.ts | 2 ++ 3 files changed, 48 insertions(+) create mode 100644 ui-plugins/photo-date-organizer/package.json create mode 100644 ui-plugins/photo-date-organizer/tsconfig.json create mode 100644 ui-plugins/photo-date-organizer/vitest.config.ts diff --git a/ui-plugins/photo-date-organizer/package.json b/ui-plugins/photo-date-organizer/package.json new file mode 100644 index 00000000..04af263d --- /dev/null +++ b/ui-plugins/photo-date-organizer/package.json @@ -0,0 +1,32 @@ +{ + "name": "@penova/plugin-photo-date-organizer", + "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": "Photo Date Organizer" + }, + "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/photo-date-organizer/tsconfig.json b/ui-plugins/photo-date-organizer/tsconfig.json new file mode 100644 index 00000000..39f7ab60 --- /dev/null +++ b/ui-plugins/photo-date-organizer/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/photo-date-organizer/vitest.config.ts b/ui-plugins/photo-date-organizer/vitest.config.ts new file mode 100644 index 00000000..27153a26 --- /dev/null +++ b/ui-plugins/photo-date-organizer/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 } }); From eda849c3ef4efe0f0f45e719c187aed42ae34d91 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:16:18 -0400 Subject: [PATCH 04/11] feat(ui-plugins): add Photo Date Organizer (photo-date-organizer) --- .../.zcode-plugin/plugin.json | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 external_plugins/photo-date-organizer/.zcode-plugin/plugin.json diff --git a/external_plugins/photo-date-organizer/.zcode-plugin/plugin.json b/external_plugins/photo-date-organizer/.zcode-plugin/plugin.json new file mode 100644 index 00000000..b7c92dd5 --- /dev/null +++ b/external_plugins/photo-date-organizer/.zcode-plugin/plugin.json @@ -0,0 +1,57 @@ +{ + "name": "photo-date-organizer", + "version": "0.1.0", + "description": "Sort a messy folder of phone photos, screenshots and videos into year/month folders by the date they were taken — read from EXIF, the video's creation time or a date in the file name, with the file time only as a last resort — and optionally rename them to 20261002_091500.jpg. Every file shows where its date came from, you can correct any date, and a move can be undone. Runs locally; no API keys.", + "description_i18n": { + "en": "Sort a messy folder of phone photos, screenshots and videos into year/month folders by the date they were taken — read from EXIF, the video's creation time or a date in the file name, with the file time only as a last resort — and optionally rename them to 20261002_091500.jpg. Every file shows where its date came from, you can correct any date, and a move can be undone. Runs locally; no API keys.", + "zh-CN": "把乱七八糟的手机照片、截图和视频,按拍摄日期整理进“年/月”文件夹——日期取自 EXIF、视频创建时间或文件名里的日期,最后才用文件修改时间——还可以统一改名成 20261002_091500.jpg。每个文件都标明日期来源,日期可以手动改正,移动后还能撤销。在本地运行,无需 API 密钥。" + }, + "author": { + "name": "Penova", + "url": "https://github.com/ppppp2005-p" + }, + "license": "MIT", + "keywords": [ + "photos", + "exif", + "date taken", + "organize", + "sort by date", + "screenshots", + "照片整理", + "按日期", + "拍摄时间", + "相册", + "归档" + ], + "skills": "skills", + "mcpServers": { + "photo-date-organizer": { + "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": "Photo Date Organizer" + }, + "icon": "calendar-days", + "server": "photo-date-organizer", + "resourceUri": "ui://photo-date-organizer/panel.html", + "availability": "session" + } + ] + } +} From bcaf55a70262a3264b9c216cdb2a65fc71afa490 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:16:53 -0400 Subject: [PATCH 05/11] feat(ui-plugins): add Photo Date Organizer (photo-date-organizer) --- .../photo-date-organizer/scripts/build.mjs | 74 ++++++++ .../photo-date-organizer/scripts/e2e.mts | 84 +++++++++ .../photo-date-organizer/scripts/harness.mjs | 162 ++++++++++++++++++ .../photo-date-organizer/scripts/licenses.mjs | 43 +++++ 4 files changed, 363 insertions(+) create mode 100644 ui-plugins/photo-date-organizer/scripts/build.mjs create mode 100644 ui-plugins/photo-date-organizer/scripts/e2e.mts create mode 100644 ui-plugins/photo-date-organizer/scripts/harness.mjs create mode 100644 ui-plugins/photo-date-organizer/scripts/licenses.mjs diff --git a/ui-plugins/photo-date-organizer/scripts/build.mjs b/ui-plugins/photo-date-organizer/scripts/build.mjs new file mode 100644 index 00000000..02ff90d4 --- /dev/null +++ b/ui-plugins/photo-date-organizer/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/photo-date-organizer/scripts/e2e.mts b/ui-plugins/photo-date-organizer/scripts/e2e.mts new file mode 100644 index 00000000..a8dd0542 --- /dev/null +++ b/ui-plugins/photo-date-organizer/scripts/e2e.mts @@ -0,0 +1,84 @@ +// 浏览器端到端测试:真实打包的 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 cell = frame.locator(`tr[data-row="${spec.uiEdit.row}"] td[data-key="${spec.uiEdit.key}"]`); + if (typeof spec.uiEdit.value === "boolean") await cell.locator("input").setChecked(spec.uiEdit.value); + else if (await cell.locator("select").count()) await cell.locator("select").selectOption(String(spec.uiEdit.value)); + else { + const input = cell.locator("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/photo-date-organizer/scripts/harness.mjs b/ui-plugins/photo-date-organizer/scripts/harness.mjs new file mode 100644 index 00000000..a45e6e41 --- /dev/null +++ b/ui-plugins/photo-date-organizer/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/photo-date-organizer/scripts/licenses.mjs b/ui-plugins/photo-date-organizer/scripts/licenses.mjs new file mode 100644 index 00000000..5107fe7c --- /dev/null +++ b/ui-plugins/photo-date-organizer/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")); +} From 72aa7f89dee4d5b245f3fabd43c8ec6589aedff6 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:18:07 -0400 Subject: [PATCH 06/11] feat(ui-plugins): add Photo Date Organizer (photo-date-organizer) --- ui-plugins/photo-date-organizer/src/dates.ts | 30 +++ ui-plugins/photo-date-organizer/src/exif.ts | 110 +++++++++++ ui-plugins/photo-date-organizer/src/main.ts | 14 ++ ui-plugins/photo-date-organizer/src/server.ts | 186 ++++++++++++++++++ 4 files changed, 340 insertions(+) create mode 100644 ui-plugins/photo-date-organizer/src/dates.ts create mode 100644 ui-plugins/photo-date-organizer/src/exif.ts create mode 100644 ui-plugins/photo-date-organizer/src/main.ts create mode 100644 ui-plugins/photo-date-organizer/src/server.ts diff --git a/ui-plugins/photo-date-organizer/src/dates.ts b/ui-plugins/photo-date-organizer/src/dates.ts new file mode 100644 index 00000000..66f030ed --- /dev/null +++ b/ui-plugins/photo-date-organizer/src/dates.ts @@ -0,0 +1,30 @@ +const z = (n: number) => String(n).padStart(2, "0"); +export const fmtLocal = (d: Date) => `${d.getFullYear()}-${z(d.getMonth() + 1)}-${z(d.getDate())} ${z(d.getHours())}:${z(d.getMinutes())}:${z(d.getSeconds())}`; + +const valid = (y: number, mo: number, d: number, h = 0, mi = 0, s = 0) => y >= 1990 && y <= 2100 && mo >= 1 && mo <= 12 && d >= 1 && d <= 31 && h < 24 && mi < 60 && s < 60; + +/** 从文件名猜日期(IMG_20261103_101522、Screenshot 2026-11-05 at 10.22.31、mmexport1762750000000 …)。 */ +export function dateFromName(name: string): string | undefined { + const full = name.match(/(? = { 1: 1, 2: 1, 3: 2, 4: 4, 5: 8, 7: 1, 9: 4, 10: 8 }; + +export function parseTiff(b: Uint8Array, start = 0): ExifInfo { + const dv = new DataView(b.buffer, b.byteOffset + start, b.byteLength - start); + const le = dv.getUint16(0) === 0x4949; + if (!le && dv.getUint16(0) !== 0x4d4d) return { tags: 0 }; + const u16 = (o: number) => dv.getUint16(o, le); + const u32 = (o: number) => dv.getUint32(o, le); + const info: ExifInfo = { tags: 0 }; + const seen = new Set(); + const readIfd = (off: number, kind: "0" | "exif" | "gps") => { + if (!off || seen.has(off) || off + 2 > dv.byteLength) return; + seen.add(off); + const n = u16(off); + const gps: Record = {}; + for (let i = 0; i < n; i++) { + const e = off + 2 + i * 12; + if (e + 12 > dv.byteLength) break; + const tag = u16(e), type = u16(e + 2), count = u32(e + 4); + const size = (TYPE_SIZE[type] ?? 1) * count; + const vo = size <= 4 ? e + 8 : u32(e + 8); + if (vo + size > dv.byteLength) continue; + info.tags++; + const str = () => new TextDecoder().decode(new Uint8Array(dv.buffer, dv.byteOffset + vo, count)).replace(/\0+$/, "").trim(); + const rats = () => Array.from({ length: count }, (_, k) => u32(vo + k * 8) / (u32(vo + k * 8 + 4) || 1)); + if (kind === "gps") { gps[tag] = type === 2 ? str() : type === 5 ? rats() : undefined; continue; } + if (tag === 0x8769) readIfd(u32(e + 8), "exif"); + else if (tag === 0x8825) readIfd(u32(e + 8), "gps"); + else if (type === 2) { + const s = str(); + if (tag === 0x9003) info.dateTaken = exifDate(s); + else if (tag === 0x9004) info.created = exifDate(s); + else if (tag === 0x0132) info.modified = exifDate(s); + else if (tag === 0x010f) info.make = s; + else if (tag === 0x0110) info.model = s; + else if (tag === 0x0131) info.software = s; + } else if (tag === 0x0112 && type === 3) info.orientation = u16(vo); + } + if (kind === "gps" && Array.isArray(gps[2]) && Array.isArray(gps[4])) { + const dms = (a: number[]) => a[0] + (a[1] ?? 0) / 60 + (a[2] ?? 0) / 3600; + info.gps = { lat: dms(gps[2] as number[]) * (gps[1] === "S" ? -1 : 1), lon: dms(gps[4] as number[]) * (gps[3] === "W" ? -1 : 1) }; + } + }; + readIfd(u32(4), "0"); + return info; +} + +function exifDate(s: string): string | undefined { + const m = s.match(/^(\d{4})[:\-](\d{2})[:\-](\d{2})[ T](\d{2}):(\d{2}):(\d{2})/); + if (!m || m[1] === "0000") return undefined; + return `${m[1]}-${m[2]}-${m[3]} ${m[4]}:${m[5]}:${m[6]}`; +} + +/** JPEG 段列表。 */ +export function jpegSegments(b: Uint8Array): { marker: number; start: number; end: number }[] { + const out: { marker: number; start: number; end: number }[] = []; + if (b[0] !== 0xff || b[1] !== 0xd8) return out; + let p = 2; + while (p + 4 <= b.length && b[p] === 0xff) { + const marker = b[p + 1]; + if (marker === 0xd9 || marker === 0xda) { out.push({ marker, start: p, end: b.length }); break; } + if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) { p += 2; continue; } + const len = (b[p + 2] << 8) | b[p + 3]; + out.push({ marker, start: p, end: p + 2 + len }); + p += 2 + len; + } + return out; +} + +const EXIF_HDR = [0x45, 0x78, 0x69, 0x66, 0, 0]; +const at = (b: Uint8Array, p: number, sig: number[]) => sig.every((v, i) => b[p + i] === v); + +export function readExif(b: Uint8Array): ExifInfo { + try { + if (b[0] === 0xff && b[1] === 0xd8) { + for (const s of jpegSegments(b)) if (s.marker === 0xe1 && at(b, s.start + 4, EXIF_HDR)) return parseTiff(b.subarray(0, s.end), s.start + 10); + return { tags: 0 }; + } + if ((b[0] === 0x49 && b[1] === 0x49 && b[2] === 0x2a) || (b[0] === 0x4d && b[1] === 0x4d && b[3] === 0x2a)) return parseTiff(b); + for (let p = 0; p + 10 < b.length; p++) if (b[p] === 0x45 && at(b, p, EXIF_HDR) && (b[p + 6] === 0x49 || b[p + 6] === 0x4d)) return parseTiff(b, p + 6); + } catch { /* 损坏的 EXIF 当作没有 */ } + return { tags: 0 }; +} + +/** MP4/MOV 的 mvhd 创建时间(UTC 秒,自 1904 年)。 */ +export function mp4Created(b: Uint8Array): Date | undefined { + for (let p = 4; p + 24 < b.length; p++) { + if (b[p] === 0x6d && b[p + 1] === 0x76 && b[p + 2] === 0x68 && b[p + 3] === 0x64) { + const dv = new DataView(b.buffer, b.byteOffset + p + 4); + const secs = dv.getUint8(0) === 1 ? Number(dv.getBigUint64(4)) : dv.getUint32(4); + if (secs <= 0) return undefined; + const d = new Date((secs - 2082844800) * 1000); + return d.getFullYear() > 1990 ? d : undefined; + } + } + return undefined; +} diff --git a/ui-plugins/photo-date-organizer/src/main.ts b/ui-plugins/photo-date-organizer/src/main.ts new file mode 100644 index 00000000..2b0ed3f6 --- /dev/null +++ b/ui-plugins/photo-date-organizer/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(`[photo-date-organizer] ${line}\n`), +}); +process.stdin.once("end", () => process.exit(0)); +await server.connect(new StdioServerTransport()); diff --git a/ui-plugins/photo-date-organizer/src/server.ts b/ui-plugins/photo-date-organizer/src/server.ts new file mode 100644 index 00000000..6b73ea57 --- /dev/null +++ b/ui-plugins/photo-date-organizer/src/server.ts @@ -0,0 +1,186 @@ +import { open as openFile } from "node:fs/promises"; +import { createApp, htmlTable, toCsv, type AppDef, type Issue, type Project } from "./kit/app.ts"; +import { KitError, type Workspace } from "./kit/workspace.ts"; +import { dateFromName, fill, fmtLocal, normalizeDate } from "./dates.ts"; +import { mp4Created, readExif } from "./exif.ts"; + +export const NAME = "photo-date-organizer"; +export const VERSION = "0.1.0"; +const MEDIA = [".jpg", ".jpeg", ".png", ".heic", ".heif", ".webp", ".gif", ".tif", ".tiff", ".dng", ".mp4", ".mov", ".m4v", ".3gp"]; +const SOURCES: Record = { exif: ["EXIF 拍摄时间", "EXIF taken"], video: ["视频创建时间", "Video created"], name: ["文件名", "File name"], file: ["文件修改时间", "File time"], manual: ["手动", "Manual"] }; + +async function head(ws: Workspace, path: string, size: number) { + const fh = await openFile(ws.resolve(path), "r"); + try { + const n = Math.min(size, 2 * 1024 * 1024); + const a = Buffer.alloc(n); + await fh.read(a, 0, n, 0); + if (size <= n) return a; + const t = Math.min(size - n, 2 * 1024 * 1024); + const b = Buffer.alloc(t); + await fh.read(b, 0, t, size - t); + return Buffer.concat([a, b]); + } finally { await fh.close(); } +} + +interface Move { from: string; to: string } +const base = (p: string) => p.split("/").pop()!; +const extOf = (p: string) => (base(p).match(/\.[^.]+$/)?.[0] ?? "").toLowerCase(); +const rootOf = (p: Project) => (p.settings.mode === "copy" ? `${NAME}/${p.name}/sorted` : p.inputs[0].replace(/\/$/, "")); + +function plan(p: Project, taken: Set) { + const pattern = String(p.settings.folders ?? "yyyy/yyyy-MM"); + const naming = String(p.settings.naming ?? "keep"); + const used = new Set(); + const sources = new Set(p.rows.map((r) => String(r.path).toLowerCase())); + return p.rows.map((r) => { + const date = normalizeDate(String(r.date ?? "")); + if (!date) return { from: String(r.path), to: "", error: `Date “${r.date}” is not a date (use 2026-10-02 09:15:00)` }; + const dir = [rootOf(p), pattern === "none" ? "" : fill(pattern, date)].filter(Boolean).join("/"); + const ext = base(String(r.path)).match(/\.[^.]+$/)?.[0] ?? ""; + const stem = base(String(r.path)).replace(/\.[^.]+$/, ""); + let name = naming === "date" ? fill("yyyyMMdd_HHmmss", date) : naming === "date-name" ? `${fill("yyyyMMdd_HHmmss", date)}_${stem}` : stem; + let to = `${dir}/${name}${ext}`; + for (let k = 2; used.has(to.toLowerCase()) || (taken.has(to.toLowerCase()) && !sources.has(to.toLowerCase())); k++) to = `${dir}/${name}-${k}${ext}`; + used.add(to.toLowerCase()); + return { from: String(r.path), to }; + }); +} + +async function takenPaths(ws: Workspace, p: Project) { + const root = rootOf(p); + if (!(await ws.exists(root))) return new Set(); + return new Set((await ws.list({ dir: root, limit: 20000 })).map((f) => f.path.toLowerCase())); +} + +async function moveAll(ws: Workspace, moves: Move[], copy: boolean) { + const done: Move[] = []; + try { + for (const m of moves) { + if (copy) await ws.write(m.to, await ws.read(m.from, 4 * 1024 ** 3)); + else await ws.move(m.from, m.to); + done.push(m); + } + } catch (e) { + if (!copy) for (const m of done.reverse()) await ws.move(m.to, m.from).catch(() => undefined); + throw e; + } +} + +const def: AppDef = { + name: NAME, + version: VERSION, + prefix: "photos", + title: ["照片按日期整理", "Photo Date Organizer"], + openDescription: + "Sort photos and videos in a workspace folder into date folders (yyyy/yyyy-MM, yyyy-MM, yyyy/MM, yyyy-MM-dd) and optionally rename them to their date (20261002_091500.jpg). The date comes from EXIF DateTimeOriginal (JPEG, HEIC, TIFF/DNG), the video creation time (MP4/MOV), a date in the file name (IMG_20261103_101522, Screenshot 2026-11-05 at 10.22.31, WeChat/mmexport timestamps) or, last, the file time — every row shows which. Dates can be corrected in the table. Mode “move” (undo available) or “copy” into the plugin's output.", + inputs: { exts: MEDIA, min: 1, max: 1, folders: true, label: ["选择照片文件夹", "Pick the photo folder"] }, + settings: [ + { key: "folders", label: ["文件夹结构", "Folder layout"], type: "select", default: "yyyy/yyyy-MM", options: [{ value: "yyyy/yyyy-MM", label: ["2026/2026-10", "2026/2026-10"] }, { value: "yyyy-MM", label: ["2026-10", "2026-10"] }, { value: "yyyy/MM", label: ["2026/10", "2026/10"] }, { value: "yyyy/yyyy-MM-dd", label: ["2026/2026-10-02", "2026/2026-10-02"] }, { value: "yyyy-MM-dd", label: ["2026-10-02", "2026-10-02"] }, { value: "none", label: ["不分文件夹", "No folders"] }] }, + { key: "naming", label: ["文件名", "File names"], type: "select", default: "keep", options: [{ value: "keep", label: ["保留原名", "Keep"] }, { value: "date", label: ["改成日期 20261002_091500", "Date 20261002_091500"] }, { value: "date-name", label: ["日期 + 原名", "Date + original"] }] }, + { key: "mode", label: ["方式", "Mode"], type: "select", default: "move", options: [{ value: "move", label: ["移动(可撤销)", "Move (undo available)"] }, { value: "copy", label: ["复制到插件输出文件夹", "Copy to the plugin output"] }] }, + { key: "recursive", label: ["包含子文件夹", "Include subfolders"], type: "bool", default: true, reload: true }, + { key: "useFileTime", label: ["没有其他日期时用文件修改时间", "Fall back to file time"], type: "bool", default: true, reload: true }, + ], + columns: () => [ + { key: "path", label: ["文件", "File"], readOnly: true, wide: true }, + { key: "date", label: ["日期", "Date"] }, + { key: "_source", label: ["日期来源", "Date from"], readOnly: true }, + { key: "camera", label: ["相机", "Camera"], readOnly: true }, + { key: "_to", label: ["整理到", "Goes to"], readOnly: true, wide: true }, + ], + async load({ ws, files, settings }) { + const dir = files[0]; + if (!(await ws.exists(dir))) throw new KitError("not_found", `Folder not found: ${dir}`); + const list = (await ws.list({ dir, exts: MEDIA, recursive: Boolean(settings.recursive ?? true), limit: 20000 })).filter((f) => !f.path.startsWith(`${NAME}/`)); + if (!list.length) throw new KitError("empty", "No photos or videos in that folder."); + const rows = []; + for (const f of list) { + const buf = await head(ws, f.path, f.size); + let date: string | undefined, source = ""; + let camera = ""; + if ([".mp4", ".mov", ".m4v", ".3gp"].includes(extOf(f.path))) { + const d = mp4Created(buf); + if (d) { date = fmtLocal(d); source = "video"; } + } else { + const ex = readExif(buf); + camera = [ex.make, ex.model].filter(Boolean).join(" "); + date = ex.dateTaken ?? ex.created; + if (date) source = "exif"; + } + if (!date) { date = dateFromName(base(f.path)); if (date) source = "name"; } + if (!date && settings.useFileTime !== false) { date = fmtLocal(await ws.mtime(f.path)); source = "file"; } + rows.push({ path: f.path, date: date ?? "", source: source || "none", camera }); + } + return { rows }; + }, + async compute(p, { ws }) { + const planned = plan(p, await takenPaths(ws, p)); + const issues: Issue[] = []; + const counts: Record = {}; + p.rows.forEach((r, i) => { + counts[String(r.source)] = (counts[String(r.source)] ?? 0) + 1; + if (planned[i].error) issues.push({ level: "error", row: i, key: "date", message: planned[i].error! }); + else if (r.source === "file") issues.push({ level: "warn", row: i, key: "date", message: `${base(String(r.path))}: no date inside the file or its name — using the file time, which may be when it was copied. Check it.` }); + else if (r.source === "none") issues.push({ level: "error", row: i, key: "date", message: `${base(String(r.path))}: no date found; type one in.` }); + }); + const renamed = planned.filter((x) => x.to && x.to !== x.from).length; + const rows = p.rows.map((r, i) => { + const s = SOURCES[String(r.source)]; + return { ...r, _source: s ? `${s[0]} / ${s[1]}` : "—", _to: planned[i].to ? planned[i].to.slice(rootOf(p).length + 1) : "" }; + }); + const byFolder = new Map(); + for (const x of planned) if (x.to) { const f = x.to.slice(rootOf(p).length + 1).split("/").slice(0, -1).join("/") || "."; byFolder.set(f, (byFolder.get(f) ?? 0) + 1); } + const last = p.meta.lastMove as Move[] | undefined; + const preview = `

${p.rows.length} files → ${byFolder.size} folders under ${rootOf(p)}${last?.length ? ` · last run moved ${last.length} files (undo available)` : ""}

` + htmlTable(["Folder / 文件夹", "Files / 张数"], [...byFolder].sort()) + `

EXIF ${counts.exif ?? 0} · video ${counts.video ?? 0} · name ${counts.name ?? 0} · file time ${counts.file ?? 0}

`; + return { rows, issues, preview, summary: `${p.rows.length} files into ${byFolder.size} folders, ${renamed} to ${p.settings.mode === "copy" ? "copy" : "move"}`, stats: { files: p.rows.length, folders: byFolder.size, moves: renamed, exif: counts.exif ?? 0, fileTime: counts.file ?? 0 } }; + }, + onCellEdit: (row, key) => { if (key === "date") row.source = "manual"; }, + exports: [ + { + id: "plan", label: ["整理清单 CSV", "Plan CSV"], description: "organize-plan.csv with each file, its date, where it came from and where it goes (changes nothing)", + async run({ ws, project, write }) { + const planned = plan(project, await takenPaths(ws, project)); + return [await write("organize-plan.csv", toCsv(["file", "date", "date_source", "camera", "to"], project.rows.map((r, i) => [r.path, r.date, r.source, r.camera, planned[i].to])))]; + }, + }, + { + id: "organize", label: ["开始整理", "Organize"], description: "move (or copy) the files into the date folders and write organize-log.csv", + async run({ ws, project, write }) { + const planned = plan(project, await takenPaths(ws, project)); + const bad = planned.find((x) => x.error); + if (bad) throw new KitError("has_errors", `Fix the dates first: ${bad.from}: ${bad.error}`); + if (project.rows.some((r) => r.source === "none")) throw new KitError("has_errors", "Some files have no date; type one in first."); + const moves = planned.filter((x) => x.to !== x.from).map((x) => ({ from: x.from, to: x.to })); + if (!moves.length) return { files: [], note: "Everything is already in place." }; + const copy = project.settings.mode === "copy"; + await moveAll(ws, moves, copy); + if (!copy) { + 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 })); + project.meta.lastMove = moves; + } + const log = await write("organize-log.csv", toCsv(["from", "to"], moves.map((m) => [m.from, m.to]))); + return { files: [log], note: `${copy ? "Copied" : "Moved"} ${moves.length} file(s) into ${rootOf(project)}.` }; + }, + }, + { + id: "undo", manual: true, label: ["撤销上次整理", "Undo last move"], description: "move the files from the last “organize” back where they were", + async run({ ws, project, write }) { + const last = project.meta.lastMove as Move[] | undefined; + if (!last?.length) throw new KitError("nothing_to_undo", "Nothing to undo (copies are never undone — delete the copy folder instead)."); + const back = last.map((m) => ({ from: m.to, to: m.from })).reverse(); + for (const m of back) if (!(await ws.exists(m.from))) throw new KitError("not_found", `Can't undo: ${m.from} is gone.`); + await moveAll(ws, back, false); + 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.lastMove; + return { files: [await write("undo-log.csv", toCsv(["from", "to"], back.map((m) => [m.from, m.to])))], note: `Moved ${back.length} file(s) back.` }; + }, + }, + ], +}; + +export function createServer(options: { workspaceRoot: string; assetRoot: string; log?: (line: string) => void }) { + return createApp(def, options).server; +} From 8d1fca9dc3f0ef247e87af74cb23217b74170b7f Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:18:42 -0400 Subject: [PATCH 07/11] feat(ui-plugins): add Photo Date Organizer (photo-date-organizer) --- ui-plugins/photo-date-organizer/test/e2e.json | 1 + .../photo-date-organizer/test/photos.test.ts | 60 +++++++++++++++++++ .../test/workspace-links.test.ts | 43 +++++++++++++ 3 files changed, 104 insertions(+) create mode 100644 ui-plugins/photo-date-organizer/test/e2e.json create mode 100644 ui-plugins/photo-date-organizer/test/photos.test.ts create mode 100644 ui-plugins/photo-date-organizer/test/workspace-links.test.ts diff --git a/ui-plugins/photo-date-organizer/test/e2e.json b/ui-plugins/photo-date-organizer/test/e2e.json new file mode 100644 index 00000000..2455b761 --- /dev/null +++ b/ui-plugins/photo-date-organizer/test/e2e.json @@ -0,0 +1 @@ +{ "prefix": "photos", "folder": "照片", "pick": ["手机相册"], "startSettings": { "naming": "date-name" }, "uiEdit": { "row": 7, "key": "date", "value": "2024-02-02 12:00" }, "expectText": "20261002_091500_PXL_0001.jpg", "expectFiles": ["organize-plan\\.csv$", "organize-log\\.csv$"] } diff --git a/ui-plugins/photo-date-organizer/test/photos.test.ts b/ui-plugins/photo-date-organizer/test/photos.test.ts new file mode 100644 index 00000000..54083927 --- /dev/null +++ b/ui-plugins/photo-date-organizer/test/photos.test.ts @@ -0,0 +1,60 @@ +import { cp, mkdtemp, readFile, stat } 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 { dateFromName, normalizeDate } from "../src/dates.ts"; +import { mp4Created, readExif } from "../src/exif.ts"; +import { connect } from "../src/kit/testing.ts"; +import { createServer } from "../src/server.ts"; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const S = join(HERE, "samples/手机相册"); + +describe("dates", () => { + it("reads EXIF, video and file-name dates", async () => { + const ex = readExif(await readFile(join(S, "PXL_0001.jpg"))); + expect(ex).toMatchObject({ dateTaken: "2026-10-02 09:15:00", make: "Google", model: "Pixel 8" }); + expect(ex.gps!.lat).toBeCloseTo(30.26, 2); + expect(readExif(await readFile(join(S, "IMG_20261103_101522.jpg"))).dateTaken).toBeUndefined(); + expect(mp4Created(await readFile(join(S, "VID_A.mp4")))!.toISOString()).toBe("2026-09-20T07:30:00.000Z"); + expect(dateFromName("IMG_20261103_101522.jpg")).toBe("2026-11-03 10:15:22"); + expect(dateFromName("Screenshot 2026-11-05 at 10.22.31.png")).toBe("2026-11-05 10:22:31"); + expect(dateFromName("微信图片_20261106.jpg")).toBe("2026-11-06 00:00:00"); + expect(dateFromName("PXL_0001.jpg")).toBeUndefined(); + expect(dateFromName("IMG_20261399_000000.jpg")).toBeUndefined(); + expect(normalizeDate("2024年2月2日 12:00")).toBe("2024-02-02 12:00:00"); + expect(normalizeDate("昨天")).toBeUndefined(); + }); +}); + +describe("photos tools", () => { + it("plans, organizes and undoes", async () => { + const root = await mkdtemp(join(tmpdir(), "photos-")); + await cp(S, join(root, "相册"), { recursive: true }); + const c = await connect(createServer({ workspaceRoot: root, assetRoot: root })); + const o = await c.call("photos_open", { inputs: ["相册"], project: "phone" }); + const by = Object.fromEntries(o.data.rows.map((r: { path: string; source: string; _to: string }) => [r.path.split("/").pop(), [r.source, r._to]])); + expect(by["PXL_0001.jpg"]).toEqual(["exif", "2026/2026-10/PXL_0001.jpg"]); + expect(by["DSC_4410.JPG"]).toEqual(["exif", "2025/2025-12/DSC_4410.JPG"]); + expect(by["Screenshot 2026-11-05 at 10.22.31.png"]).toEqual(["name", "2026/2026-11/Screenshot 2026-11-05 at 10.22.31.png"]); + expect(by["VID_A.mp4"][0]).toBe("video"); + expect(by["mmexport1762750000000.jpg"]).toEqual(["name", "2025/2025-11/mmexport1762750000000.jpg"]); + expect(by["无日期.png"][0]).toBe("file"); + expect(o.data.issues.filter((i: { level: string }) => i.level === "warn")).toHaveLength(1); + const row = o.data.rows.findIndex((r: { path: string }) => r.path.endsWith("无日期.png")); + const e = await c.call("photos_edit", { project: "phone", settings: { naming: "date" }, set: [{ row, values: { date: "2024年2月2日 12:00" } }] }); + expect(e.data.rows[row]).toMatchObject({ source: "manual", _to: "2024/2024-02/20240202_120000.png" }); + expect(e.data.issues).toHaveLength(0); + const p1 = e.data.rows.find((r: { path: string }) => r.path.endsWith("PXL_0001.jpg")); + expect(p1._to).toBe("2026/2026-10/20261002_091500.jpg"); + const x = await c.call("photos_export", { project: "phone" }); + expect(x.text).toMatch(/Moved 8/); + expect((await stat(join(root, "相册/2026/2026-10/20261002_184012.jpg"))).size).toBeGreaterThan(0); + expect(await readFile(join(root, "photo-date-organizer/phone/organize-plan.csv"), "utf8")).toMatch(/exif/); + const again = await c.call("photos_status", { project: "phone" }); + expect(again.data.stats.moves).toBe(0); + await c.call("photos_export", { project: "phone", formats: ["undo"] }); + expect((await stat(join(root, "相册/PXL_0002.jpg"))).size).toBeGreaterThan(0); + }); +}); diff --git a/ui-plugins/photo-date-organizer/test/workspace-links.test.ts b/ui-plugins/photo-date-organizer/test/workspace-links.test.ts new file mode 100644 index 00000000..f3dae538 --- /dev/null +++ b/ui-plugins/photo-date-organizer/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" }); + }); +}); From af56855638962ab4eb40bbd89b2f94aaae3da0ae Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:19:50 -0400 Subject: [PATCH 08/11] feat(ui-plugins): add Photo Date Organizer (photo-date-organizer) --- ui-plugins/photo-date-organizer/ui/app.css | 39 ++++ ui-plugins/photo-date-organizer/ui/app.ts | 236 ++++++++++++++++++++ ui-plugins/photo-date-organizer/ui/env.d.ts | 4 + ui-plugins/photo-date-organizer/ui/kit.css | 34 +++ ui-plugins/photo-date-organizer/ui/kit.ts | 133 +++++++++++ ui-plugins/photo-date-organizer/ui/main.ts | 3 + 6 files changed, 449 insertions(+) create mode 100644 ui-plugins/photo-date-organizer/ui/app.css create mode 100644 ui-plugins/photo-date-organizer/ui/app.ts create mode 100644 ui-plugins/photo-date-organizer/ui/env.d.ts create mode 100644 ui-plugins/photo-date-organizer/ui/kit.css create mode 100644 ui-plugins/photo-date-organizer/ui/kit.ts create mode 100644 ui-plugins/photo-date-organizer/ui/main.ts diff --git a/ui-plugins/photo-date-organizer/ui/app.css b/ui-plugins/photo-date-organizer/ui/app.css new file mode 100644 index 00000000..19894635 --- /dev/null +++ b/ui-plugins/photo-date-organizer/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/photo-date-organizer/ui/app.ts b/ui-plugins/photo-date-organizer/ui/app.ts new file mode 100644 index 00000000..dba63195 --- /dev/null +++ b/ui-plugins/photo-date-organizer/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/photo-date-organizer/ui/env.d.ts b/ui-plugins/photo-date-organizer/ui/env.d.ts new file mode 100644 index 00000000..4210a464 --- /dev/null +++ b/ui-plugins/photo-date-organizer/ui/env.d.ts @@ -0,0 +1,4 @@ +declare module "*.css" { + const text: string; + export default text; +} diff --git a/ui-plugins/photo-date-organizer/ui/kit.css b/ui-plugins/photo-date-organizer/ui/kit.css new file mode 100644 index 00000000..398bc83a --- /dev/null +++ b/ui-plugins/photo-date-organizer/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/photo-date-organizer/ui/kit.ts b/ui-plugins/photo-date-organizer/ui/kit.ts new file mode 100644 index 00000000..b0646f25 --- /dev/null +++ b/ui-plugins/photo-date-organizer/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/photo-date-organizer/ui/main.ts b/ui-plugins/photo-date-organizer/ui/main.ts new file mode 100644 index 00000000..88de027b --- /dev/null +++ b/ui-plugins/photo-date-organizer/ui/main.ts @@ -0,0 +1,3 @@ +import { startApp } from "./app.ts"; + +startApp("photo-date-organizer", "0.1.0"); From ff6c6b92d8755694b36b4c2ae2d041702d3ca71e Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:20:23 -0400 Subject: [PATCH 09/11] feat(ui-plugins): add Photo Date Organizer (photo-date-organizer) --- .../skills/photo-date-organizer/SKILL.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 external_plugins/photo-date-organizer/skills/photo-date-organizer/SKILL.md diff --git a/external_plugins/photo-date-organizer/skills/photo-date-organizer/SKILL.md b/external_plugins/photo-date-organizer/skills/photo-date-organizer/SKILL.md new file mode 100644 index 00000000..2a0b197b --- /dev/null +++ b/external_plugins/photo-date-organizer/skills/photo-date-organizer/SKILL.md @@ -0,0 +1,15 @@ +--- +name: photo-date-organizer +description: 把乱七八糟的手机照片、截图和视频,按拍摄日期整理进“年/月”文件夹——日期取自 EXIF、视频创建时间或文件名里的日期,最后才用文件修改时间——还可以统一改名成 20261002_091500.jpg。每个文件都标明日期来源,日期可以手动改正,移动后还能撤销。在本地运行,无需 API 密钥。 用户提到“整理照片 / 按日期归档 / 拍摄时间 / 相册分文件夹 / 照片改名成日期”时使用。 +--- + +# 照片按日期整理 + +1. `photos_open(inputs, settings?, project?)`:读取文件夹里每张照片和每个视频的日期,规划日期文件夹。inputs 是工作区相对路径。 + - 结果里有汇总、问题列表(错误 / 提醒)和前几行数据,每行有编号 `#n`。 + - inputs 传一个文件夹;settings 可设 folders(如 "yyyy/yyyy-MM")、naming(keep/date/date-name)、mode(move/copy)。 +2. 向用户简要说明结果,先说错误和需要确认的地方,不要逐行念。 +3. 用户要改时调用 `photos_edit(project, settings?, set?: [{row, values}], add?, remove?)`。 + - 改日期:`set: [{row, values: {date: "2024-02-02 12:00"}}]`。 +4. `photos_export(project, formats?)`:导出 organize-plan.csv,再把文件移动或复制到日期文件夹(organize-log.csv);undo 可移回原处。把文件路径告诉用户。 +5. 来源是“文件修改时间”的要提醒用户核对。先导出 plan 给用户看,同意后再导出 organize。 From 8e90edadb630ea6c9488d8d7783476d2235f71c8 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:21:01 -0400 Subject: [PATCH 10/11] feat(ui-plugins): add Photo Date Organizer (photo-date-organizer) --- .../photo-date-organizer/src/kit/app.ts | 398 ++++++++++++++++++ .../photo-date-organizer/src/kit/columns.ts | 53 +++ .../photo-date-organizer/src/kit/console.ts | 5 + .../src/kit/server-kit.ts | 84 ++++ .../photo-date-organizer/src/kit/testing.ts | 16 + .../photo-date-organizer/src/kit/workspace.ts | 170 ++++++++ 6 files changed, 726 insertions(+) create mode 100644 ui-plugins/photo-date-organizer/src/kit/app.ts create mode 100644 ui-plugins/photo-date-organizer/src/kit/columns.ts create mode 100644 ui-plugins/photo-date-organizer/src/kit/console.ts create mode 100644 ui-plugins/photo-date-organizer/src/kit/server-kit.ts create mode 100644 ui-plugins/photo-date-organizer/src/kit/testing.ts create mode 100644 ui-plugins/photo-date-organizer/src/kit/workspace.ts diff --git a/ui-plugins/photo-date-organizer/src/kit/app.ts b/ui-plugins/photo-date-organizer/src/kit/app.ts new file mode 100644 index 00000000..de09bb49 --- /dev/null +++ b/ui-plugins/photo-date-organizer/src/kit/app.ts @@ -0,0 +1,398 @@ +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; + /** 单元格被用户/助手改过之后调用(例如把来源标成“手动”)。 */ + onCellEdit?: (row: Row, key: string) => void; +} + +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); + def.onCellEdit?.(row, k); + } + } + 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/photo-date-organizer/src/kit/columns.ts b/ui-plugins/photo-date-organizer/src/kit/columns.ts new file mode 100644 index 00000000..4cb79023 --- /dev/null +++ b/ui-plugins/photo-date-organizer/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/photo-date-organizer/src/kit/console.ts b/ui-plugins/photo-date-organizer/src/kit/console.ts new file mode 100644 index 00000000..f6817656 --- /dev/null +++ b/ui-plugins/photo-date-organizer/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/photo-date-organizer/src/kit/server-kit.ts b/ui-plugins/photo-date-organizer/src/kit/server-kit.ts new file mode 100644 index 00000000..6bc31594 --- /dev/null +++ b/ui-plugins/photo-date-organizer/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/photo-date-organizer/src/kit/testing.ts b/ui-plugins/photo-date-organizer/src/kit/testing.ts new file mode 100644 index 00000000..0d8dc72e --- /dev/null +++ b/ui-plugins/photo-date-organizer/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/photo-date-organizer/src/kit/workspace.ts b/ui-plugins/photo-date-organizer/src/kit/workspace.ts new file mode 100644 index 00000000..7326158b --- /dev/null +++ b/ui-plugins/photo-date-organizer/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); +} From 2a01c7adf0b7e7163da4c944ec6d004b543947b3 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:22:24 -0400 Subject: [PATCH 11/11] feat(ui-plugins): add Photo Date Organizer (photo-date-organizer) --- .../DSC_4410.JPG" | Bin 0 -> 2535 bytes .../IMG_20261103_101522.jpg" | Bin 0 -> 1148 bytes .../PXL_0001.jpg" | Bin 0 -> 2651 bytes .../PXL_0002.jpg" | Bin 0 -> 2660 bytes .../Screenshot 2026-11-05 at 10.22.31.png" | Bin 0 -> 390 bytes .../VID_A.mp4" | Bin 0 -> 2289 bytes .../mmexport1762750000000.jpg" | Bin 0 -> 1043 bytes .../\346\227\240\346\227\245\346\234\237.png" | Bin 0 -> 288 bytes 8 files changed, 0 insertions(+), 0 deletions(-) create mode 100644 "ui-plugins/photo-date-organizer/test/samples/\346\211\213\346\234\272\347\233\270\345\206\214/DSC_4410.JPG" create mode 100644 "ui-plugins/photo-date-organizer/test/samples/\346\211\213\346\234\272\347\233\270\345\206\214/IMG_20261103_101522.jpg" create mode 100644 "ui-plugins/photo-date-organizer/test/samples/\346\211\213\346\234\272\347\233\270\345\206\214/PXL_0001.jpg" create mode 100644 "ui-plugins/photo-date-organizer/test/samples/\346\211\213\346\234\272\347\233\270\345\206\214/PXL_0002.jpg" create mode 100644 "ui-plugins/photo-date-organizer/test/samples/\346\211\213\346\234\272\347\233\270\345\206\214/Screenshot 2026-11-05 at 10.22.31.png" create mode 100644 "ui-plugins/photo-date-organizer/test/samples/\346\211\213\346\234\272\347\233\270\345\206\214/VID_A.mp4" create mode 100644 "ui-plugins/photo-date-organizer/test/samples/\346\211\213\346\234\272\347\233\270\345\206\214/mmexport1762750000000.jpg" create mode 100644 "ui-plugins/photo-date-organizer/test/samples/\346\211\213\346\234\272\347\233\270\345\206\214/\346\227\240\346\227\245\346\234\237.png" diff --git "a/ui-plugins/photo-date-organizer/test/samples/\346\211\213\346\234\272\347\233\270\345\206\214/DSC_4410.JPG" "b/ui-plugins/photo-date-organizer/test/samples/\346\211\213\346\234\272\347\233\270\345\206\214/DSC_4410.JPG" new file mode 100644 index 0000000000000000000000000000000000000000..665079a1d38131b9caeed10a5ba67d4dd80582af GIT binary patch literal 2535 zcmex=**@)=3@ktzXaYk55Hq;v=cnhSGB8Bwh8P<#7#SFuS{WKy85=4X z8C#iJ0uciP(*$O?{<;Y)aP}mSer!6hiT%IL;LO0r!pg?V!p6qR#?H>h!6m@O#mUJf z!pF}eATA;yAub{&CMByXFD0!kBPOPxqoAy&uBoLdDX(jwt6`w3p{W5fgpr+{or{A@ zn2SqTLrP3agJkgk0D~Y0!v{tOW=16jCP7AKLB{__803Lr!paB+Aa8*HBNH>wz3d#E zT--nfTY&+}$jr>d!pzFb0t`aNTA(}wiy*6zqM;+3a9|?4QlW@Z(iUwW$ zpkka<)WpdpCN3cY31zV>gMj@=@lFj8WtWA8I_!pnwFlCnN?g; zT2@|BS=HRq+ScCD*)?hMl&RCE&zL!D(c&dbmn~nha@D5ITefc7zGLUELx+zXJ$C%W z$y1juU%7hi`i+~n9zJ^f z!py=B@)sjhImqLJEUb!#Y(kEK?1_cKN=A(wB2E(*Zam1TY#j7KG^yw!mzavlL)DKU zuYr9=oX48T@)_J?2!GvT;9+J2Mjo>ugFVBfE^WW-{#$G9xM#24sbK8)VMT=VidzCt z`yM#_Jnm2x-Zl07e9yf-r?e|7@9%X<*+gHY?hH$-Vnq7MV6WD+x~4Ki5_Gg6-q^{ZBNuuh7`GEZrMKbk$IP`gQZ3#d6tUR4!(!{ssIFU9 zCW5Xy)6I)kt-rbPse{a96F0xscAw;X(*rIlU4B0A(yO0gzf{t1ZvLLa=Wu`Ck|H+i z##uEzma02DT}47Bi3GYbkb^~+XRnA_HlKCt)!F9~=00;$yS2Q)u}#`j`H3vY>&Phq zbK7P|OJA!~s*Y~o(~?d7U-v&Opul!DE z(}%hcc|CSp&M(iq&MjI!b1&Podp$QUn-(v=?{dxeTX*Oz%b9A8qH|V$wchsCLgD+e za*H$L?p1ytJI)B!+zDKnyUT;`5 tX~&ZW_nN{Ba@ky6HE(J@acL}C(y*vYgJBephQVkW7)=8dqygstHv!)Xb&mi5 literal 0 HcmV?d00001 diff --git "a/ui-plugins/photo-date-organizer/test/samples/\346\211\213\346\234\272\347\233\270\345\206\214/IMG_20261103_101522.jpg" "b/ui-plugins/photo-date-organizer/test/samples/\346\211\213\346\234\272\347\233\270\345\206\214/IMG_20261103_101522.jpg" new file mode 100644 index 0000000000000000000000000000000000000000..c4f17072e16f61173bb1d2adbea6aff6040a3205 GIT binary patch literal 1148 zcmex=^(PF6}rMnOeST|r4lSw=>~TvNxu(8R<HEAm;@P_1sVSzVUP#9la&z+7@&ZWiJ66!jh%y&iyNq5 zs{jKNBQrA-3o|P#3ky(nEl{3;MUYiU(a@1iI53f2sZhkIapFP_Wv7h?MT0JWP%%y_ zYU1P)6PJ*bQdLve(9|+9H8Z!cv~qTFb#wRd^a>6M4GWKmj7m;PO-s+n%qlJ^Ei136 ztZHs)ZENr7?3y%r%G7DoXUv?nXz`Mz%a*TLxoXqqEnBy3-?4Mop~FXx9y@;G&P778mFHFAhJOJ)_h>M7cNy)0pOGzush>0oaC@8C`Yiemq%Ig~FY8a?$Xlj5A zVPt1#=i=ZJ=He38kP?&9AQ}8Wz#z!M@PW~RnNf*>Nsy6Qkn#T!26>Muc{znEB9m|56C{$gY*2V!PH7FI<=HX+AA_QXPAC8I_T5vPd@Hy-3vHV*nAnpAX= zOH9S&q3TDF*T6m_&SOnv`3&wcguiYv@Gt`ttst`?gFVCPMP0Wql|04V_6sH$;oQvGf#QvV$p|C0Y`IP7zzdb!&V`oeWcTRtJbjP#9Wuif00WD^g_IrGK z`1jryX?EUT;d>|i+^-^?HqV+K3yl*?Sni(l+4y+k_uWbJRa)OB-Z{8vyV8Zl*{@Hh z?+r1GHa%m%Tjk6?&nbl$ix#A-H@QbGOkQ>;e$n4)W)p8cvQCu@;6AxK0*8fz4 z_W#)*r6B(%M$G;vzx>+ti@s;~o(y@kHAehzts}V`YoByntXf)-g;laOm zDu4Fh{l2WX=&qvK#E4y)=QeRFeg5=hx3Z9YzJ#HBAOGF=vkormtK`1vym9T{4fR`> z?fJxZZCiCnkNF*E#@5Q?7A&=ex7Pp24&1o$x3;fl2e03`hf|u41}Xf$uTXOO1DpS6 zo2w$4Ti#g)^-S$sbv*R4p2<#=)g5QocFc%bbyC~V=!<&Q!pC`RclUo#sCxK%duIK* zEc1y>$~$&UN@ZWcbEM~Asau!K?XW~CFTEEUi@GK|Eb7u=7{#MuFq#HN(*Ol&fcgJT E0L&$n&j0`b literal 0 HcmV?d00001 diff --git "a/ui-plugins/photo-date-organizer/test/samples/\346\211\213\346\234\272\347\233\270\345\206\214/PXL_0002.jpg" "b/ui-plugins/photo-date-organizer/test/samples/\346\211\213\346\234\272\347\233\270\345\206\214/PXL_0002.jpg" new file mode 100644 index 0000000000000000000000000000000000000000..a80baeae6255ae050f593fe966850a4dba281d5b GIT binary patch literal 2660 zcmex=J)_h>M7cNy)0pOGzush>0oaC@8C`Yiemq%Ig~FY8a?$Xlj5A zVPt1#=i=ZJ=He38kP?&9AQ}8Wz#z!M@PW~RnNf*>Nsy6Qkn#T!26>Muc{znEB9m|56C{$gY*2V!PH7FI<=HX+AA_QXPAC8I_T5vPd@Hy-3vHV*nAnpAX= zOH9S&q3TDF*T6m_&SOnv`3&wcguiYv@Gt`ttst`?gFVBsMO}9;m3ZX8&6)e|Nmuph z6sH$;oQvGf#QvV$p|C0YwW_LYGYdI#KGj#s zxv}4S-{rV4dXL&W>F2eUV$Le}++;*jf|&B2t3`Y~@%!$^;J3+l>dv|Gitf!{;HtLr zo1}h|O|Q`HiDESemEMOXPTX1$u0AJy;hNXHW{>`gznQqD@4Db^jZ+PAzPH&t-*5SL zTxO#GJlmrum8OcW{?EYiZ|T8L$v518owu`{dCu(J-QJu3WS-yJ{9bqI=H2tIJvH-Z z-cqFJc<@z;@GLRP4*(mcEOT$8=v?4-$2wZab zzS$h<`^;a;QTlL!z)`LRzRem%UJaa&d-|R&|8Q<;a^knJS-}EQOQ#;zWbInw_$$OgYnR1j24#i|&W>g@*cCb{Ea}qUOXaKN%pT<4KL5S( zb?f@rWeeA3nNMU=-m!C1D(@AxB)592#jb+O7QJiL+^KD_s7u?4sY_$QC>{-i(KIlc M1}I4b{QqwP0EuFZt^fc4 literal 0 HcmV?d00001 diff --git "a/ui-plugins/photo-date-organizer/test/samples/\346\211\213\346\234\272\347\233\270\345\206\214/Screenshot 2026-11-05 at 10.22.31.png" "b/ui-plugins/photo-date-organizer/test/samples/\346\211\213\346\234\272\347\233\270\345\206\214/Screenshot 2026-11-05 at 10.22.31.png" new file mode 100644 index 0000000000000000000000000000000000000000..d00f418ef9a7a8ab40d86dc6613b9f59b1c48c50 GIT binary patch literal 390 zcmeAS@N?(olHy`uVBq!ia0vp^CxEzug9%7le9+p%z`*G1>EaktG3V_iM_vX+fddB~ z|LKn9oUuSr(U|Mki&-=I{eI`Oe^5)FXduQpN)QNxPTqCg%m*?QI{1O%%i!ti=d#Wz Gp$Pz|hi8KT literal 0 HcmV?d00001 diff --git "a/ui-plugins/photo-date-organizer/test/samples/\346\211\213\346\234\272\347\233\270\345\206\214/VID_A.mp4" "b/ui-plugins/photo-date-organizer/test/samples/\346\211\213\346\234\272\347\233\270\345\206\214/VID_A.mp4" new file mode 100644 index 0000000000000000000000000000000000000000..9d7fde8d4d6106a51f802c3df99a3b4a8ecd1ebb GIT binary patch literal 2289 zcmd5+OK4nG7(RKlG;QreQ)waKv1XY}?wv{VDi<;h!AL7UpcSETIdkus%r*Cwb5D|) zE+oY&iYpN!R!Ax+wYAtTv|ULfDEL?u7eWJWq*^RRE!9OgX8is;Go5L0Mie_M<{dML2TjI0i$N64GsgU2zT|?kn?D@9N1L&ZU(?;j z7=F$5fB^LddA#ZQZ(KWKzNM9zf$_MWNpp5Ib2g$;?hR{0o`z?`Yn+%f*kxi^uXJ?+ z+9Ul$r<(Mn6t}Z}=8mqw^#p7@a5vVTg*wZQewiZsORlf#G1$E4$_7vL802V5gsv~i zr~T8w3yWa7=Yuq8>#=*?nytrGl6+{9efym9d5v$^i7xoyR}-D24XNqbC2AUYTCFi_ znlmVS3M_3}ZF`Quf5^<3qZ!jMx$hOq*`dLjG5zkXRzZj0HPPm>ZPlOHzG=`4Yllv~ ze7tiUZDROrf90#Ka2BmY*?k;FmzvTVbA=BEM=(GXE zlg~aHK&)=mMUA1=z+ZQozVIVGnv~M5b=r_gBzqbQ^nY#dL9I@D;%2S&`dAsZ6LlLA zx}V#iyRaW>*^h$X`5)vx8~iuQxPK>t4=uXqB~UTvY61FUAX7@V$6JRU4@HSMrn$Vo z`n=l9>OH3;3fSX{6pWyZVfu=gzF`bs4&s)gl6Wtq`pM=^)#~{lCvSazb8YI% zQr~sH_Qdah(1h}S?nFv*6RgUa#t6@u(i|<0!Z4MA!@$$ePCnT`$n(c0;OR;ShKVSy z__C;Z)-ZDYStFZ+vZQr9HZZWTu#llQ8~Gy4L~43~vSdm+@Zl51+Ka+uj60$r9LwZ* zmsXCuvfxL~jAf1)V+I$Y@GFV5jB;+wD4S-E2hu9ZGEe3T;D&jeQ~<@-R<31c41n=_L(Lx zibUISGULVMQ425|+flKYNNx3Jxh^Rn5^IqAQ8Xh;5bTD|re@KB{W94`=> z&f$exDqp|}`hq{FM8$TZAQl?3gDb*cwihA<9F-uSq7s2ja9IUAu7LMkD+^w@BBm+| zcEJ+~CGnI@>spZBbV(Ori((nt(@_j-O&J3^BP)n)We*s2*2W(xM4mV@l+K*C1`Rr< z5_F|XCMCd?W8W{A?8>nmRpbHwk0g}^!OG?`2A`#3EF&`nHm1NS6=iE^6pBR47&qs| zXc7hjJwz-qi~dtL*&-(RfPDQFJ6K)6@$tRx?=QZ8ZQ+CGhA;l*Jaeu49slkl!#$Ud z?!0#Xm++3feE9HP_BGq|^JBm1Hv!z9Ki%t3TwOo6#7?Y2?#eG8D!*D~Z=WQgZCU6; zSJ^j!SJ9T(eT|aw@{Ye?N^(PF6}rMnOeST|r4lSw=>~TvNxu(8R<| zHF0u@iAzXIsj8`KXlj|5nweWzS~We&gn?hmRgVdHU@6i$mSee*Oaai;;mD;w>Nv@fe!F1cClyVqsxs zVF&q(k*OSrnFU!`6%E;h90S=C3x$=88aYIqCNA7~kW<+>=!0ld(M2vX6_bamA3