From 039fcf4f92eac1c33a1d1b4059787f0a5ccf0340 Mon Sep 17 00:00:00 2001 From: tanranran Date: Thu, 26 Nov 2026 14:00:06 +0800 Subject: [PATCH 1/2] =?UTF-8?q?docs(install):=20README=20=E5=AE=89?= =?UTF-8?q?=E8=A3=85=E6=96=87=E6=A1=88=E5=86=99=E6=88=90=E8=87=AA=E5=8C=85?= =?UTF-8?q?=E5=90=AB=E7=9A=84=E4=B8=89=E6=AD=A5=E5=91=BD=E4=BB=A4=EF=BC=8C?= =?UTF-8?q?=E4=BB=A3=E7=90=86=E4=B8=8D=E5=86=8D=E6=91=B8=E7=B4=A2=E5=AE=89?= =?UTF-8?q?=E8=A3=85=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 文案写明宿主命令行的调用方式(ELECTRON_RUN_AS_NODE=1 + ZCode 可执行文件 + resources/glm/zcode.cjs)、 添加市场与安装插件两条 plugins 子命令(--json)、GitHub 失败自动换 GitCode 地址、 安装器脚本的调用方式(installPath 取自安装输出)、完全退出的重启措辞与失败时原样转述 - 三份 README 同步;用户指南补「对话安装时实际执行的步骤」;文档规则写入「安装文案必须自包含」 - tests/test_install_prompt_contract.py:锁定三份 README 的安装文案包含实跑脚本用的每一条命令, 且不再把执行方式留给代理摸索 - tests/install-prompt-smoke.py(macOS,联网):在隔离的临时环境里按文案实跑一遍并逐步计时 为什么:宿主不提供单独的 zcode 命令,也不给代理任何安装插件的指引;旧文案只给地址并让代理 「执行 /install-overlay」,而插件刚装好时当前会话里还没有这条命令,代理只能自行摸索。 --- .zcode/rules/docs.md | 1 + AGENTS.md | 2 +- README.en.md | 18 ++- README.md | 18 ++- README.zh-CN.md | 18 ++- docs/user-guide.md | 10 ++ tests/README.md | 10 ++ tests/install-prompt-smoke.py | 184 ++++++++++++++++++++++++++ tests/test_install_prompt_contract.py | 68 ++++++++++ 9 files changed, 310 insertions(+), 19 deletions(-) create mode 100644 tests/install-prompt-smoke.py create mode 100644 tests/test_install_prompt_contract.py diff --git a/.zcode/rules/docs.md b/.zcode/rules/docs.md index 4f1175ab2..433a312a2 100644 --- a/.zcode/rules/docs.md +++ b/.zcode/rules/docs.md @@ -17,6 +17,7 @@ - 差异化卖点=上下文占比 + 中英双语 + 首屏截图三条守住,不拼竞品功能清单。 - 逐问速率行的标签(`token_rate.py format_turn_line`)不分语言恒中文(硬编码无 locale 分支,英文宣传图里速率行是手写演示文案,已知产品限制);`overlay.js` 自身 `L()` 双语可在布景页 `localStorage.setItem("zusage3.lang","en")` 取真实英文文案,不手写翻译。 - 市场条目保留 `description_i18n`;门面显示名「速度状态栏」与市场 UI 显示的 slug 派生名("ZCode Token Usage Statusbar")不一致**刻意保留**——slug、市场名、命令、配置键、仓库/安装指引里的英文名都不擅改(受插件市场 UI 名约束,真改是破坏性工程)。README 安装指引中的英文名是市场实际显示名,不能翻译。 +- **README 安装文案必须自包含**(`tests/test_install_prompt_contract.py` 锁定):宿主不提供单独的 `zcode` 命令,也不给代理任何「怎么装插件」的指引(引擎里没有面向模型的添加市场说明,`SearchPlugins`/`SuggestPluginInstall` 只覆盖官方市场,本插件不在其中),代理只能靠文案本身。只给地址、或只说「执行 /install-overlay」时,代理得自己摸索调用方式(插件刚装好时当前会话里还没有这条命令)。文案须写明:命令行调用方式(`ELECTRON_RUN_AS_NODE=1` + ZCode 可执行文件 + `resources/glm/zcode.cjs`)、两条 `plugins` 子命令及 `--json`、GitHub 失败自动换带 `.git` 的 GitCode 地址、安装器脚本的调用路径(`installPath` 取自安装输出)、完全退出的重启措辞与失败时原样转述。改文案里的命令后跑 `python3 -B tests/install-prompt-smoke.py`(macOS,联网)确认全新环境仍装得上;两步安装之外不要塞进与安装无关的内容。 - GitHub 默认仓库搜索只匹配 name+description+topics(README 需 `in:readme`)——辨识度关键词写 Description/Topics 而非正文堆同义词;topics ≤20、仅小写字母数字连字符、≤50 字符、不加竞品名不凑满。远端写入(Description/Topics/README)后 `gh api` 回读确认。 ## 3. 宣传图与 tour 截图(docs/promo、docs/tour) diff --git a/AGENTS.md b/AGENTS.md index 965c69812..fa374851e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -233,7 +233,7 @@ python3 sync_plugin.py --check | 桥/SSH 路由 | `test_renderer_bridge.py`、`test_bridge_pending.py`、`test_remote_targets.py`、`test_serve_stdio.py`、`inject-remote-recovery.test.cjs`、`overlay-remote-scope.test.cjs`;实机身份/重连与认证另验 | | 安装/更新/锁/解包 | `test_install_discovery.py`、`test_plugin_sudo_install.py`、`test_pending_asar.py`、`test_quiet_monitor.py`、`test_pending_zip_patch.py`、`test_config_transactions.py`、`test_plugin_upgrade.py`、`test_runtime_sync_guard.py`、`test_release*.py` 及 `plugin-*.test.cjs`、`runtime-lock.test.cjs`、`test_runtime_lock_windows.py` | | 插件命令/hooks/MCP | `test_command_frontmatter.py`、`test_plugin_contract.py`、`test_usage_mcp_stdio.py`(MCP 直启的 stdio 帧契约)、`test_plugin_package.py`、`test_plugin_runtime.py`、`test_session_start_channels.py`、`test_restart_notice.py`、`test_zusage_doctor.py`(体检命令)、`test_test_file_layout.py`(测试文件布局契约,新增测试文件后必跑);共享文件同时同步并检查漂移 | -| 文档/本地化 | 路径、相对链接/锚点、JSON 示例、双语对应与 manifest 一致性;涉及默认值/协议时加对应契约测试 | +| 文档/本地化 | 路径、相对链接/锚点、JSON 示例、双语对应与 manifest 一致性;涉及默认值/协议时加对应契约测试;README 安装文案的自包含契约见 `test_install_prompt_contract.py`(文案里的命令须与 `install-prompt-smoke.py` 实跑的一致) | 宿主真实 CLI 沙箱测试和交互演示见 [测试说明](tests/README.md)。它们使用真实 ZCode、认证和模型,可能联网/消耗 token,不属于默认纯隔离测试;测试对象必须指向自有临时 HOME、插件库存与夹具。 真实桌面安装会改客户端文件;默认回归不得接触个人数据库、配置、真实插件库存或客户端。语法通过、手工 hook 成功、Windows 收尾夹具通过均不能替代自然 SessionStart/重启/多窗口/远端实机证据。 diff --git a/README.en.md b/README.en.md index f78510cde..a78c7dc41 100644 --- a/README.en.md +++ b/README.en.md @@ -29,16 +29,22 @@ Promotional image with staged UI and demonstration data; the actual interface va ### Installation -Send this to ZCode to install or update the plugin (when GitHub is unreachable it retries through the mirror on its own, so you do not have to send anything again): +Send this to ZCode to install or update the plugin. The message spells out every command, so ZCode does not have to work out how to install on its own; when GitHub is unreachable it retries through the mirror by itself, so you do not have to send anything again: ```text -Please install or update and enable this ZCode plugin: https://github.com/ByteRax/zcode-token-usage-statusbar#plugin-releases -If GitHub is unreachable, retry with https://gitcode.com/tanranran/zcode-token-usage-statusbar.git#plugin-releases-gitcode on your own; do not ask me again. -Then run /install-overlay in the ZCode chat. Once you confirm the status bar installation succeeded, remind me to quit ZCode completely and reopen it (closing the window is not enough); do not restart it automatically. -If installation fails, explain why. If you cannot run the command in the current session, ask me to run it manually; do not skip this step or claim installation succeeded. +Please install or update the ZCode plugin zcode-token-usage-statusbar. Follow the three steps below exactly and do not look for another installation method: + +1. Add the marketplace and install the plugin with ZCode's own command line. There is no separate zcode command: set the environment variable ELECTRON_RUN_AS_NODE=1, run the ZCode executable, and pass resources/glm/zcode.cjs from the installation directory as its first argument. On macOS the defaults are /Applications/ZCode.app/Contents/MacOS/ZCode and /Applications/ZCode.app/Contents/Resources/glm/zcode.cjs. On Windows ZCode.exe and resources\glm\zcode.cjs sit in the same installation directory; when it is not in the default location, find the running ZCode.exe with (Get-Process ZCode).Path in PowerShell. Run these two commands in that command line, in order: + plugins marketplace add "https://github.com/ByteRax/zcode-token-usage-statusbar#plugin-releases" --json + plugins install "zcode-token-usage-statusbar@zusage-marketplace" --scope user --json + If the first one fails (usually because GitHub is unreachable), retry with the address https://gitcode.com/tanranran/zcode-token-usage-statusbar.git#plugin-releases-gitcode instead; do not ask me again. +2. Run python3 "/overlay_install.py" install (on Windows, if python3 is unavailable, try python and then py -3). +3. Report step 2's output to me: when it asks for a restart, remind me to quit ZCode completely (from the menu or the tray; closing the window is not enough) and reopen it; do not restart it automatically. + +If any step fails, relay the error as is; do not skip it and do not claim installation succeeded. ``` -Keep `#plugin-releases` and `.git#plugin-releases-gitcode` in the URLs: they select the project's stable release channels. The mirror route needs local [Git](https://git-scm.com/downloads) (the host fetches the channel manifest through git), and the `.git` suffix cannot be dropped: the host treats only URLs ending in `.git` as repository sources and would otherwise download the page as if it were the manifest. +Keep `#plugin-releases` and `.git#plugin-releases-gitcode` in the URLs: they select the project's stable release channels. The mirror route needs local [Git](https://git-scm.com/downloads), and the `.git` suffix cannot be dropped: the host treats only URLs ending in `.git` as repository sources and would otherwise download the page as if it were the manifest. > **Important:** installing the bar modifies ZCode's program files (`app.asar`), so proceed only if you trust the project. **After the first successful injection, quit ZCode completely and reopen it** (closing the window or reopening a session is not enough), then check that the bar appears. If installation fails or permissions are insufficient, diagnose that first; restarting does not replace installation. diff --git a/README.md b/README.md index 6506ff1c1..2ca8411e6 100644 --- a/README.md +++ b/README.md @@ -31,16 +31,22 @@ A community toolkit for ZCode desktop: generation speed, token usage, context tr ### 安装方法 -把下面这段话发给 ZCode,安装或更新插件(GitHub 连不上时,它会自动改用国内源重试,不用你再发一次): +把下面这段话发给 ZCode,安装或更新插件。文案把要执行的命令都写明了,ZCode 不需要自己摸索安装方式;GitHub 连不上时它会自动改用国内源重试,不用你再发一次: ```text -请安装或更新并启用 ZCode 插件:https://github.com/ByteRax/zcode-token-usage-statusbar#plugin-releases -GitHub 连不上时,自动改用 https://gitcode.com/tanranran/zcode-token-usage-statusbar.git#plugin-releases-gitcode 重试,不用再问我。 -完成后,在 ZCode 对话中执行 /install-overlay;确认状态条安装成功后,提醒我完全退出并重新打开 ZCode(仅关闭窗口不算),不要自动重启。 -若安装失败,请说明原因;若当前会话无法执行该命令,请提示我手动执行,不要跳过这一步或声称安装成功。 +请安装或更新 ZCode 插件 zcode-token-usage-statusbar,严格按下面三步做,不要另找安装方式: + +1. 用 ZCode 自带的命令行添加市场并安装插件。调用方法:先设置环境变量 ELECTRON_RUN_AS_NODE=1,再运行 ZCode 的可执行文件,把安装目录里的 resources/glm/zcode.cjs 作为第一个参数。macOS 默认是 /Applications/ZCode.app/Contents/MacOS/ZCode 和 /Applications/ZCode.app/Contents/Resources/glm/zcode.cjs;Windows 上 ZCode.exe 与 resources\glm\zcode.cjs 在同一个安装目录,位置不固定时用 PowerShell 的 (Get-Process ZCode).Path 查到正在运行的 ZCode.exe。在这个命令行里依次执行: + plugins marketplace add "https://github.com/ByteRax/zcode-token-usage-statusbar#plugin-releases" --json + plugins install "zcode-token-usage-statusbar@zusage-marketplace" --scope user --json + 第一条失败时(多半是 GitHub 连不上),把地址换成 https://gitcode.com/tanranran/zcode-token-usage-statusbar.git#plugin-releases-gitcode 重试,不用再问我。 +2. 运行 python3 "<第 1 步第二条命令输出里的 installPath>/overlay_install.py" install(Windows 上 python3 不可用就依次换 python、py -3)。 +3. 按第 2 步的输出提醒我:出现重启提醒时,提醒我完全退出 ZCode(从菜单或托盘退出,只关窗口不算)再重新打开;不要自动重启。 + +任何一步失败都原样转述错误,不要跳过,也不要声称安装成功。 ``` -保留地址里的 `#plugin-releases` 与 `.git#plugin-releases-gitcode`,它们选择正式发布的稳定渠道。国内源要求本机装有 [Git](https://git-scm.com/downloads)(宿主通过 git 拉取渠道清单),而且地址里的 `.git` 不能省:宿主只把以 `.git` 结尾的地址当作仓库来源,否则会把它当成清单文件的直链去下载。 +两个地址里的 `#plugin-releases` 与 `.git#plugin-releases-gitcode` 选择正式发布的稳定渠道,保持原样。国内源要求本机装有 [Git](https://git-scm.com/downloads),而且地址里的 `.git` 不能省:宿主只把以 `.git` 结尾的地址当作仓库来源,否则会把它当成清单文件的直链去下载。 > **注意**:状态条安装会修改 ZCode 的程序文件(`app.asar`),请先确认信任本项目。**首次注入成功后,须完全退出并重开 ZCode**(仅关闭窗口或重开会话不算),再检查状态条是否出现;安装失败或权限不足时,先排查原因,重启不能替代安装。 diff --git a/README.zh-CN.md b/README.zh-CN.md index 6506ff1c1..2ca8411e6 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -31,16 +31,22 @@ A community toolkit for ZCode desktop: generation speed, token usage, context tr ### 安装方法 -把下面这段话发给 ZCode,安装或更新插件(GitHub 连不上时,它会自动改用国内源重试,不用你再发一次): +把下面这段话发给 ZCode,安装或更新插件。文案把要执行的命令都写明了,ZCode 不需要自己摸索安装方式;GitHub 连不上时它会自动改用国内源重试,不用你再发一次: ```text -请安装或更新并启用 ZCode 插件:https://github.com/ByteRax/zcode-token-usage-statusbar#plugin-releases -GitHub 连不上时,自动改用 https://gitcode.com/tanranran/zcode-token-usage-statusbar.git#plugin-releases-gitcode 重试,不用再问我。 -完成后,在 ZCode 对话中执行 /install-overlay;确认状态条安装成功后,提醒我完全退出并重新打开 ZCode(仅关闭窗口不算),不要自动重启。 -若安装失败,请说明原因;若当前会话无法执行该命令,请提示我手动执行,不要跳过这一步或声称安装成功。 +请安装或更新 ZCode 插件 zcode-token-usage-statusbar,严格按下面三步做,不要另找安装方式: + +1. 用 ZCode 自带的命令行添加市场并安装插件。调用方法:先设置环境变量 ELECTRON_RUN_AS_NODE=1,再运行 ZCode 的可执行文件,把安装目录里的 resources/glm/zcode.cjs 作为第一个参数。macOS 默认是 /Applications/ZCode.app/Contents/MacOS/ZCode 和 /Applications/ZCode.app/Contents/Resources/glm/zcode.cjs;Windows 上 ZCode.exe 与 resources\glm\zcode.cjs 在同一个安装目录,位置不固定时用 PowerShell 的 (Get-Process ZCode).Path 查到正在运行的 ZCode.exe。在这个命令行里依次执行: + plugins marketplace add "https://github.com/ByteRax/zcode-token-usage-statusbar#plugin-releases" --json + plugins install "zcode-token-usage-statusbar@zusage-marketplace" --scope user --json + 第一条失败时(多半是 GitHub 连不上),把地址换成 https://gitcode.com/tanranran/zcode-token-usage-statusbar.git#plugin-releases-gitcode 重试,不用再问我。 +2. 运行 python3 "<第 1 步第二条命令输出里的 installPath>/overlay_install.py" install(Windows 上 python3 不可用就依次换 python、py -3)。 +3. 按第 2 步的输出提醒我:出现重启提醒时,提醒我完全退出 ZCode(从菜单或托盘退出,只关窗口不算)再重新打开;不要自动重启。 + +任何一步失败都原样转述错误,不要跳过,也不要声称安装成功。 ``` -保留地址里的 `#plugin-releases` 与 `.git#plugin-releases-gitcode`,它们选择正式发布的稳定渠道。国内源要求本机装有 [Git](https://git-scm.com/downloads)(宿主通过 git 拉取渠道清单),而且地址里的 `.git` 不能省:宿主只把以 `.git` 结尾的地址当作仓库来源,否则会把它当成清单文件的直链去下载。 +两个地址里的 `#plugin-releases` 与 `.git#plugin-releases-gitcode` 选择正式发布的稳定渠道,保持原样。国内源要求本机装有 [Git](https://git-scm.com/downloads),而且地址里的 `.git` 不能省:宿主只把以 `.git` 结尾的地址当作仓库来源,否则会把它当成清单文件的直链去下载。 > **注意**:状态条安装会修改 ZCode 的程序文件(`app.asar`),请先确认信任本项目。**首次注入成功后,须完全退出并重开 ZCode**(仅关闭窗口或重开会话不算),再检查状态条是否出现;安装失败或权限不足时,先排查原因,重启不能替代安装。 diff --git a/docs/user-guide.md b/docs/user-guide.md index 6f1daf621..fc4bf1f3d 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -44,6 +44,16 @@ https://gitcode.com/tanranran/zcode-token-usage-statusbar.git#plugin-releases-gi 此渠道从经过校验的正式 Release ZIP 安装插件,不跟随开发分支,也不需要自己下载源码。当前正式版自动安装/修复状态条(始终开启,旧自动安装开关配置只保留不再读取);成功后完全退出并重开;不需要状态条时用 `/uninstall-overlay` 移除并阻止自动重注入。 +### 对话安装时实际执行的步骤 + +README 的安装文案把命令写明了,ZCode 不必自己摸索。想手动走同一条路,或排查看它卡在哪一步时,步骤如下: + +1. 添加市场并安装插件:设置环境变量 `ELECTRON_RUN_AS_NODE=1`,运行 ZCode 的可执行文件并把安装目录里的 `resources/glm/zcode.cjs` 作为第一个参数,依次执行 `plugins marketplace add "<渠道地址>" --json` 和 `plugins install "zcode-token-usage-statusbar@zusage-marketplace" --scope user --json`。已装用户重复执行第一条就是刷新市场。 +2. 运行 `python3 "<上一步输出里的 installPath>/overlay_install.py" install`。插件刚装好时当前会话里还没有 `/install-overlay` 命令,所以这一步直接运行脚本。 +3. 完全退出 ZCode 后重新打开。 + +国内源地址必须带 `.git`:宿主只把以 `.git` 结尾的地址当作仓库来源,否则会把它当成清单文件的直链去下载。 + ### 方式二:本地目录安装 从 [ByteRax 仓库](https://github.com/ByteRax/zcode-token-usage-statusbar) 下载或克隆源码后: diff --git a/tests/README.md b/tests/README.md index 73da20d41..f3b4ed3de 100644 --- a/tests/README.md +++ b/tests/README.md @@ -64,6 +64,16 @@ python3 -B tests/plugin-commands-cli-smoke.py `plugin-commands-cli-smoke.py` 使用真实客户端 CLI 和临时 bundle 副本,验证三个裸名命令的 list/inspect、实际协议命令目录与纯文本参数展开,旧插件前缀名明确 not-found;还验证旧聊天安装/更新子命令只返回 Usage,以及短 MCP 服务键对应的模型工具名。只复制清单、命令和被测分派代码,不复制或运行 hook/安装器;不启动模型、NDJSON 会话或 UI,因此不是界面端到端测试。bundle 结构改变时会明确失败,不退回模拟实现。 +## 安装文案冒烟(macOS,联网) + +```bash +python3 -B tests/install-prompt-smoke.py github # 或 gitcode +``` + +需要已安装 `/Applications/ZCode.app`、macOS 自带 `sandbox-exec` 和网络。脚本在临时目录里模拟一台全新机器(独立 HOME;真实 HOME、仓库与任何 asar 不可读,临时目录外不可写,执行前先用探针证明隔离成立),按 README 安装文案里的命令原样走一遍:添加市场、安装插件、运行安装器,最后核对插件登记与状态条注入,并输出每一步的耗时。状态条注入打到临时目录里的假归档上,不触碰真实客户端。不调用模型、不读取凭据;它量的是「代理照做即可」的确定性部分,代理自己摸索的时间不在其中。 + +文案与脚本的一致性由默认回归 `test_install_prompt_contract.py` 锁定:三份 README 的安装文案必须包含脚本实跑的每一条命令。改动文案里的命令后,先跑本脚本确认在全新环境里仍然装得上。 + ## 速度格实机量宽探针 ```bash diff --git a/tests/install-prompt-smoke.py b/tests/install-prompt-smoke.py new file mode 100644 index 000000000..5952a6d6d --- /dev/null +++ b/tests/install-prompt-smoke.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +"""README 安装文案的实跑冒烟(macOS,联网):在隔离的临时环境里按文案写明的命令装一遍并逐步计时。 + +宿主不提供单独的 zcode 命令,也不给代理任何「怎么装插件」的指引,README 的安装文案因此必须自包含。 +本脚本把文案里的命令原样跑一遍:先证明隔离成立(真实 HOME 与仓库不可读,临时目录外不可写), +再执行「添加市场 → 安装插件 → 运行安装器」,最后核对插件登记与状态条注入。状态条注入打到临时 +目录里的假归档上(经 ZCODE_ASAR 指给安装器),不触碰真实客户端。不调用模型、不读取任何凭据。 + +用法:python3 -B tests/install-prompt-smoke.py [github|gitcode] +""" +import json +import os +import shlex +import signal +import struct +import subprocess +import sys +import tempfile +import time +from pathlib import Path + +EXECUTABLE = Path("/Applications/ZCode.app/Contents/MacOS/ZCode") +BUNDLE = Path("/Applications/ZCode.app/Contents/Resources/glm/zcode.cjs") +SANDBOX = Path("/usr/bin/sandbox-exec") +REPOSITORY = Path(__file__).resolve().parents[1] +PLUGIN = "zcode-token-usage-statusbar" +PLUGIN_ID = PLUGIN + "@zusage-marketplace" +# 与 README 安装文案逐字一致(tests/test_install_prompt_contract.py 锁定) +CHANNELS = { + "github": "https://github.com/ByteRax/zcode-token-usage-statusbar#plugin-releases", + "gitcode": "https://gitcode.com/tanranran/zcode-token-usage-statusbar.git#plugin-releases-gitcode", +} +ADD_COMMAND = 'plugins marketplace add "%s" --json' +INSTALL_COMMAND = 'plugins install "%s" --scope user --json' % PLUGIN_ID +OVERLAY_COMMAND = 'python3 "%s/overlay_install.py" install' +TIMEOUT = 300 + + +def require(condition, message): + if not condition: + raise AssertionError(message) + + +def write_fake_asar(path): + """微型合法 asar:包身份是 ZCode 桌面端,安装器会把它当成客户端。""" + files = {"package.json": json.dumps({"name": "@zcode/desktop", "version": "0.0.0", + "type": "module"}).encode(), + "out/main/index.js": b"console.log('fake ZCode desktop entry');\n"} + header, payload = {"files": {}}, bytearray() + for name, data in files.items(): + parent = header + parts = [part for part in name.split("/") if part] + for part in parts[:-1]: + parent = parent["files"].setdefault(part, {"files": {}}) + parent["files"][parts[-1]] = {"offset": str(len(payload)), "size": len(data)} + payload.extend(data) + raw = json.dumps(header, separators=(",", ":")).encode() + aligned = (len(raw) + 7) // 4 * 4 + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(struct.pack("<4I", 4, aligned + 4, aligned, len(raw)) + raw + + b"\0" * (aligned - len(raw) - 4) + payload) + + +class FreshMachine: + """临时目录里的「全新机器」:独立 HOME,只能写临时目录,真实 HOME、仓库与任何 asar 不可读。""" + + def __init__(self, parent): + self.root = parent / "machine" + self.home = self.root / "home" + self.cwd = self.root / "cwd" + for directory in (self.home, self.cwd, self.root / "tmp"): + directory.mkdir(parents=True) + self.asar = self.root / "client" / "resources" / "app.asar" + write_fake_asar(self.asar) + self.real_home = Path.home().resolve() + require(self.inside(self.root), "临时目录不能位于真实 HOME 或仓库内") + self.env = { + "HOME": str(self.home), "USERPROFILE": str(self.home), "ELECTRON_RUN_AS_NODE": "1", + "ZCODE_STORAGE_DIR": str(self.home / ".zcode"), "ZCODE_DATA_BASE_DIR": str(self.home), + "ZCODE_SESSION_DB_PATH": str(self.home / ".zcode" / "cli" / "db" / "db.sqlite"), + "ZCODE_LOG_DIR": str(self.home / ".zcode" / "cli" / "log"), + "ZCODE_ASAR": str(self.asar), "TMPDIR": str(self.root / "tmp"), + # 安装器用当前这个解释器跑(系统 python3 可能是没有命令行工具的存根) + "PATH": "%s:/usr/bin:/bin:/usr/sbin:/sbin" % shlex.quote(os.path.dirname(sys.executable)), + "LANG": "zh_CN.UTF-8", "PYTHONDONTWRITEBYTECODE": "1", + } + quote = json.dumps + self.profile = "\n".join([ + "(version 1)", + "(allow default)", + "(deny file-write*)", + '(allow file-write* (subpath %s) (literal "/dev/null"))' % quote(str(self.root)), + "(deny file-read* (subpath %s) (subpath %s))" % (quote(str(self.real_home)), quote(str(REPOSITORY))), + '(deny file-read* (regex #"\\.asar($|/)"))', + "(allow file-read* (literal %s))" % quote(str(self.asar)), + ]) + + def inside(self, value): + path = Path(value) + try: + path.resolve().relative_to(self.root) + return True + except (ValueError, OSError, RuntimeError): + return False + + def run(self, argv, timeout=TIMEOUT): + command = [str(SANDBOX), "-p", self.profile, *map(str, argv)] + started = time.time() + with subprocess.Popen(command, cwd=self.cwd, env=self.env, stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + start_new_session=True) as process: + try: + stdout, stderr = process.communicate(timeout=timeout) + except BaseException: + # 超时/中断:先清理整组子进程,之后 TemporaryDirectory 才删除状态。 + os.killpg(process.pid, signal.SIGKILL) + process.communicate() + raise + return process.returncode, round(time.time() - started, 2), stdout, stderr + + def isolate(self): + """先证明隔离成立,再执行任何会联网、写盘的命令。探针不接管道,免得退出码被末端命令顶掉。""" + real = shlex.quote(str(self.real_home)) + probes = ( + ("write real home", "touch %s/.zusage-smoke-probe" % real, False), + ("write client", "touch /Applications/ZCode.app/.zusage-smoke-probe", False), + ("write client archive", "touch /Applications/ZCode.app/Contents/Resources/app.asar", False), + ("read real home", "ls %s" % real, False), + ("read repository", "ls %s" % shlex.quote(str(REPOSITORY)), False), + ("write sandbox", "touch %s/ok" % shlex.quote(str(self.root / "tmp")), True), + ) + for label, script, expected in probes: + code, _, _, error = self.run(["/bin/sh", "-c", script], timeout=30) + require((code == 0) is expected, "隔离不成立(%s):exit=%s %s" % (label, code, error.strip()[:160])) + + def audit(self): + """登记里的任何路径都必须落在临时目录里:沙箱外的位置根本写不进去,这里再核一遍。""" + for name in ("installed_plugins.json", "known_marketplaces.json"): + path = self.home / ".zcode" / "cli" / "plugins" / name + if not path.exists(): + continue + data = json.loads(path.read_text(encoding="utf-8")) + for row in data.get("plugins", data.get("marketplaces", [])): + for key in ("installPath", "cachePath", "path"): + if row.get(key): + require(self.inside(row[key]), "登记路径越过临时目录: " + str(row[key])) + + +def install_as_documented(machine, variant): + """按 README 文案的三步执行,返回逐步耗时。命令经 shlex.split 原样变成参数,不经 shell 二次解释。""" + steps = {} + for label, command in (("marketplace add", ADD_COMMAND % CHANNELS[variant]), ("plugin install", INSTALL_COMMAND)): + code, seconds, stdout, stderr = machine.run([EXECUTABLE, BUNDLE, *shlex.split(command)]) + steps[label] = seconds + require(code == 0, "%s 失败(exit=%s):%s%s" % (label, code, stdout.strip()[-300:], stderr.strip()[-300:])) + if label == "plugin install": + installed = json.loads(stdout)["installed"] + require(len(installed) == 1 and installed[0].get("id") == PLUGIN_ID, "安装记录不是本插件: " + stdout[-300:]) + install_path = Path(installed[0]["installPath"]) + code, seconds, stdout, stderr = machine.run(shlex.split(OVERLAY_COMMAND % str(install_path))) + steps["overlay install"] = seconds + require(code == 0, "安装器失败(exit=%s):%s%s" % (code, stdout.strip()[-400:], stderr.strip()[-400:])) + require(b"inject-main.cjs" in machine.asar.read_bytes(), "状态条没有注入到假归档") + require((machine.home / ".zcode" / PLUGIN).is_dir(), "运行目录没有创建") + require("完全退出" in stdout, "安装器没有给出完全退出的重启提醒") + return dict(steps, variant=variant, version=installed[0].get("version")) + + +def main(argv=None): + require(sys.platform == "darwin" and SANDBOX.is_file() and EXECUTABLE.is_file() and BUNDLE.is_file(), + "仅支持带系统 sandbox-exec 的 macOS 与默认位置安装的 /Applications/ZCode.app;不进行无沙箱回退") + variant = (argv or ["github"])[0] + require(variant in CHANNELS, "unknown variant: " + variant) + with tempfile.TemporaryDirectory(prefix="zusage-install-smoke-") as temporary: + machine = FreshMachine(Path(temporary).resolve()) + machine.isolate() + result = install_as_documented(machine, variant) + machine.audit() + print(json.dumps(result, ensure_ascii=False, indent=1)) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/tests/test_install_prompt_contract.py b/tests/test_install_prompt_contract.py new file mode 100644 index 000000000..d139b6329 --- /dev/null +++ b/tests/test_install_prompt_contract.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- +"""README 安装文案的自包含契约。 + +宿主不提供单独的 zcode 命令,也不给代理任何「怎么装插件」的指引,代理只能靠文案本身。 +这里锁定三份 README 的安装文案包含 tests/install-prompt-smoke.py 实跑的每一条命令, +并且不再把「怎么执行安装」留给代理自己摸索。 +""" +from pathlib import Path +import sys +import unittest + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from tests.helpers.py_test_support import load_module # noqa: E402 + +SMOKE = load_module("install_prompt_smoke_contract", ROOT / "tests" / "install-prompt-smoke.py") +README = ("README.md", "README.zh-CN.md", "README.en.md") + + +def install_prompt(name): + """每个 README 里第一个 text 代码块就是安装文案。""" + return (ROOT / name).read_text(encoding="utf-8").split("```text", 2)[1] + + +class InstallPromptContractTests(unittest.TestCase): + def test_chinese_readmes_stay_identical(self): + self.assertEqual((ROOT / "README.md").read_bytes(), (ROOT / "README.zh-CN.md").read_bytes()) + + def test_prompt_contains_every_command_the_smoke_runs(self): + needles = ( + "ELECTRON_RUN_AS_NODE=1", + "resources/glm/zcode.cjs", + SMOKE.ADD_COMMAND % SMOKE.CHANNELS["github"], + SMOKE.INSTALL_COMMAND, + SMOKE.CHANNELS["gitcode"], + '/overlay_install.py" install', + ) + for name in README: + with self.subTest(readme=name): + prompt = install_prompt(name) + for needle in needles: + self.assertIn(needle, prompt, "%s 的安装文案缺少:%s" % (name, needle)) + + def test_prompt_spells_out_the_overlay_instead_of_naming_a_command(self): + # 旧文案只说「在对话中执行 /install-overlay」:插件刚装好时当前会话里还没有这条命令, + # 代理只能自行摸索。新文案直接给出安装器脚本的调用方式。 + for name in README: + with self.subTest(readme=name): + prompt = install_prompt(name) + self.assertNotIn("/install-overlay", prompt) + self.assertIn("installPath", prompt) + + def test_prompt_asks_for_a_full_quit_and_forbids_silent_skips(self): + expectations = { + "README.md": ("完全退出", "不要自动重启", "原样转述错误", "声称安装成功"), + "README.zh-CN.md": ("完全退出", "不要自动重启", "原样转述错误", "声称安装成功"), + "README.en.md": ("quit ZCode completely", "do not restart it automatically", + "relay the error as is", "claim installation succeeded"), + } + for name, needles in expectations.items(): + with self.subTest(readme=name): + prompt = install_prompt(name) + for needle in needles: + self.assertIn(needle, prompt, "%s 的安装文案缺少:%s" % (name, needle)) + + +if __name__ == "__main__": + unittest.main() From 7fe6969662870754595c2270691e0ba26439688a Mon Sep 17 00:00:00 2001 From: tanranran Date: Thu, 26 Nov 2026 14:25:27 +0800 Subject: [PATCH 2/2] =?UTF-8?q?test(install-prompt):=20=E5=AE=A1=E6=9F=A5?= =?UTF-8?q?=E6=94=B6=E5=8F=A3=E2=80=94=E2=80=94=E5=A5=91=E7=BA=A6=E6=B5=8B?= =?UTF-8?q?=E8=AF=95=E6=95=B4=E8=A1=8C=E5=8C=B9=E9=85=8D=E5=B9=B6=E6=8C=89?= =?UTF-8?q?=E9=94=9A=E9=80=89=E5=9D=97=EF=BC=8C=E5=86=92=E7=83=9F=E8=84=9A?= =?UTF-8?q?=E6=9C=AC=E4=BF=AE=E6=AD=A3=20PATH=20=E4=B8=8E=E5=A4=B1?= =?UTF-8?q?=E8=B4=A5=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 契约测试对两条 plugins 命令改为整行相等才通过(只做子串包含时,冒烟脚本的命令常量被改弱仍会放行), 安装器命令除占位路径外逐字一致且后面不能再跟参数;取安装文案改为「含 plugins marketplace add 的 text 代码块」并在收尾处截断,不再把文案后面的说明段落算进去,前面多一个代码块也不会取错。 冒烟脚本的 PATH 条目去掉 shell 引号(PATH 只按 : 切分,解释器目录含空格时引号会让该条目失效), 安装输出的形状不对时带上输出尾巴报错而不是裸抛 JSON/KeyError。文档规则的「两步安装」统一为「三步」。 --- .zcode/rules/docs.md | 2 +- tests/install-prompt-smoke.py | 25 +++++++++++++++------- tests/test_install_prompt_contract.py | 30 ++++++++++++++++++--------- 3 files changed, 39 insertions(+), 18 deletions(-) diff --git a/.zcode/rules/docs.md b/.zcode/rules/docs.md index 433a312a2..751bddfb6 100644 --- a/.zcode/rules/docs.md +++ b/.zcode/rules/docs.md @@ -17,7 +17,7 @@ - 差异化卖点=上下文占比 + 中英双语 + 首屏截图三条守住,不拼竞品功能清单。 - 逐问速率行的标签(`token_rate.py format_turn_line`)不分语言恒中文(硬编码无 locale 分支,英文宣传图里速率行是手写演示文案,已知产品限制);`overlay.js` 自身 `L()` 双语可在布景页 `localStorage.setItem("zusage3.lang","en")` 取真实英文文案,不手写翻译。 - 市场条目保留 `description_i18n`;门面显示名「速度状态栏」与市场 UI 显示的 slug 派生名("ZCode Token Usage Statusbar")不一致**刻意保留**——slug、市场名、命令、配置键、仓库/安装指引里的英文名都不擅改(受插件市场 UI 名约束,真改是破坏性工程)。README 安装指引中的英文名是市场实际显示名,不能翻译。 -- **README 安装文案必须自包含**(`tests/test_install_prompt_contract.py` 锁定):宿主不提供单独的 `zcode` 命令,也不给代理任何「怎么装插件」的指引(引擎里没有面向模型的添加市场说明,`SearchPlugins`/`SuggestPluginInstall` 只覆盖官方市场,本插件不在其中),代理只能靠文案本身。只给地址、或只说「执行 /install-overlay」时,代理得自己摸索调用方式(插件刚装好时当前会话里还没有这条命令)。文案须写明:命令行调用方式(`ELECTRON_RUN_AS_NODE=1` + ZCode 可执行文件 + `resources/glm/zcode.cjs`)、两条 `plugins` 子命令及 `--json`、GitHub 失败自动换带 `.git` 的 GitCode 地址、安装器脚本的调用路径(`installPath` 取自安装输出)、完全退出的重启措辞与失败时原样转述。改文案里的命令后跑 `python3 -B tests/install-prompt-smoke.py`(macOS,联网)确认全新环境仍装得上;两步安装之外不要塞进与安装无关的内容。 +- **README 安装文案必须自包含**(`tests/test_install_prompt_contract.py` 锁定):宿主不提供单独的 `zcode` 命令,也不给代理任何「怎么装插件」的指引(引擎里没有面向模型的添加市场说明,`SearchPlugins`/`SuggestPluginInstall` 只覆盖官方市场,本插件不在其中),代理只能靠文案本身。只给地址、或只说「执行 /install-overlay」时,代理得自己摸索调用方式(插件刚装好时当前会话里还没有这条命令)。文案须写明:命令行调用方式(`ELECTRON_RUN_AS_NODE=1` + ZCode 可执行文件 + `resources/glm/zcode.cjs`)、两条 `plugins` 子命令及 `--json`、GitHub 失败自动换带 `.git` 的 GitCode 地址、安装器脚本的调用路径(`installPath` 取自安装输出)、完全退出的重启措辞与失败时原样转述。改文案里的命令后跑 `python3 -B tests/install-prompt-smoke.py`(macOS,联网)确认全新环境仍装得上;这三步之外不要塞进与安装无关的内容。 - GitHub 默认仓库搜索只匹配 name+description+topics(README 需 `in:readme`)——辨识度关键词写 Description/Topics 而非正文堆同义词;topics ≤20、仅小写字母数字连字符、≤50 字符、不加竞品名不凑满。远端写入(Description/Topics/README)后 `gh api` 回读确认。 ## 3. 宣传图与 tour 截图(docs/promo、docs/tour) diff --git a/tests/install-prompt-smoke.py b/tests/install-prompt-smoke.py index 5952a6d6d..5172c956e 100644 --- a/tests/install-prompt-smoke.py +++ b/tests/install-prompt-smoke.py @@ -80,8 +80,9 @@ def __init__(self, parent): "ZCODE_SESSION_DB_PATH": str(self.home / ".zcode" / "cli" / "db" / "db.sqlite"), "ZCODE_LOG_DIR": str(self.home / ".zcode" / "cli" / "log"), "ZCODE_ASAR": str(self.asar), "TMPDIR": str(self.root / "tmp"), - # 安装器用当前这个解释器跑(系统 python3 可能是没有命令行工具的存根) - "PATH": "%s:/usr/bin:/bin:/usr/sbin:/sbin" % shlex.quote(os.path.dirname(sys.executable)), + # 安装器用当前这个解释器跑(系统 python3 可能是没有命令行工具的存根); + # PATH 只按 : 切分、不经 shell 解释,条目不能加引号 + "PATH": "%s:/usr/bin:/bin:/usr/sbin:/sbin" % os.path.dirname(sys.executable), "LANG": "zh_CN.UTF-8", "PYTHONDONTWRITEBYTECODE": "1", } quote = json.dumps @@ -146,6 +147,18 @@ def audit(self): require(self.inside(row[key]), "登记路径越过临时目录: " + str(row[key])) +def install_record(stdout, stderr): + """安装命令的成功输出必须恰是一条本插件的安装记录并带 installPath;形状不对时带上输出尾巴报错。""" + try: + records = json.loads(stdout)["installed"] + row = records[0] + valid = len(records) == 1 and row["id"] == PLUGIN_ID and isinstance(row["installPath"], str) + except (ValueError, KeyError, IndexError, TypeError): + valid = False + require(valid, "安装记录不是本插件或缺 installPath:%s%s" % (stdout.strip()[-300:], stderr.strip()[-300:])) + return row + + def install_as_documented(machine, variant): """按 README 文案的三步执行,返回逐步耗时。命令经 shlex.split 原样变成参数,不经 shell 二次解释。""" steps = {} @@ -154,16 +167,14 @@ def install_as_documented(machine, variant): steps[label] = seconds require(code == 0, "%s 失败(exit=%s):%s%s" % (label, code, stdout.strip()[-300:], stderr.strip()[-300:])) if label == "plugin install": - installed = json.loads(stdout)["installed"] - require(len(installed) == 1 and installed[0].get("id") == PLUGIN_ID, "安装记录不是本插件: " + stdout[-300:]) - install_path = Path(installed[0]["installPath"]) - code, seconds, stdout, stderr = machine.run(shlex.split(OVERLAY_COMMAND % str(install_path))) + record = install_record(stdout, stderr) + code, seconds, stdout, stderr = machine.run(shlex.split(OVERLAY_COMMAND % record["installPath"])) steps["overlay install"] = seconds require(code == 0, "安装器失败(exit=%s):%s%s" % (code, stdout.strip()[-400:], stderr.strip()[-400:])) require(b"inject-main.cjs" in machine.asar.read_bytes(), "状态条没有注入到假归档") require((machine.home / ".zcode" / PLUGIN).is_dir(), "运行目录没有创建") require("完全退出" in stdout, "安装器没有给出完全退出的重启提醒") - return dict(steps, variant=variant, version=installed[0].get("version")) + return dict(steps, variant=variant, version=record.get("version")) def main(argv=None): diff --git a/tests/test_install_prompt_contract.py b/tests/test_install_prompt_contract.py index d139b6329..7ed663604 100644 --- a/tests/test_install_prompt_contract.py +++ b/tests/test_install_prompt_contract.py @@ -5,6 +5,7 @@ 这里锁定三份 README 的安装文案包含 tests/install-prompt-smoke.py 实跑的每一条命令, 并且不再把「怎么执行安装」留给代理自己摸索。 """ +import re from pathlib import Path import sys import unittest @@ -15,11 +16,16 @@ SMOKE = load_module("install_prompt_smoke_contract", ROOT / "tests" / "install-prompt-smoke.py") README = ("README.md", "README.zh-CN.md", "README.en.md") +ANCHOR = "plugins marketplace add" def install_prompt(name): - """每个 README 里第一个 text 代码块就是安装文案。""" - return (ROOT / name).read_text(encoding="utf-8").split("```text", 2)[1] + """安装文案 = 含 plugins marketplace add 的那个 text 代码块(README 里另有别的 text 块)。""" + blocks = [block for block in re.findall(r"^```text\n(.*?)\n```", (ROOT / name).read_text(encoding="utf-8"), + re.S | re.M) if ANCHOR in block] + if len(blocks) != 1: + raise AssertionError("%s 里含 %r 的 text 代码块应有 1 个,实际 %d 个" % (name, ANCHOR, len(blocks))) + return blocks[0] class InstallPromptContractTests(unittest.TestCase): @@ -27,17 +33,21 @@ def test_chinese_readmes_stay_identical(self): self.assertEqual((ROOT / "README.md").read_bytes(), (ROOT / "README.zh-CN.md").read_bytes()) def test_prompt_contains_every_command_the_smoke_runs(self): - needles = ( - "ELECTRON_RUN_AS_NODE=1", - "resources/glm/zcode.cjs", - SMOKE.ADD_COMMAND % SMOKE.CHANNELS["github"], - SMOKE.INSTALL_COMMAND, - SMOKE.CHANNELS["gitcode"], - '/overlay_install.py" install', - ) + # 两条 plugins 命令在文案里各占一整行,整行相等才算数:只做子串包含的话, + # 脚本常量被改弱(如去掉 --json)时仍然会放行。 + commands = (SMOKE.ADD_COMMAND % SMOKE.CHANNELS["github"], SMOKE.INSTALL_COMMAND) + # 安装器命令嵌在第 2 步的句子里,路径是占位符:除路径外逐字一致,同一行后面不能再跟别的参数 + # (参数形如 --force、extra 或中文词,前面隔普通空格、制表符、不换行空格或反斜杠续行都算; + # 换行、括号、逗号等标点续写不算参数) + overlay = re.escape(SMOKE.OVERLAY_COMMAND).replace("%s", '[^"]*') + r"(?![^\S\r\n]*[\w\\-])" + needles = ("ELECTRON_RUN_AS_NODE=1", "resources/glm/zcode.cjs", SMOKE.CHANNELS["gitcode"]) for name in README: with self.subTest(readme=name): prompt = install_prompt(name) + lines = [line.strip() for line in prompt.splitlines()] + for command in commands: + self.assertIn(command, lines, "%s 的安装文案里没有这一整行命令:%s" % (name, command)) + self.assertRegex(prompt, overlay, "%s 的安装文案里没有安装器命令:%s" % (name, SMOKE.OVERLAY_COMMAND)) for needle in needles: self.assertIn(needle, prompt, "%s 的安装文案缺少:%s" % (name, needle))