diff --git a/external_plugins/app-installer-builder/.zcode-plugin/plugin.json b/external_plugins/app-installer-builder/.zcode-plugin/plugin.json new file mode 100644 index 00000000..daedf41f --- /dev/null +++ b/external_plugins/app-installer-builder/.zcode-plugin/plugin.json @@ -0,0 +1,58 @@ +{ + "name": "app-installer-builder", + "version": "0.1.0", + "description": "Wrap an existing website or Node project as a desktop app with Electron and electron-builder: detects a static site (dist/ with index.html) or a Node server, generates desktop/ with the Electron shell (static sites served at app:// with SPA routes; Node servers started with Electron's own Node on a free port), electron-builder.yml for macOS dmg and Windows nsis (plus Linux AppImage), an icon and a README. Shows which targets this computer can build and runs the build with a live log. Signing is optional and only uses a certificate you provide; otherwise builds are unsigned and the README says so.", + "description_i18n": { + "en": "Wrap an existing website or Node project as a desktop app with Electron and electron-builder: detects a static site (dist/ with index.html) or a Node server, generates desktop/ with the Electron shell (static sites served at app:// with SPA routes; Node servers started with Electron's own Node on a free port), electron-builder.yml for macOS dmg and Windows nsis (plus Linux AppImage), an icon and a README. Shows which targets this computer can build and runs the build with a live log. Signing is optional and only uses a certificate you provide; otherwise builds are unsigned and the README says so.", + "zh-CN": "用 Electron + electron-builder 把现有网站或 Node 项目包装成桌面应用:自动识别静态网站(含 index.html 的 dist/)或 Node 服务,在项目里生成 desktop/ 目录——Electron 外壳(静态站点通过 app:// 加载并支持前端路由;Node 服务用 Electron 自带的 Node 在空闲端口启动)、面向 macOS dmg 和 Windows nsis(另含 Linux AppImage)的 electron-builder.yml、图标和说明。面板显示本机能打哪些安装包,并实时显示打包日志。签名可选,只使用你自己提供的证书;没有证书就不签名,并在说明里写明。" + }, + "author": { + "name": "Penova", + "url": "https://github.com/ppppp2005-p" + }, + "license": "MIT", + "keywords": [ + "electron", + "electron-builder", + "desktop app", + "installer", + "dmg", + "nsis", + "appimage", + "package", + "桌面应用", + "安装包", + "打包", + "网站转应用" + ], + "skills": "skills", + "mcpServers": { + "app-installer-builder": { + "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": "App Installer Builder" + }, + "icon": "package", + "server": "app-installer-builder", + "resourceUri": "ui://app-installer-builder/panel.html", + "availability": "session" + } + ] + } +} diff --git a/external_plugins/app-installer-builder/LICENSE b/external_plugins/app-installer-builder/LICENSE new file mode 100644 index 00000000..67e98093 --- /dev/null +++ b/external_plugins/app-installer-builder/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/app-installer-builder/README.md b/external_plugins/app-installer-builder/README.md new file mode 100644 index 00000000..cf744caf --- /dev/null +++ b/external_plugins/app-installer-builder/README.md @@ -0,0 +1,64 @@ +# App Installer Builder + +Wrap an existing **website or Node project** as a desktop app with **Electron + electron-builder**. The plugin detects the project, generates a `desktop/` folder next to it, shows which installers this computer can build, and runs the build with a live log. + +## Defaults (v0.1) + +- **Tooling**: electron-builder (MIT) packages an Electron shell. Both are installed into `desktop/` with `npm install` on the first build, which downloads Electron (about 150 MB). +- **Targets**: macOS **dmg** and Windows **nsis** by default. Linux AppImage and an unpacked "dir" build (for testing) are also available. + - dmg can only be built on macOS. + - nsis needs Windows, or Wine on macOS/Linux. + - The panel shows what this computer can build. The generated config can be copied to another computer, where you run the README command. +- **Signing**: optional, and **only with a certificate you provide**. + - macOS: the name of a keychain identity ("Developer ID Application: …"). + - Windows: a `.pfx` file path. The password is read from the `WIN_CSC_KEY_PASSWORD` environment variable and is never stored. + - Without a certificate the builds are **unsigned**, and the README explains what users will see (macOS right-click → Open; Windows SmartScreen → Run anyway). + - No Apple notarization. + +## Features + +- **Detect** (`app_scan`): + - Static site: a folder with `index.html` such as dist/, build/ or out/. + - Node server: the start script or entry calls `listen()`. The plugin also checks whether it reads `process.env.PORT`. + - Name, version and author from package.json, and square PNG icon candidates. +- **Generate** (`app_setup`) creates `desktop/` containing: + - `main.cjs`: + - Static sites are served at `app://local/`, so absolute `/assets/…` paths and client-side routes work (SPA fallback). + - Node servers are started with Electron's own Node (no Node install needed) on a free port. They get `APP_DATA_DIR` for data and log to `server.log`. + - Single instance, external links open in the browser, and sandboxed renderer. + - `package.json` with pinned electron and electron-builder. + - `electron-builder.yml`: appId, productName, dmg, nsis (assisted installer with shortcuts), AppImage, and the website or server copied as extra resources. + - `build/icon.png`: your PNG (≥512 px square) or a generated icon. + - `README.md` with build commands and the signing status. +- **Check** (`app_check`): config validation and a per-target "can build here" matrix. + - Validation covers reverse-DNS appId, semver version, web folder or entry present, icon size, fixed-port warning and certificate file present. +- **Build** (`app_build` / `app_status`): `npm install` the first time, then `electron-builder --publish never`. The log streams to the panel, and outputs in `desktop/release/` are listed. + +## Usage + +Ask the agent in ZCode Desktop: + +- "Turn this web app into a Mac and Windows desktop app" +- "Package my Node server as a desktop app" +- "Which installers can I build on this computer?" + +## Tools + +| Tool | Purpose | +|---|---| +| `app_scan` | Detect the project type, entry, port and icons | +| `app_setup` | Generate / update `desktop/` (shell, electron-builder.yml, icon, README) | +| `app_check` | Validate the config; which targets this computer can build | +| `app_build` | Run electron-builder for one target | +| `app_status` | Build progress and log | + +## Scope (v0.1) + +- No auto-update server, no app store submission, and no notarization (it needs an Apple account). +- Server-rendered Next/Nuxt apps are not supported; use a static export. Servers must start with `node `. +- For Node servers, the whole project folder, including `node_modules`, is packaged. + +## Privacy, network and files + +- No API keys and no accounts. The only network use is `npm install` in `desktop/` during the first build, which downloads Electron and electron-builder from npm and GitHub. +- Writes `/desktop/` and `.app-installer/state.json`. Certificate passwords are never written to disk. diff --git a/external_plugins/app-installer-builder/README_CN.md b/external_plugins/app-installer-builder/README_CN.md new file mode 100644 index 00000000..9ff8797b --- /dev/null +++ b/external_plugins/app-installer-builder/README_CN.md @@ -0,0 +1,64 @@ +# 应用安装包制作 + +用 **Electron + electron-builder** 把现有的**网站或 Node 项目**包装成桌面应用。插件会识别项目,在项目旁生成 `desktop/` 目录,显示本机能打哪些安装包,并带着实时日志完成打包。 + +## 默认设定(v0.1) + +- **工具**:electron-builder(MIT)打包 Electron 外壳。两者在第一次打包时通过 `npm install` 装进 `desktop/`,会下载 Electron(约 150 MB)。 +- **目标**:默认是 macOS **dmg** 和 Windows **nsis**;另外可选 Linux AppImage 和本机免安装目录(dir,测试用)。 + - dmg 只能在 macOS 上打。 + - nsis 需要 Windows,或者在 macOS/Linux 上装 Wine。 + - 面板会显示本机能打哪些目标。生成的配置可以拿到对应的电脑上,按 README 里的命令运行。 +- **签名**:可选,**只使用你自己提供的证书**。 + - macOS:填钥匙串里的证书名称(“Developer ID Application: …”)。 + - Windows:填 `.pfx` 证书文件路径。密码从环境变量 `WIN_CSC_KEY_PASSWORD` 读取,插件不保存。 + - 没有证书就**不签名**。README 会写明用户第一次打开时会看到什么(macOS:右键 → 打开;Windows:SmartScreen → 仍要运行)。 + - 不做 Apple 公证。 + +## 功能 + +- **识别项目**(`app_scan`): + - 静态网站:含 `index.html` 的目录,例如 dist/、build/、out/。 + - Node 服务:start 脚本或入口文件调用了 `listen()`。同时检查它是否读取 `process.env.PORT`。 + - 从 package.json 读取名称、版本和作者,并找出可用作图标的正方形 PNG。 +- **生成配置**(`app_setup`):在项目里生成 `desktop/`,包括: + - `main.cjs`: + - 静态网站通过 `app://local/` 加载,绝对路径 `/assets/…` 和前端路由都能用(找不到的路径回退到 index.html)。 + - Node 服务用 Electron 自带的 Node 在空闲端口启动,不需要另装 Node;数据目录通过 `APP_DATA_DIR` 传入,日志写到 `server.log`。 + - 只允许运行一个实例;外部链接用浏览器打开;渲染进程开启沙箱。 + - `package.json`:固定 electron 和 electron-builder 的版本。 + - `electron-builder.yml`:appId、产品名、dmg、nsis(可选安装目录,创建快捷方式)、AppImage,网站或服务代码作为附加资源打进安装包。 + - `build/icon.png`:你的 PNG(至少 512 px 的正方形),或自动生成的图标。 + - `README.md`:打包命令和签名状态。 +- **检查**(`app_check`):校验配置,并显示每个目标能否在本机打包。 + - 校验内容:appId 必须是反向域名格式;版本必须是 semver;网页目录或入口文件要存在;图标尺寸;使用固定端口时给出提醒;证书文件要存在。 +- **打包**(`app_build` / `app_status`):第一次先 `npm install`,然后运行 `electron-builder --publish never`。面板实时显示日志,并列出 `desktop/release/` 里的产物。 + +## 用法 + +在 ZCode Desktop 里对 Agent 说: + +- “把这个网站做成 Mac 和 Windows 桌面应用” +- “把我的 Node 服务打包成桌面应用” +- “这台电脑能打哪些安装包?” + +## 工具 + +| 工具 | 作用 | +|---|---| +| `app_scan` | 识别项目类型、入口、端口和图标 | +| `app_setup` | 生成或更新 `desktop/`(外壳、electron-builder.yml、图标、README) | +| `app_check` | 校验配置,查看本机能打哪些目标 | +| `app_build` | 运行 electron-builder 打包一个目标 | +| `app_status` | 查看打包进度和日志 | + +## 范围(v0.1) + +- 不做自动更新服务器、应用商店上架和 Apple 公证(公证需要 Apple 账号)。 +- 不支持 Next/Nuxt 服务端渲染,请改用静态导出。Node 服务必须能用 `node <入口>` 启动。 +- Node 服务会把整个项目目录(包括 `node_modules`)打进安装包。 + +## 隐私、网络和文件 + +- 不需要 API 密钥,也不需要账号。只有第一次打包时会在 `desktop/` 里运行 `npm install`,从 npm 和 GitHub 下载 Electron 和 electron-builder。 +- 只写 `<项目>/desktop/` 和 `.app-installer/state.json`。证书密码不会写入磁盘。 diff --git a/external_plugins/app-installer-builder/skills/app-installer-builder/SKILL.md b/external_plugins/app-installer-builder/skills/app-installer-builder/SKILL.md new file mode 100644 index 00000000..aca5566e --- /dev/null +++ b/external_plugins/app-installer-builder/skills/app-installer-builder/SKILL.md @@ -0,0 +1,26 @@ +--- +name: app-installer-builder +description: 用 Electron + electron-builder 把现有网站或 Node 项目打包成桌面应用(macOS dmg、Windows nsis、Linux AppImage):识别项目、生成 desktop/ 外壳与 electron-builder.yml、显示本机能打哪些安装包、实际打包。用户提到“做成桌面应用 / 安装包 / exe / dmg / Electron 打包”时使用。签名只用用户自己提供的证书。 +--- + +# 应用安装包制作(electron-builder) + +1. 先用 `app_scan(dir)` 识别项目: + - 静态网站:需要有构建好的 index.html。没有的话,先让用户运行 `npm run build`,或者由你来运行。 + - Node 服务:最好读取 `process.env.PORT`。如果用的是固定端口,提醒用户改成读取 `process.env.PORT`。 + - Next/Nuxt 服务端渲染不支持,请改用静态导出。 +2. 用 `app_setup(dir, name, appId, version, targets)` 生成配置: + - appId 用反向域名,例如 `com.公司.应用`,不要保留 `com.example`。 + - 默认目标是 `["dmg","nsis"]`。 + - 图标用正方形 PNG,至少 512 px;没有的话插件会自动生成。 +3. 签名:只有用户明确提供了证书才填。 + - macOS:`macIdentity` 填钥匙串里的证书名称。 + - Windows:`winCertificateFile` 填 .pfx 证书路径。 + - **不要索取、也不要传入证书密码**。请用户自己把密码设到环境变量 `WIN_CSC_KEY_PASSWORD`。 + - 没有证书就不签名,并告诉用户首次打开时会出现的提示。 +4. 用 `app_check()` 查看本机能打哪些安装包:dmg 只能在 Mac 上打;nsis 需要 Windows,或者安装了 Wine。 +5. 用 `app_build(target)` 打包: + - 第一次打包会下载 Electron(约 150 MB)。 + - 如果返回时还在打包,就继续调用 `app_status()`,直到完成。 + - 本机不能打的目标:告诉用户把项目带到对应的电脑上,在 desktop/ 里运行 README 中的命令。 +6. 完成后告诉用户:安装包在 `desktop/release/` 里,以及是否已签名。 diff --git a/marketplace.json b/marketplace.json index 32e8c8ef..952745ec 100644 --- a/marketplace.json +++ b/marketplace.json @@ -1673,6 +1673,56 @@ "把上一个 Hi3D 任务生成的模型按角色拆分成部件" ] } + }, + { + "name": "app-installer-builder", + "componentTypes": [ + "ui" + ], + "source": "./external_plugins/app-installer-builder", + "displayName": "App Installer Builder", + "displayName_i18n": { + "en": "App Installer Builder", + "zh-CN": "应用安装包制作" + }, + "description": "Wrap an existing website or Node project as a desktop app with Electron and electron-builder: detects a static site (dist/ with index.html) or a Node server, generates desktop/ with the Electron shell (static sites served at app:// with SPA routes; Node servers started with Electron's own Node on a free port), electron-builder.yml for macOS dmg and Windows nsis (plus Linux AppImage), an icon and a README. Shows which targets this computer can build and runs the build with a live log. Signing is optional and only uses a certificate you provide; otherwise builds are unsigned and the README says so.", + "description_i18n": { + "en": "Wrap an existing website or Node project as a desktop app with Electron and electron-builder: detects a static site (dist/ with index.html) or a Node server, generates desktop/ with the Electron shell (static sites served at app:// with SPA routes; Node servers started with Electron's own Node on a free port), electron-builder.yml for macOS dmg and Windows nsis (plus Linux AppImage), an icon and a README. Shows which targets this computer can build and runs the build with a live log. Signing is optional and only uses a certificate you provide; otherwise builds are unsigned and the README says so.", + "zh-CN": "用 Electron + electron-builder 把现有网站或 Node 项目包装成桌面应用:自动识别静态网站(含 index.html 的 dist/)或 Node 服务,在项目里生成 desktop/ 目录——Electron 外壳(静态站点通过 app:// 加载并支持前端路由;Node 服务用 Electron 自带的 Node 在空闲端口启动)、面向 macOS dmg 和 Windows nsis(另含 Linux AppImage)的 electron-builder.yml、图标和说明。面板显示本机能打哪些安装包,并实时显示打包日志。签名可选,只使用你自己提供的证书;没有证书就不签名,并在说明里写明。" + }, + "version": "0.1.0", + "author": { + "name": "Penova", + "url": "https://github.com/ppppp2005-p" + }, + "license": "MIT", + "category": "developer-tools", + "keywords": [ + "electron", + "electron-builder", + "desktop app", + "installer", + "dmg", + "nsis", + "appimage", + "package", + "桌面应用", + "安装包", + "打包", + "网站转应用" + ], + "examplePrompts": [ + "Turn this web app into a Mac and Windows desktop app", + "Package my Node server as a desktop app", + "Which installers can I build on this computer?" + ], + "examplePrompts_i18n": { + "zh-CN": [ + "把这个网站做成 Mac 和 Windows 桌面应用", + "把我的 Node 服务打包成桌面应用", + "这台电脑能打哪些安装包?" + ] + } } ] } \ No newline at end of file diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 14b35f76..821a722d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -42,6 +42,37 @@ importers: specifier: 4.6.5 version: 4.6.5 + ui-plugins/app-installer-builder: + dependencies: + '@modelcontextprotocol/sdk': + specifier: 1.29.0 + version: 1.29.0(zod@4.6.5) + zod: + specifier: ^4.6.5 + version: 4.6.5 + devDependencies: + '@modelcontextprotocol/core': + specifier: 2.0.0 + version: 2.0.0 + '@modelcontextprotocol/ext-apps': + specifier: 2.0.0 + version: 2.0.0(@modelcontextprotocol/client@2.2.0)(@modelcontextprotocol/core@2.0.0)(@modelcontextprotocol/server@2.0.0)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.5) + '@types/node': + specifier: 25.5.0 + version: 25.5.0 + esbuild: + specifier: ^0.25.12 + version: 0.25.12 + playwright-core: + specifier: 1.59.1 + version: 1.59.1 + typescript: + specifier: 6.0.2 + version: 6.0.2 + vitest: + specifier: 4.1.4 + version: 4.1.4(@opentelemetry/api@1.9.1)(@types/node@25.5.0)(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.0)) + ui-plugins/cadcraft: {} ui-plugins/craft-runtime: {} @@ -2475,10 +2506,6 @@ packages: resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==} engines: {node: '>= 0.6'} - eventsource-parser@3.1.0: - resolution: {integrity: sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg==} - engines: {node: '>=18.0.0'} - eventsource-parser@3.1.1: resolution: {integrity: sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==} engines: {node: '>=18.0.0'} @@ -2714,9 +2741,6 @@ packages: jose@6.2.12: resolution: {integrity: sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==} - jose@6.2.2: - resolution: {integrity: sha512-d7kPDd34KO/YnzaDOlikGpOurfF0ByC2sEV4cANCtdqLlTfBlw2p14O/5d/zv40gJPbIQxfES3nSx1/oYNyuZQ==} - jotai-scope@0.7.2: resolution: {integrity: sha512-Gwed97f3dDObrO43++2lRcgOqw4O2sdr4JCjP/7eHK1oPACDJ7xKHGScpJX9XaflU+KBHXF+VhwECnzcaQiShg==} peerDependencies: @@ -3068,10 +3092,6 @@ packages: resolution: {integrity: sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==} engines: {node: '>=8.6'} - picomatch@4.0.4: - resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==} - engines: {node: '>=12'} - picomatch@4.0.7: resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} engines: {node: '>=12'} @@ -3383,18 +3403,10 @@ packages: tinybench@2.9.0: resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} - tinyexec@1.1.1: - resolution: {integrity: sha512-VKS/ZaQhhkKFMANmAOhhXVoIfBXblQxGX1myCQ2faQrfmobMftXeJPcZGp0gS07ocvGJWDLZGyOZDadDBqYIJg==} - engines: {node: '>=18'} - tinyexec@1.3.1: resolution: {integrity: sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==} engines: {node: '>=18'} - tinyglobby@0.2.16: - resolution: {integrity: sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==} - engines: {node: '>=12.0.0'} - tinyglobby@0.2.17: resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} engines: {node: '>=12.0.0'} @@ -3742,7 +3754,7 @@ snapshots: '@antfu/install-pkg@1.1.0': dependencies: package-manager-detector: 1.6.0 - tinyexec: 1.1.1 + tinyexec: 1.3.1 '@atlaskit/pragmatic-drag-and-drop-hitbox@1.2.0': dependencies: @@ -4285,11 +4297,11 @@ snapshots: cors: 2.8.6 cross-spawn: 7.0.6 eventsource: 3.0.7 - eventsource-parser: 3.1.0 + eventsource-parser: 3.1.1 express: 5.2.1 express-rate-limit: 8.3.2(express@5.2.1) hono: 4.12.12 - jose: 6.2.2 + jose: 6.2.12 json-schema-typed: 8.0.2 pkce-challenge: 5.0.1 raw-body: 3.0.2 @@ -5809,13 +5821,11 @@ snapshots: etag@1.8.1: {} - eventsource-parser@3.1.0: {} - eventsource-parser@3.1.1: {} eventsource@3.0.7: dependencies: - eventsource-parser: 3.1.0 + eventsource-parser: 3.1.1 expect-type@1.4.0: {} @@ -5869,10 +5879,6 @@ snapshots: fast-uri@3.1.0: {} - fdir@6.5.0(picomatch@4.0.4): - optionalDependencies: - picomatch: 4.0.4 - fdir@6.5.0(picomatch@4.0.7): optionalDependencies: picomatch: 4.0.7 @@ -6048,8 +6054,6 @@ snapshots: jose@6.2.12: {} - jose@6.2.2: {} - jotai-scope@0.7.2(jotai@2.11.0(@types/react@19.2.14)(react@19.2.7))(react@19.2.7): dependencies: jotai: 2.11.0(@types/react@19.2.14)(react@19.2.7) @@ -6406,8 +6410,6 @@ snapshots: picomatch@2.3.2: {} - picomatch@4.0.4: {} - picomatch@4.0.7: {} pirates@4.0.7: {} @@ -6745,7 +6747,7 @@ snapshots: lines-and-columns: 1.2.4 mz: 2.7.0 pirates: 4.0.7 - tinyglobby: 0.2.16 + tinyglobby: 0.2.17 ts-interface-checker: 0.1.13 svg-pathdata@6.0.3: @@ -6779,15 +6781,8 @@ snapshots: tinybench@2.9.0: {} - tinyexec@1.1.1: {} - tinyexec@1.3.1: {} - tinyglobby@0.2.16: - dependencies: - fdir: 6.5.0(picomatch@4.0.4) - picomatch: 4.0.4 - tinyglobby@0.2.17: dependencies: fdir: 6.5.0(picomatch@4.0.7) diff --git a/ui-plugins/app-installer-builder/package.json b/ui-plugins/app-installer-builder/package.json new file mode 100644 index 00000000..ca075a8e --- /dev/null +++ b/ui-plugins/app-installer-builder/package.json @@ -0,0 +1,32 @@ +{ + "name": "@penova/plugin-app-installer-builder", + "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": "App Installer Builder" + }, + "engines": { + "node": ">=22.0.0" + }, + "dependencies": { + "@modelcontextprotocol/sdk": "1.29.0", + "zod": "^4.6.5" + }, + "devDependencies": { + "@modelcontextprotocol/core": "2.0.0", + "@modelcontextprotocol/ext-apps": "2.0.0", + "@types/node": "25.5.0", + "esbuild": "^0.25.12", + "playwright-core": "1.59.1", + "typescript": "6.0.2", + "vitest": "4.1.4" + } +} diff --git a/ui-plugins/app-installer-builder/scripts/build.mjs b/ui-plugins/app-installer-builder/scripts/build.mjs new file mode 100644 index 00000000..02ff90d4 --- /dev/null +++ b/ui-plugins/app-installer-builder/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/app-installer-builder/scripts/e2e.mts b/ui-plugins/app-installer-builder/scripts/e2e.mts new file mode 100644 index 00000000..14ebae3d --- /dev/null +++ b/ui-plugins/app-installer-builder/scripts/e2e.mts @@ -0,0 +1,73 @@ +// 浏览器端到端测试:真实打包的 server + 官方 AppBridge 宿主 + 隔离 iframe 中的面板;真的运行 electron-builder, +// 再用 xvfb 启动打好的应用(APP_INSTALLER_SMOKE=1 打印页面标题后退出)。需要 Chrome、网络(首次下载 Electron)和 xvfb-run(Linux)。 +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { cp, mkdir, mkdtemp, readFile, readdir } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { startHarness } from "./harness.mjs"; + +const shots = process.env.E2E_SHOTS ?? join(tmpdir(), "app-installer-builder-shots"); +await mkdir(shots, { recursive: true }); +const workspace = await mkdtemp(join(tmpdir(), "aib-e2e-")); +await cp(process.env.APP_SAMPLES ?? "/workspace/zcode-new-plugins/samples/app", workspace, { recursive: true }); +execFileSync(process.execPath, ["build.mjs"], { cwd: join(workspace, "focus-timer") }); +const userData = await mkdtemp(join(tmpdir(), "aib-home-")); +const smoke = (bin: string[], path = "") => { + const out = execFileSync("xvfb-run", ["-a", ...bin, "--no-sandbox"], { env: { ...process.env, APP_INSTALLER_SMOKE: "1", APP_INSTALLER_SMOKE_PATH: path, XDG_CONFIG_HOME: userData }, encoding: "utf8", maxBuffer: 64 << 20, timeout: 120_000, stdio: ["ignore", "pipe", "ignore"] }); + const m = /APP_INSTALLER_SMOKE (\{[^\n]*\})/.exec(out); // AppImage extraction output can interleave with it + assert.ok(m, "app printed its smoke line"); + return JSON.parse(m[1]) as { title: string; url: string; text: string }; +}; +const harness = await startHarness({ workspace }); +const step = (t: string) => process.stdout.write(`• ${t}\n`); +try { + const { outer, frame } = await harness.open("?locale=zh-CN", { width: 1400, height: 1000 }); + step("user picks the static site and generates the desktop config"); + await frame.locator("button.proj", { hasText: "focus-timer" }).click(); + await frame.locator(".head", { hasText: "静态网站(dist)" }).waitFor(); + await frame.locator("button", { hasText: "生成桌面配置" }).click(); + await frame.locator("pre.code", { hasText: "target: [dmg]" }).waitFor({ timeout: 30_000 }); + await frame.locator(".head img.icon").waitFor(); + assert.equal(await frame.locator("input.appid").inputValue(), "com.penovalabs.focustimer"); // from package.json author + await frame.locator(".issue", { hasText: "SmartScreen" }).waitFor(); + step("user bumps the version, adds the Linux target and regenerates"); + await frame.locator("input.short").first().fill("1.3.1"); + await frame.locator('input[data-target="appimage"]').check(); + await frame.locator("button", { hasText: "保存并重新生成" }).click(); + await frame.locator(".head", { hasText: "1.3.1" }).waitFor({ timeout: 30_000 }); + assert.match(await readFile(join(workspace, "focus-timer/desktop/package.json"), "utf8"), /"version": "1.3.1"/); + assert.equal(await frame.locator('button[data-build="dmg"]').isDisabled(), true); + await frame.locator(".matrix td", { hasText: "需要在 Mac 上打包" }).waitFor(); + await outer.screenshot({ path: join(shots, "01-config.png") }); + step("user builds the unpacked Linux app (real electron-builder run)"); + await frame.locator('button[data-build="dir"]').click(); + await frame.locator(".job .badge", { hasText: "完成" }).waitFor({ timeout: 600_000 }); + await frame.locator(".out", { hasText: "linux-unpacked/" }).waitFor(); + await frame.locator(".job pre.log", { hasText: "electron-builder" }).waitFor(); + await outer.screenshot({ path: join(shots, "02-built.png") }); + step("the packaged app serves the SPA over app:// (incl. a client-side route)"); + const desk = join(workspace, "focus-timer/desktop/release/linux-unpacked"); + const s1 = smoke([join(desk, "focus-timer")], "/stats"); + assert.equal(s1.title, "Focus Timer"); + assert.equal(s1.url, "app://local/stats"); + assert.match(s1.text, /focus sessions completed/); + step("agent packages the Node server as an AppImage"); + await harness.agent(outer, "app_setup", { dir: "notes-server", appId: "com.penovalabs.teamnotes", iconColor: "#0f766e", targets: ["dmg", "nsis", "appimage"] }); + await frame.locator(".head", { hasText: "Node 服务(server.js)" }).waitFor({ timeout: 30_000 }); + let r = await harness.agent(outer, "app_build", { target: "appimage" }); + for (let i = 0; i < 20 && (r as any).structuredContent?.job?.state === "running"; i++) r = await harness.agent(outer, "app_status", {}); + await frame.locator(".out", { hasText: ".AppImage" }).waitFor({ timeout: 120_000 }); + await outer.screenshot({ path: join(shots, "03-appimage.png") }); + const rel = join(workspace, "notes-server/desktop/release"); + const appimage = (await readdir(rel)).find((f) => f.endsWith(".AppImage"))!; + const s2 = smoke([join(rel, appimage), "--appimage-extract-and-run"]); + assert.equal(s2.title, "Team Notes"); + assert.match(s2.url, /^http:\/\/127\.0\.0\.1:\d+\/$/); + assert.match(s2.text, /Welcome to Team Notes/); + assert.ok((await readFile(join(userData, "Team Notes/server.log"), "utf8")).includes("Team Notes on http://127.0.0.1:")); + assert.deepEqual(harness.errors, []); + step(`ok — screenshots in ${shots}`); +} finally { + await harness.close(); +} diff --git a/ui-plugins/app-installer-builder/scripts/harness.mjs b/ui-plugins/app-installer-builder/scripts/harness.mjs new file mode 100644 index 00000000..a45e6e41 --- /dev/null +++ b/ui-plugins/app-installer-builder/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/app-installer-builder/scripts/licenses.mjs b/ui-plugins/app-installer-builder/scripts/licenses.mjs new file mode 100644 index 00000000..5107fe7c --- /dev/null +++ b/ui-plugins/app-installer-builder/scripts/licenses.mjs @@ -0,0 +1,43 @@ +import { readFile, readdir, writeFile } from "node:fs/promises"; +import { dirname, join, resolve } from "node:path"; + +// 从实际参与打包的模块收集许可证,避免只列直接依赖而漏掉 Canvas/SDK 的传递依赖。 +export async function writeNotices(metafiles, destination, extra = []) { + const packages = new Map(); + const { createRequire } = await import("node:module"); + const require = createRequire(resolve("package.json")); + const extraInputs = extra.map((spec) => require.resolve(spec)); + for (const input of [...metafiles.flatMap((meta) => Object.keys(meta.inputs)), ...extraInputs]) { + if (!input.includes("node_modules/")) continue; + let directory = dirname(resolve(input)); + while (directory.includes("node_modules")) { + try { + const pkg = JSON.parse(await readFile(join(directory, "package.json"), "utf8")); + if (pkg.name && pkg.version) { + packages.set(directory, pkg); + break; + } + } catch (error) { + if (error.code !== "ENOENT") throw error; + } + directory = dirname(directory); + } + } + const notices = []; + const seen = new Set(); + for (const [directory, pkg] of [...packages].sort((a, b) => a[1].name.localeCompare(b[1].name))) { + const key = `${pkg.name}@${pkg.version}`; + if (seen.has(key)) continue; + seen.add(key); + const files = (await readdir(directory)).filter((name) => + /^(license|copying|notice)([.-]|$)/i.test(name), + ); + const texts = await Promise.all(files.map((file) => readFile(join(directory, file), "utf8"))); + if (!texts.length && !pkg.license) throw new Error(`Missing license for bundled dependency ${key}`); + if (!texts.length) texts.push(`(No license file is shipped in this package; its package.json declares the ${pkg.license} license.)`); + notices.push( + `${key} — ${typeof pkg.license === "string" ? pkg.license : JSON.stringify(pkg.license)}\n${texts.join("\n\n")}`, + ); + } + await writeFile(destination, notices.join("\n\n----------------------------------------\n\n")); +} diff --git a/ui-plugins/app-installer-builder/src/build.ts b/ui-plugins/app-installer-builder/src/build.ts new file mode 100644 index 00000000..abd3134c --- /dev/null +++ b/ui-plugins/app-installer-builder/src/build.ts @@ -0,0 +1,60 @@ +import { spawn, spawnSync } from "node:child_process"; +import { existsSync, readdirSync, statSync } from "node:fs"; +import { join, relative } from "node:path"; +import { builderArgs, type Target } from "./config.ts"; + +export interface Job { + id: number; + target: Target; + state: "running" | "done" | "failed"; + step: "install" | "build" | ""; + started: number; + ended?: number; + log: string[]; + outputs: { path: string; size: number }[]; + error?: string; +} + +const MAX_LOG = 4000; +export const hasWine = () => { try { return spawnSync(process.platform === "win32" ? "where" : "which", ["wine"], { stdio: "ignore" }).status === 0; } catch { return false; } }; + +/** npm install(如需要)+ electron-builder,日志逐行收集;完成后列出 release/ 里的安装包。 */ +export function runBuild(id: number, desktopAbs: string, target: Target, env: Record, onEnd: (j: Job) => void): Job { + const job: Job = { id, target, state: "running", step: "", started: Date.now(), log: [], outputs: [] }; + const push = (s: string) => { for (const l of s.split(/\r?\n/)) if (l.trim()) job.log.push(l.replace(/\x1b\[[0-9;]*m/g, "")); if (job.log.length > MAX_LOG) job.log.splice(0, job.log.length - MAX_LOG); }; + const npm = process.platform === "win32" ? "npm.cmd" : "npm", npx = process.platform === "win32" ? "npx.cmd" : "npx"; + const run = (cmd: string, args: string[]) => new Promise((resolve) => { + push(`$ ${cmd} ${args.join(" ")}`); + const p = spawn(cmd, args, { cwd: desktopAbs, env: { ...process.env, ...env, FORCE_COLOR: "0", npm_config_fund: "false", npm_config_audit: "false" }, shell: process.platform === "win32" }); + p.stdout.on("data", (d) => push(String(d))); + p.stderr.on("data", (d) => push(String(d))); + p.on("error", (e) => { push(String(e)); resolve(127); }); + p.on("close", (code) => resolve(code ?? 1)); + }); + (async () => { + if (!existsSync(join(desktopAbs, "node_modules/electron-builder")) || !existsSync(join(desktopAbs, "node_modules/electron"))) { + job.step = "install"; + push("Installing Electron and electron-builder (first build only; downloads ~150 MB)…"); + if ((await run(npm, ["install", "--no-audit", "--no-fund"])) !== 0) throw new Error("npm install failed — see the log."); + } + job.step = "build"; + if ((await run(npx, ["electron-builder", ...builderArgs(target, process.platform), "--publish", "never"])) !== 0) throw new Error("electron-builder failed — see the log."); + job.outputs = listOutputs(desktopAbs); + })().then(() => { job.state = "done"; }, (e: Error) => { job.state = "failed"; job.error = e.message; push(`✗ ${e.message}`); }) + .finally(() => { job.ended = Date.now(); onEnd(job); }); + return job; +} + +/** release/ 下的安装包与免安装目录(只列一层 + 可执行目录)。 */ +export function listOutputs(desktopAbs: string) { + const rel = join(desktopAbs, "release"); + if (!existsSync(rel)) return []; + const out: { path: string; size: number }[] = []; + for (const name of readdirSync(rel)) { + const p = join(rel, name), st = statSync(p); + if (st.isFile() && /\.(dmg|exe|AppImage|zip|blockmap)$/i.test(name) && !name.endsWith(".blockmap")) out.push({ path: relative(desktopAbs, p).split("\\").join("/"), size: st.size }); + if (st.isDirectory() && /-unpacked$|^mac(-arm64|-universal)?$/.test(name)) out.push({ path: relative(desktopAbs, p).split("\\").join("/") + "/", size: dirSize(p) }); + } + return out; +} +function dirSize(p: string): number { let n = 0; for (const e of readdirSync(p, { withFileTypes: true })) { const c = join(p, e.name); n += e.isDirectory() ? dirSize(c) : e.isFile() ? statSync(c).size : 0; } return n; } diff --git a/ui-plugins/app-installer-builder/src/config.ts b/ui-plugins/app-installer-builder/src/config.ts new file mode 100644 index 00000000..7388c00a --- /dev/null +++ b/ui-plugins/app-installer-builder/src/config.ts @@ -0,0 +1,223 @@ +// 生成 Electron 外壳 + electron-builder.yml。生成结果放在项目的 desktop/ 目录,用户可以自己继续改。 +export const ELECTRON_VERSION = "45.5.0"; +export const BUILDER_VERSION = "26.18.0"; +export type Target = "dmg" | "nsis" | "appimage" | "dir"; +export const TARGETS: Target[] = ["dmg", "nsis", "appimage", "dir"]; + +export interface AppConfig { + name: string; + appId: string; + version: string; + description?: string; + author?: string; + mode: "static" | "server"; + /** static:网页目录(相对项目);server:入口 JS(相对项目) */ + webDir?: string; + entry?: string; + /** server:服务读取 PORT 环境变量就用空闲端口,否则用固定端口 */ + usesPortEnv?: boolean; + port?: number; + width: number; + height: number; + /** 项目里的 PNG(≥512,正方形);没有就用生成的默认图标 */ + icon?: string; + iconColor?: string; + targets: Target[]; + signing?: { + /** macOS:钥匙串里 “Developer ID Application: …” 证书的名字 */ + macIdentity?: string; + /** Windows:.pfx / .p12 证书文件(相对项目或绝对路径);密码只从环境变量 WIN_CSC_KEY_PASSWORD 读取 */ + winCertificateFile?: string; + }; +} +export interface Issue { severity: "error" | "warning" | "info"; field: string; message: string } + +const y = (s: string) => JSON.stringify(s); // JSON 字符串就是合法的 YAML 标量 +export const pkgName = (name: string) => name.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "") || "app"; + +export function validate(c: AppConfig, has: { web?: boolean; entry?: boolean; icon?: { width: number; height: number } | null; cert?: boolean }): Issue[] { + const out: Issue[] = []; + const e = (field: string, message: string) => out.push({ severity: "error", field, message }); + const w = (field: string, message: string) => out.push({ severity: "warning", field, message }); + if (!c.name.trim()) e("name", "App name is empty."); + if (/[\\/:*?"<>|]/.test(c.name)) e("name", "App name cannot contain \\ / : * ? \" < > |."); + if (!/^[a-zA-Z][\w-]*(\.[a-zA-Z][\w-]*){2,}$/.test(c.appId)) e("appId", `appId “${c.appId}” must be reverse-DNS, e.g. com.yourcompany.${pkgName(c.name).replace(/-/g, "")}.`); + if (/^com\.example\./.test(c.appId)) w("appId", "appId still uses com.example; change it to your own domain before shipping (it identifies the app and its settings folder)."); + if (!/^\d+\.\d+\.\d+(-[\w.]+)?$/.test(c.version)) e("version", `Version “${c.version}” must be semver like 1.2.0.`); + if (c.mode === "static") { + if (!c.webDir) e("webDir", "Choose the folder with index.html."); + else if (has.web === false) e("webDir", `${c.webDir}/index.html not found. Build the site first (e.g. npm run build).`); + } else { + if (!c.entry) e("entry", "Choose the server entry file (e.g. server.js)."); + else if (has.entry === false) e("entry", `${c.entry} not found.`); + if (!c.usesPortEnv && !c.port) e("port", "The server does not read process.env.PORT; enter the port it listens on."); + if (!c.usesPortEnv && c.port) w("port", `Fixed port ${c.port}: the app fails to start if another program uses it. Prefer reading process.env.PORT.`); + } + if (c.icon) { + if (has.icon === null) e("icon", `${c.icon} is not a PNG.`); + else if (has.icon && (has.icon.width !== has.icon.height || has.icon.width < 512)) e("icon", `Icon is ${has.icon.width}×${has.icon.height}; use a square PNG of at least 512×512 (1024×1024 is best).`); + } + if (!c.targets.length) e("targets", "Pick at least one target."); + if (c.width < 320 || c.height < 240) e("window", "Window must be at least 320×240."); + if (!c.signing?.macIdentity && c.targets.includes("dmg")) out.push({ severity: "info", field: "signing", message: "macOS build is unsigned: users must right-click → Open (or allow it in System Settings → Privacy & Security) the first time." }); + if (!c.signing?.winCertificateFile && c.targets.includes("nsis")) out.push({ severity: "info", field: "signing", message: "Windows installer is unsigned: SmartScreen shows “Windows protected your PC” → More info → Run anyway." }); + if (c.signing?.winCertificateFile && has.cert === false) e("signing", `Certificate ${c.signing.winCertificateFile} not found.`); + if (c.signing?.macIdentity && !/^(Developer ID Application|Apple Development|Mac Developer):|^[0-9A-F]{40}$/.test(c.signing.macIdentity)) w("signing", "macIdentity is usually “Developer ID Application: Name (TEAMID)”."); + return out; +} + +/** 本机能不能打这个目标。 */ +export function buildableHere(t: Target, platform: NodeJS.Platform, wine: boolean): { ok: boolean; why?: string } { + if (t === "dir") return { ok: true }; + if (t === "dmg") return platform === "darwin" ? { ok: true } : { ok: false, why: "dmg can only be built on macOS" }; + if (t === "appimage") return platform === "linux" ? { ok: true } : { ok: false, why: "AppImage is built on Linux" }; + if (platform === "win32") return { ok: true }; + return wine ? { ok: true } : { ok: false, why: platform === "darwin" ? "nsis on macOS needs Wine (brew install --cask wine-stable), or build on Windows" : "nsis on Linux needs Wine, or build on Windows" }; +} + +export function builderArgs(t: Target, platform: NodeJS.Platform): string[] { + if (t === "dmg") return ["--mac", "dmg"]; + if (t === "nsis") return ["--win", "nsis"]; + if (t === "appimage") return ["--linux", "AppImage"]; + return [platform === "darwin" ? "--mac" : platform === "win32" ? "--win" : "--linux", "dir"]; +} + +export function builderYml(c: AppConfig): string { + const L: string[] = [ + "# Generated by App Installer Builder (ZCode). Edit freely; re-generating overwrites this file.", + `appId: ${y(c.appId)}`, `productName: ${y(c.name)}`, `copyright: ${y(`Copyright © ${new Date().getFullYear()} ${c.author || c.name}`)}`, + "directories:", " output: release", " buildResources: build", + "files:", " - main.cjs", " - package.json", + "extraResources:", + ]; + if (c.mode === "static") L.push(` - from: ${y(`../${c.webDir === "." ? "" : c.webDir}`.replace(/\/$/, "") || "..")}`, " to: web", " filter: [\"**/*\", \"!desktop{,/**}\", \"!node_modules{,/**}\", \"!.git{,/**}\"]"); + else L.push(" - from: ..", " to: server", " filter: [\"**/*\", \"!desktop{,/**}\", \"!.git{,/**}\", \"!release{,/**}\"]"); + L.push("asar: true", "mac:", " target: [dmg]", " category: public.app-category.productivity", " icon: build/icon.png"); + if (c.signing?.macIdentity) L.push(` identity: ${y(c.signing.macIdentity)}`, " hardenedRuntime: true", " notarize: false"); + else L.push(" identity: null # unsigned: no certificate was provided"); + L.push("dmg:", " writeUpdateInfo: false", "win:", " target: [nsis]", " icon: build/icon.png"); + if (c.signing?.winCertificateFile) L.push(" signtoolOptions:", ` certificateFile: ${y(c.signing.winCertificateFile.startsWith("/") ? c.signing.winCertificateFile : `../${c.signing.winCertificateFile}`)}`, " # password: set the WIN_CSC_KEY_PASSWORD environment variable; it is never written here"); + else L.push(" # unsigned: no certificate was provided"); + L.push("nsis:", " oneClick: false", " perMachine: false", " allowToChangeInstallationDirectory: true", " createDesktopShortcut: true", " createStartMenuShortcut: true", ` shortcutName: ${y(c.name)}`, " differentialPackage: false", + "linux:", " target: [AppImage]", " category: Utility", " icon: build/icon.png", ` maintainer: ${y(c.author || c.name)}`, "publish: null", ""); + return L.join("\n"); +} + +export function packageJson(c: AppConfig): string { + return JSON.stringify({ + name: pkgName(c.name), productName: c.name, version: c.version, description: c.description || c.name, author: c.author || c.name, private: true, main: "main.cjs", desktopName: `${pkgName(c.name)}.desktop`, + scripts: { start: "electron .", dist: "electron-builder" }, + devDependencies: { electron: ELECTRON_VERSION, "electron-builder": BUILDER_VERSION }, + }, null, 2) + "\n"; +} + +export function mainCjs(c: AppConfig): string { + const cfg = { name: c.name, mode: c.mode, width: c.width, height: c.height, webDir: c.webDir ?? ".", entry: c.entry ?? "server.js", usesPortEnv: !!c.usesPortEnv, port: c.port ?? 0 }; + return `// Electron shell generated by App Installer Builder (ZCode). Edit freely. +"use strict"; +const { app, BrowserWindow, protocol, net, shell } = require("electron"); +const path = require("node:path"); +const fs = require("node:fs"); +const http = require("node:http"); +const { spawn } = require("node:child_process"); +const { pathToFileURL } = require("node:url"); + +const CONFIG = ${JSON.stringify(cfg, null, 2)}; +const SMOKE = process.env.APP_INSTALLER_SMOKE === "1"; // used by the plugin's self-test: print the page title and quit +let server = null; + +if (!SMOKE && !app.requestSingleInstanceLock()) app.quit(); +protocol.registerSchemesAsPrivileged([{ scheme: "app", privileges: { standard: true, secure: true, supportFetchAPI: true, corsEnabled: true } }]); + +/** Static site: served from app://local/ so absolute paths (/assets/…) and client-side routes work. */ +function serveStatic() { + const root = app.isPackaged ? path.join(process.resourcesPath, "web") : path.resolve(__dirname, "..", CONFIG.webDir); + protocol.handle("app", (request) => { + let rel = decodeURIComponent(new URL(request.url).pathname); + let file = path.join(root, rel); + if (!file.startsWith(root)) return new Response("Forbidden", { status: 403 }); + if (fs.existsSync(file) && fs.statSync(file).isDirectory()) file = path.join(file, "index.html"); + if (!fs.existsSync(file)) file = path.extname(rel) ? "" : path.join(root, "index.html"); // SPA fallback + if (!file) return new Response("Not found", { status: 404 }); + return net.fetch(pathToFileURL(file).toString()); + }); + return "app://local/"; +} + +function freePort() { + return new Promise((resolve, reject) => { + const s = require("node:net").createServer(); + s.unref(); s.on("error", reject); + s.listen(0, "127.0.0.1", () => { const { port } = s.address(); s.close(() => resolve(port)); }); + }); +} +function waitFor(url, ms) { + const end = Date.now() + ms; + return new Promise((resolve, reject) => { + const tryOnce = () => http.get(url, (res) => { res.resume(); resolve(); }).on("error", () => (Date.now() > end ? reject(new Error("Server did not start: " + url)) : setTimeout(tryOnce, 200))); + tryOnce(); + }); +} + +/** Node server: started with Electron's own Node (no separate Node install needed). */ +async function startServer() { + const root = app.isPackaged ? path.join(process.resourcesPath, "server") : path.resolve(__dirname, ".."); + const port = CONFIG.usesPortEnv ? await freePort() : CONFIG.port; + const logFile = path.join(app.getPath("userData"), "server.log"); + fs.mkdirSync(path.dirname(logFile), { recursive: true }); + const log = fs.openSync(logFile, "a"); + server = spawn(process.execPath, [path.join(root, CONFIG.entry)], { + cwd: root, stdio: ["ignore", log, log], + env: { ...process.env, ELECTRON_RUN_AS_NODE: "1", PORT: String(port), HOST: "127.0.0.1", NODE_ENV: "production", APP_DATA_DIR: app.getPath("userData") }, + }); + server.on("exit", (code) => { if (code && !app.isQuitting) console.error("server exited with code " + code + "; see " + logFile); }); + const url = "http://127.0.0.1:" + port + "/"; + await waitFor(url, 20000); + return url; +} + +async function createWindow() { + const url = CONFIG.mode === "server" ? await startServer() : serveStatic(); + const win = new BrowserWindow({ width: CONFIG.width, height: CONFIG.height, title: CONFIG.name, show: !SMOKE, autoHideMenuBar: true, webPreferences: { contextIsolation: true, nodeIntegration: false, sandbox: true } }); + win.webContents.setWindowOpenHandler(({ url: target }) => { if (/^https?:/.test(target)) shell.openExternal(target); return { action: "deny" }; }); + if (SMOKE) win.webContents.once("did-finish-load", async () => { + const title = await win.webContents.executeJavaScript("document.title"); + const text = await win.webContents.executeJavaScript("document.body.innerText.slice(0, 400)"); + console.log("APP_INSTALLER_SMOKE " + JSON.stringify({ title, url: win.webContents.getURL(), text })); + app.quit(); + }); + const extra = SMOKE ? (process.env.APP_INSTALLER_SMOKE_PATH || "") : ""; + await win.loadURL(url + (extra.startsWith("/") ? extra.slice(1) : extra)); +} + +app.on("second-instance", () => { const w = BrowserWindow.getAllWindows()[0]; if (w) { if (w.isMinimized()) w.restore(); w.focus(); } }); +app.on("before-quit", () => { app.isQuitting = true; if (server) server.kill(); }); +app.on("window-all-closed", () => { if (process.platform !== "darwin" || SMOKE) app.quit(); }); +app.on("activate", () => { if (BrowserWindow.getAllWindows().length === 0) createWindow(); }); +app.whenReady().then(createWindow).catch((error) => { console.error(error); app.exit(1); }); +`; +} + +export function desktopReadme(c: AppConfig): string { + const unsignedMac = !c.signing?.macIdentity, unsignedWin = !c.signing?.winCertificateFile; + return `# ${c.name} — desktop app + +Generated by App Installer Builder. This folder wraps the project in Electron and packages it with electron-builder. + +- Mode: ${c.mode === "static" ? `static site from \`${c.webDir}\` (served at app://local/)` : `Node server \`${c.entry}\` started with Electron's Node (${c.usesPortEnv ? "free port via PORT" : `fixed port ${c.port}`})`} +- Targets: ${c.targets.join(", ")} +- Signing: macOS ${unsignedMac ? "**unsigned**" : `signed as “${c.signing!.macIdentity}” (not notarized)`}, Windows ${unsignedWin ? "**unsigned**" : "signed with the provided certificate (password from WIN_CSC_KEY_PASSWORD)"} + +## Build + +\`\`\`sh +cd desktop +npm install +npx electron-builder --mac dmg # on macOS +npx electron-builder --win nsis # on Windows (or macOS/Linux with Wine) +npx electron-builder --linux AppImage +\`\`\` + +Output goes to \`desktop/release/\`. ${c.mode === "static" ? "Rebuild the website first if it changed." : "Run npm install in the project first so node_modules is packaged."} +${unsignedMac ? "\nUnsigned macOS apps: the first time, right-click the app → Open, or allow it in System Settings → Privacy & Security.\n" : ""}${unsignedWin ? "\nUnsigned Windows installers: SmartScreen shows “Windows protected your PC” → More info → Run anyway.\n" : ""}`; +} diff --git a/ui-plugins/app-installer-builder/src/detect.ts b/ui-plugins/app-installer-builder/src/detect.ts new file mode 100644 index 00000000..5e5ebace --- /dev/null +++ b/ui-plugins/app-installer-builder/src/detect.ts @@ -0,0 +1,79 @@ +import { readFile, readdir, stat } from "node:fs/promises"; +import { join } from "node:path"; +import { pngSize } from "./png.ts"; + +export interface Detected { + dir: string; + kind: "static" | "server" | "unknown"; + name: string; + version: string; + description: string; + author?: string; + /** 静态站点目录(相对项目) */ + webDir?: string; + /** Node 服务入口(相对项目) */ + entry?: string; + usesPortEnv?: boolean; + port?: number; + /** 需要先构建(有 build 脚本但还没有输出目录) */ + needsBuild?: string; + icons: { path: string; width: number; height: number }[]; + notes: string[]; +} + +const WEB_DIRS = ["dist", "build", "out", "public", "www", "site", "_site", "docs", "."]; +const exists = async (p: string) => stat(p).then(() => true, () => false); + +/** 识别项目:静态站点(某个目录里有 index.html)或 Node 服务(package.json 的 start/main 指向 .js 入口)。 */ +export async function detect(abs: string, rel: string): Promise { + const notes: string[] = []; + let pkg: Record = {}; + if (await exists(join(abs, "package.json"))) { + try { pkg = JSON.parse(await readFile(join(abs, "package.json"), "utf8")); } catch { notes.push("package.json is not valid JSON."); } + } + const base = rel === "." ? "app" : rel.split("/").pop()!; + const d: Detected = { + dir: rel, kind: "unknown", name: String(pkg.productName ?? pkg.name ?? base).replace(/^@[^/]+\//, ""), version: /^\d+\.\d+\.\d+/.test(pkg.version ?? "") ? pkg.version : "1.0.0", + description: pkg.description ?? "", author: typeof pkg.author === "string" ? pkg.author : pkg.author?.name, icons: [], notes, + }; + // Node 服务:start 脚本 "node x.js" 或 main 字段,且代码里有 listen( + const start: string = pkg.scripts?.start ?? ""; + const m = /^\s*node\s+(?:--[\w-]+(?:=\S+)?\s+)*([\w./-]+\.(?:c|m)?js)\b/.exec(start); + const candidates = [m?.[1], pkg.main, "server.js", "index.js", "app.js", "server.mjs"].filter(Boolean) as string[]; + for (const c of candidates) { + const f = join(abs, c); + if (!(await exists(f))) continue; + const src = await readFile(f, "utf8"); + if (/\.listen\s*\(|createServer\s*\(/.test(src)) { + d.kind = "server"; d.entry = c.replace(/^\.\//, ""); + d.usesPortEnv = /process\.env\.PORT\b/.test(src); + const pm = /\.listen\s*\(\s*(?:process\.env\.PORT\s*(?:\|\||\?\?)\s*)?(\d{2,5})/.exec(src) ?? /\bPORT\s*=\s*(?:Number\(|parseInt\()?\s*(?:process\.env\.PORT\s*(?:\|\||\?\?)\s*)?["\x27]?(\d{2,5})/.exec(src); + if (pm) d.port = Number(pm[1]); + if (!d.usesPortEnv) notes.push(`${d.entry} does not read process.env.PORT; the app will use the fixed port ${d.port ?? "(unknown — set it)"}.`); + break; + } + } + if (d.kind === "unknown") { + for (const w of WEB_DIRS) if (await exists(join(abs, w, "index.html"))) { d.kind = "static"; d.webDir = w; break; } + if (d.kind === "unknown" && pkg.scripts?.build) d.needsBuild = `npm run build`; + if (d.kind === "static" && d.webDir === "." ) notes.push("The site is at the project root; the whole folder (except desktop/) will be packaged."); + } + if (pkg.dependencies?.next || pkg.dependencies?.nuxt) notes.push("Next/Nuxt server rendering is not supported in v0.1; use a static export (next export / nuxt generate)."); + // 图标候选:项目里 ≥256 的 PNG,名字含 icon/logo 的优先 + const pngs: string[] = []; + const walk = async (p: string, r: string, depth: number) => { + if (depth > 3 || pngs.length > 200) return; + for (const e of await readdir(p, { withFileTypes: true }).catch(() => [])) { + if (e.name.startsWith(".") || ["node_modules", "desktop", "release"].includes(e.name)) continue; + if (e.isDirectory()) await walk(join(p, e.name), `${r}${e.name}/`, depth + 1); + else if (/\.png$/i.test(e.name)) pngs.push(`${r}${e.name}`); + } + }; + await walk(abs, "", 0); + for (const p of pngs) { + const s = pngSize(await readFile(join(abs, p)).catch(() => new Uint8Array())); + if (s && s.width >= 256 && s.width === s.height) d.icons.push({ path: p, ...s }); + } + d.icons.sort((a, b) => Number(/icon|logo/i.test(b.path)) - Number(/icon|logo/i.test(a.path)) || b.width - a.width); + return d; +} diff --git a/ui-plugins/app-installer-builder/src/kit/console.ts b/ui-plugins/app-installer-builder/src/kit/console.ts new file mode 100644 index 00000000..f6817656 --- /dev/null +++ b/ui-plugins/app-installer-builder/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/app-installer-builder/src/kit/server-kit.ts b/ui-plugins/app-installer-builder/src/kit/server-kit.ts new file mode 100644 index 00000000..6bc31594 --- /dev/null +++ b/ui-plugins/app-installer-builder/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/app-installer-builder/src/kit/workspace.ts b/ui-plugins/app-installer-builder/src/kit/workspace.ts new file mode 100644 index 00000000..f02c4fcb --- /dev/null +++ b/ui-plugins/app-installer-builder/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/app-installer-builder/src/main.ts b/ui-plugins/app-installer-builder/src/main.ts new file mode 100644 index 00000000..340a06ed --- /dev/null +++ b/ui-plugins/app-installer-builder/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(`[app-installer-builder] ${line}\n`), +}); +process.stdin.once("end", () => process.exit(0)); +await server.connect(new StdioServerTransport()); diff --git a/ui-plugins/app-installer-builder/src/png.ts b/ui-plugins/app-installer-builder/src/png.ts new file mode 100644 index 00000000..95b54359 --- /dev/null +++ b/ui-plugins/app-installer-builder/src/png.ts @@ -0,0 +1,51 @@ +import { deflateSync } from "node:zlib"; + +/** PNG 宽高(读 IHDR);不是 PNG 返回 undefined。 */ +export function pngSize(buf: Uint8Array): { width: number; height: number } | undefined { + if (buf.length < 24 || buf[0] !== 0x89 || buf[1] !== 0x50 || buf[2] !== 0x4e || buf[3] !== 0x47) return undefined; + const dv = new DataView(buf.buffer, buf.byteOffset, buf.byteLength); + return { width: dv.getUint32(16), height: dv.getUint32(20) }; +} + +const CRC = (() => { const t = new Uint32Array(256); for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; t[n] = c >>> 0; } return t; })(); +const crc32 = (b: Uint8Array) => { let c = 0xffffffff; for (const x of b) c = CRC[(c ^ x) & 0xff] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; }; +function chunk(type: string, data: Uint8Array) { + const out = Buffer.alloc(12 + data.length); + out.writeUInt32BE(data.length, 0); out.write(type, 4, "ascii"); Buffer.from(data).copy(out, 8); + out.writeUInt32BE(crc32(out.subarray(4, 8 + data.length)), 8 + data.length); + return out; +} +const hex = (c: string) => { const m = /^#?([0-9a-f]{6})$/i.exec(c); const n = parseInt(m ? m[1] : "2563eb", 16); return [n >> 16, (n >> 8) & 255, n & 255]; }; + +/** + * 没有图标时生成默认图标:圆角方块 + 渐变 + 白色“窗口”图形,1024×1024 RGBA PNG。 + * electron-builder 会从 1024 PNG 生成 .icns / .ico。 + */ +export function defaultIcon(color = "#2563eb", size = 1024): Buffer { + const [r, g, b] = hex(color); + const raw = Buffer.alloc((size * 4 + 1) * size); + const R = size * 0.2, pad = size * 0.06; + const inRound = (x: number, y: number, x0: number, y0: number, x1: number, y1: number, rad: number) => { + if (x < x0 || x > x1 || y < y0 || y > y1) return false; + const cx = Math.min(Math.max(x, x0 + rad), x1 - rad), cy = Math.min(Math.max(y, y0 + rad), y1 - rad); + return (x - cx) ** 2 + (y - cy) ** 2 <= rad * rad; + }; + const w0 = size * 0.24, w1 = size * 0.76, h0 = size * 0.3, h1 = size * 0.72, bar = size * 0.4, t = size * 0.035; + for (let y = 0; y < size; y++) { + const row = y * (size * 4 + 1); + raw[row] = 0; + for (let x = 0; x < size; x++) { + const o = row + 1 + x * 4; + if (!inRound(x + 0.5, y + 0.5, pad, pad, size - pad, size - pad, R)) continue; + const k = 1.15 - (y / size) * 0.35; + let px = [Math.min(255, r * k), Math.min(255, g * k), Math.min(255, b * k)]; + const frame = inRound(x, y, w0, h0, w1, h1, size * 0.05) && !inRound(x, y, w0 + t, bar, w1 - t, h1 - t, size * 0.02); + const dot = [0.29, 0.34, 0.39].some((cx) => (x - cx * size) ** 2 + (y - (h0 + bar) / 2) ** 2 <= (size * 0.018) ** 2); + if (frame && !dot) px = [255, 255, 255]; + raw[o] = px[0]; raw[o + 1] = px[1]; raw[o + 2] = px[2]; raw[o + 3] = 255; + } + } + const ihdr = Buffer.alloc(13); + ihdr.writeUInt32BE(size, 0); ihdr.writeUInt32BE(size, 4); ihdr[8] = 8; ihdr[9] = 6; + return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk("IHDR", ihdr), chunk("IDAT", deflateSync(raw, { level: 6 })), chunk("IEND", new Uint8Array())]); +} diff --git a/ui-plugins/app-installer-builder/src/server.ts b/ui-plugins/app-installer-builder/src/server.ts new file mode 100644 index 00000000..94140e50 --- /dev/null +++ b/ui-plugins/app-installer-builder/src/server.ts @@ -0,0 +1,188 @@ +import { existsSync } from "node:fs"; +import { readFile } from "node:fs/promises"; +import { join, posix } from "node:path"; +import { z } from "zod"; +import { createKitServer } from "./kit/server-kit.ts"; +import { KitError, Workspace } from "./kit/workspace.ts"; +import { type Job, hasWine, listOutputs, runBuild } from "./build.ts"; +import { type AppConfig, type Issue, TARGETS, type Target, buildableHere, builderYml, desktopReadme, mainCjs, packageJson, pkgName, validate } from "./config.ts"; +import { type Detected, detect } from "./detect.ts"; +import { defaultIcon, pngSize } from "./png.ts"; + +export const NAME = "app-installer-builder"; +export const VERSION = "0.1.0"; +export const PANEL_URI = `ui://${NAME}/panel.html`; +const STATE = ".app-installer/state.json"; +const WAIT = 45_000; + +export interface ServerOptions { workspaceRoot: string; assetRoot: string; log?: (line: string) => void; platform?: NodeJS.Platform; wine?: boolean } + +export function createServer(options: ServerOptions) { + const ws = new Workspace(options.workspaceRoot); + const platform = options.platform ?? process.platform; + const wine = options.wine ?? hasWine(); + 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 jobs = new Map(); + let jobSeq = 0; + + const norm = (d: string) => posix.normalize(d.replace(/\\/g, "/")).replace(/^\.\/|\/+$/g, "") || "."; + const cfgPath = (dir: string) => posix.join(dir, "desktop/app-installer.json"); + async function current(dir?: string): Promise { + if (dir) { const d = norm(dir); ws.resolve(d); await ws.write(STATE, JSON.stringify({ current: d }) + "\n"); return d; } + if (await ws.exists(STATE)) return JSON.parse(await ws.readText(STATE)).current; + throw new KitError("no_project", "No project chosen yet; call app_setup with dir (use app_scan to inspect a folder first)."); + } + const loadCfg = async (dir: string): Promise => ((await ws.exists(cfgPath(dir))) ? JSON.parse(await ws.readText(cfgPath(dir))) : undefined); + const inProject = (dir: string, p: string) => (p.startsWith("/") ? p : posix.join(dir, p)); + async function facts(dir: string, c: AppConfig) { + const icon = c.icon ? ((await ws.exists(inProject(dir, c.icon))) ? pngSize(await ws.read(inProject(dir, c.icon))) ?? null : null) : undefined; + return { + web: c.webDir ? existsSync(ws.resolve(posix.join(dir, c.webDir, "index.html"))) : undefined, + entry: c.entry ? existsSync(ws.resolve(posix.join(dir, c.entry))) : undefined, + icon, cert: c.signing?.winCertificateFile ? existsSync(c.signing.winCertificateFile.startsWith("/") ? c.signing.winCertificateFile : ws.resolve(posix.join(dir, c.signing.winCertificateFile))) : undefined, + }; + } + const envInfo = (c?: AppConfig) => ({ + platform, wine, + targets: Object.fromEntries(TARGETS.map((t) => [t, buildableHere(t, platform, wine)])) as Record, + wanted: c?.targets ?? [], + }); + async function view(dir: string, extra: Record = {}) { + const c = await loadCfg(dir); + const d = await detect(ws.resolve(dir), dir); + const issues = c ? validate(c, await facts(dir, c)) : []; + const generated = ["package.json", "main.cjs", "electron-builder.yml", "build/icon.png", "README.md"].filter((f) => existsSync(ws.resolve(posix.join(dir, "desktop", f)))); + const job = jobs.get(dir); + return { + kind: "app", dir, detected: d, config: c ?? null, issues, generated, env: envInfo(c), + job: job ? { ...job, log: job.log.slice(-400) } : null, outputs: existsSync(ws.resolve(posix.join(dir, "desktop"))) ? listOutputs(ws.resolve(posix.join(dir, "desktop"))) : [], ...extra, + }; + } + const issueLine = (i: Issue) => `${i.severity === "error" ? "✗" : i.severity === "warning" ? "!" : "·"} [${i.field}] ${i.message}`; + const envLine = (c: AppConfig) => c.targets.map((t) => { const b = buildableHere(t, platform, wine); return `${t}: ${b.ok ? "can build here" : `not here — ${b.why}`}`; }).join("; "); + + tool("app_scan", { + description: "Inspect a project folder before packaging it as a desktop app: detects a static website (a folder with index.html, e.g. dist/) or a Node server (start script / entry that calls listen()), whether it reads process.env.PORT, the name/version from package.json, and square PNG icon candidates.", + input: { dir: z.string().default(".").describe("Project folder in the workspace") }, readOnly: true, + }, async ({ dir }) => { + const d = await detect(ws.resolve(norm(dir)), norm(dir)); + return { text: `${d.dir}: ${d.kind}${d.webDir ? ` (web folder ${d.webDir})` : ""}${d.entry ? ` (entry ${d.entry}, ${d.usesPortEnv ? "reads PORT" : `fixed port ${d.port ?? "?"}`})` : ""}; name “${d.name}” v${d.version}; icons: ${d.icons.map((i) => `${i.path} ${i.width}px`).join(", ") || "none (a default icon will be generated)"}.${d.needsBuild ? ` No built site found — run \`${d.needsBuild}\` first.` : ""}${d.notes.map((n) => `\n! ${n}`).join("")}`, structured: { kind: "scan", detected: d } }; + }); + + tool("app_setup", { + description: "Create or update the desktop wrapper for a project: writes /desktop/ with an Electron shell (main.cjs: static sites served at app://local/ with SPA fallback; Node servers started with Electron's own Node on a free port), package.json (electron + electron-builder), electron-builder.yml (macOS dmg, Windows nsis, Linux AppImage), build/icon.png and a README. Unspecified fields come from the detected project / the previous config. Signing is optional and only uses a certificate the user provides: macIdentity (keychain certificate name) and/or winCertificateFile (.pfx path; the password must be in the WIN_CSC_KEY_PASSWORD environment variable, never passed here). Without them the builds are unsigned.", + input: { + dir: z.string().optional().describe("Project folder (default: the current one)"), + name: z.string().optional(), appId: z.string().optional().describe("Reverse-DNS id, e.g. com.acme.notes"), version: z.string().optional(), description: z.string().optional(), author: z.string().optional(), + mode: z.enum(["static", "server"]).optional(), webDir: z.string().optional(), entry: z.string().optional(), port: z.number().int().min(1).max(65535).optional(), usesPortEnv: z.boolean().optional(), + width: z.number().int().optional(), height: z.number().int().optional(), icon: z.string().optional().describe("Square PNG ≥512 px, relative to the project; empty string = generated icon"), iconColor: z.string().optional(), + targets: z.array(z.enum(["dmg", "nsis", "appimage", "dir"])).optional(), + signing: z.object({ macIdentity: z.string().optional(), winCertificateFile: z.string().optional() }).optional(), + }, + openPanel: true, + }, async (input) => { + const dir = await current(input.dir); + const d: Detected = await detect(ws.resolve(dir), dir); + const prev = await loadCfg(dir); + const pick = (k: K, fallback: AppConfig[K]): AppConfig[K] => (input[k as string] !== undefined ? input[k as string] : prev?.[k] !== undefined ? prev[k] : fallback); + const authorSlug = (d.author ?? "").toLowerCase().replace(/[^a-z0-9]+/g, ""); + const c: AppConfig = { + name: pick("name", d.name), appId: pick("appId", `com.${authorSlug || "example"}.${pkgName(input.name ?? prev?.name ?? d.name).replace(/-/g, "")}`), version: pick("version", d.version), + description: pick("description", d.description), author: pick("author", d.author), mode: pick("mode", d.kind === "server" ? "server" : "static"), + webDir: pick("webDir", d.webDir), entry: pick("entry", d.entry), usesPortEnv: pick("usesPortEnv", d.usesPortEnv ?? true), port: pick("port", d.port), + width: pick("width", 1200), height: pick("height", 800), icon: pick("icon", d.icons.find((i) => i.width >= 512)?.path ?? ""), iconColor: pick("iconColor", "#2563eb"), + targets: pick("targets", ["dmg", "nsis"]), signing: pick("signing", undefined), + }; + if (c.signing && !c.signing.macIdentity && !c.signing.winCertificateFile) c.signing = undefined; + const issues = validate(c, await facts(dir, c)); + await ws.write(cfgPath(dir), JSON.stringify(c, null, 2) + "\n"); + const errors = issues.filter((i) => i.severity === "error"); + if (!errors.length) { + const base = posix.join(dir, "desktop"); + await ws.write(`${base}/package.json`, packageJson(c)); + await ws.write(`${base}/main.cjs`, mainCjs(c)); + await ws.write(`${base}/electron-builder.yml`, builderYml(c)); + await ws.write(`${base}/README.md`, desktopReadme(c)); + await ws.write(`${base}/build/icon.png`, c.icon ? await ws.read(inProject(dir, c.icon)) : defaultIcon(c.iconColor)); + const gi = posix.join(base, ".gitignore"); + if (!(await ws.exists(gi))) await ws.write(gi, "node_modules/\nrelease/\n"); + } + const v = await view(dir); + return { + text: errors.length + ? `Config saved to ${cfgPath(dir)} but files were NOT generated — fix these:\n${issues.map(issueLine).join("\n")}` + : `Generated ${dir}/desktop/ (package.json, main.cjs, electron-builder.yml, build/icon.png${c.icon ? ` from ${c.icon}` : " (generated)"}, README.md) for “${c.name}” ${c.version} (${c.mode}${c.mode === "static" ? ` from ${c.webDir}` : ` ${c.entry}`}). Signing: macOS ${c.signing?.macIdentity ? "with the provided identity" : "unsigned"}, Windows ${c.signing?.winCertificateFile ? "with the provided certificate" : "unsigned"}. Targets — ${envLine(c)}.${issues.length ? `\n${issues.map(issueLine).join("\n")}` : ""}`, + structured: v, + }; + }); + + tool("app_check", { + description: "Re-check the desktop config and this computer: which targets can be built here (dmg needs macOS; nsis needs Windows or Wine; AppImage needs Linux; dir = unpacked app for this OS, works everywhere).", + input: { dir: z.string().optional() }, readOnly: true, + }, async ({ dir: d0 }) => { + const dir = await current(d0); + const c = await loadCfg(dir); + if (!c) throw new KitError("no_config", `${dir} has no desktop config yet; call app_setup.`); + const v = await view(dir); + return { text: `${dir}: ${v.issues.filter((i) => i.severity === "error").length} error(s). This computer: ${platform}${wine ? " + Wine" : ""}. ${envLine(c)}.${v.issues.length ? `\n${v.issues.map(issueLine).join("\n")}` : ""}`, structured: v }; + }); + + const status = (job: Job) => job.state === "running" + ? `Building ${job.target} (${job.step}) — ${Math.round((Date.now() - job.started) / 1000)} s so far. Call app_status to wait for it.\n${job.log.slice(-8).join("\n")}` + : job.state === "done" ? `Built ${job.target} in ${Math.round(((job.ended ?? 0) - job.started) / 1000)} s:\n${job.outputs.map((o) => `- desktop/${o.path} (${(o.size / 1048576).toFixed(1)} MB)`).join("\n")}` + : `Build failed: ${job.error}\n${job.log.slice(-25).join("\n")}`; + const waitJob = (job: Job, ms: number) => new Promise((resolve) => { const end = Date.now() + ms; const tick = () => (job.state !== "running" || Date.now() > end ? resolve() : setTimeout(tick, 300)); tick(); }); + + tool("app_build", { + description: "Build an installer with electron-builder on this computer: runs npm install in desktop/ the first time (downloads Electron, ~150 MB), then electron-builder. Output in /desktop/release/. Refuses targets this computer cannot build (dmg needs macOS, nsis needs Windows or Wine). Waits up to ~45 s, then keep calling app_status until it finishes.", + input: { target: z.enum(["dmg", "nsis", "appimage", "dir"]), dir: z.string().optional() }, timeoutMs: 120_000, + }, async ({ target, dir: d0 }) => { + const dir = await current(d0); + const c = await loadCfg(dir); + if (!c) throw new KitError("no_config", "No desktop config yet; call app_setup first."); + const errors = validate(c, await facts(dir, c)).filter((i) => i.severity === "error"); + if (errors.length) throw new KitError("invalid_config", `Fix the config first:\n${errors.map(issueLine).join("\n")}`); + if (!existsSync(ws.resolve(posix.join(dir, "desktop/electron-builder.yml")))) throw new KitError("not_generated", "desktop/ files are missing; call app_setup."); + const b = buildableHere(target, platform, wine); + if (!b.ok) throw new KitError("wrong_platform", `${b.why}. Generate the config here and run \`npx electron-builder ${target === "dmg" ? "--mac dmg" : "--win nsis"}\` in desktop/ on that computer.`); + if (jobs.get(dir)?.state === "running") throw new KitError("busy", "A build is already running; call app_status."); + const env: Record = {}; + if (!c.signing?.macIdentity) env.CSC_IDENTITY_AUTO_DISCOVERY = "false"; + const job = runBuild(++jobSeq, ws.resolve(posix.join(dir, "desktop")), target, env, (j) => options.log?.(`build ${j.target} ${j.state}`)); + jobs.set(dir, job); + await waitJob(job, WAIT); + return { text: status(job), structured: await view(dir) }; + }); + + tool("app_status", { + description: "Status and log of the current build; waits up to ~45 s for it to finish (wait=false returns at once).", + input: { dir: z.string().optional(), wait: z.boolean().default(true) }, readOnly: true, timeoutMs: 120_000, + }, async ({ dir: d0, wait }) => { + const dir = await current(d0); + const job = jobs.get(dir); + if (job && wait) await waitJob(job, WAIT); + return { text: job ? status(job) : "No build has run in this session.", structured: await view(dir) }; + }); + + // —— 面板专用 —— + tool("app_state", { description: "Panel state.", input: { dir: z.string().optional() }, visibility: ["app"], readOnly: true }, async ({ dir }) => { + try { return { text: "", structured: await view(await current(dir)) }; } catch { return { text: "", structured: { kind: "none" } }; } + }); + tool("app_projects", { description: "Folders that look like projects.", input: {}, visibility: ["app"], readOnly: true }, async () => { + const files = await ws.list({ exts: [".json", ".html"], limit: 4000 }); + const dirs = new Set(); + for (const f of files) if (/(^|\/)(package\.json|index\.html)$/.test(f.path) && !/(^|\/)(desktop|release)\//.test(f.path)) { const p = posix.dirname(f.path); dirs.add(/\/(public|www|site|docs|_site)$/.test(p) ? posix.dirname(p) : p); } + // 子目录(例如 src/、public/)已被上层项目包含时不单独列出 + const list = [...dirs].filter((d) => ![...dirs].some((p) => p !== d && (p === "." ? d !== "." : d.startsWith(`${p}/`)))); + return { text: "", structured: { dirs: list.sort().slice(0, 100) } }; + }); + tool("app_file", { description: "A generated file.", input: { dir: z.string(), file: z.enum(["package.json", "main.cjs", "electron-builder.yml", "README.md"]) }, visibility: ["app"], readOnly: true }, async ({ dir, file }) => ({ + text: "", structured: { text: await ws.readText(posix.join(norm(dir), "desktop", file)) }, + })); + tool("app_icon", { description: "The icon for the panel.", input: { dir: z.string() }, visibility: ["app"], readOnly: true }, async ({ dir }) => { + const p = posix.join(norm(dir), "desktop/build/icon.png"); + if (!(await ws.exists(p))) return { text: "", structured: { dataUrl: null } }; + return { text: "", structured: { dataUrl: `data:image/png;base64,${(await ws.read(p)).toString("base64")}` } }; + }); + return server; +} diff --git a/ui-plugins/app-installer-builder/test/tools.test.ts b/ui-plugins/app-installer-builder/test/tools.test.ts new file mode 100644 index 00000000..9b2b0900 --- /dev/null +++ b/ui-plugins/app-installer-builder/test/tools.test.ts @@ -0,0 +1,117 @@ +import { execFileSync } from "node:child_process"; +import { cp, mkdtemp, readFile, writeFile } 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 { type AppConfig, buildableHere, builderArgs, builderYml, mainCjs, packageJson, validate } from "../src/config.ts"; +import { detect } from "../src/detect.ts"; +import { defaultIcon, pngSize } from "../src/png.ts"; +import { createServer } from "../src/server.ts"; + +// 两个虚构样例项目:focus-timer(静态单页应用,绝对路径 /assets、前端路由)和 notes-server(无依赖 Node 服务)。 +const SAMPLES = process.env.APP_SAMPLES ?? "/workspace/zcode-new-plugins/samples/app"; +let ws: string; +async function connect(platform: NodeJS.Platform, wine = false) { + const server = createServer({ workspaceRoot: ws, assetRoot: join(import.meta.dirname, "../dist"), platform, wine }); + const [a, b] = InMemoryTransport.createLinkedPair(); + await server.connect(a); + const client = new Client({ name: "t", version: "1" }); + await client.connect(b); + return async (name: string, args: Record) => (await client.callTool({ name, arguments: args })) as any; +} +beforeAll(async () => { + ws = await mkdtemp(join(tmpdir(), "aib-")); + await cp(SAMPLES, ws, { recursive: true }); + execFileSync(process.execPath, ["build.mjs"], { cwd: join(ws, "focus-timer") }); +}); + +const base: AppConfig = { name: "Focus Timer", appId: "com.penovalabs.focustimer", version: "1.3.0", mode: "static", webDir: "dist", width: 1200, height: 800, targets: ["dmg", "nsis"] }; + +describe("detect", () => { + it("finds the static site, the server and icons", async () => { + const s = await detect(join(ws, "focus-timer"), "focus-timer"); + expect(s).toMatchObject({ kind: "static", webDir: "dist", name: "Focus Timer", version: "1.3.0", author: "Penova Labs" }); + expect(s.icons[0]).toEqual({ path: "branding/icon-1024.png", width: 1024, height: 1024 }); + const n = await detect(join(ws, "notes-server"), "notes-server"); + expect(n).toMatchObject({ kind: "server", entry: "server.js", usesPortEnv: true, port: 3000, name: "Team Notes", version: "0.4.2" }); + expect(n.icons).toEqual([]); + }); +}); + +describe("config", () => { + it("validates", () => { + expect(validate(base, { web: true }).filter((i) => i.severity !== "info")).toEqual([]); + const bad = validate({ ...base, appId: "focus", version: "1.3", name: "A/B", targets: [], width: 100 }, { web: false, icon: { width: 256, height: 256 } }); + expect(bad.filter((i) => i.severity === "error").map((i) => i.field).sort()).toEqual(["appId", "name", "targets", "version", "webDir", "window"]); + expect(validate({ ...base, icon: "x.png" }, { web: true, icon: { width: 256, height: 256 } }).find((i) => i.field === "icon")?.message).toMatch(/at least 512/); + expect(validate({ ...base, mode: "server", entry: "server.js", usesPortEnv: false }, { entry: true }).find((i) => i.field === "port")?.severity).toBe("error"); + expect(validate({ ...base, appId: "com.example.focustimer" }, { web: true }).find((i) => i.field === "appId")?.severity).toBe("warning"); + expect(validate(base, { web: true }).filter((i) => i.field === "signing").map((i) => i.message).join()).toMatch(/unsigned.*SmartScreen/s); + }); + it("writes electron-builder.yml for dmg + nsis, unsigned or with the user's certificate", () => { + const y = builderYml(base); + expect(y).toMatch(/appId: "com\.penovalabs\.focustimer"/); + expect(y).toMatch(/mac:\n target: \[dmg\]/); + expect(y).toMatch(/win:\n target: \[nsis\]/); + expect(y).toMatch(/identity: null/); + expect(y).toMatch(/- from: "\.\.\/dist"\n to: web/); + expect(y).not.toMatch(/certificateFile/); + const s = builderYml({ ...base, signing: { macIdentity: "Developer ID Application: Penova Labs (ABCDE12345)", winCertificateFile: "certs/sign.pfx" } }); + expect(s).toMatch(/identity: "Developer ID Application: Penova Labs \(ABCDE12345\)"\n hardenedRuntime: true/); + expect(s).toMatch(/certificateFile: "\.\.\/certs\/sign\.pfx"/); + expect(s).not.toMatch(/certificatePassword/); + const srv = builderYml({ ...base, mode: "server", entry: "server.js" }); + expect(srv).toMatch(/- from: \.\.\n to: server/); + expect(JSON.parse(packageJson(base))).toMatchObject({ name: "focus-timer", productName: "Focus Timer", main: "main.cjs", devDependencies: { electron: expect.any(String), "electron-builder": expect.any(String) } }); + }); + it("generates a main.cjs that parses", async () => { + for (const c of [base, { ...base, mode: "server" as const, entry: "server.js", usesPortEnv: true }]) { + const f = join(ws, `main-${c.mode}.cjs`); + await writeFile(f, mainCjs(c)); + expect(() => execFileSync(process.execPath, ["--check", f])).not.toThrow(); + } + expect(mainCjs(base)).toMatch(/protocol\.handle\("app"/); + expect(mainCjs({ ...base, mode: "server", entry: "server.js" })).toMatch(/ELECTRON_RUN_AS_NODE/); + }); + it("knows what each OS can build", () => { + expect(buildableHere("dmg", "linux", false).ok).toBe(false); + expect(buildableHere("dmg", "darwin", false).ok).toBe(true); + expect(buildableHere("nsis", "darwin", false)).toEqual({ ok: false, why: expect.stringMatching(/Wine/) }); + expect(buildableHere("nsis", "linux", true).ok).toBe(true); + expect(buildableHere("appimage", "win32", false).ok).toBe(false); + expect(builderArgs("dir", "darwin")).toEqual(["--mac", "dir"]); + expect(builderArgs("nsis", "linux")).toEqual(["--win", "nsis"]); + }); + it("draws a default icon", () => { + const png = defaultIcon("#0f766e"); + expect(pngSize(png)).toEqual({ width: 1024, height: 1024 }); + expect(png.length).toBeLessThan(200_000); + }); +}); + +describe("tools", () => { + it("scans, generates and refuses targets this OS cannot build", async () => { + const call = await connect("linux"); + expect((await call("app_scan", { dir: "notes-server" })).content[0].text).toMatch(/server \(entry server\.js, reads PORT\)/); + const s = await call("app_setup", { dir: "focus-timer", appId: "com.penovalabs.focustimer" }); + expect(s.content[0].text).toMatch(/Generated focus-timer\/desktop\/.*icon-1024\.png/); + expect(s.structuredContent.generated).toEqual(["package.json", "main.cjs", "electron-builder.yml", "build/icon.png", "README.md"]); + expect(await readFile(join(ws, "focus-timer/desktop/README.md"), "utf8")).toMatch(/\*\*unsigned\*\*/); + expect((await call("app_build", { target: "dmg" })).content[0].text).toMatch(/\[wrong_platform\] dmg can only be built on macOS\. .*--mac dmg/); + expect((await call("app_build", { target: "nsis" })).content[0].text).toMatch(/needs Wine/); + const bad = await call("app_setup", { version: "two" }); + expect(bad.content[0].text).toMatch(/NOT generated[\s\S]*semver/); + expect((await call("app_build", { target: "dir" })).content[0].text).toMatch(/\[invalid_config\]/); + const n = await call("app_setup", { dir: "notes-server", appId: "com.penovalabs.teamnotes", targets: ["dmg", "nsis", "appimage"] }); + expect(n.content[0].text).toMatch(/build\/icon\.png \(generated\).*\(server server\.js\)/s); + expect(pngSize(await readFile(join(ws, "notes-server/desktop/build/icon.png")))).toEqual({ width: 1024, height: 1024 }); + expect((await call("app_setup", { dir: "../x" })).content[0].text).toMatch(/outside_workspace/); + }); + it("on a Mac the same config can build dmg; nsis needs Wine", async () => { + const call = await connect("darwin"); + const c = await call("app_check", { dir: "notes-server" }); + expect(c.content[0].text).toMatch(/dmg: can build here; nsis: not here — nsis on macOS needs Wine/); + }); +}); diff --git a/ui-plugins/app-installer-builder/test/workspace-links.test.ts b/ui-plugins/app-installer-builder/test/workspace-links.test.ts new file mode 100644 index 00000000..f3dae538 --- /dev/null +++ b/ui-plugins/app-installer-builder/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/app-installer-builder/tsconfig.json b/ui-plugins/app-installer-builder/tsconfig.json new file mode 100644 index 00000000..39f7ab60 --- /dev/null +++ b/ui-plugins/app-installer-builder/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/app-installer-builder/ui/env.d.ts b/ui-plugins/app-installer-builder/ui/env.d.ts new file mode 100644 index 00000000..4210a464 --- /dev/null +++ b/ui-plugins/app-installer-builder/ui/env.d.ts @@ -0,0 +1,4 @@ +declare module "*.css" { + const text: string; + export default text; +} diff --git a/ui-plugins/app-installer-builder/ui/kit.css b/ui-plugins/app-installer-builder/ui/kit.css new file mode 100644 index 00000000..398bc83a --- /dev/null +++ b/ui-plugins/app-installer-builder/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/app-installer-builder/ui/kit.ts b/ui-plugins/app-installer-builder/ui/kit.ts new file mode 100644 index 00000000..b0646f25 --- /dev/null +++ b/ui-plugins/app-installer-builder/ui/kit.ts @@ -0,0 +1,133 @@ +import { App } from "@modelcontextprotocol/ext-apps"; + +export class ToolError extends Error { + readonly code: string; + constructor(code: string, message: string) { + super(message); + this.code = code; + } +} + +let app: App | undefined; +let connection: Promise | undefined; +let created!: () => void; +const appCreated = new Promise((resolve) => (created = resolve)); +const resultListeners = new Set<(value: Record | undefined, tool?: string) => void>(); +const contextListeners = new Set<() => void>(); + +export function initHost(name: string, version: string) { + app = new App({ name, version }, { availableDisplayModes: ["inline", "fullscreen"] }); + app.ontoolresult = (result) => { + const content = result.structuredContent as Record | undefined; + resultListeners.forEach((listener) => listener(content)); + }; + app.onhostcontextchanged = () => contextListeners.forEach((listener) => listener()); + created(); + return ready(); +} + +export function ready(): Promise { + if (!app) return appCreated.then(() => ready()); + return (connection ??= app.connect().then(() => contextListeners.forEach((listener) => listener()))); +} + +export function onToolResult(listener: (value: Record | undefined) => void) { + resultListeners.add(listener); +} + +export function onHostContext(listener: () => void) { + contextListeners.add(listener); +} + +export function hostContext() { + return app?.getHostContext(); +} + +export function locale(): "zh" | "en" { + const fromHost = (app?.getHostContext()?.locale as string | undefined) ?? navigator.language ?? "en"; + return /^zh/i.test(fromHost) ? "zh" : "en"; +} + +export async function call>(name: string, args: Record = {}, timeout = 300_000): Promise { + await ready(); + let result; + try { + result = await app!.callServerTool({ name, arguments: args }, { timeout }); + } catch (error) { + throw new ToolError("host_error", error instanceof Error ? error.message : String(error)); + } + const content = result.structuredContent as Record | undefined; + const error = content?.error as { code?: string; message?: string } | undefined; + if (result.isError || error) { + const text = (result.content?.[0] as { text?: string } | undefined)?.text; + throw new ToolError(error?.code ?? "tool_error", error?.message ?? text ?? "The tool failed."); + } + return (content ?? {}) as T; +} + +/** 读取插件资源(二进制)。 */ +export async function readBlob(uri: string): Promise { + await ready(); + const result = await app!.readServerResource({ uri }); + const first = result.contents[0] as { blob?: string; text?: string } | undefined; + if (typeof first?.blob !== "string") throw new ToolError("host_error", first?.text?.slice(0, 300) ?? `Empty resource ${uri}`); + return base64ToBytes(first.blob); +} + +export function base64ToBytes(base64: string): Uint8Array { + const binary = atob(base64); + const bytes = new Uint8Array(binary.length); + for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index); + return bytes; +} + +/** 由用户点击触发:把一句话发到对话里交给 Agent。 */ +export async function sendMessage(text: string) { + await ready(); + return app!.sendMessage({ role: "user", content: [{ type: "text", text }] }); +} + +export async function updateContext(text: string) { + await ready(); + return app!.updateModelContext({ content: [{ type: "text", text }] }); +} + +type Child = Node | string | number | null | undefined | false; +/** 极简 DOM 构建器。 */ +export function h( + tag: K, + props: Record = {}, + ...children: (Child | Child[])[] +): HTMLElementTagNameMap[K] { + const element = document.createElement(tag); + for (const [key, value] of Object.entries(props)) { + if (value === undefined || value === null || value === false) continue; + if (key.startsWith("on") && typeof value === "function") element.addEventListener(key.slice(2).toLowerCase(), value as EventListener); + else if (key === "class") element.className = String(value); + else if (key === "style" && typeof value === "object") Object.assign(element.style, value); + else if (key === "value" || (key in element && typeof value !== "string")) (element as any)[key] = value; + else element.setAttribute(key, value === true ? "" : String(value)); + } + for (const child of children.flat()) { + if (child === null || child === undefined || child === false) continue; + element.append(child instanceof Node ? child : String(child)); + } + return element; +} + +export function toast(message: string, kind: "ok" | "error" = "ok") { + const node = h("div", { class: `toast ${kind}`, role: "status" }, message); + document.body.append(node); + setTimeout(() => node.remove(), kind === "error" ? 6000 : 3000); +} + +/** 主题:跟随宿主的浅色 / 深色。 */ +export function applyTheme() { + const theme = (app?.getHostContext()?.theme as string | undefined) ?? "light"; + document.documentElement.dataset.theme = theme === "dark" ? "dark" : "light"; +} + +/** replaceChildren,跳过 null / false。 */ +export function put(element: Element, ...children: (Node | string | null | undefined | false)[]) { + element.replaceChildren(...(children.filter((c) => c !== null && c !== undefined && c !== false) as (Node | string)[])); +} diff --git a/ui-plugins/app-installer-builder/ui/main.ts b/ui-plugins/app-installer-builder/ui/main.ts new file mode 100644 index 00000000..3e936f06 --- /dev/null +++ b/ui-plugins/app-installer-builder/ui/main.ts @@ -0,0 +1,135 @@ +import css from "./kit.css"; +import panelCss from "./panel.css"; +import { applyTheme, call, h, initHost, locale, onHostContext, onToolResult, put, toast, updateContext } from "./kit.ts"; + +const style = document.createElement("style"); +style.textContent = css + panelCss; +document.head.append(style); + +type Target = "dmg" | "nsis" | "appimage" | "dir"; +interface Issue { severity: "error" | "warning" | "info"; field: string; message: string } +interface Config { name: string; appId: string; version: string; description?: string; author?: string; mode: "static" | "server"; webDir?: string; entry?: string; usesPortEnv?: boolean; port?: number; width: number; height: number; icon?: string; iconColor?: string; targets: Target[]; signing?: { macIdentity?: string; winCertificateFile?: string } } +interface Detected { dir: string; kind: string; name: string; version: string; webDir?: string; entry?: string; usesPortEnv?: boolean; port?: number; needsBuild?: string; icons: { path: string; width: number }[]; notes: string[] } +interface Job { id: number; target: Target; state: "running" | "done" | "failed"; step: string; started: number; ended?: number; log: string[]; outputs: { path: string; size: number }[]; error?: string } +interface View { kind: "app"; dir: string; detected: Detected; config: Config | null; issues: Issue[]; generated: string[]; env: { platform: string; wine: boolean; targets: Record; wanted: Target[] }; job: Job | null; outputs: { path: string; size: number }[] } + +const T = (cn: string, en: string) => (locale() === "zh" ? cn : en); +const root = document.getElementById("root")!; +const TNAME: Record = { dmg: ["macOS 安装包(dmg)", "macOS (dmg)"], nsis: ["Windows 安装程序(nsis)", "Windows (nsis)"], appimage: ["Linux(AppImage)", "Linux (AppImage)"], dir: ["本机免安装目录(测试用)", "Unpacked app for this OS (test)"] }; +const FIELD: Record = { name: ["名称", "Name"], appId: ["应用 ID", "App ID"], version: ["版本", "Version"], webDir: ["网页目录", "Web folder"], entry: ["入口", "Entry"], port: ["端口", "Port"], icon: ["图标", "Icon"], targets: ["目标", "Targets"], window: ["窗口", "Window"], signing: ["签名", "Signing"] }; +const state: { v?: View; projects: string[]; icon?: string; form?: Config; file: string; fileText?: string; poll?: number } = { projects: [], file: "electron-builder.yml" }; +const mb = (n: number) => `${(n / 1048576).toFixed(1)} MB`; + +async function busy(work: () => Promise): Promise { + root.classList.add("busy"); + try { return await work(); } catch (error) { toast(error instanceof Error ? error.message.replace(/^\[\w+\]\s*/, "") : String(error), "error"); return undefined; } finally { root.classList.remove("busy"); } +} +async function setView(v: View, refreshFiles = true) { + const dirChanged = state.v?.dir !== v.dir; + state.v = v; + if (dirChanged || refreshFiles || !state.form) state.form = v.config ? structuredClone(v.config) : undefined; + if (refreshFiles) { + state.icon = v.generated.includes("build/icon.png") ? (await call<{ dataUrl: string | null }>("app_icon", { dir: v.dir }).catch(() => ({ dataUrl: null }))).dataUrl ?? undefined : undefined; + state.fileText = v.generated.includes(state.file) ? (await call<{ text: string }>("app_file", { dir: v.dir, file: state.file }).catch(() => ({ text: "" }))).text : undefined; + } + render(); + if (v.job?.state === "running" && !state.poll) state.poll = window.setInterval(poll, 1500); + if (v.job?.state !== "running" && state.poll) { clearInterval(state.poll); state.poll = undefined; } + const c = v.config; + void updateContext(c ? `Desktop app for ${v.dir}: “${c.name}” ${c.version}, ${c.mode}, targets ${c.targets.join("/")}, ${v.issues.filter((i) => i.severity === "error").length} errors.${v.job ? ` Build ${v.job.target}: ${v.job.state}.` : ""}` : `Project ${v.dir} not configured yet.`).catch(() => undefined); +} +async function poll() { + const r = await call("app_status", { dir: state.v!.dir, wait: false }).catch(() => undefined); + if (r) await setView(r, r.job?.state !== "running"); +} +onToolResult((v) => { if (v?.kind === "app") void setView(v as unknown as View); }); + +const choose = async (dir: string) => { + const r = await busy(() => call("app_state", { dir })); + if (r?.kind === "app") await setView(r); +}; +const setup = async () => { + const f = state.form, v = state.v!; + const r = await busy(() => call("app_setup", f ? { dir: v.dir, ...f, icon: f.icon ?? "", signing: { macIdentity: f.signing?.macIdentity ?? "", winCertificateFile: f.signing?.winCertificateFile ?? "" } } : { dir: v.dir })); + if (r) { await setView(r); toast(r.issues.some((i) => i.severity === "error") ? T("配置有错误,未生成文件", "Config has errors; files not generated") : T("已生成 desktop/ 目录", "Generated desktop/")); } +}; +const build = async (t: Target) => { const r = await busy(() => call("app_build", { dir: state.v!.dir, target: t }, 120_000)); if (r) await setView(r); }; +const showFile = async (f: string) => { state.file = f; state.fileText = (await call<{ text: string }>("app_file", { dir: state.v!.dir, file: f }).catch(() => ({ text: "" }))).text; render(); }; + +function field(label: string, input: HTMLElement, hint?: string) { return h("label", { class: "fld" }, h("span", { class: "lb" }, label), input, hint ? h("span", { class: "hint" }, hint) : null); } +function text(get: () => string | undefined, set: (s: string) => void, attrs: Record = {}) { return h("input", { value: get() ?? "", oninput: (e: Event) => set((e.target as HTMLInputElement).value), ...attrs }); } + +function render() { + applyTheme(); + const v = state.v; + if (!v) { + put(root, h("h1", {}, T("把项目做成桌面安装包", "Package a project as a desktop app")), + h("div", { class: "muted" }, T("选择工作区里的网站或 Node 项目:", "Choose a website or Node project in the workspace:")), + h("div", { class: "plist" }, ...state.projects.map((d) => h("button", { class: "proj", onclick: () => void choose(d) }, d === "." ? T("(工作区根目录)", "(workspace root)") : d))), + state.projects.length ? null : h("div", { class: "empty" }, T("没有找到含 package.json 或 index.html 的文件夹。", "No folder with package.json or index.html found."))); + return; + } + const d = v.detected, f = state.form; + const head = h("div", { class: "head" }, + state.icon ? h("img", { class: "icon", src: state.icon, alt: "icon" }) : h("div", { class: "icon none" }), + h("div", {}, h("div", { class: "title" }, f?.name ?? d.name, h("span", { class: "muted" }, ` ${f?.version ?? d.version}`)), + h("div", { class: "muted" }, `${v.dir} · ${d.kind === "static" ? T(`静态网站(${d.webDir})`, `static site (${d.webDir})`) : d.kind === "server" ? T(`Node 服务(${d.entry})`, `Node server (${d.entry})`) : T("未识别", "not recognised")}`)), + h("span", { class: "grow" }), + h("button", { onclick: () => { state.v = undefined; render(); } }, T("换项目", "Other project"))); + const notes = [...d.notes, ...(d.needsBuild ? [T(`还没有构建好的网站,请先运行 ${d.needsBuild}`, `No built site yet — run ${d.needsBuild} first`)] : [])]; + if (!f) { + put(root, head, ...notes.map((n) => h("div", { class: "note" }, n)), + h("div", { class: "card" }, T("将在项目里生成 desktop/ 目录:Electron 外壳、electron-builder.yml、图标和说明。默认目标是 macOS(dmg)和 Windows(nsis),不签名。", "Creates desktop/ in the project: Electron shell, electron-builder.yml, icon and README. Default targets: macOS (dmg) and Windows (nsis), unsigned."), + h("div", { class: "row" }, h("button", { class: "primary", onclick: () => void setup() }, T("生成桌面配置", "Generate desktop config"))))); + return; + } + const errors = v.issues.filter((i) => i.severity === "error"); + const form = h("div", { class: "card form" }, + h("div", { class: "cols" }, + field(T("名称", "Name"), text(() => f.name, (s) => (f.name = s))), + field(T("应用 ID", "App ID"), text(() => f.appId, (s) => (f.appId = s), { class: "appid" })), + field(T("版本", "Version"), text(() => f.version, (s) => (f.version = s), { class: "short" })), + field(T("窗口", "Window"), h("span", { class: "row tight" }, text(() => String(f.width), (s) => (f.width = Number(s) || 0), { class: "num" }), "×", text(() => String(f.height), (s) => (f.height = Number(s) || 0), { class: "num" }))), + f.mode === "static" ? field(T("网页目录", "Web folder"), text(() => f.webDir, (s) => (f.webDir = s), { class: "short" }), T("里面要有 index.html", "must contain index.html")) + : field(T("服务入口", "Server entry"), text(() => f.entry, (s) => (f.entry = s), { class: "short" }), f.usesPortEnv ? T("读取 PORT,自动选空闲端口", "reads PORT; a free port is used") : T(`固定端口 ${f.port ?? "?"}`, `fixed port ${f.port ?? "?"}`)), + field(T("图标", "Icon"), h("select", { class: "iconsel", onchange: (e: Event) => { f.icon = (e.target as HTMLSelectElement).value || undefined; } }, + h("option", { value: "", selected: !f.icon }, T("自动生成", "Generated")), ...d.icons.map((i) => h("option", { value: i.path, selected: f.icon === i.path }, `${i.path} (${i.width}px)`))))), + h("div", { class: "row" }, h("b", {}, T("目标:", "Targets: ")), ...(["dmg", "nsis", "appimage", "dir"] as Target[]).map((t) => h("label", { class: "chk" }, h("input", { type: "checkbox", "data-target": t, checked: f.targets.includes(t), onchange: (e: Event) => { f.targets = (e.target as HTMLInputElement).checked ? [...f.targets, t] : f.targets.filter((x) => x !== t); } }), TNAME[t][locale() === "zh" ? 0 : 1]))), + h("details", { class: "sign", open: !!(f.signing?.macIdentity || f.signing?.winCertificateFile) }, h("summary", {}, T("签名(可选,只用你自己的证书)", "Signing (optional, your own certificate only)")), + h("div", { class: "cols" }, + field(T("macOS 证书名称", "macOS identity"), text(() => f.signing?.macIdentity, (s) => (f.signing = { ...f.signing, macIdentity: s }), { placeholder: "Developer ID Application: Name (TEAMID)" })), + field(T("Windows 证书文件", "Windows certificate"), text(() => f.signing?.winCertificateFile, (s) => (f.signing = { ...f.signing, winCertificateFile: s }), { placeholder: "certs/code-signing.pfx" }))), + h("div", { class: "hint" }, T("不填就不签名。Windows 证书密码请放在环境变量 WIN_CSC_KEY_PASSWORD,插件不会保存密码。不做 Apple 公证。", "Leave empty to build unsigned. Put the Windows certificate password in the WIN_CSC_KEY_PASSWORD environment variable; it is never stored. No Apple notarization."))), + h("div", { class: "row" }, h("button", { class: "primary", onclick: () => void setup() }, T("保存并重新生成", "Save and regenerate")), + v.generated.length ? h("span", { class: "muted" }, T(`已生成:desktop/${v.generated.join("、desktop/")}`, `Generated: desktop/${v.generated.join(", desktop/")}`)) : null)); + const issues = v.issues.length ? h("div", { class: "issues" }, ...v.issues.map((i) => h("div", { class: `issue ${i.severity}` }, h("b", {}, FIELD[i.field] ? FIELD[i.field][locale() === "zh" ? 0 : 1] : i.field), " ", i.message))) : null; + const running = v.job?.state === "running"; + const matrix = h("div", { class: "card" }, h("b", {}, T(`在这台电脑上打包(${v.env.platform === "darwin" ? "macOS" : v.env.platform === "win32" ? "Windows" : "Linux"}${v.env.wine ? " + Wine" : ""})`, `Build on this computer (${v.env.platform}${v.env.wine ? " + Wine" : ""})`)), + h("table", { class: "data matrix" }, ...(["dmg", "nsis", "appimage", "dir"] as Target[]).map((t) => { + const b = v.env.targets[t]; + return h("tr", { class: f.targets.includes(t) ? "want" : "" }, h("td", {}, TNAME[t][locale() === "zh" ? 0 : 1], f.targets.includes(t) ? h("span", { class: "badge ok" }, T("已选", "selected")) : null), + h("td", { class: b.ok ? "okc" : "noc" }, b.ok ? T("✓ 可以在本机打包", "✓ can build here") : `✗ ${t === "dmg" ? T("需要在 Mac 上打包", "needs a Mac") : t === "nsis" ? T("需要 Windows,或安装 Wine", "needs Windows or Wine") : T("需要 Linux", "needs Linux")}`), + h("td", {}, h("button", { "data-build": t, disabled: !b.ok || running || errors.length > 0 || !v.generated.length, onclick: () => void build(t) }, T("打包", "Build")))); + })), + h("div", { class: "hint" }, T("首次打包会在 desktop/ 里 npm install(下载 Electron 约 150 MB)。不能在本机打的目标:把项目带到对应电脑,在 desktop/ 里运行 README 里的命令。", "The first build runs npm install in desktop/ (downloads Electron, ~150 MB). For targets this computer can't build, run the README command in desktop/ on that computer."))); + const job = v.job ? h("div", { class: "card job" }, + h("div", { class: "row" }, h("b", {}, T(`打包 ${v.job.target}`, `Build ${v.job.target}`)), + h("span", { class: `badge ${v.job.state === "done" ? "ok" : v.job.state === "failed" ? "bad" : ""}` }, v.job.state === "running" ? T(v.job.step === "install" ? "安装依赖中…" : "打包中…", v.job.step === "install" ? "installing…" : "building…") : v.job.state === "done" ? T("完成", "done") : T("失败", "failed")), + h("span", { class: "muted" }, `${Math.round(((v.job.ended ?? Date.now()) - v.job.started) / 1000)} s`)), + h("pre", { class: "log" }, v.job.log.slice(-60).join("\n"))) : null; + const outs = v.outputs.length ? h("div", { class: "card" }, h("b", {}, T("产物(desktop/release)", "Output (desktop/release)")), + ...v.outputs.map((o) => h("div", { class: "out" }, h("code", {}, `desktop/${o.path}`), h("span", { class: "muted" }, mb(o.size))))) : null; + const files = v.generated.length ? h("div", { class: "card" }, h("div", { class: "tbar" }, ...["electron-builder.yml", "main.cjs", "package.json", "README.md"].map((x) => h("button", { class: `tab${state.file === x ? " on" : ""}`, onclick: () => void showFile(x) }, x))), + h("pre", { class: "code" }, state.fileText ?? "")) : null; + put(root, head, ...notes.map((n) => h("div", { class: "note" }, n)), form, issues, h("div", { class: "split" }, h("div", {}, matrix, job, outs), files)); + const log = root.querySelector("pre.log"); + if (log) log.scrollTop = log.scrollHeight; +} + +onHostContext(() => render()); +render(); +void initHost("app-installer-builder", "0.1.0").then(async () => { + state.projects = (await call<{ dirs: string[] }>("app_projects").catch(() => ({ dirs: [] }))).dirs; + const st = await call>("app_state", {}).catch(() => undefined); + if (st?.kind === "app") await setView(st as unknown as View); else render(); +}); diff --git a/ui-plugins/app-installer-builder/ui/panel.css b/ui-plugins/app-installer-builder/ui/panel.css new file mode 100644 index 00000000..edddceb3 --- /dev/null +++ b/ui-plugins/app-installer-builder/ui/panel.css @@ -0,0 +1,25 @@ +.head { display:flex; gap:12px; align-items:center; margin-bottom:8px; } +.head .icon { width:56px; height:56px; border-radius:12px; object-fit:contain; } +.head .icon.none { background: var(--panel); border:1px dashed var(--line); } +.head .title { font-size:16px; font-weight:600; } +.grow { flex:1; } +.plist { display:flex; flex-wrap:wrap; gap:8px; margin:10px 0; } .proj { font-family: ui-monospace, monospace; } +.note { background: var(--warnbg); color: var(--warn); padding:6px 10px; border-radius:6px; margin:4px 0; font-size:12px; } +.cols { display:grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap:8px 14px; } +.fld { flex-direction:column; align-items:stretch; gap:2px; } +.fld .lb { font-size:12px; color: var(--muted); } +.fld input, .fld select { width:100%; } +.fld .num { width:70px; } .row.tight { margin:0; gap:4px; flex-wrap:nowrap; } +.hint { font-size:11px; color: var(--muted); } +.chk { margin-right:10px; } +details.sign { margin:8px 0; } details.sign summary { cursor:pointer; font-weight:600; margin-bottom:6px; } +.issues { margin:6px 0; } +.issue { font-size:12px; margin:2px 0; } .issue.error b { color: var(--bad); } .issue.warning b { color: var(--warn); } .issue.info b { color: var(--muted); } +.matrix td { vertical-align: middle; } .matrix tr.want td:first-child { font-weight:600; } +.matrix .badge { margin-left:6px; } .okc { color: var(--ok); } .noc { color: var(--muted); } +pre.log { max-height: 240px; overflow:auto; background:#111827; color:#d1d5db; padding:8px; border-radius:6px; font-size:11px; white-space:pre-wrap; margin:6px 0 0; } +pre.code { max-height: 420px; overflow:auto; background: var(--bg); padding:8px; border-radius:6px; font-size:11.5px; margin:0; white-space:pre; } +.out { display:flex; justify-content:space-between; gap:8px; margin:4px 0; font-size:12px; } +.tbar { display:flex; gap:4px; flex-wrap:wrap; margin-bottom:6px; } +.tab { border:none; border-bottom:2px solid transparent; border-radius:0; background:none; font-size:12px; } +.tab.on { border-bottom-color: var(--accent); color: var(--accent); } diff --git a/ui-plugins/app-installer-builder/vitest.config.ts b/ui-plugins/app-installer-builder/vitest.config.ts new file mode 100644 index 00000000..27153a26 --- /dev/null +++ b/ui-plugins/app-installer-builder/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 } });