diff --git a/external_plugins/product-photo-studio/.zcode-plugin/plugin.json b/external_plugins/product-photo-studio/.zcode-plugin/plugin.json new file mode 100644 index 00000000..1188283b --- /dev/null +++ b/external_plugins/product-photo-studio/.zcode-plugin/plugin.json @@ -0,0 +1,56 @@ +{ + "name": "product-photo-studio", + "version": "0.1.0", + "description": "Batch-prepare e-commerce product photos: remove plain studio backgrounds, crop and normalise product size and position, add ground or drop shadows, and export white-background JPGs, transparent PNGs and marketplace sizes (Taobao, Amazon, Shopify, social). Tweak any photo on its own in the side panel. Runs locally; no API keys.", + "description_i18n": { + "en": "Batch-prepare e-commerce product photos: remove plain studio backgrounds, crop and normalise product size and position, add ground or drop shadows, and export white-background JPGs, transparent PNGs and marketplace sizes (Taobao, Amazon, Shopify, social). Tweak any photo on its own in the side panel. Runs locally; no API keys.", + "zh-CN": "批量处理电商商品图:去掉纯色/浅色棚拍背景,自动裁切并统一商品大小和位置,加地面柔影或投影,导出白底 JPG、透明 PNG 和各平台尺寸(淘宝、拼多多、Amazon、Shopify、社媒)。不满意的图可以在侧栏单独调整。全部本地处理,无需 API 密钥。" + }, + "author": { + "name": "Penova", + "url": "https://github.com/ppppp2005-p" + }, + "license": "MIT", + "keywords": [ + "e-commerce", + "product-photo", + "white-background", + "remove-background", + "batch", + "taobao", + "amazon", + "shopify", + "商品图", + "白底图" + ], + "skills": "skills", + "mcpServers": { + "product-photo-studio": { + "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": "Product Photo Studio" + }, + "icon": "image", + "server": "product-photo-studio", + "resourceUri": "ui://product-photo-studio/panel.html", + "availability": "session" + } + ] + } +} diff --git a/external_plugins/product-photo-studio/LICENSE b/external_plugins/product-photo-studio/LICENSE new file mode 100644 index 00000000..67e98093 --- /dev/null +++ b/external_plugins/product-photo-studio/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/product-photo-studio/README.md b/external_plugins/product-photo-studio/README.md new file mode 100644 index 00000000..cbb3e4e9 --- /dev/null +++ b/external_plugins/product-photo-studio/README.md @@ -0,0 +1,50 @@ +# Product Photo Studio + +Turn a batch of product photos into listing-ready images: remove plain backgrounds, make every product the same size and position, add a shadow, and export white-background main images, transparent PNGs and marketplace sizes in one go. Tweak any photo on its own in the side panel. + +## What it does + +- **Batch background removal**: removes plain, light or gradient studio backgrounds connected to the photo edge while keeping white labels inside the product; PNGs that already have transparency are used as-is. Edges are softened and de-fringed. +- **Consistent size and position**: crops to the product and places it by "product size" (fraction of the canvas), centred or bottom-aligned, so every product looks the same size. +- **Shadows**: soft ground ellipse or silhouette drop shadow with adjustable strength. +- **Multi-size export**: white 800×800 (Taobao/Tmall/JD), 1000×1000 (Pinduoduo/Douyin), Amazon 2000×2000, Shopify 2048×2048, social 1080×1080, Xiaohongshu 1080×1440, transparent PNG 1600×1600, plus custom sizes. +- **Per-photo tweaks**: select any photo in the panel and change tolerance, size, position, shadow or background for that photo only, then re-export just that one. +- **Warnings**: busy backgrounds, little background removed, product touching the edge, tolerance too high — flagged on the thumbnails. +- **Reusable settings**: save the batch as `.photostudio.json` and apply the same look to the next batch. + +## Usage + +In ZCode Desktop, ask the agent: + +- "Turn every photo in products/ into 800×800 white-background main images and transparent PNGs" +- "Make all product photos the same size with a soft shadow, Amazon 2000×2000" +- "The perfume photo sits too high — lower it and export just that one again" + +Or open "Product Photo Studio" from the session sidebar and tick images in the workspace. Global settings and output sizes are on the left, thumbnails in the middle; click one to adjust it below, then "Export all". + +## Tools + +| Tool | Purpose | +|---|---| +| `photos_open` | Open a batch (folder, paths or saved project), check it and open the panel | +| `project_save` | Save the settings as `.photostudio.json` | +| `photos_export` | Export all or some photos in the chosen sizes | + +## Scope (v0.1) + +- Input: JPG (auto-rotated by EXIF orientation) and PNG (with alpha). +- Background removal targets plain, light or gradient studio backdrops. **Busy backgrounds** (tables, outdoors, lifestyle shots), hair and clear glass are out of scope for v0.1: the thumbnail says "busy background", and the photo should be cut out with another tool first. +- Not yet: WebP/HEIC input, brush refinement, scene backgrounds. + +## Privacy, network and file writes + +- **Everything runs locally.** No network access, nothing is uploaded, no API keys or accounts. +- Reads and writes only inside the workspace: originals are never modified; results go to the output folder (default `product-photos-output//`), settings to the `.photostudio.json` you choose. No commands are executed and there are no hooks. + +## Build and test (developers) + +Source lives in `ui-plugins/product-photo-studio/`. From the repository root run `pnpm install --frozen-lockfile && pnpm build`, add `dist/local-marketplace` as a local source in the ZCode plugin store and install. Tests: `pnpm --filter @penova/plugin-product-photo-studio test` (real product photos plus synthetic samples; checks product fraction, centring, pure-white background and transparency) and `test:e2e` (browser panel test; point `E2E_PHOTOS` at your own photos). + +## Third-party components and licenses + +The plugin is MIT-licensed (author: Penova). Bundled dependencies: pngjs (MIT), jpeg-js (BSD-3-Clause), the MCP SDK and ext-apps (MIT). The full list ships in `dist/THIRD_PARTY_NOTICES.txt`. Test photo sources are listed in `ui-plugins/product-photo-studio/test/fixtures/SOURCES.md` (CC0 / public domain) and are not part of the installed package. diff --git a/external_plugins/product-photo-studio/README_CN.md b/external_plugins/product-photo-studio/README_CN.md new file mode 100644 index 00000000..7f25ee4a --- /dev/null +++ b/external_plugins/product-photo-studio/README_CN.md @@ -0,0 +1,50 @@ +# 电商商品图助手(Product Photo Studio) + +把一批商品照片处理成可以直接上架的图片:去掉纯色背景、统一商品大小和位置、加阴影,一次导出白底主图、透明 PNG 和各平台需要的尺寸。不满意的图可以在侧栏单独调整。 + +## 能做什么 + +- **批量去背景**:去掉与照片边缘相连的纯色 / 浅色 / 渐变棚拍背景,保留商品内部的白色标签;已有透明通道的 PNG 直接使用。边缘做柔化和去色边处理。 +- **统一尺寸和位置**:自动裁到商品本身,按“主体占比”放到画布中央(或底部对齐),所有图的商品大小一致。 +- **阴影**:地面椭圆柔影或轮廓投影,可调浓度。 +- **多尺寸导出**:白底 800×800(淘宝/天猫/京东主图)、1000×1000(拼多多/抖店)、Amazon 2000×2000、Shopify 2048×2048、社媒 1080×1080、小红书 1080×1440、透明 PNG 1600×1600,以及自定义尺寸。 +- **单张调整**:在面板里选中任意一张,单独改容差、大小、位置、阴影、背景色,只重新导出这一张。 +- **自动提醒**:背景复杂、几乎没去掉背景、商品贴边、容差过高等情况会在缩略图上标出。 +- **设置可复用**:整批设置保存为 `.photostudio.json`,下一批商品直接套用同样的风格。 + +## 使用 + +在 ZCode Desktop 中对 Agent 说: + +- “把 products 文件夹里的商品照全部做成 800×800 白底主图和透明 PNG” +- “把所有商品图统一大小、加柔和阴影,导出 Amazon 2000×2000” +- “香水那张位置太靠上了,往下挪一点,只重新导出这一张” + +也可以从会话侧栏打开“电商商品图助手”,勾选工作区里的图片。左侧是全部图片的设置和输出尺寸,中间是缩略图,点一张在下方单独调整,最后点“全部导出”。 + +## 工具 + +| 工具 | 作用 | +|---|---| +| `photos_open` | 打开一批照片(文件夹、路径或已保存的项目),检查并打开面板 | +| `project_save` | 保存设置为 `.photostudio.json` | +| `photos_export` | 按所选尺寸导出全部或部分照片 | + +## 支持范围(v0.1) + +- 输入:JPG(自动按 EXIF 方向旋转)、PNG(含透明通道)。 +- 去背景适用于纯色、浅色或渐变的棚拍背景。**复杂背景**(桌面、户外、场景图)、头发、透明玻璃不在 v0.1 范围内:缩略图会提示“背景不是纯色”,建议先用其他工具抠好透明 PNG 再放进来。 +- 暂不支持:WebP / HEIC 输入、画笔精修、换场景背景。 + +## 隐私、网络与文件写入 + +- **全部在本机处理**,不联网,不上传图片,不需要任何 API 密钥或账号。 +- 只读写当前工作区:原图不会被修改,结果写到输出文件夹(默认 `product-photos-output/<尺寸>/`),项目设置写到你指定的 `.photostudio.json`。不执行命令,没有 Hook。 + +## 构建与测试(开发者) + +源码在 `ui-plugins/product-photo-studio/`。仓库根目录执行 `pnpm install --frozen-lockfile && pnpm build`,在 ZCode 插件商店添加 `dist/local-marketplace` 为本地来源后安装。测试:`pnpm --filter @penova/plugin-product-photo-studio test`(真实商品照 + 合成样本,校验主体占比、居中、白底纯白、透明背景)与 `test:e2e`(浏览器面板测试,可用 `E2E_PHOTOS` 指向自己的商品照文件夹)。 + +## 第三方组件与许可证 + +插件本身以 MIT 许可证发布(作者 Penova)。打包依赖:pngjs(MIT)、jpeg-js(BSD-3-Clause)、MCP SDK 与 ext-apps(MIT)。完整清单随安装包附在 `dist/THIRD_PARTY_NOTICES.txt`。测试照片来源见 `ui-plugins/product-photo-studio/test/fixtures/SOURCES.md`(CC0 / 公有领域),不随插件安装包分发。 diff --git a/external_plugins/product-photo-studio/skills/product-photo-studio/SKILL.md b/external_plugins/product-photo-studio/skills/product-photo-studio/SKILL.md new file mode 100644 index 00000000..3c335357 --- /dev/null +++ b/external_plugins/product-photo-studio/skills/product-photo-studio/SKILL.md @@ -0,0 +1,21 @@ +--- +name: product-photo-studio +description: 批量处理电商商品照:去纯色背景、统一商品大小与位置、加阴影,导出白底主图、透明 PNG 和淘宝/拼多多/Amazon/Shopify/社媒尺寸。用户提到“白底图 / 主图 / 商品图批量处理 / 抠图统一尺寸”时使用。 +--- + +# 电商商品图助手 + +处理工作区里的 JPG / PNG 商品照,全部在本机完成。 + +1. **打开**:`photos_open(folder | paths, presets?)`,或 `photos_open(project: "xxx.photostudio.json")` 复用上次的设置。返回每张图的检查结果并打开侧栏面板。 + - 内置尺寸 id:`white-800`(淘宝/天猫/京东主图)、`white-1000`(拼多多/抖店)、`amazon-2000`、`shopify-2048`、`square-1080`、`portrait-1080x1440`(小红书)、`transparent-png`(1600×1600 透明)。其他尺寸放进 `customPresets`。 +2. **看警告**: + - `background_not_uniform`:背景不是纯色(桌面、场景图),自动去背可能不准; + - `little_background_removed`:几乎没去掉背景,建议调高该图的 tolerance; + - `subject_touches_edge`:商品贴到照片边缘,原图可能被裁掉; + - `empty_subject`:容差太高把商品也去掉了,调低 tolerance。 + 把这些图告诉用户,建议在面板里单独调整;本插件只能去掉与边缘相连的纯色/浅色背景,复杂背景请用户先用 PhotoCraft 等工具抠好透明 PNG(已有透明通道的 PNG 会直接使用)。 +3. **调整**:全局设置在 `project.settings`;单张差异写进 `images[i].overrides`(只写不同的字段)。字段:`removeBackground`(auto/off)、`tolerance` 1–100(默认 20)、`fill` 主体占比 0.2–0.99(默认 0.85)、`offsetY` −0.4–0.4、`align` center/bottom、`shadow` none/ground/drop、`shadowOpacity` 0–1、`background` 颜色。用 `project_save(path, project)` 保存为 `.photostudio.json`,下次同一批风格直接复用。 +4. **导出**:`photos_export(project, indices?)` 写到 `/<尺寸 id>/<原文件名>.jpg|png`;只重做某几张时传 `indices`(从 0 开始)。导出后告诉用户输出位置和仍需检查的图。 + +用户在面板里拖滑块即可看到预览;面板操作和你的工具调用共用同一个项目格式。不要覆盖原图。 diff --git a/marketplace.json b/marketplace.json index 32e8c8ef..df7ed7a4 100644 --- a/marketplace.json +++ b/marketplace.json @@ -1673,6 +1673,54 @@ "把上一个 Hi3D 任务生成的模型按角色拆分成部件" ] } + }, + { + "name": "product-photo-studio", + "componentTypes": [ + "ui" + ], + "source": "./external_plugins/product-photo-studio", + "displayName": "Product Photo Studio", + "displayName_i18n": { + "en": "Product Photo Studio", + "zh-CN": "电商商品图助手" + }, + "description": "Batch-prepare e-commerce product photos: remove plain studio backgrounds, crop and normalise product size and position, add ground or drop shadows, and export white-background JPGs, transparent PNGs and marketplace sizes (Taobao, Amazon, Shopify, social). Tweak any photo on its own in the side panel. Runs locally; no API keys.", + "description_i18n": { + "en": "Batch-prepare e-commerce product photos: remove plain studio backgrounds, crop and normalise product size and position, add ground or drop shadows, and export white-background JPGs, transparent PNGs and marketplace sizes (Taobao, Amazon, Shopify, social). Tweak any photo on its own in the side panel. Runs locally; no API keys.", + "zh-CN": "批量处理电商商品图:去掉纯色/浅色棚拍背景,自动裁切并统一商品大小和位置,加地面柔影或投影,导出白底 JPG、透明 PNG 和各平台尺寸(淘宝、拼多多、Amazon、Shopify、社媒)。不满意的图可以在侧栏单独调整。全部本地处理,无需 API 密钥。" + }, + "version": "0.1.0", + "author": { + "name": "Penova", + "url": "https://github.com/ppppp2005-p" + }, + "license": "MIT", + "category": "productivity", + "keywords": [ + "e-commerce", + "product-photo", + "white-background", + "remove-background", + "batch", + "taobao", + "amazon", + "shopify", + "商品图", + "白底图" + ], + "examplePrompts": [ + "Turn every photo in products/ into 800×800 white-background main images and transparent PNGs", + "Make all product photos the same size with a soft shadow, Amazon 2000×2000", + "The perfume photo sits too high — lower it and export just that one again" + ], + "examplePrompts_i18n": { + "zh-CN": [ + "把 products 文件夹里的商品照全部做成 800×800 白底主图和透明 PNG", + "把所有商品图统一大小、加柔和阴影,导出 Amazon 2000×2000", + "香水那张位置太靠上了,往下挪一点,只重新导出这一张" + ] + } } ] } \ No newline at end of file diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 14b35f76..158a036d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -224,6 +224,46 @@ importers: ui-plugins/photocraft: {} + ui-plugins/product-photo-studio: + dependencies: + '@modelcontextprotocol/sdk': + specifier: 1.29.0 + version: 1.29.0(zod@4.6.5) + jpeg-js: + specifier: 0.4.4 + version: 0.4.4 + pngjs: + specifier: 7.0.0 + version: 7.0.0 + 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 + '@types/pngjs': + specifier: 6.0.5 + version: 6.0.5 + 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/soundcraft: {} ui-plugins/typst-workbench: @@ -1884,6 +1924,9 @@ packages: '@types/pako@2.0.4': resolution: {integrity: sha512-VWDCbrLeVXJM9fihYodcLiIv0ku+AlOa/TQ1SvYOaBuyrSKgEcro95LJyIsJ4vSo6BXIxOKxiJAat04CmST9Fw==} + '@types/pngjs@6.0.5': + resolution: {integrity: sha512-0k5eKfrA83JOZPppLtS2C7OUtyNAl2wKNxfyYl9Q5g9lPkgBl/9hNyAu6HuEH2J4XmIv2znEpkDd0SaZVxW6iQ==} + '@types/raf@3.4.3': resolution: {integrity: sha512-c4YAvMedbPZ5tEyxzQdMoOhhJ4RD3rngZIdwC2/qDN3d7JpEhB6fiBRKVY1lg5B7Wk+uPBjn5f39j1/2MY1oOw==} @@ -2475,10 +2518,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 +2753,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: @@ -2735,6 +2771,9 @@ packages: react: optional: true + jpeg-js@0.4.4: + resolution: {integrity: sha512-WZzeDOEtTOBK4Mdsar0IqEU5sMr3vSV2RqkAIzUEV2BHnUfKGyswWFPFwK5EeDo93K3FohSHbLAjj0s1Wzd+dg==} + js-base64@3.9.4: resolution: {integrity: sha512-PtOMXpEGuP0RRiRXsjzHzl44dMHxSu2CPvAhinupR1tBa88me+1DPqsobl7eupn5UukjLkln1ZnAOAOXOrYG0Q==} @@ -3101,6 +3140,10 @@ packages: png-chunks-extract@1.0.0: resolution: {integrity: sha512-ZiVwF5EJ0DNZyzAqld8BP1qyJBaGOFaq9zl579qfbkcmOwWLLO4I9L8i2O4j3HkI6/35i0nKG2n+dZplxiT89Q==} + pngjs@7.0.0: + resolution: {integrity: sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow==} + engines: {node: '>=14.19.0'} + points-on-curve@0.2.0: resolution: {integrity: sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A==} @@ -4285,11 +4328,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 @@ -5118,6 +5161,10 @@ snapshots: '@types/pako@2.0.4': {} + '@types/pngjs@6.0.5': + dependencies: + '@types/node': 25.5.0 + '@types/raf@3.4.3': optional: true @@ -5809,13 +5856,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: {} @@ -6048,8 +6093,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) @@ -6060,6 +6103,8 @@ snapshots: '@types/react': 19.2.14 react: 19.2.7 + jpeg-js@0.4.4: {} + js-base64@3.9.4: {} json-schema-traverse@1.0.0: {} @@ -6433,6 +6478,8 @@ snapshots: dependencies: crc-32: 0.3.0 + pngjs@7.0.0: {} + points-on-curve@0.2.0: {} points-on-curve@1.0.1: {} diff --git a/ui-plugins/product-photo-studio/package.json b/ui-plugins/product-photo-studio/package.json new file mode 100644 index 00000000..99612bcc --- /dev/null +++ b/ui-plugins/product-photo-studio/package.json @@ -0,0 +1,35 @@ +{ + "name": "@penova/plugin-product-photo-studio", + "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": "Product Photo Studio" + }, + "engines": { + "node": ">=22.0.0" + }, + "dependencies": { + "@modelcontextprotocol/sdk": "1.29.0", + "jpeg-js": "0.4.4", + "pngjs": "7.0.0", + "zod": "^4.6.5" + }, + "devDependencies": { + "@modelcontextprotocol/core": "2.0.0", + "@modelcontextprotocol/ext-apps": "2.0.0", + "@types/node": "25.5.0", + "@types/pngjs": "6.0.5", + "esbuild": "^0.25.12", + "playwright-core": "1.59.1", + "typescript": "6.0.2", + "vitest": "4.1.4" + } +} diff --git a/ui-plugins/product-photo-studio/scripts/build.mjs b/ui-plugins/product-photo-studio/scripts/build.mjs new file mode 100644 index 00000000..02ff90d4 --- /dev/null +++ b/ui-plugins/product-photo-studio/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/product-photo-studio/scripts/e2e.mts b/ui-plugins/product-photo-studio/scripts/e2e.mts new file mode 100644 index 00000000..df47d907 --- /dev/null +++ b/ui-plugins/product-photo-studio/scripts/e2e.mts @@ -0,0 +1,69 @@ +// 浏览器端到端测试:真实打包的 server + 官方 AppBridge 宿主 + 隔离 iframe 中的面板。 +// 运行:node --experimental-strip-types scripts/e2e.mts(需要本机 Chrome,或设置 CHROME_PATH)。 +// 可用 E2E_PHOTOS 指向一个装有真实商品照的文件夹。 +import assert from "node:assert/strict"; +import { copyFile, mkdir, mkdtemp, readdir, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { startHarness } from "./harness.mjs"; +import { cutoutPng, gradientProduct } from "../test/fixtures.ts"; + +const shots = process.env.E2E_SHOTS ?? join(tmpdir(), "product-photo-studio-shots"); +await mkdir(shots, { recursive: true }); +const workspace = await mkdtemp(join(tmpdir(), "photostudio-e2e-")); +await mkdir(join(workspace, "商品图")); +await writeFile(join(workspace, "商品图/red-bottle.jpg"), gradientProduct()); +await writeFile(join(workspace, "商品图/blue-ball.png"), cutoutPng()); +const fixtures = new URL("../test/fixtures/", import.meta.url).pathname; +for (const f of ["headphones-cc0.jpg", "perfume.jpg"]) await copyFile(join(fixtures, f), join(workspace, "商品图", f)); +if (process.env.E2E_PHOTOS) for (const f of await readdir(process.env.E2E_PHOTOS)) await copyFile(join(process.env.E2E_PHOTOS, f), join(workspace, "商品图", f)); +const count = (await readdir(join(workspace, "商品图"))).length; + +const harness = await startHarness({ workspace }); +const step = (text: string) => process.stdout.write(`• ${text}\n`); +try { + const { outer, frame } = await harness.open("?locale=zh-CN", { width: 1280, height: 1000 }); + step("empty panel lists workspace images"); + await frame.locator("label", { hasText: "red-bottle.jpg" }).waitFor(); + + step("agent opens the folder"); + await harness.agent(outer, "photos_open", { folder: "商品图", presets: ["white-800", "transparent-png"] }); + await frame.locator(".thumb img").nth(count - 1).waitFor({ timeout: 120_000 }); + await frame.waitForFunction(() => !!(document.getElementById("large") as HTMLImageElement)?.src, null, { timeout: 60_000 }); + await outer.screenshot({ path: join(shots, "01-batch.png") }); + + step("change global size and shadow, previews refresh"); + const fill = frame.locator(".side .slider", { hasText: "主体占比" }).locator("input"); + await fill.fill("0.7"); + await frame.locator(".side select").nth(1).selectOption("drop"); + await frame.waitForTimeout(2500); + await outer.screenshot({ path: join(shots, "02-global-settings.png") }); + + step("adjust one photo only"); + await frame.locator(".thumb", { hasText: "perfume" }).click(); + await frame.locator(".detail .slider", { hasText: "上下位置" }).locator("input").fill("0.1"); + await frame.waitForTimeout(1500); + await frame.locator(".thumb", { hasText: "✎" }).waitFor({ state: "attached" }).catch(() => undefined); + await outer.screenshot({ path: join(shots, "03-single-photo.png") }); + + step("transparent preview"); + await frame.locator(".main select").first().selectOption("transparent-png"); + await frame.waitForTimeout(2500); + await outer.screenshot({ path: join(shots, "04-transparent.png") }); + + step("export all"); + await frame.locator("button", { hasText: "全部导出" }).click(); + await frame.locator("h2", { hasText: "已导出" }).waitFor({ timeout: 300_000 }); + const white = await readdir(join(workspace, "product-photos-output/white-800")); + const png = await readdir(join(workspace, "product-photos-output/transparent-png")); + assert.equal(white.length, count); + assert.equal(png.length, count); + await outer.screenshot({ path: join(shots, "05-exported.png") }); + assert.deepEqual(harness.errors, []); + step(`ok — ${count} photos, screenshots in ${shots}`); +} catch (error) { + console.error("page errors:", harness.errors, harness.stderr.join("")); + throw error; +} finally { + await harness.close(); +} diff --git a/ui-plugins/product-photo-studio/scripts/harness.mjs b/ui-plugins/product-photo-studio/scripts/harness.mjs new file mode 100644 index 00000000..a45e6e41 --- /dev/null +++ b/ui-plugins/product-photo-studio/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/product-photo-studio/scripts/licenses.mjs b/ui-plugins/product-photo-studio/scripts/licenses.mjs new file mode 100644 index 00000000..162c2a73 --- /dev/null +++ b/ui-plugins/product-photo-studio/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) { + packages.set(directory, pkg); + break; + } + } catch (error) { + if (error.code !== "ENOENT") throw error; + } + directory = dirname(directory); + } + } + const notices = []; + const seen = new Set(); + for (const [directory, pkg] of [...packages].sort((a, b) => a[1].name.localeCompare(b[1].name))) { + const key = `${pkg.name}@${pkg.version}`; + if (seen.has(key)) continue; + seen.add(key); + const files = (await readdir(directory)).filter((name) => + /^(license|copying|notice)([.-]|$)/i.test(name), + ); + const texts = await Promise.all(files.map((file) => readFile(join(directory, file), "utf8"))); + if (!texts.length && !pkg.license) throw new Error(`Missing license for bundled dependency ${key}`); + if (!texts.length) texts.push(`(No license file is shipped in this package; its package.json declares the ${pkg.license} license.)`); + notices.push( + `${key} — ${typeof pkg.license === "string" ? pkg.license : JSON.stringify(pkg.license)}\n${texts.join("\n\n")}`, + ); + } + await writeFile(destination, notices.join("\n\n----------------------------------------\n\n")); +} diff --git a/ui-plugins/product-photo-studio/src/kit/console.ts b/ui-plugins/product-photo-studio/src/kit/console.ts new file mode 100644 index 00000000..f6817656 --- /dev/null +++ b/ui-plugins/product-photo-studio/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/product-photo-studio/src/kit/raster.ts b/ui-plugins/product-photo-studio/src/kit/raster.ts new file mode 100644 index 00000000..324b8316 --- /dev/null +++ b/ui-plugins/product-photo-studio/src/kit/raster.ts @@ -0,0 +1,238 @@ +import jpeg from "jpeg-js"; +import { PNG } from "pngjs"; +import { KitError } from "./workspace.ts"; + +/** RGBA 8 位图像。 */ +export interface Raster { + width: number; + height: number; + data: Uint8ClampedArray | Uint8Array; +} + +export function createRaster(width: number, height: number, fill?: [number, number, number, number]): Raster { + const data = new Uint8ClampedArray(width * height * 4); + if (fill && (fill[0] || fill[1] || fill[2] || fill[3])) for (let i = 0; i < data.length; i += 4) data.set(fill, i); + return { width, height, data }; +} + +/** JPEG 的 EXIF 方向(1–8),没有则为 1。 */ +export function jpegOrientation(bytes: Uint8Array): number { + if (bytes[0] !== 0xff || bytes[1] !== 0xd8) return 1; + let offset = 2; + while (offset + 4 < bytes.length) { + if (bytes[offset] !== 0xff) return 1; + const marker = bytes[offset + 1]; + const length = (bytes[offset + 2] << 8) | bytes[offset + 3]; + if (marker === 0xe1 && bytes[offset + 4] === 0x45 && bytes[offset + 5] === 0x78 && bytes[offset + 6] === 0x69 && bytes[offset + 7] === 0x66) { + const tiff = offset + 10; + const little = bytes[tiff] === 0x49; + const u16 = (at: number) => (little ? bytes[at] | (bytes[at + 1] << 8) : (bytes[at] << 8) | bytes[at + 1]); + const u32 = (at: number) => (little ? (bytes[at] | (bytes[at + 1] << 8) | (bytes[at + 2] << 16)) + bytes[at + 3] * 16777216 : bytes[at] * 16777216 + ((bytes[at + 1] << 16) | (bytes[at + 2] << 8) | bytes[at + 3])); + const ifd = tiff + u32(tiff + 4); + const count = u16(ifd); + for (let i = 0; i < count; i++) { + const entry = ifd + 2 + i * 12; + if (entry + 12 > bytes.length) break; + if (u16(entry) === 0x0112) return u16(entry + 8) || 1; + } + return 1; + } + if (marker === 0xda) return 1; + offset += 2 + length; + } + return 1; +} + +function orient(image: Raster, orientation: number): Raster { + if (orientation <= 1 || orientation > 8) return image; + const { width: w, height: h, data } = image; + const swap = orientation >= 5; + const out = createRaster(swap ? h : w, swap ? w : h); + for (let y = 0; y < h; y++) + for (let x = 0; x < w; x++) { + let nx = x; + let ny = y; + switch (orientation) { + case 2: nx = w - 1 - x; break; + case 3: nx = w - 1 - x; ny = h - 1 - y; break; + case 4: ny = h - 1 - y; break; + case 5: nx = y; ny = x; break; + case 6: nx = h - 1 - y; ny = x; break; + case 7: nx = h - 1 - y; ny = w - 1 - x; break; + case 8: nx = y; ny = w - 1 - x; break; + } + const s = (y * w + x) * 4; + const d = (ny * out.width + nx) * 4; + out.data[d] = data[s]; + out.data[d + 1] = data[s + 1]; + out.data[d + 2] = data[s + 2]; + out.data[d + 3] = data[s + 3]; + } + return out; +} + +export function decodeImage(bytes: Uint8Array, name = "image"): Raster { + try { + if (bytes.length >= 2 && bytes[0] === 0x89 && bytes[1] === 0x50) { + const png = PNG.sync.read(Buffer.from(bytes)); + return { width: png.width, height: png.height, data: new Uint8ClampedArray(png.data.buffer, png.data.byteOffset, png.data.length) }; + } + if (bytes.length >= 2 && bytes[0] === 0xff && bytes[1] === 0xd8) { + const image = jpeg.decode(bytes, { useTArray: true, formatAsRGBA: true, maxMemoryUsageInMB: 1024, maxResolutionInMP: 200 }); + return orient({ width: image.width, height: image.height, data: new Uint8ClampedArray(image.data.buffer) }, jpegOrientation(bytes)); + } + } catch (error) { + throw new KitError("bad_image", `Cannot decode ${name}: ${error instanceof Error ? error.message : error}`); + } + const base = name.split(/[\\/]/).pop() ?? name; + const looksNamedRaster = !bytes.length || /\.(png|jpe?g)$/i.test(base); + if (looksNamedRaster) { + throw new KitError("bad_image", `${name}: not a valid PNG or JPEG (empty, corrupt, or the file is not an image).`); + } + throw new KitError("unsupported_image", `${name}: only PNG and JPEG are supported (convert WebP/HEIC first).`); +} + +export function encodePng(image: Raster): Buffer { + const png = new PNG({ width: image.width, height: image.height }); + png.data = Buffer.from(image.data.buffer, image.data.byteOffset, image.data.length); + return PNG.sync.write(png, { colorType: 6 }); +} + +/** JPEG 不支持透明:先与背景色合成。 */ +export function encodeJpeg(image: Raster, quality = 90, background: [number, number, number] = [255, 255, 255]): Buffer { + const data = Buffer.alloc(image.width * image.height * 4); + for (let i = 0; i < data.length; i += 4) { + const a = image.data[i + 3] / 255; + data[i] = Math.round(image.data[i] * a + background[0] * (1 - a)); + data[i + 1] = Math.round(image.data[i + 1] * a + background[1] * (1 - a)); + data[i + 2] = Math.round(image.data[i + 2] * a + background[2] * (1 - a)); + data[i + 3] = 255; + } + return jpeg.encode({ width: image.width, height: image.height, data }, quality).data; +} + +/** 缩放:缩小用区域平均(预乘 alpha,避免透明边发黑),放大用双线性。 */ +export function resize(image: Raster, width: number, height: number): Raster { + width = Math.max(1, Math.round(width)); + height = Math.max(1, Math.round(height)); + if (width === image.width && height === image.height) return image; + const out = createRaster(width, height); + const sx = image.width / width; + const sy = image.height / height; + const src = image.data; + if (sx >= 1 && sy >= 1) { + for (let y = 0; y < height; y++) { + const y0 = y * sy; + const y1 = Math.min(image.height, (y + 1) * sy); + for (let x = 0; x < width; x++) { + const x0 = x * sx; + const x1 = Math.min(image.width, (x + 1) * sx); + let r = 0, g = 0, b = 0, a = 0, total = 0; + for (let yy = Math.floor(y0); yy < Math.ceil(y1); yy++) { + const wy = Math.min(yy + 1, y1) - Math.max(yy, y0); + for (let xx = Math.floor(x0); xx < Math.ceil(x1); xx++) { + const wgt = wy * (Math.min(xx + 1, x1) - Math.max(xx, x0)); + const i = (yy * image.width + xx) * 4; + const alpha = src[i + 3] * wgt; + r += src[i] * alpha; + g += src[i + 1] * alpha; + b += src[i + 2] * alpha; + a += alpha; + total += wgt; + } + } + const o = (y * width + x) * 4; + if (a > 0) { + out.data[o] = r / a; + out.data[o + 1] = g / a; + out.data[o + 2] = b / a; + } + out.data[o + 3] = a / total; + } + } + return out; + } + for (let y = 0; y < height; y++) { + const fy = Math.min(image.height - 1, Math.max(0, (y + 0.5) * sy - 0.5)); + const y0 = Math.floor(fy); + const y1 = Math.min(image.height - 1, y0 + 1); + const ty = fy - y0; + for (let x = 0; x < width; x++) { + const fx = Math.min(image.width - 1, Math.max(0, (x + 0.5) * sx - 0.5)); + const x0 = Math.floor(fx); + const x1 = Math.min(image.width - 1, x0 + 1); + const tx = fx - x0; + const o = (y * width + x) * 4; + const i00 = (y0 * image.width + x0) * 4, i10 = (y0 * image.width + x1) * 4, i01 = (y1 * image.width + x0) * 4, i11 = (y1 * image.width + x1) * 4; + const w00 = (1 - tx) * (1 - ty) * src[i00 + 3], w10 = tx * (1 - ty) * src[i10 + 3], w01 = (1 - tx) * ty * src[i01 + 3], w11 = tx * ty * src[i11 + 3]; + const a = w00 + w10 + w01 + w11; + if (a > 0) for (let c = 0; c < 3; c++) out.data[o + c] = (src[i00 + c] * w00 + src[i10 + c] * w10 + src[i01 + c] * w01 + src[i11 + c] * w11) / a; + out.data[o + 3] = a; + } + } + return out; +} + +/** 等比缩小到最长边不超过 max。 */ +export function fitWithin(image: Raster, max: number): Raster { + const scale = Math.min(1, max / Math.max(image.width, image.height)); + return scale < 1 ? resize(image, image.width * scale, image.height * scale) : image; +} + +/** 单通道盒式模糊(3 次近似高斯)。 */ +export function blurChannel(values: Float32Array, width: number, height: number, radius: number, passes = 3): Float32Array { + const r = Math.max(0, Math.round(radius)); + if (!r) return values; + let src = values; + let tmp = new Float32Array(values.length); + for (let pass = 0; pass < passes; pass++) { + for (let y = 0; y < height; y++) { + let sum = 0; + const row = y * width; + for (let x = -r; x <= r; x++) sum += src[row + Math.min(width - 1, Math.max(0, x))]; + for (let x = 0; x < width; x++) { + tmp[row + x] = sum / (2 * r + 1); + sum += src[row + Math.min(width - 1, x + r + 1)] - src[row + Math.max(0, x - r)]; + } + } + const out = new Float32Array(values.length); + for (let x = 0; x < width; x++) { + let sum = 0; + for (let y = -r; y <= r; y++) sum += tmp[Math.min(height - 1, Math.max(0, y)) * width + x]; + for (let y = 0; y < height; y++) { + out[y * width + x] = sum / (2 * r + 1); + sum += tmp[Math.min(height - 1, y + r + 1) * width + x] - tmp[Math.max(0, y - r) * width + x]; + } + } + src = out; + } + tmp = new Float32Array(0); + return src; +} + +export function parseColor(color: string | undefined, fallback: [number, number, number] = [255, 255, 255]): [number, number, number] { + const match = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec((color ?? "").trim()); + if (!match) return fallback; + const hex = match[1].length === 3 ? [...match[1]].map((c) => c + c).join("") : match[1]; + return [parseInt(hex.slice(0, 2), 16), parseInt(hex.slice(2, 4), 16), parseInt(hex.slice(4, 6), 16)]; +} + +/** 把 src 按 alpha 叠到 dst 的 (dx, dy) 位置。 */ +export function drawOver(dst: Raster, src: Raster, dx: number, dy: number, opacity = 1) { + for (let y = 0; y < src.height; y++) { + const ty = y + dy; + if (ty < 0 || ty >= dst.height) continue; + for (let x = 0; x < src.width; x++) { + const tx = x + dx; + if (tx < 0 || tx >= dst.width) continue; + const s = (y * src.width + x) * 4; + const a = (src.data[s + 3] / 255) * opacity; + if (a <= 0) continue; + const d = (ty * dst.width + tx) * 4; + const da = dst.data[d + 3] / 255; + const oa = a + da * (1 - a); + for (let c = 0; c < 3; c++) dst.data[d + c] = (src.data[s + c] * a + dst.data[d + c] * da * (1 - a)) / oa; + dst.data[d + 3] = oa * 255; + } + } +} diff --git a/ui-plugins/product-photo-studio/src/kit/server-kit.ts b/ui-plugins/product-photo-studio/src/kit/server-kit.ts new file mode 100644 index 00000000..6bc31594 --- /dev/null +++ b/ui-plugins/product-photo-studio/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/product-photo-studio/src/kit/workspace.ts b/ui-plugins/product-photo-studio/src/kit/workspace.ts new file mode 100644 index 00000000..f02c4fcb --- /dev/null +++ b/ui-plugins/product-photo-studio/src/kit/workspace.ts @@ -0,0 +1,151 @@ +import { lstatSync, readlinkSync, realpathSync } from "node:fs"; +import { mkdir, readFile, readdir, 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 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 || wanted.includes(extname(entry.name).toLowerCase()))) { + out.push({ path: this.rel(child), size: (await stat(child)).size }); + } + } + }; + await walk(this.resolve(dir), 0); + return out; + } +} + +/** 把文件名中不适合的字符替换掉,保留中文。 */ +export function safeFileName(name: string, fallback = "file"): string { + const cleaned = name + .replace(/[\\/:*?"<>|]+/g, "_") + .replace(/\p{Cc}+/gu, "_") + .replace(/\s+/g, " ") + .trim() + .replace(/^\.+/, ""); + return (cleaned || fallback).slice(0, 120); +} diff --git a/ui-plugins/product-photo-studio/src/main.ts b/ui-plugins/product-photo-studio/src/main.ts new file mode 100644 index 00000000..fb70ffa0 --- /dev/null +++ b/ui-plugins/product-photo-studio/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(`[product-photo-studio] ${line}\n`), +}); +process.stdin.once("end", () => process.exit(0)); +await server.connect(new StdioServerTransport()); diff --git a/ui-plugins/product-photo-studio/src/server.ts b/ui-plugins/product-photo-studio/src/server.ts new file mode 100644 index 00000000..82736199 --- /dev/null +++ b/ui-plugins/product-photo-studio/src/server.ts @@ -0,0 +1,301 @@ +import { stat, readFile } from "node:fs/promises"; +import { basename, extname, join } from "node:path"; +import { z } from "zod"; +import { createKitServer } from "./kit/server-kit.ts"; +import { decodeImage, encodeJpeg, encodePng, fitWithin, parseColor } from "./kit/raster.ts"; +import { KitError, Workspace, safeFileName } from "./kit/workspace.ts"; +import { DEFAULT_SETTINGS, PRESETS, compose, cutout, mergeSettings, type Cutout, type Preset, type Settings } from "./studio.ts"; + +export const NAME = "product-photo-studio"; +export const VERSION = "0.1.0"; +export const PANEL_URI = `ui://${NAME}/panel.html`; +const IMAGE_EXTS = [".jpg", ".jpeg", ".png"]; +const MAX_IMAGES = 300; + +export interface Project { + version: 1; + images: { path: string; overrides?: Partial }[]; + settings: Settings; + presets: string[]; + customPresets?: Preset[]; + outputDir: string; +} + +export interface ServerOptions { + workspaceRoot: string; + assetRoot: string; + log?: (line: string) => void; +} + +const WARNING_TEXT: Record = { + background_not_uniform: "background is not a plain colour — removal may be inaccurate", + little_background_removed: "almost no background was removed — raise the tolerance or check the photo", + subject_touches_edge: "the product touches the photo edge — it may be cut off in the original", + empty_subject: "nothing left after background removal — lower the tolerance", +}; + +/** + * 保存前检查项目引用的文件:不存在、0 字节、或内容不像所写的格式时给出提示(仍然保存,TEST-FINDINGS #9)。 + */ +async function checkRefs(ws: Workspace, refs: [string, unknown][]): Promise { + const out: string[] = []; + const sniff = (b: Buffer, ext: string) => { + if (ext === "pdf") return b.toString("latin1", 0, 1024).includes("%PDF-"); + if (ext === "png") return b[0] === 0x89 && b.toString("ascii", 1, 4) === "PNG"; + if (ext === "jpg" || ext === "jpeg") return b[0] === 0xff && b[1] === 0xd8; + if (ext === "webp") return b.toString("ascii", 0, 4) === "RIFF" && b.toString("ascii", 8, 12) === "WEBP"; + if (ext === "xlsx") return b[0] === 0x50 && b[1] === 0x4b; + if (ext === "csv" || ext === "tsv" || ext === "txt") return !b.subarray(0, 8192).includes(0); + return true; + }; + for (const [label, ref] of refs) { + if (typeof ref !== "string" || !ref) continue; + let b: Buffer; + try { b = await ws.read(ref, 300 * 1024 * 1024); } catch { out.push(`${label} ${ref} not found`); continue; } + if (!b.length) { out.push(`${label} ${ref} is empty (0 bytes)`); continue; } + const ext = ref.toLowerCase().split(".").pop() ?? ""; + if (!sniff(b, ext)) out.push(`${label} ${ref} does not look like a .${ext} file`); + } + return out; +} + +export function createServer(options: ServerOptions) { + const ws = new Workspace(options.workspaceRoot); + const { server, tool } = createKitServer({ + name: NAME, + version: VERSION, + panelUri: PANEL_URI, + surface: "editor", + panelHtml: () => readFile(join(options.assetRoot, "ui/panel.html"), "utf8"), + log: options.log, + }); + + const cache = new Map(); + async function getCutout(path: string, settings: Settings): Promise { + const info = await stat(ws.resolve(path)).catch(() => { + throw new KitError("not_found", `File not found: ${path}`); + }); + const key = `${path}|${info.mtimeMs}|${settings.removeBackground}|${settings.tolerance}`; + const hit = cache.get(key); + if (hit) return hit; + const result = cutout(decodeImage(await ws.read(path, 80 * 1024 * 1024), path), settings); + cache.set(key, result); + if (cache.size > 60) cache.delete(cache.keys().next().value!); + return result; + } + + function presetsOf(project: Project): Preset[] { + const all = [...PRESETS, ...(project.customPresets ?? [])]; + const chosen = project.presets.map((id) => all.find((p) => p.id === id)).filter(Boolean) as Preset[]; + if (!chosen.length) throw new KitError("no_preset", `Choose at least one output size. Available: ${all.map((p) => p.id).join(", ")}`); + return chosen; + } + + function normalizeProject(value: unknown): Project { + if (!value || typeof value !== "object") throw new KitError("bad_project", "Project must be an object."); + const p = value as Partial; + const images = (Array.isArray(p.images) ? p.images : []) + .map((item) => (typeof item === "string" ? { path: item } : item)) + .filter((item): item is { path: string; overrides?: Partial } => !!item && typeof item.path === "string"); + for (const image of images) ws.resolve(image.path); + if (images.length > MAX_IMAGES) throw new KitError("too_many_images", `At most ${MAX_IMAGES} images per batch.`); + const custom = (Array.isArray(p.customPresets) ? p.customPresets : []).map((c) => { + const width = Math.round(Number(c.width)); + const height = Math.round(Number(c.height)); + if (!(width >= 16 && width <= 6000 && height >= 16 && height <= 6000)) throw new KitError("bad_preset", "Custom sizes must be between 16 and 6000 px."); + return { id: c.id || `custom-${width}x${height}`, label: c.label || `${width}×${height}`, width, height, format: c.format === "png" ? "png" : "jpg", transparent: !!c.transparent, quality: c.quality } as Preset; + }); + return { + version: 1, + images, + settings: mergeSettings(DEFAULT_SETTINGS, p.settings), + presets: Array.isArray(p.presets) && p.presets.length ? p.presets.map(String) : ["white-800", "transparent-png"], + customPresets: custom, + outputDir: typeof p.outputDir === "string" && p.outputDir.trim() ? p.outputDir.trim() : "product-photos-output", + }; + } + + async function loadProject(value: unknown): Promise<{ project: Project; path?: string }> { + if (typeof value === "string") { + let parsed: unknown; + try { + parsed = JSON.parse(await ws.readText(value)); + } catch (error) { + if (error instanceof KitError) throw error; + throw new KitError("bad_project", `${value} is not valid JSON.`); + } + return { project: normalizeProject(parsed), path: value }; + } + return { project: normalizeProject(value) }; + } + + async function analyse(project: Project) { + const items = []; + for (const image of project.images) { + const settings = mergeSettings(project.settings, image.overrides); + try { + const result = await getCutout(image.path, settings); + items.push({ path: image.path, report: result.report, subject: { width: result.subject.width, height: result.subject.height } }); + } catch (error) { + items.push({ path: image.path, error: error instanceof Error ? error.message : String(error) }); + } + } + return items; + } + + const projectInput = z.union([z.string(), z.record(z.string(), z.unknown())]).describe("Project object, or the workspace path of a saved .photostudio.json project."); + + tool( + "photos_open", + { + description: + "Open Product Photo Studio with a batch of product photos (JPG/PNG in the workspace). Removes plain studio backgrounds, crops to the product, and reports per-photo warnings (busy background, product touching the edge). Pass `paths` and/or `folder`, or a saved `project` (.photostudio.json). Opens the side panel where the user tunes each photo.", + input: { + paths: z.array(z.string()).max(MAX_IMAGES).optional().describe("Workspace paths of photos."), + folder: z.string().optional().describe("Workspace folder: every JPG/PNG directly inside it."), + project: z.string().optional().describe("Workspace path of a saved .photostudio.json project."), + presets: z.array(z.string()).optional().describe(`Output sizes. Built-in: ${PRESETS.map((p) => p.id).join(", ")}.`), + }, + openPanel: true, + readOnly: true, + timeoutMs: 600_000, + }, + async ({ paths, folder, project: projectPath, presets }) => { + let project: Project; + let saved: string | undefined; + if (projectPath) ({ project, path: saved } = await loadProject(projectPath)); + else { + const list = [...(paths ?? [])]; + if (folder) list.push(...(await ws.list({ dir: folder, exts: IMAGE_EXTS, recursive: false, limit: MAX_IMAGES })).map((f) => f.path)); + if (!list.length) throw new KitError("missing_input", "Pass photo `paths`, a `folder`, or a saved `project`."); + project = normalizeProject({ images: [...new Set(list)].map((path) => ({ path })), presets }); + } + if (presets?.length && projectPath) project.presets = presets; + const items = await analyse(project); + const flagged = items.filter((i) => ("error" in i && i.error) || (i.report?.warnings.length ?? 0)); + const lines = [ + `${items.length} photo(s). Output sizes: ${presetsOf(project).map((p) => p.id).join(", ")}. Output folder: ${project.outputDir}/`, + flagged.length ? `${flagged.length} photo(s) need a look:` : "All photos look clean.", + ...flagged.slice(0, 30).map((i) => `- ${i.path}: ${"error" in i && i.error ? i.error : i.report!.warnings.map((w) => WARNING_TEXT[w] ?? w).join("; ")}`), + "Next: let the user review in the panel, then call photos_export.", + ]; + return { text: lines.join("\n"), structured: { kind: "project", project, projectPath: saved, items, presets: PRESETS } }; + }, + ); + + tool( + "photos_preview", + { + description: "Render one photo of the project with its settings for the panel preview (small JPEG/PNG, base64).", + input: { project: projectInput, index: z.number().int().min(0), preset: z.string().optional(), size: z.number().int().min(64).max(1200).optional() }, + visibility: ["app"], + readOnly: true, + }, + async ({ project: value, index, preset: presetId, size }) => { + const { project } = await loadProject(value); + const image = project.images[index]; + if (!image) throw new KitError("bad_index", `No photo #${index}.`); + const settings = mergeSettings(project.settings, image.overrides); + const presets = presetsOf(project); + const preset = presets.find((p) => p.id === presetId) ?? presets[0]; + const k = Math.min(1, (size ?? 480) / Math.max(preset.width, preset.height)); + const result = await getCutout(image.path, settings); + const canvas = compose(result.subject, { width: Math.round(preset.width * k), height: Math.round(preset.height * k), transparent: preset.transparent }, settings); + const bytes = preset.transparent ? encodePng(canvas) : encodeJpeg(canvas, 85, parseColor(settings.background)); + return { + text: `${image.path} → ${preset.id}`, + structured: { image: bytes.toString("base64"), mime: preset.transparent ? "image/png" : "image/jpeg", report: result.report, preset: preset.id }, + }; + }, + ); + + tool( + "photo_thumbs", + { + description: "Small thumbnails of original photos for the panel.", + input: { paths: z.array(z.string()).max(60), size: z.number().int().min(32).max(400).optional() }, + visibility: ["app"], + readOnly: true, + }, + async ({ paths, size }) => { + const thumbs: Record = {}; + for (const path of paths) { + try { + thumbs[path] = encodeJpeg(fitWithin(decodeImage(await ws.read(path, 80 * 1024 * 1024), path), size ?? 160), 75).toString("base64"); + } catch { + // 无法解码的图片在面板里显示占位。 + } + } + return { text: `${Object.keys(thumbs).length} thumbnail(s)`, structured: { thumbs } }; + }, + ); + + tool( + "project_save", + { + description: + 'Save the batch settings as a .photostudio.json project in the workspace so the same look can be applied to the next batch. Shape: {images:[{path, overrides?}], settings:{removeBackground:"auto"|"off", tolerance:1-100, fill:0.2-0.99, offsetY:-0.4..0.4, align:"center"|"bottom", shadow:"none"|"ground"|"drop", shadowOpacity:0-1, background:"#ffffff"}, presets:[ids], customPresets?:[{id,label,width,height,format:"jpg"|"png",transparent?}], outputDir}.', + input: { path: z.string(), project: z.record(z.string(), z.unknown()) }, + }, + async ({ path, project: value }) => { + const project = normalizeProject(value); + const target = /\.json$/i.test(path) ? path : `${path}.photostudio.json`; + const written = await ws.write(target, JSON.stringify(project, null, 2) + "\n"); + const warnings = await checkRefs(ws, project.images.map((i: { path: string }) => ["Photo", i.path] as [string, unknown])); + return { text: `Saved ${written}.${warnings.length ? `\nCheck:\n${warnings.map((w) => `- ${w}`).join("\n")}` : ""}`, structured: { kind: "saved", path: written, project, warnings } }; + }, + ); + + tool( + "photos_export", + { + description: + "Export every photo (or only `indices`, 0-based) in every chosen output size: //.jpg|png. White-background sizes are JPEG, transparent sizes PNG. Per-photo overrides in the project (tolerance, fill, offset, shadow, background) are applied.", + input: { project: projectInput, indices: z.array(z.number().int().min(0)).optional() }, + timeoutMs: 900_000, + }, + async ({ project: value, indices }) => { + const { project } = await loadProject(value); + const presets = presetsOf(project); + const files: string[] = []; + const problems: string[] = []; + const used = new Map(); + for (const [index, image] of project.images.entries()) { + if (indices && !indices.includes(index)) continue; + const settings = mergeSettings(project.settings, image.overrides); + let result: Cutout; + try { + result = await getCutout(image.path, settings); + } catch (error) { + problems.push(`${image.path}: ${error instanceof Error ? error.message : error}`); + continue; + } + if (result.report.warnings.length) problems.push(`${image.path}: ${result.report.warnings.map((w) => WARNING_TEXT[w] ?? w).join("; ")}`); + let stem = safeFileName(basename(image.path, extname(image.path)), `photo-${index + 1}`); + const seen = used.get(stem.toLowerCase()) ?? 0; + used.set(stem.toLowerCase(), seen + 1); + if (seen) stem = `${stem}-${seen + 1}`; + for (const preset of presets) { + const canvas = compose(result.subject, preset, settings); + const bytes = preset.format === "png" ? encodePng(canvas) : encodeJpeg(canvas, preset.quality ?? 90, parseColor(settings.background)); + files.push(await ws.write(`${project.outputDir}/${preset.id}/${stem}.${preset.format}`, bytes)); + } + } + return { + text: [`Wrote ${files.length} file(s) to ${project.outputDir}/ (${presets.map((p) => p.id).join(", ")}).`, ...(problems.length ? ["Check these photos:", ...problems.map((p) => `- ${p}`)] : [])].join("\n"), + structured: { kind: "exported", files, problems, outputDir: project.outputDir }, + }; + }, + ); + + tool( + "workspace_images", + { description: "List JPG/PNG files in the workspace for the panel picker.", input: {}, visibility: ["app"], readOnly: true }, + async () => { + const files = await ws.list({ exts: IMAGE_EXTS, limit: 1000 }); + return { text: `${files.length} image(s)`, structured: { files: files.map((f) => f.path) } }; + }, + ); + + return server; +} diff --git a/ui-plugins/product-photo-studio/src/studio.ts b/ui-plugins/product-photo-studio/src/studio.ts new file mode 100644 index 00000000..0cc08619 --- /dev/null +++ b/ui-plugins/product-photo-studio/src/studio.ts @@ -0,0 +1,270 @@ +import { blurChannel, createRaster, drawOver, fitWithin, parseColor, resize, type Raster } from "./kit/raster.ts"; + +export interface Settings { + /** auto:已有透明通道就直接用,否则去掉与边缘相连的纯色/浅色背景;off:不去背景。 */ + removeBackground: "auto" | "off"; + /** 去背景容差 1–100。 */ + tolerance: number; + /** 主体占画布的比例(长边方向)。 */ + fill: number; + /** 垂直偏移,画布高度的比例,正数向下。 */ + offsetY: number; + align: "center" | "bottom"; + shadow: "none" | "ground" | "drop"; + shadowOpacity: number; + background: string; +} + +export interface Preset { + id: string; + label: string; + width: number; + height: number; + format: "jpg" | "png"; + transparent?: boolean; + quality?: number; +} + +export const DEFAULT_SETTINGS: Settings = { + removeBackground: "auto", + tolerance: 20, + fill: 0.85, + offsetY: 0, + align: "center", + shadow: "ground", + shadowOpacity: 0.3, + background: "#ffffff", +}; + +export const PRESETS: Preset[] = [ + { id: "white-800", label: "白底 800×800(淘宝/天猫/京东主图)", width: 800, height: 800, format: "jpg", quality: 92 }, + { id: "white-1000", label: "白底 1000×1000(拼多多/抖店)", width: 1000, height: 1000, format: "jpg", quality: 92 }, + { id: "amazon-2000", label: "Amazon 2000×2000 white", width: 2000, height: 2000, format: "jpg", quality: 90 }, + { id: "shopify-2048", label: "Shopify 2048×2048", width: 2048, height: 2048, format: "jpg", quality: 90 }, + { id: "square-1080", label: "社媒方图 1080×1080", width: 1080, height: 1080, format: "jpg", quality: 92 }, + { id: "portrait-1080x1440", label: "小红书竖图 1080×1440", width: 1080, height: 1440, format: "jpg", quality: 92 }, + { id: "transparent-png", label: "透明 PNG 1600×1600", width: 1600, height: 1600, format: "png", transparent: true }, +]; + +export interface CutoutReport { + /** 原图边缘中接近背景色的比例;低说明背景复杂,去背可能不准。 */ + borderUniform: number; + /** 被去掉的像素比例。 */ + removed: number; + hadAlpha: boolean; + touchesEdge: boolean; + warnings: string[]; +} + +export interface Cutout { + subject: Raster; + report: CutoutReport; +} + +const WORK_SIZE = 1800; + +function colorDistance(data: ArrayLike, i: number, r: number, g: number, b: number) { + const dr = data[i] - r; + const dg = data[i + 1] - g; + const db = data[i + 2] - b; + return Math.sqrt((2 * dr * dr + 4 * dg * dg + 3 * db * db) / 9); +} + +function median(values: number[]) { + values.sort((a, b) => a - b); + return values[values.length >> 1] ?? 0; +} + +/** 去背景并裁到主体。 */ +export function cutout(source: Raster, settings: Settings): Cutout { + const image = fitWithin(source, WORK_SIZE); + const { width: w, height: h, data } = image; + const n = w * h; + const alpha = new Float32Array(n); + let transparent = 0; + for (let p = 0; p < n; p++) { + alpha[p] = data[p * 4 + 3] / 255; + if (alpha[p] < 0.98) transparent++; + } + const hadAlpha = transparent > n * 0.01; + const warnings: string[] = []; + let borderUniform = 1; + let removed = 0; + let bg: [number, number, number] = [255, 255, 255]; + + if (!hadAlpha && settings.removeBackground === "auto") { + // 1. 边缘取样估计背景色。 + const border: number[] = []; + const band = Math.max(1, Math.round(Math.min(w, h) * 0.004)); + for (let y = 0; y < h; y++) + for (let x = 0; x < w; x++) if (x < band || y < band || x >= w - band || y >= h - band) border.push(y * w + x); + bg = [0, 1, 2].map((c) => median(border.map((p) => data[p * 4 + c]))) as [number, number, number]; + const tol = Math.max(1, Math.min(100, settings.tolerance)); + const globalTol = tol * 2.2; + const localTol = 4 + tol * 0.35; + borderUniform = border.filter((p) => colorDistance(data, p * 4, ...bg) < globalTol).length / border.length; + + // 2. 从边缘开始洪水填充:与相邻背景像素接近、且与背景色不太远。 + const isBg = new Uint8Array(n); + const queue = new Int32Array(n); + let head = 0; + let tail = 0; + for (const p of border) + if (!isBg[p] && colorDistance(data, p * 4, ...bg) < globalTol) { + isBg[p] = 1; + queue[tail++] = p; + } + while (head < tail) { + const p = queue[head++]; + const x = p % w; + const y = (p - x) / w; + const i = p * 4; + const neighbors = [x > 0 ? p - 1 : -1, x < w - 1 ? p + 1 : -1, y > 0 ? p - w : -1, y < h - 1 ? p + w : -1]; + for (const q of neighbors) { + if (q < 0 || isBg[q]) continue; + const j = q * 4; + if (colorDistance(data, j, data[i], data[i + 1], data[i + 2]) < localTol && colorDistance(data, j, ...bg) < globalTol * 1.3) { + isBg[q] = 1; + queue[tail++] = q; + } + } + } + removed = tail / n; + + // 3. 去掉零碎小块:只保留面积不小于最大块 2% 的前景连通区域。 + const label = new Int32Array(n).fill(-1); + const sizes: number[] = []; + for (let p = 0; p < n; p++) { + if (isBg[p] || label[p] >= 0) continue; + const id = sizes.length; + let size = 0; + head = tail = 0; + queue[tail++] = p; + label[p] = id; + while (head < tail) { + const q = queue[head++]; + size++; + const x = q % w; + const neighbors = [x > 0 ? q - 1 : -1, x < w - 1 ? q + 1 : -1, q >= w ? q - w : -1, q < n - w ? q + w : -1]; + for (const r of neighbors) + if (r >= 0 && !isBg[r] && label[r] < 0) { + label[r] = id; + queue[tail++] = r; + } + } + sizes.push(size); + } + const largest = Math.max(0, ...sizes); + for (let p = 0; p < n; p++) alpha[p] = !isBg[p] && sizes[label[p]] >= largest * 0.02 ? 1 : 0; + + // 4. 边缘柔化 + 去除背景色溢色。 + const soft = blurChannel(alpha, w, h, 1, 2); + for (let p = 0; p < n; p++) { + const a = Math.min(1, Math.max(0, (soft[p] - 0.3) / 0.6)); + alpha[p] = Math.min(alpha[p] > 0 ? 1 : a, a); + } + if (borderUniform < 0.6) warnings.push("background_not_uniform"); + if (removed < 0.05) warnings.push("little_background_removed"); + } + + // 5. 主体包围盒。 + let minX = w, minY = h, maxX = -1, maxY = -1; + for (let y = 0; y < h; y++) + for (let x = 0; x < w; x++) + if (alpha[y * w + x] > 0.05) { + if (x < minX) minX = x; + if (x > maxX) maxX = x; + if (y < minY) minY = y; + if (y > maxY) maxY = y; + } + if (maxX < 0) { + warnings.push("empty_subject"); + minX = minY = 0; + maxX = w - 1; + maxY = h - 1; + alpha.fill(1); + } + const edges = [minX === 0, minY === 0, maxX === w - 1, maxY === h - 1].filter(Boolean).length; + const touchesEdge = settings.removeBackground === "auto" && edges >= 1 && !warnings.includes("empty_subject"); + if (touchesEdge && !hadAlpha) warnings.push("subject_touches_edge"); + const sw = maxX - minX + 1; + const sh = maxY - minY + 1; + const subject = createRaster(sw, sh); + for (let y = 0; y < sh; y++) + for (let x = 0; x < sw; x++) { + const p = (y + minY) * w + (x + minX); + const a = alpha[p]; + const o = (y * sw + x) * 4; + const i = p * 4; + if (a <= 0) continue; + for (let c = 0; c < 3; c++) { + // 半透明边缘:把混进来的背景色减掉。 + const value = !hadAlpha && a < 1 ? (data[i + c] - (1 - a) * bg[c]) / a : data[i + c]; + subject.data[o + c] = value; + } + subject.data[o + 3] = hadAlpha ? data[i + 3] : a * 255; + } + return { subject, report: { borderUniform: round(borderUniform), removed: round(removed), hadAlpha, touchesEdge, warnings } }; +} + +const round = (value: number) => Math.round(value * 1000) / 1000; + +/** 把主体按设置放到指定尺寸的画布上(含阴影与背景)。 */ +export function compose(subject: Raster, preset: { width: number; height: number; transparent?: boolean }, settings: Settings): Raster { + const { width: W, height: H } = preset; + const fill = Math.min(0.99, Math.max(0.2, settings.fill)); + const scale = Math.min((W * fill) / subject.width, (H * fill) / subject.height); + const sw = Math.max(1, Math.round(subject.width * scale)); + const sh = Math.max(1, Math.round(subject.height * scale)); + const scaled = resize(subject, sw, sh); + const x = Math.round((W - sw) / 2); + let y = settings.align === "bottom" ? Math.round(H - (H - H * fill) / 2 - sh) : Math.round((H - sh) / 2); + y += Math.round(settings.offsetY * H); + + const canvas = preset.transparent ? createRaster(W, H) : createRaster(W, H, [...parseColor(settings.background), 255]); + const opacity = Math.min(1, Math.max(0, settings.shadowOpacity)); + if (settings.shadow !== "none" && opacity > 0) { + const shadow = new Float32Array(W * H); + if (settings.shadow === "ground") { + // 地面椭圆柔影:位于主体底部。 + const cx = x + sw / 2; + const cy = y + sh - Math.max(1, sh * 0.01); + const rx = sw * 0.46; + const ry = Math.max(3, sw * 0.05); + for (let py = Math.max(0, Math.floor(cy - ry * 3)); py < Math.min(H, Math.ceil(cy + ry * 3)); py++) + for (let px = Math.max(0, Math.floor(cx - rx * 1.6)); px < Math.min(W, Math.ceil(cx + rx * 1.6)); px++) { + const d = ((px - cx) / rx) ** 2 + ((py - cy) / ry) ** 2; + shadow[py * W + px] = Math.exp(-d * 1.6); + } + } else { + // 投影:主体轮廓向下偏移并模糊。 + const dy = Math.round(sh * 0.025); + for (let py = 0; py < sh; py++) + for (let px = 0; px < sw; px++) { + const ty = y + py + dy; + const tx = x + px; + if (tx >= 0 && tx < W && ty >= 0 && ty < H) shadow[ty * W + tx] = scaled.data[(py * sw + px) * 4 + 3] / 255; + } + } + const blurred = settings.shadow === "drop" ? blurChannel(shadow, W, H, Math.max(2, Math.round(Math.min(W, H) * 0.012))) : shadow; + const layer = createRaster(W, H); + for (let p = 0; p < W * H; p++) layer.data[p * 4 + 3] = Math.min(1, blurred[p]) * opacity * 255; + drawOver(canvas, layer, 0, 0); + } + drawOver(canvas, scaled, x, y); + return canvas; +} + +export function mergeSettings(base: Settings, overrides?: Partial): Settings { + const merged = { ...base, ...overrides } as Settings; + merged.tolerance = clamp(Number(merged.tolerance) || DEFAULT_SETTINGS.tolerance, 1, 100); + merged.fill = clamp(Number(merged.fill) || DEFAULT_SETTINGS.fill, 0.2, 0.99); + merged.offsetY = clamp(Number(merged.offsetY) || 0, -0.4, 0.4); + merged.shadowOpacity = clamp(Number(merged.shadowOpacity ?? DEFAULT_SETTINGS.shadowOpacity), 0, 1); + if (!["auto", "off"].includes(merged.removeBackground)) merged.removeBackground = "auto"; + if (!["none", "ground", "drop"].includes(merged.shadow)) merged.shadow = "ground"; + if (!["center", "bottom"].includes(merged.align)) merged.align = "center"; + return merged; +} + +const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value)); diff --git a/ui-plugins/product-photo-studio/test/_mkclient.ts b/ui-plugins/product-photo-studio/test/_mkclient.ts new file mode 100644 index 00000000..ab96ba54 --- /dev/null +++ b/ui-plugins/product-photo-studio/test/_mkclient.ts @@ -0,0 +1,18 @@ +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { createServer } from "../src/server.ts"; + +export async function mkclient(prefix: string) { + const root = mkdtempSync(join(tmpdir(), prefix)); + const server = createServer({ workspaceRoot: root, assetRoot: join(import.meta.dirname, "../dist") } as any); + const [a, b] = InMemoryTransport.createLinkedPair(); + await server.connect(a); + const client = new Client({ name: "t", version: "1" }); + await client.connect(b); + const call = async (name: string, args: Record) => (await client.callTool({ name, arguments: args })) as any; + const text = (r: any) => (r.content ?? []).map((c: any) => c.text ?? "").join(" "); + return { root, call, text }; +} diff --git a/ui-plugins/product-photo-studio/test/findings-fixes.test.ts b/ui-plugins/product-photo-studio/test/findings-fixes.test.ts new file mode 100644 index 00000000..0b1c2e88 --- /dev/null +++ b/ui-plugins/product-photo-studio/test/findings-fixes.test.ts @@ -0,0 +1,16 @@ +import { writeFileSync, copyFileSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { mkclient } from "./_mkclient.ts"; + +describe("TEST-FINDINGS #9: project_save warns about bad photos", () => { + it("lists empty and fake photos, and nothing for a real JPG", async () => { + const { root, call, text } = await mkclient("pps-"); + writeFileSync(join(root, "空.jpg"), ""); + writeFileSync(join(root, "假.png"), "hello"); + copyFileSync(join(import.meta.dirname, "fixtures/perfume.jpg"), join(root, "香水 图.jpg")); + const r = await call("project_save", { path: "批次", project: { images: [{ path: "空.jpg" }, { path: "假.png" }, { path: "香水 图.jpg" }] } }); + expect(r.isError, text(r)).toBeFalsy(); + expect(r.structuredContent.warnings).toEqual(["Photo 空.jpg is empty (0 bytes)", "Photo 假.png does not look like a .png file"]); + }); +}); diff --git a/ui-plugins/product-photo-studio/test/fixtures.ts b/ui-plugins/product-photo-studio/test/fixtures.ts new file mode 100644 index 00000000..9fe93a63 --- /dev/null +++ b/ui-plugins/product-photo-studio/test/fixtures.ts @@ -0,0 +1,28 @@ +import { createRaster, encodeJpeg, encodePng } from "../src/kit/raster.ts"; + +/** 灰色渐变背景上的一个红色“商品”(圆角矩形 + 白色标签),偏左上放置。 */ +export function gradientProduct(): Buffer { + const w = 900, h = 700; + const image = createRaster(w, h); + for (let y = 0; y < h; y++) + for (let x = 0; x < w; x++) { + const i = (y * w + x) * 4; + const g = 235 - Math.round((y / h) * 25); + image.data.set([g, g, g + 2, 255], i); + const inBody = x > 150 && x < 450 && y > 120 && y < 560 && !((x < 180 || x > 420) && (y < 150 || y > 530)); + if (inBody) { + const label = x > 220 && x < 380 && y > 280 && y < 400; + image.data.set(label ? [250, 250, 250, 255] : [200, 30, 40, 255], i); + } + } + return encodeJpeg(image, 92); +} + +/** 已抠好的透明 PNG:一个蓝色圆。 */ +export function cutoutPng(): Buffer { + const w = 500, h = 400; + const image = createRaster(w, h); + for (let y = 0; y < h; y++) + for (let x = 0; x < w; x++) if ((x - 300) ** 2 + (y - 200) ** 2 < 120 ** 2) image.data.set([30, 80, 200, 255], (y * w + x) * 4); + return encodePng(image); +} diff --git a/ui-plugins/product-photo-studio/test/fixtures/SOURCES.md b/ui-plugins/product-photo-studio/test/fixtures/SOURCES.md new file mode 100644 index 00000000..8aa7fb2f --- /dev/null +++ b/ui-plugins/product-photo-studio/test/fixtures/SOURCES.md @@ -0,0 +1,4 @@ +Test photos (not shipped in the plugin package): + +- `headphones-cc0.jpg` — "Headphones on white background", Wikimedia Commons, CC0. https://commons.wikimedia.org/wiki/File:Headphones_on_white_background.jpg +- `perfume.jpg` — "CHANEL No5 parfum", Wikimedia Commons, public domain. https://commons.wikimedia.org/wiki/File:CHANEL_No5_parfum.jpg diff --git a/ui-plugins/product-photo-studio/test/fixtures/headphones-cc0.jpg b/ui-plugins/product-photo-studio/test/fixtures/headphones-cc0.jpg new file mode 100644 index 00000000..fa6b8f88 Binary files /dev/null and b/ui-plugins/product-photo-studio/test/fixtures/headphones-cc0.jpg differ diff --git a/ui-plugins/product-photo-studio/test/fixtures/perfume.jpg b/ui-plugins/product-photo-studio/test/fixtures/perfume.jpg new file mode 100644 index 00000000..e03062f6 Binary files /dev/null and b/ui-plugins/product-photo-studio/test/fixtures/perfume.jpg differ diff --git a/ui-plugins/product-photo-studio/test/tools.test.ts b/ui-plugins/product-photo-studio/test/tools.test.ts new file mode 100644 index 00000000..bc51422d --- /dev/null +++ b/ui-plugins/product-photo-studio/test/tools.test.ts @@ -0,0 +1,111 @@ +import { mkdtemp, readFile, writeFile, readdir, mkdir, copyFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { beforeAll, describe, expect, it } from "vitest"; +import { decodeImage } from "../src/kit/raster.ts"; +import { createServer } from "../src/server.ts"; +import { cutoutPng, gradientProduct } from "./fixtures.ts"; + +let workspace: string; +let client: Client; +const call = async (name: string, args: Record) => (await client.callTool({ name, arguments: args })) as any; + +beforeAll(async () => { + workspace = await mkdtemp(join(tmpdir(), "photostudio-")); + await mkdir(join(workspace, "photos")); + await writeFile(join(workspace, "photos/red-bottle.jpg"), gradientProduct()); + await writeFile(join(workspace, "photos/blue-ball.png"), cutoutPng()); + for (const f of ["headphones-cc0.jpg", "perfume.jpg"]) await copyFile(join(import.meta.dirname, "fixtures", f), join(workspace, "photos", f)); + const server = createServer({ workspaceRoot: workspace, assetRoot: join(import.meta.dirname, "../dist") }); + const [a, b] = InMemoryTransport.createLinkedPair(); + client = new Client({ name: "test", version: "1" }); + await Promise.all([server.connect(a), client.connect(b)]); +}); + +function alphaBox(png: { width: number; height: number; data: ArrayLike }) { + let minX = png.width, minY = png.height, maxX = -1, maxY = -1; + for (let y = 0; y < png.height; y++) + for (let x = 0; x < png.width; x++) + if (png.data[(y * png.width + x) * 4 + 3] > 128) { + minX = Math.min(minX, x); maxX = Math.max(maxX, x); minY = Math.min(minY, y); maxY = Math.max(maxY, y); + } + return { w: maxX - minX + 1, h: maxY - minY + 1, cx: (minX + maxX) / 2, cy: (minY + maxY) / 2 }; +} + +describe("product-photo-studio", () => { + it("opens a folder and reports each photo", async () => { + const result = await call("photos_open", { folder: "photos" }); + expect(result.isError).toBeFalsy(); + const items = result.structuredContent.items; + expect(items.length).toBe(4); + const red = items.find((i: any) => i.path.endsWith("red-bottle.jpg")); + expect(red.report.warnings).toEqual([]); + expect(red.report.removed).toBeGreaterThan(0.7); + // 主体 300×440 左右(去背后裁到商品本身)。 + expect(Math.abs(red.subject.width - 299)).toBeLessThan(6); + expect(Math.abs(red.subject.height - 439)).toBeLessThan(6); + const ball = items.find((i: any) => i.path.endsWith("blue-ball.png")); + expect(ball.report.hadAlpha).toBe(true); + }); + + it("exports white and transparent sizes with consistent product size", async () => { + const project = { + images: [{ path: "photos/red-bottle.jpg" }, { path: "photos/blue-ball.png" }, { path: "photos/headphones-cc0.jpg" }, { path: "photos/perfume.jpg", overrides: { fill: 0.7 } }], + settings: { fill: 0.8, shadow: "ground" }, + presets: ["white-800", "transparent-png", "custom-1200x900"], + customPresets: [{ id: "custom-1200x900", width: 1200, height: 900, format: "jpg" }], + outputDir: "out", + }; + const saved = await call("project_save", { path: "batch.photostudio.json", project }); + expect(saved.isError).toBeFalsy(); + const result = await call("photos_export", { project: "batch.photostudio.json" }); + expect(result.isError).toBeFalsy(); + expect(result.structuredContent.files.length).toBe(12); + expect((await readdir(join(workspace, "out/white-800"))).sort()).toEqual(["blue-ball.jpg", "headphones-cc0.jpg", "perfume.jpg", "red-bottle.jpg"]); + + // 白底图:四角纯白。 + const white = decodeImage(await readFile(join(workspace, "out/white-800/red-bottle.jpg"))); + expect([white.width, white.height]).toEqual([800, 800]); + for (const [x, y] of [[2, 2], [797, 2], [2, 797], [797, 797]]) { + const i = (y * 800 + x) * 4; + expect(Math.min(white.data[i], white.data[i + 1], white.data[i + 2])).toBeGreaterThanOrEqual(250); + } + // 透明图:主体长边 = 80% 画布,居中,背景透明。 + for (const name of ["red-bottle", "blue-ball"]) { + const png = decodeImage(await readFile(join(workspace, `out/transparent-png/${name}.png`))); + expect(png.data[3]).toBe(0); + const box = alphaBox(png); + expect(Math.abs(Math.max(box.w, box.h) / 1600 - 0.8)).toBeLessThan(0.02); + expect(Math.abs(box.cx - 800)).toBeLessThan(10); + expect(Math.abs(box.cy - 800)).toBeLessThan(10); + } + // 单张覆盖设置:perfume 占 70%。 + const perfume = alphaBox(decodeImage(await readFile(join(workspace, "out/transparent-png/perfume.png")))); + expect(Math.abs(perfume.h / 1600 - 0.7)).toBeLessThan(0.02); + const custom = decodeImage(await readFile(join(workspace, "out/custom-1200x900/headphones-cc0.jpg"))); + expect([custom.width, custom.height]).toEqual([1200, 900]); + }); + + it("renders previews and rejects bad input", async () => { + const preview = await call("photos_preview", { project: { images: ["photos/red-bottle.jpg"], presets: ["white-800"] }, index: 0, size: 200 }); + expect(preview.isError).toBeFalsy(); + expect(decodeImage(Buffer.from(preview.structuredContent.image, "base64")).width).toBe(200); + expect((await call("photos_open", { paths: ["../outside.jpg"] })).content[0].text).toMatch(/outside_workspace/); + expect((await call("photos_export", { project: { images: ["photos/red-bottle.jpg"], presets: ["nope"] } })).content[0].text).toMatch(/no_preset/); + }); + + it("reports corrupt or empty PNG/JPEG as invalid files, not a WebP/HEIC hint", async () => { + await writeFile(join(workspace, "photos/empty.png"), Buffer.alloc(0)); + await writeFile(join(workspace, "photos/not-an-image.jpg"), "this is not a jpeg"); + expect(() => decodeImage(Buffer.alloc(0), "empty.png")).toThrow(/not a valid PNG or JPEG/); + expect(() => decodeImage(Buffer.from("this is not a jpeg"), "not-an-image.jpg")).toThrow(/not a valid PNG or JPEG/); + expect(() => decodeImage(Buffer.from("RIFF....WEBP"), "shot.webp")).toThrow(/convert WebP\/HEIC first/); + const result = await call("photos_open", { paths: ["photos/empty.png", "photos/not-an-image.jpg"] }); + const errors = result.structuredContent.items.map((i: any) => `${i.path}: ${i.error}`); + expect(errors.join("\n")).toMatch(/empty\.png: not a valid PNG or JPEG/); + expect(errors.join("\n")).toMatch(/not-an-image\.jpg: not a valid PNG or JPEG/); + expect(errors.join("\n")).not.toMatch(/WebP\/HEIC/); + }); +}); diff --git a/ui-plugins/product-photo-studio/test/workspace-links.test.ts b/ui-plugins/product-photo-studio/test/workspace-links.test.ts new file mode 100644 index 00000000..f3dae538 --- /dev/null +++ b/ui-plugins/product-photo-studio/test/workspace-links.test.ts @@ -0,0 +1,43 @@ +import { existsSync, mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { Workspace } from "../src/kit/workspace.ts"; + +// 回归测试:工作区里的符号链接不能把读写带到工作区之外(TEST-FINDINGS #2) +describe("workspace symlink containment", () => { + const base = mkdtempSync(join(tmpdir(), "wslinks-")); + const root = join(base, "项目 ws"), outside = join(base, "outside"); + mkdirSync(join(root, "inner"), { recursive: true }); + mkdirSync(outside, { recursive: true }); + writeFileSync(join(outside, "secret.txt"), "SECRET"); + writeFileSync(join(root, "inner", "ok.txt"), "ok"); + symlinkSync(outside, join(root, "out-link")); + symlinkSync(join(outside, "secret.txt"), join(root, "secret-link.txt")); + symlinkSync(join(outside, "new-file.txt"), join(root, "dangling.txt")); + symlinkSync(join(root, "inner"), join(root, "inner-link")); + symlinkSync(root, join(base, "root-link")); + const ws = new Workspace(root); + + it("refuses to read through a link to outside (directory and file links)", async () => { + await expect(ws.read("out-link/secret.txt")).rejects.toMatchObject({ code: "outside_workspace" }); + await expect(ws.read("secret-link.txt")).rejects.toMatchObject({ code: "outside_workspace" }); + expect(await ws.exists("out-link/secret.txt")).toBe(false); + }); + it("refuses to write through a link, including to targets that do not exist yet", async () => { + await expect(ws.write("out-link/a/b/new.txt", "x")).rejects.toMatchObject({ code: "outside_workspace" }); + await expect(ws.write("dangling.txt", "x")).rejects.toMatchObject({ code: "outside_workspace" }); + expect(existsSync(join(outside, "a"))).toBe(false); + expect(existsSync(join(outside, "new-file.txt"))).toBe(false); + }); + it("still allows normal paths, new nested files and links that stay inside", async () => { + expect(await ws.write("新 目录/子/文件.txt", "中文")).toBe("新 目录/子/文件.txt"); + expect((await ws.read("inner-link/ok.txt")).toString()).toBe("ok"); + await expect(ws.read("../outside/secret.txt")).rejects.toMatchObject({ code: "outside_workspace" }); + }); + it("works when the workspace root itself is reached through a link", async () => { + const viaLink = new Workspace(join(base, "root-link")); + expect((await viaLink.read("inner/ok.txt")).toString()).toBe("ok"); + await expect(viaLink.read("out-link/secret.txt")).rejects.toMatchObject({ code: "outside_workspace" }); + }); +}); diff --git a/ui-plugins/product-photo-studio/tsconfig.json b/ui-plugins/product-photo-studio/tsconfig.json new file mode 100644 index 00000000..39f7ab60 --- /dev/null +++ b/ui-plugins/product-photo-studio/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/product-photo-studio/ui/env.d.ts b/ui-plugins/product-photo-studio/ui/env.d.ts new file mode 100644 index 00000000..4210a464 --- /dev/null +++ b/ui-plugins/product-photo-studio/ui/env.d.ts @@ -0,0 +1,4 @@ +declare module "*.css" { + const text: string; + export default text; +} diff --git a/ui-plugins/product-photo-studio/ui/kit.css b/ui-plugins/product-photo-studio/ui/kit.css new file mode 100644 index 00000000..398bc83a --- /dev/null +++ b/ui-plugins/product-photo-studio/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/product-photo-studio/ui/kit.ts b/ui-plugins/product-photo-studio/ui/kit.ts new file mode 100644 index 00000000..fe0bce0d --- /dev/null +++ b/ui-plugins/product-photo-studio/ui/kit.ts @@ -0,0 +1,128 @@ +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 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"; +} diff --git a/ui-plugins/product-photo-studio/ui/main.ts b/ui-plugins/product-photo-studio/ui/main.ts new file mode 100644 index 00000000..9d3ce221 --- /dev/null +++ b/ui-plugins/product-photo-studio/ui/main.ts @@ -0,0 +1,292 @@ +import css from "./kit.css"; +import panelCss from "./panel.css"; +import { applyTheme, call, h, initHost, locale, onHostContext, onToolResult, sendMessage, toast } from "./kit.ts"; + +const style = document.createElement("style"); +style.textContent = css + panelCss; +document.head.append(style); + +interface Settings { removeBackground: "auto" | "off"; tolerance: number; fill: number; offsetY: number; align: "center" | "bottom"; shadow: "none" | "ground" | "drop"; shadowOpacity: number; background: string } +interface Preset { id: string; label: string; width: number; height: number; format: "jpg" | "png"; transparent?: boolean } +interface Project { version: 1; images: { path: string; overrides?: Partial }[]; settings: Settings; presets: string[]; customPresets?: Preset[]; outputDir: string } +interface Report { borderUniform: number; removed: number; hadAlpha: boolean; touchesEdge: boolean; warnings: string[] } + +const T = (cn: string, en: string) => (locale() === "zh" ? cn : en); +const WARN = (w: string) => + (({ + background_not_uniform: T("背景不是纯色,去背可能不准", "Busy background — removal may be inaccurate"), + little_background_removed: T("几乎没去掉背景,可调高容差", "Little background removed — raise tolerance"), + subject_touches_edge: T("商品贴到照片边缘,原图可能被裁切", "Product touches the photo edge"), + empty_subject: T("去背后什么都没剩,请调低容差", "Nothing left — lower tolerance"), + }) as Record)[w] ?? w; + +const state: { + project?: Project; + projectPath: string; + presets: Preset[]; + previews: Map; + selected: number; + previewPreset?: string; + result?: { files: string[]; problems: string[]; outputDir: string }; +} = { projectPath: "product-photos.photostudio.json", presets: [], previews: new Map(), selected: 0 }; + +const root = document.getElementById("root")!; + +async function busy(work: () => Promise): Promise { + root.classList.add("busy"); + try { + return await work(); + } catch (error) { + toast(error instanceof Error ? error.message : String(error), "error"); + return undefined; + } finally { + root.classList.remove("busy"); + } +} + +function allPresets(): Preset[] { + return [...state.presets, ...(state.project?.customPresets ?? [])]; +} + +function load(value: Record) { + state.project = value.project as Project; + state.presets = (value.presets as Preset[]) ?? state.presets; + if (typeof value.projectPath === "string") state.projectPath = value.projectPath; + state.previews.clear(); + state.selected = 0; + state.result = undefined; + state.previewPreset = state.project.presets[0]; + render(); + void refreshAll(); +} + +// ---------------------------------------------------------------- 预览 + +let generation = 0; +async function refreshAll() { + const token = ++generation; + const project = state.project; + if (!project) return; + for (let index = 0; index < project.images.length; index++) { + if (token !== generation) return; + await refreshOne(index, 260); + } + if (token === generation) await refreshOne(state.selected, 560, true); +} + +async function refreshOne(index: number, size: number, large = false) { + const project = state.project; + if (!project?.images[index]) return; + try { + const result = await call<{ image: string; mime: string; report: Report }>("photos_preview", { project, index, preset: state.previewPreset, size }); + const src = `data:${result.mime};base64,${result.image}`; + if (large) { + const img = document.getElementById("large") as HTMLImageElement | null; + if (img) img.src = src; + } else { + state.previews.set(index, { src, report: result.report }); + const card = document.querySelector(`.thumb[data-index="${index}"]`); + if (card) card.replaceWith(thumb(index)); + } + if (index === state.selected) renderWarnings(result.report); + } catch (error) { + if (index === state.selected) toast(error instanceof Error ? error.message : String(error), "error"); + } +} + +function renderWarnings(report: Report) { + const box = document.getElementById("warnings"); + if (!box) return; + box.replaceChildren( + ...(report.warnings.length ? report.warnings.map((w) => h("div", { class: "badge bad" }, WARN(w))) : [h("span", { class: "badge ok" }, T("看起来没问题", "Looks clean"))]), + h("span", { class: "muted small" }, T(` 去掉背景 ${Math.round(report.removed * 100)}%`, ` ${Math.round(report.removed * 100)}% background removed`)), + ); +} + +let debounce: ReturnType | undefined; +function changed(scope: "all" | "one") { + clearTimeout(debounce); + debounce = setTimeout(() => { + if (scope === "all") void refreshAll(); + else { + void refreshOne(state.selected, 260); + void refreshOne(state.selected, 560, true); + } + }, 250); +} + +// ---------------------------------------------------------------- 界面 + +function render() { + applyTheme(); + root.replaceChildren(state.project ? editor() : picker()); +} + +function picker() { + const list = h("div", { class: "pick-list" }, h("div", { class: "muted" }, T("正在读取工作区图片…", "Loading workspace images…"))); + const chosen = new Set(); + void call<{ files: string[] }>("workspace_images").then(({ files }) => { + list.replaceChildren( + ...(files.length + ? files.map((file) => h("label", {}, h("input", { type: "checkbox", onchange: (e: Event) => ((e.target as HTMLInputElement).checked ? chosen.add(file) : chosen.delete(file)) }), file)) + : [h("div", { class: "empty" }, T("工作区里没有 JPG/PNG 图片", "No JPG/PNG images in the workspace"))]), + ); + }); + return h("div", {}, + h("h1", {}, T("电商商品图助手", "Product Photo Studio")), + h("p", { class: "muted" }, T("批量去掉纯色背景、统一商品大小和位置、加阴影,导出白底图、透明图和各平台尺寸;不满意的图可以单独调整。", "Batch-remove plain backgrounds, normalise product size and position, add shadows, and export white-background, transparent and marketplace sizes — tweak any photo on its own.")), + h("div", { class: "card" }, list, h("div", { class: "row" }, h("button", { class: "primary", onclick: () => chosen.size && open({ paths: [...chosen] }) }, T("打开所选图片", "Open selected")))), + ); +} + +async function open(args: Record) { + const result = await busy(() => call>("photos_open", args, 600_000)); + if (result) load(result); +} + +function slider(label: string, value: number, min: number, max: number, step: number, format: (v: number) => string, onInput: (v: number) => void) { + const out = h("span", { class: "value" }, format(value)); + return h("label", { class: "slider" }, h("span", { class: "lbl" }, label), + h("input", { type: "range", min, max, step, value, oninput: (e: Event) => { const v = Number((e.target as HTMLInputElement).value); out.textContent = format(v); onInput(v); } }), out); +} + +function settingsControls(get: () => Settings, set: (patch: Partial) => void) { + const s = get(); + return h("div", { class: "controls" }, + h("label", {}, h("input", { type: "checkbox", checked: s.removeBackground === "auto", onchange: (e: Event) => set({ removeBackground: (e.target as HTMLInputElement).checked ? "auto" : "off" }) }), T("去背景", "Remove background")), + slider(T("容差", "Tolerance"), s.tolerance, 1, 100, 1, (v) => String(v), (v) => set({ tolerance: v })), + slider(T("主体占比", "Product size"), s.fill, 0.4, 0.98, 0.01, (v) => `${Math.round(v * 100)}%`, (v) => set({ fill: v })), + slider(T("上下位置", "Vertical offset"), s.offsetY, -0.3, 0.3, 0.01, (v) => `${Math.round(v * 100)}%`, (v) => set({ offsetY: v })), + h("label", {}, T("对齐", "Align"), h("select", { onchange: (e: Event) => set({ align: (e.target as HTMLSelectElement).value as Settings["align"] }) }, + h("option", { value: "center", selected: s.align === "center" }, T("居中", "Center")), h("option", { value: "bottom", selected: s.align === "bottom" }, T("底部对齐", "Bottom")))), + h("label", {}, T("阴影", "Shadow"), h("select", { onchange: (e: Event) => set({ shadow: (e.target as HTMLSelectElement).value as Settings["shadow"] }) }, + h("option", { value: "none", selected: s.shadow === "none" }, T("无", "None")), h("option", { value: "ground", selected: s.shadow === "ground" }, T("地面柔影", "Ground")), h("option", { value: "drop", selected: s.shadow === "drop" }, T("投影", "Drop")))), + slider(T("阴影浓度", "Shadow strength"), s.shadowOpacity, 0, 1, 0.05, (v) => `${Math.round(v * 100)}%`, (v) => set({ shadowOpacity: v })), + h("label", {}, T("背景色", "Background"), h("input", { type: "color", value: s.background, oninput: (e: Event) => set({ background: (e.target as HTMLInputElement).value }) })), + ); +} + +function thumb(index: number) { + const image = state.project!.images[index]; + const preview = state.previews.get(index); + const card = h("div", { class: `thumb ${index === state.selected ? "selected" : ""} ${preview?.report.warnings.length ? "warn" : ""}`, onclick: () => selectPhoto(index) }, + preview ? h("img", { src: preview.src, alt: image.path }) : h("div", { class: "placeholder" }, "…"), + h("div", { class: "cap" }, image.overrides && Object.keys(image.overrides).length ? "✎ " : "", image.path.split("/").pop()), + preview?.report.warnings.length ? h("span", { class: "flag", title: preview.report.warnings.map(WARN).join("\n") }, "!") : null, + ); + card.dataset.index = String(index); + return card; +} + +function selectPhoto(index: number) { + state.selected = index; + render(); + void refreshOne(index, 560, true); +} + +function editor() { + const project = state.project!; + const image = project.images[state.selected]; + const presetBoxes = allPresets().map((preset) => + h("label", { class: "preset" }, h("input", { type: "checkbox", checked: project.presets.includes(preset.id), onchange: (e: Event) => { + const on = (e.target as HTMLInputElement).checked; + project.presets = on ? [...project.presets, preset.id] : project.presets.filter((id) => id !== preset.id); + if (!project.presets.includes(state.previewPreset ?? "")) state.previewPreset = project.presets[0]; + render(); + changed("all"); + } }), `${preset.label}`, h("span", { class: "muted small" }, ` ${preset.format.toUpperCase()}`)), + ); + const customW = h("input", { type: "number", min: 16, max: 6000, placeholder: "W", class: "num" }); + const customH = h("input", { type: "number", min: 16, max: 6000, placeholder: "H", class: "num" }); + const customPng = h("input", { type: "checkbox" }); + + const overrides = () => ({ ...project.settings, ...image?.overrides }); + const setOverride = (patch: Partial) => { + image.overrides = { ...image.overrides, ...patch }; + changed("one"); + }; + + return h("div", {}, + h("div", { class: "toolbar" }, + h("strong", {}, T(`${project.images.length} 张商品图`, `${project.images.length} photos`)), + h("span", { class: "spacer" }), + h("label", {}, T("输出到", "Output"), h("input", { value: project.outputDir, size: 18, oninput: (e: Event) => (project.outputDir = (e.target as HTMLInputElement).value) })), + h("input", { value: state.projectPath, size: 26, title: T("项目文件", "Project file"), oninput: (e: Event) => (state.projectPath = (e.target as HTMLInputElement).value) }), + h("button", { onclick: save }, T("保存设置", "Save settings")), + h("button", { class: "primary", onclick: exportAll }, T("全部导出", "Export all")), + ), + h("div", { class: "layout" }, + h("div", { class: "side" }, + h("div", { class: "card" }, h("h2", {}, T("全部图片的设置", "Settings for all photos")), settingsControls(() => project.settings, (patch) => { Object.assign(project.settings, patch); changed("all"); })), + h("div", { class: "card" }, h("h2", {}, T("输出尺寸", "Output sizes")), ...presetBoxes, + h("div", { class: "row" }, customW, "×", customH, h("label", {}, customPng, T("透明 PNG", "Transparent PNG")), + h("button", { onclick: () => { + const w = Number(customW.value), hgt = Number(customH.value); + if (!(w >= 16 && hgt >= 16)) return; + const id = `custom-${w}x${hgt}${customPng.checked ? "-png" : ""}`; + project.customPresets = [...(project.customPresets ?? []).filter((p) => p.id !== id), { id, label: `${w}×${hgt}`, width: w, height: hgt, format: customPng.checked ? "png" : "jpg", transparent: customPng.checked }]; + project.presets = [...new Set([...project.presets, id])]; + render(); + } }, T("添加尺寸", "Add size")))), + ), + h("div", { class: "main" }, + h("div", { class: "row" }, T("预览尺寸", "Preview size"), h("select", { onchange: (e: Event) => { state.previewPreset = (e.target as HTMLSelectElement).value; state.previews.clear(); render(); changed("all"); } }, + ...allPresets().filter((p) => project.presets.includes(p.id)).map((p) => h("option", { value: p.id, selected: p.id === state.previewPreset }, p.label)))), + h("div", { class: "grid" }, ...project.images.map((_, index) => thumb(index))), + image ? h("div", { class: "card detail" }, + h("div", { class: "detail-img" }, h("img", { id: "large", alt: image.path })), + h("div", {}, + h("h2", {}, image.path), + h("div", { id: "warnings", class: "row" }), + h("h2", {}, T("只调整这一张", "Adjust this photo only")), + settingsControls(overrides, setOverride), + h("div", { class: "row" }, + h("button", { onclick: () => { image.overrides = undefined; render(); changed("one"); } }, T("恢复全局设置", "Use global settings")), + h("button", { onclick: () => exportOne(state.selected) }, T("只导出这一张", "Export this photo")), + ), + ), + ) : null, + state.result ? h("div", { class: "card" }, + h("h2", {}, T(`已导出 ${state.result.files.length} 个文件到 ${state.result.outputDir}/`, `Exported ${state.result.files.length} files to ${state.result.outputDir}/`)), + ...state.result.problems.map((p) => h("div", { class: "muted small" }, p)), + state.result.problems.length ? h("button", { onclick: () => sendMessage(T(`导出的商品图里有 ${state.result!.problems.length} 张需要检查,请帮我看看这些图:${state.result!.problems.join(";")}`, `${state.result!.problems.length} exported photos need a look: ${state.result!.problems.join("; ")}`)) }, T("交给 Agent 看看", "Ask the agent")) : null, + ) : null, + ), + ), + ); +} + +async function save() { + const result = await busy(() => call<{ path: string }>("project_save", { path: state.projectPath, project: state.project })); + if (result) { + state.projectPath = result.path; + toast(T(`已保存 ${result.path}`, `Saved ${result.path}`)); + } +} + +async function exportAll() { + const result = await busy(() => call<{ files: string[]; problems: string[]; outputDir: string }>("photos_export", { project: state.project }, 900_000)); + if (result) { + state.result = result; + render(); + void refreshOne(state.selected, 560, true); + toast(T(`已导出 ${result.files.length} 个文件`, `Exported ${result.files.length} files`)); + } +} + +async function exportOne(index: number) { + const result = await busy(() => call<{ files: string[]; problems: string[]; outputDir: string }>("photos_export", { project: state.project, indices: [index] })); + if (result) toast(T(`已导出:${result.files.join("、")}`, `Exported: ${result.files.join(", ")}`)); +} + +onToolResult((value) => { + if (!value || value.error) return; + if (value.kind === "project") load(value); + else if (value.kind === "exported" && state.project) { + state.result = value as never; + render(); + } else if (value.kind === "saved" && state.project) state.projectPath = value.path as string; +}); +onHostContext(() => applyTheme()); +render(); +void initHost("product-photo-studio", "0.1.0").then(() => render()); diff --git a/ui-plugins/product-photo-studio/ui/panel.css b/ui-plugins/product-photo-studio/ui/panel.css new file mode 100644 index 00000000..f4e16143 --- /dev/null +++ b/ui-plugins/product-photo-studio/ui/panel.css @@ -0,0 +1,18 @@ +.toolbar { display:flex; gap:8px; align-items:center; flex-wrap:wrap; padding-bottom:8px; border-bottom:1px solid var(--line); margin-bottom:8px; } +.spacer { flex:1; } +.layout { display:grid; grid-template-columns: 280px minmax(0,1fr); gap: 10px; } +@media (max-width: 760px) { .layout { grid-template-columns: 1fr; } } +.controls { display:flex; flex-direction:column; gap:6px; } +.slider { display:grid; grid-template-columns: 76px 1fr 44px; gap:6px; } +.slider .value { text-align:right; color: var(--muted); font-variant-numeric: tabular-nums; } +.preset { display:flex; gap:6px; margin: 3px 0; } +.num { width: 64px; } +.grid { grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); } +.thumb .placeholder { aspect-ratio:1; display:flex; align-items:center; justify-content:center; color: var(--muted); } +.thumb.warn { border-color: #f59e0b; } +.thumb .flag { position:absolute; top:4px; right:4px; background:#f59e0b; color:#fff; border-radius:50%; width:18px; height:18px; text-align:center; font-weight:700; font-size:12px; line-height:18px; } +.detail { display:grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 12px; } +@media (max-width: 900px) { .detail { grid-template-columns: 1fr; } } +.detail-img img { width:100%; display:block; border:1px solid var(--line); border-radius:6px; background: repeating-conic-gradient(#ddd 0 25%, #fff 0 50%) 50% / 16px 16px; min-height: 120px; } +.pick-list { display:flex; flex-direction:column; gap:4px; max-height: 50vh; overflow:auto; } +.small { font-size: 11px; } diff --git a/ui-plugins/product-photo-studio/vitest.config.ts b/ui-plugins/product-photo-studio/vitest.config.ts new file mode 100644 index 00000000..27153a26 --- /dev/null +++ b/ui-plugins/product-photo-studio/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 } });