From 162d53589cfb04854383e8a43c8869738c97d814 Mon Sep 17 00:00:00 2001 From: tanranran Date: Thu, 26 Nov 2026 12:15:03 +0800 Subject: [PATCH 1/4] =?UTF-8?q?feat(install):=20=E5=BD=92=E6=A1=A3?= =?UTF-8?q?=E5=8D=95=E4=BA=8B=E5=8A=A1=E2=80=94=E2=80=94=E5=BE=85=E6=9B=BF?= =?UTF-8?q?=E6=8D=A2=E5=8C=85=E6=91=98=E8=A6=81=E8=BE=B9=E5=86=99=E8=BE=B9?= =?UTF-8?q?=E7=AE=97=EF=BC=8C=E6=B8=B2=E6=9F=93=E6=A1=A5=E5=B9=B6=E5=85=A5?= =?UTF-8?q?=20loader=20=E7=9A=84=E5=90=8C=E4=B8=80=E6=AC=A1=E9=87=8D?= =?UTF-8?q?=E6=89=93=E5=8C=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - repack 改为逐文件边读边写,不再把整包数据拼在内存里;产物字节与旧实现一致 - 重打包时同步计算 stage 的整包 SHA256,stage 与落成后的 TMP 不再整包回读(repack 被替身顶替或没喂满时自动回退回读) - 完整安装与卸载在同一把目标锁内刚生成并校验过待替换包时,替换前只核对身份戳;复用磁盘上的待替换包与监控收尾仍完整验包 - install() 新增可选 extra_modify 钩子:插件链把渲染桥改写并入同一次重打包,来源指纹不符、路径不合法或钩子异常时静默退回独立补桥 - 客户端占用归档时一次待替换同时带上 loader 与桥,Windows 首次安装不再需要两次完全退出 规格:specs/asar-single-transaction.md。 在本机真实 384MB 归档的临时副本上对比:新旧实现的最终内容逐条一致,整包写入由两次收敛为一次。 --- patch_install.py | 166 +++++++++-- .../overlay_install.py | 17 +- .../patch_install.py | 166 +++++++++-- .../renderer_bridge.py | 18 ++ renderer_bridge.py | 18 ++ specs/asar-install.md | 2 + specs/asar-single-transaction.md | 47 ++++ tests/test_pending_asar.py | 264 ++++++++++++++++++ tests/test_plugin_runtime.py | 43 +++ tests/test_renderer_bridge.py | 118 +++++++- tests/test_session_start_channels.py | 16 +- 11 files changed, 804 insertions(+), 71 deletions(-) create mode 100644 specs/asar-single-transaction.md diff --git a/patch_install.py b/patch_install.py index 5bd836995..e969d2869 100644 --- a/patch_install.py +++ b/patch_install.py @@ -85,6 +85,9 @@ rb'\(e\) => console\.error\("\[zusage\] load failed", e\)\);' ) ZCODE_EXE = ZCODE_EXE_DEFAULT +# install(extra_modify=...) 的能力标记:调用方(overlay_install)按此探测——旧运行目录里的 +# 模块或测试替身没有该常量时不传钩子,install() 的调用形状保持不变。 +EXTRA_MODIFY = True ALIGN = 4 BLOCK = 4194304 @@ -643,8 +646,36 @@ def compute_integrity(data: bytes): } +class _Digest: + """边写边算的整包摘要;size 记录喂入的字节数,对不上产物大小即不可信。""" + + def __init__(self): + self.hash = hashlib.sha256() + self.size = 0 + + def update(self, data): + self.hash.update(data) + self.size += len(data) + + +_REPACK_SINK = None # _repack_digest() 持有期间的摘要接收方 + + +@contextmanager +def _repack_digest(): + """让其间的 repack() 边写边算产物的 SHA256。repack 被替身顶替或没写满时 + sink.size 为 0 或小于产物,调用方回退整包回读。""" + global _REPACK_SINK + sink = _Digest() + _REPACK_SINK = sink + try: + yield sink + finally: + _REPACK_SINK = None + + def repack(src_path: Path, modify: dict, dst_path: Path): - """重建 asar。modify: {asar内路径: 新内容bytes}。流式拷贝未改动文件。""" + """重建 asar。modify: {asar内路径: 新内容bytes}。逐文件边读边写,未改动文件不落内存。""" with open(src_path, "rb") as src: header, base = read_header(src) header = json.loads(json.dumps(header)) # 深拷贝 @@ -652,8 +683,8 @@ def repack(src_path: Path, modify: dict, dst_path: Path): missing = set(modify) - set(nodes) assert not missing, f"paths not in asar: {missing}" - data_parts = [] - offset = 0 + # 第一遍只定新偏移:改写项记新内容,其余记源数据起点,都不读数据 + plan, offset = [], 0 for p, node in nodes.items(): if node.get("unpacked"): node["offset"] = "0" @@ -664,24 +695,39 @@ def repack(src_path: Path, modify: dict, dst_path: Path): data = modify[p] node["size"] = len(data) node["integrity"] = compute_integrity(data) + plan.append((None, data)) else: - src.seek(base + int(node["offset"])) - data = src.read(node["size"]) + plan.append((base + int(node["offset"]), node["size"])) node["offset"] = str(offset) - data_parts.append(data) - offset += len(data) + offset += node["size"] - payload = b"".join(data_parts) header_bytes = json.dumps(header, ensure_ascii=False, separators=(",", ":")).encode("utf-8") d = len(header_bytes) c = (d + 4 + ALIGN - 1) // ALIGN * ALIGN b_total = c + 4 - with open(dst_path, "wb") as out: - out.write(struct.pack("<4I", 4, b_total, c, d)) - out.write(header_bytes) - out.write(b"\0" * (c - d - 4)) # pickle 对齐:数据区从 8+b = 12+c 处开始 + sink = _REPACK_SINK + with open(dst_path, "wb", buffering=BLOCK) as out: + def write(data): + out.write(data) + if sink is not None: + sink.update(data) + + write(struct.pack("<4I", 4, b_total, c, d)) + write(header_bytes) + write(b"\0" * (c - d - 4)) # pickle 对齐:数据区从 8+b = 12+c 处开始 assert out.tell() == 8 + b_total, f"header pad mismatch: {out.tell()} vs {8 + b_total}" - out.write(payload) + for start, payload in plan: + if start is None: + write(payload) + continue + src.seek(start) + remaining = payload + while remaining: + chunk = src.read(min(BLOCK, remaining)) + if not chunk: + raise OSError(f"source archive truncated: {src_path}") + write(chunk) + remaining -= len(chunk) return dst_path @@ -975,11 +1021,16 @@ def monitor_instance_lock(): os.close(fd) # 释放即关闭句柄:显式解锁与关闭之间的窗口没有意义 -def _checked_tmp_metadata(path, source, operation): +def _checked_tmp_metadata(path, source, operation, fingerprint=None): if operation not in ("install", "remove"): raise PendingTmpError("invalid pending operation") _same_stamp(ASAR, source) - before = source_fingerprint(path) + if fingerprint is None: + before = source_fingerprint(path) + else: + # 重打包边写边算的摘要:身份戳仍对得上才沿用,对不上按既有语义失败 + _same_stamp(path, fingerprint) + before = fingerprint try: ok = self_check(path, expect=operation == "install") and syntax_check(path) except (ValueError, AssertionError, KeyError, struct.error) as e: @@ -1074,10 +1125,11 @@ def _same_renamed_file(current, before): return all(current[key] == before[key] for key in ("size", "mtime_ns", "dev", "ino")) -def _publish_pending(stage, source, operation, previous, *, validated_mobile=None): - """按 journal→原子发布→sidecar 落成 TMP。普通调用完整校验;手机只复用锁外校验的私有 stage。""" +def _publish_pending(stage, source, operation, previous, *, validated_mobile=None, fingerprint=None): + """按 journal→原子发布→sidecar 落成 TMP。普通调用完整校验;手机只复用锁外校验的私有 stage。 + fingerprint 是本进程重打包边写边算的 stage 指纹:有则免掉 stage 与落成后 TMP 的两次整包回读。""" mobile = validated_mobile is not None - meta = (_checked_tmp_metadata(stage, source, operation) if not mobile + meta = (_checked_tmp_metadata(stage, source, operation, fingerprint) if not mobile else dict(validated_mobile)) # Two files cannot be atomically published together. Persist a cancelled # ownership journal first, so any interruption is safe and recoverable. @@ -1099,7 +1151,12 @@ def _publish_pending(stage, source, operation, previous, *, validated_mobile=Non raise PendingTmpError("published TMP does not match validated mobile stage") meta["tmp"] = dict(moved, sha256=meta["tmp"]["sha256"]) else: - meta["tmp"] = source_fingerprint(TMP) + moved = file_stamp(TMP) + if fingerprint is None or not _same_renamed_file(moved, meta["tmp"]): + meta["tmp"] = source_fingerprint(TMP) + else: + # 同目录 rename 只动 ctime:内容未变,沿用写入期摘要,只换身份戳 + meta["tmp"] = dict(moved, sha256=meta["tmp"]["sha256"]) _same_stamp(ASAR, source) _atomic_tmp_metadata(meta) except BaseException: @@ -1162,13 +1219,20 @@ def _archive_stage(*, mobile_only=False): def _repack_stage(stage, modify): - repack(ASAR, modify, stage) + with _repack_digest() as sink: + repack(ASAR, modify, stage) original_stat = ASAR.stat() if os.name != "nt": stage_stat = stage.stat() if (stage_stat.st_uid, stage_stat.st_gid) != (original_stat.st_uid, original_stat.st_gid): os.chown(stage, original_stat.st_uid, original_stat.st_gid) os.chmod(stage, stat.S_IMODE(original_stat.st_mode)) + # 身份戳取在 chown/chmod 之后(ctime 属于身份戳);摘要只在喂满整个 stage 时可用, + # repack 被替身顶替时 sink.size 为 0,返回 None 让调用方回退整包回读 + stamp = file_stamp(stage) + if sink.size != stamp["size"]: + return None + return dict(stamp, sha256=sink.hash.hexdigest()) @contextmanager @@ -1214,8 +1278,8 @@ def _prepare_tmp(modify, operation="install", source=None): if TMP.exists() or TMP.is_symlink() or TMP_META.exists() or TMP_META.is_symlink(): previous = _owned_tmp_metadata() with _archive_stage() as stage: - _repack_stage(stage, modify) - return _publish_pending(stage, source, operation, previous) + fingerprint = _repack_stage(stage, modify) + return _publish_pending(stage, source, operation, previous, fingerprint=fingerprint) def _mobile_pending_exists(): @@ -1515,10 +1579,36 @@ def _reusable_pending_install(new_entry, *, verified=None): return False -def install(finalize=False, before_publish=None, mobile_only=False, *, record_mobile_intent=False): +def _extra_modifications(hook, source): + """并入同一次重打包的旁路改写(渲染桥等)。返回 {} 表示不并入:未提供钩子、抛异常、 + 形态不符、不是基于同一份来源归档算出的、路径不在归档内、路径是外置/链接项,或触碰 + 主入口。旁路改写绝不影响 loader 安装。""" + if hook is None: + return {} + try: + planned = hook() + extra = planned.get("modify") if isinstance(planned, dict) else None + if not isinstance(extra, dict) or not extra or not _same_fingerprint(source, planned.get("source")): + return {} + with open(ASAR, "rb") as stream: + nodes = dict(iter_files(read_header(stream)[0])) + if any(not isinstance(path, str) or path == "/" + ENTRY or not isinstance(data, bytes) + or not data or path not in nodes or nodes[path].get("unpacked") or "link" in nodes[path] + for path, data in extra.items()): + return {} + return dict(extra) + except Exception: + return {} + + +def install(finalize=False, before_publish=None, mobile_only=False, *, record_mobile_intent=False, + extra_modify=None): """Serialize install/remove/finalize; optional callback records a new package intent. mobile_only 仅供已有当前 loader 的 SessionStart 补装手机钩子,不改变 loader 路径。 + extra_modify() 只在完整安装确需生成新包时调用:返回 + {"source": <计算改写时的归档指纹>, "modify": {归档内路径: bytes}} 且来源指纹与本次一致时, + 改写并入同一次重打包(specs/asar-single-transaction.md);其余情形一律不并入。 """ global _LAST_MOBILE_STATUS if finalize: @@ -1592,13 +1682,13 @@ def install(finalize=False, before_publish=None, mobile_only=False, *, record_mo return False try: with _target_lock(): - return _install(before_publish=before_publish) + return _install(before_publish=before_publish, extra_modify=extra_modify) except OSError as e: print(L(f"安装锁获取失败:{e}", f"Cannot acquire install lock: {e}")) return False -def _install(finalize=False, before_publish=None): +def _install(finalize=False, before_publish=None, extra_modify=None): """返回 True=已安装/已指向当前目录,False=失败或待收尾。""" global _LAST_MOBILE_STATUS if finalize: @@ -1641,25 +1731,33 @@ def _install(finalize=False, before_publish=None): new_entry = stripped + INJECT_LINE.encode() if stripped != entry: print(L("检测到旧注入行(可能指向旧目录),将替换为新路径。", - "Old injection line detected (possibly pointing at an old directory); it will be replaced with the new path.")) + "Old injection line detected (possibly pointing to an old directory); it will be replaced with the new path.")) + verified = {} if _reusable_pending_install(new_entry): # 客户端持续运行期间每次 SessionStart 自动安装都会走到这里:直接复用磁盘上 - # 已排定的待收尾包,不再 307MB 重打包/重写(issue #120 的写放大)。不新建意图。 + # 已排定的待收尾包,不再整包重打包/重写(issue #120 的写放大)。不新建意图。 print(L("已有有效的待收尾包(内容一致),跳过重打包。", "A valid identical pending package already exists; skipping the repack.")) else: - print(L("重打包(307MB,约需十几秒)...", "repacking (307MB, takes ~10-20 seconds)...")) + print(L("重打包(约需十几秒)...", "repacking (takes ~10-20 seconds)...")) try: if before_publish is not None: before_publish({"asar": str(ASAR.resolve()), "entryHash": hashlib.sha256(new_entry).hexdigest()}) - _prepare_tmp({"/" + ENTRY: new_entry}, source=source) + modify = {"/" + ENTRY: new_entry} + modify.update(_extra_modifications(extra_modify, source)) + _prepare_tmp(modify, source=source) + # 本进程刚生成并完整校验过待替换包,目标锁也全程未放:把 sidecar 登记进本进程 + # 的校验缓存,紧随其后的替换只核对身份戳。读不回就按未校验处理,照常完整验包。 + try: + verified["metadata"] = _load_tmp_metadata() + except PendingTmpError: + pass except (OSError, PendingTmpError) as e: if mobile_changed: _LAST_MOBILE_STATUS = {"status": "skipped-error", "detail": str(e)} print(L(f"待替换包生成失败,未替换:{e}", f"Pending package preparation failed; not replaced: {e}")) return False - verified = {} if client_running(): try: _replace_pending("install", verified=verified) @@ -1787,14 +1885,20 @@ def _remove(): cleanup_legacy_bak() return True print(L("重打包(剥离注入行,约需十几秒)...", "repacking (stripping the injection line, takes ~10-20 seconds)...")) + verified = {} try: _prepare_tmp({"/" + ENTRY: stripped}, operation="remove", source=source) + # 同 _install:本进程刚生成并完整校验过,替换前只核对身份戳 + try: + verified["metadata"] = _load_tmp_metadata() + except PendingTmpError: + pass except (OSError, PendingTmpError) as e: print(L(f"卸载待替换包生成失败:{e}", f"Remove pending package preparation failed: {e}")) return False running = client_running() try: - _replace_pending("remove") + _replace_pending("remove", verified=verified) except PendingTmpError as e: print(L(f"卸载待替换包已失效,未替换:{e}", f"Remove pending package invalidated; not replaced: {e}")) return False diff --git a/plugins/zcode-token-usage-statusbar/overlay_install.py b/plugins/zcode-token-usage-statusbar/overlay_install.py index 0e2c8880c..508d451c5 100644 --- a/plugins/zcode-token-usage-statusbar/overlay_install.py +++ b/plugins/zcode-token-usage-statusbar/overlay_install.py @@ -838,10 +838,25 @@ def _nudge(output, message, label="安装提醒", detail="状态条安装尚未 return output +def _plan_bridge(pi): + """并入 loader 安装事务的桥改写(renderer_bridge.plan_deploy);任何失败都返回 None。""" + try: + from renderer_bridge import plan_deploy + return plan_deploy(pi.ASAR) + except Exception as e: # noqa: BLE001 — 桥只是增强 + print(f"[zusage-plugin] renderer bridge plan failed(已忽略):{e}", file=sys.stderr) + return None + + def _install_overlay(runtime, pi): from restart_notice import record_restart + kwargs = {} + if getattr(pi, "EXTRA_MODIFY", False) is True: + # 已加载的 patch_install 支持把桥改写并入同一次重打包(specs/asar-single-transaction.md); + # 旧运行目录模块或替身没有该能力时不传钩子,install() 的调用形状不变。 + kwargs["extra_modify"] = lambda: _plan_bridge(pi) return pi.install(before_publish=lambda installation: record_restart( - runtime, {"state": "pending-install", "installation": installation})) + runtime, {"state": "pending-install", "installation": installation}), **kwargs) _MOBILE_LOCK_RETRY_BUDGET_S = 15.0 diff --git a/plugins/zcode-token-usage-statusbar/patch_install.py b/plugins/zcode-token-usage-statusbar/patch_install.py index 5bd836995..e969d2869 100644 --- a/plugins/zcode-token-usage-statusbar/patch_install.py +++ b/plugins/zcode-token-usage-statusbar/patch_install.py @@ -85,6 +85,9 @@ rb'\(e\) => console\.error\("\[zusage\] load failed", e\)\);' ) ZCODE_EXE = ZCODE_EXE_DEFAULT +# install(extra_modify=...) 的能力标记:调用方(overlay_install)按此探测——旧运行目录里的 +# 模块或测试替身没有该常量时不传钩子,install() 的调用形状保持不变。 +EXTRA_MODIFY = True ALIGN = 4 BLOCK = 4194304 @@ -643,8 +646,36 @@ def compute_integrity(data: bytes): } +class _Digest: + """边写边算的整包摘要;size 记录喂入的字节数,对不上产物大小即不可信。""" + + def __init__(self): + self.hash = hashlib.sha256() + self.size = 0 + + def update(self, data): + self.hash.update(data) + self.size += len(data) + + +_REPACK_SINK = None # _repack_digest() 持有期间的摘要接收方 + + +@contextmanager +def _repack_digest(): + """让其间的 repack() 边写边算产物的 SHA256。repack 被替身顶替或没写满时 + sink.size 为 0 或小于产物,调用方回退整包回读。""" + global _REPACK_SINK + sink = _Digest() + _REPACK_SINK = sink + try: + yield sink + finally: + _REPACK_SINK = None + + def repack(src_path: Path, modify: dict, dst_path: Path): - """重建 asar。modify: {asar内路径: 新内容bytes}。流式拷贝未改动文件。""" + """重建 asar。modify: {asar内路径: 新内容bytes}。逐文件边读边写,未改动文件不落内存。""" with open(src_path, "rb") as src: header, base = read_header(src) header = json.loads(json.dumps(header)) # 深拷贝 @@ -652,8 +683,8 @@ def repack(src_path: Path, modify: dict, dst_path: Path): missing = set(modify) - set(nodes) assert not missing, f"paths not in asar: {missing}" - data_parts = [] - offset = 0 + # 第一遍只定新偏移:改写项记新内容,其余记源数据起点,都不读数据 + plan, offset = [], 0 for p, node in nodes.items(): if node.get("unpacked"): node["offset"] = "0" @@ -664,24 +695,39 @@ def repack(src_path: Path, modify: dict, dst_path: Path): data = modify[p] node["size"] = len(data) node["integrity"] = compute_integrity(data) + plan.append((None, data)) else: - src.seek(base + int(node["offset"])) - data = src.read(node["size"]) + plan.append((base + int(node["offset"]), node["size"])) node["offset"] = str(offset) - data_parts.append(data) - offset += len(data) + offset += node["size"] - payload = b"".join(data_parts) header_bytes = json.dumps(header, ensure_ascii=False, separators=(",", ":")).encode("utf-8") d = len(header_bytes) c = (d + 4 + ALIGN - 1) // ALIGN * ALIGN b_total = c + 4 - with open(dst_path, "wb") as out: - out.write(struct.pack("<4I", 4, b_total, c, d)) - out.write(header_bytes) - out.write(b"\0" * (c - d - 4)) # pickle 对齐:数据区从 8+b = 12+c 处开始 + sink = _REPACK_SINK + with open(dst_path, "wb", buffering=BLOCK) as out: + def write(data): + out.write(data) + if sink is not None: + sink.update(data) + + write(struct.pack("<4I", 4, b_total, c, d)) + write(header_bytes) + write(b"\0" * (c - d - 4)) # pickle 对齐:数据区从 8+b = 12+c 处开始 assert out.tell() == 8 + b_total, f"header pad mismatch: {out.tell()} vs {8 + b_total}" - out.write(payload) + for start, payload in plan: + if start is None: + write(payload) + continue + src.seek(start) + remaining = payload + while remaining: + chunk = src.read(min(BLOCK, remaining)) + if not chunk: + raise OSError(f"source archive truncated: {src_path}") + write(chunk) + remaining -= len(chunk) return dst_path @@ -975,11 +1021,16 @@ def monitor_instance_lock(): os.close(fd) # 释放即关闭句柄:显式解锁与关闭之间的窗口没有意义 -def _checked_tmp_metadata(path, source, operation): +def _checked_tmp_metadata(path, source, operation, fingerprint=None): if operation not in ("install", "remove"): raise PendingTmpError("invalid pending operation") _same_stamp(ASAR, source) - before = source_fingerprint(path) + if fingerprint is None: + before = source_fingerprint(path) + else: + # 重打包边写边算的摘要:身份戳仍对得上才沿用,对不上按既有语义失败 + _same_stamp(path, fingerprint) + before = fingerprint try: ok = self_check(path, expect=operation == "install") and syntax_check(path) except (ValueError, AssertionError, KeyError, struct.error) as e: @@ -1074,10 +1125,11 @@ def _same_renamed_file(current, before): return all(current[key] == before[key] for key in ("size", "mtime_ns", "dev", "ino")) -def _publish_pending(stage, source, operation, previous, *, validated_mobile=None): - """按 journal→原子发布→sidecar 落成 TMP。普通调用完整校验;手机只复用锁外校验的私有 stage。""" +def _publish_pending(stage, source, operation, previous, *, validated_mobile=None, fingerprint=None): + """按 journal→原子发布→sidecar 落成 TMP。普通调用完整校验;手机只复用锁外校验的私有 stage。 + fingerprint 是本进程重打包边写边算的 stage 指纹:有则免掉 stage 与落成后 TMP 的两次整包回读。""" mobile = validated_mobile is not None - meta = (_checked_tmp_metadata(stage, source, operation) if not mobile + meta = (_checked_tmp_metadata(stage, source, operation, fingerprint) if not mobile else dict(validated_mobile)) # Two files cannot be atomically published together. Persist a cancelled # ownership journal first, so any interruption is safe and recoverable. @@ -1099,7 +1151,12 @@ def _publish_pending(stage, source, operation, previous, *, validated_mobile=Non raise PendingTmpError("published TMP does not match validated mobile stage") meta["tmp"] = dict(moved, sha256=meta["tmp"]["sha256"]) else: - meta["tmp"] = source_fingerprint(TMP) + moved = file_stamp(TMP) + if fingerprint is None or not _same_renamed_file(moved, meta["tmp"]): + meta["tmp"] = source_fingerprint(TMP) + else: + # 同目录 rename 只动 ctime:内容未变,沿用写入期摘要,只换身份戳 + meta["tmp"] = dict(moved, sha256=meta["tmp"]["sha256"]) _same_stamp(ASAR, source) _atomic_tmp_metadata(meta) except BaseException: @@ -1162,13 +1219,20 @@ def _archive_stage(*, mobile_only=False): def _repack_stage(stage, modify): - repack(ASAR, modify, stage) + with _repack_digest() as sink: + repack(ASAR, modify, stage) original_stat = ASAR.stat() if os.name != "nt": stage_stat = stage.stat() if (stage_stat.st_uid, stage_stat.st_gid) != (original_stat.st_uid, original_stat.st_gid): os.chown(stage, original_stat.st_uid, original_stat.st_gid) os.chmod(stage, stat.S_IMODE(original_stat.st_mode)) + # 身份戳取在 chown/chmod 之后(ctime 属于身份戳);摘要只在喂满整个 stage 时可用, + # repack 被替身顶替时 sink.size 为 0,返回 None 让调用方回退整包回读 + stamp = file_stamp(stage) + if sink.size != stamp["size"]: + return None + return dict(stamp, sha256=sink.hash.hexdigest()) @contextmanager @@ -1214,8 +1278,8 @@ def _prepare_tmp(modify, operation="install", source=None): if TMP.exists() or TMP.is_symlink() or TMP_META.exists() or TMP_META.is_symlink(): previous = _owned_tmp_metadata() with _archive_stage() as stage: - _repack_stage(stage, modify) - return _publish_pending(stage, source, operation, previous) + fingerprint = _repack_stage(stage, modify) + return _publish_pending(stage, source, operation, previous, fingerprint=fingerprint) def _mobile_pending_exists(): @@ -1515,10 +1579,36 @@ def _reusable_pending_install(new_entry, *, verified=None): return False -def install(finalize=False, before_publish=None, mobile_only=False, *, record_mobile_intent=False): +def _extra_modifications(hook, source): + """并入同一次重打包的旁路改写(渲染桥等)。返回 {} 表示不并入:未提供钩子、抛异常、 + 形态不符、不是基于同一份来源归档算出的、路径不在归档内、路径是外置/链接项,或触碰 + 主入口。旁路改写绝不影响 loader 安装。""" + if hook is None: + return {} + try: + planned = hook() + extra = planned.get("modify") if isinstance(planned, dict) else None + if not isinstance(extra, dict) or not extra or not _same_fingerprint(source, planned.get("source")): + return {} + with open(ASAR, "rb") as stream: + nodes = dict(iter_files(read_header(stream)[0])) + if any(not isinstance(path, str) or path == "/" + ENTRY or not isinstance(data, bytes) + or not data or path not in nodes or nodes[path].get("unpacked") or "link" in nodes[path] + for path, data in extra.items()): + return {} + return dict(extra) + except Exception: + return {} + + +def install(finalize=False, before_publish=None, mobile_only=False, *, record_mobile_intent=False, + extra_modify=None): """Serialize install/remove/finalize; optional callback records a new package intent. mobile_only 仅供已有当前 loader 的 SessionStart 补装手机钩子,不改变 loader 路径。 + extra_modify() 只在完整安装确需生成新包时调用:返回 + {"source": <计算改写时的归档指纹>, "modify": {归档内路径: bytes}} 且来源指纹与本次一致时, + 改写并入同一次重打包(specs/asar-single-transaction.md);其余情形一律不并入。 """ global _LAST_MOBILE_STATUS if finalize: @@ -1592,13 +1682,13 @@ def install(finalize=False, before_publish=None, mobile_only=False, *, record_mo return False try: with _target_lock(): - return _install(before_publish=before_publish) + return _install(before_publish=before_publish, extra_modify=extra_modify) except OSError as e: print(L(f"安装锁获取失败:{e}", f"Cannot acquire install lock: {e}")) return False -def _install(finalize=False, before_publish=None): +def _install(finalize=False, before_publish=None, extra_modify=None): """返回 True=已安装/已指向当前目录,False=失败或待收尾。""" global _LAST_MOBILE_STATUS if finalize: @@ -1641,25 +1731,33 @@ def _install(finalize=False, before_publish=None): new_entry = stripped + INJECT_LINE.encode() if stripped != entry: print(L("检测到旧注入行(可能指向旧目录),将替换为新路径。", - "Old injection line detected (possibly pointing at an old directory); it will be replaced with the new path.")) + "Old injection line detected (possibly pointing to an old directory); it will be replaced with the new path.")) + verified = {} if _reusable_pending_install(new_entry): # 客户端持续运行期间每次 SessionStart 自动安装都会走到这里:直接复用磁盘上 - # 已排定的待收尾包,不再 307MB 重打包/重写(issue #120 的写放大)。不新建意图。 + # 已排定的待收尾包,不再整包重打包/重写(issue #120 的写放大)。不新建意图。 print(L("已有有效的待收尾包(内容一致),跳过重打包。", "A valid identical pending package already exists; skipping the repack.")) else: - print(L("重打包(307MB,约需十几秒)...", "repacking (307MB, takes ~10-20 seconds)...")) + print(L("重打包(约需十几秒)...", "repacking (takes ~10-20 seconds)...")) try: if before_publish is not None: before_publish({"asar": str(ASAR.resolve()), "entryHash": hashlib.sha256(new_entry).hexdigest()}) - _prepare_tmp({"/" + ENTRY: new_entry}, source=source) + modify = {"/" + ENTRY: new_entry} + modify.update(_extra_modifications(extra_modify, source)) + _prepare_tmp(modify, source=source) + # 本进程刚生成并完整校验过待替换包,目标锁也全程未放:把 sidecar 登记进本进程 + # 的校验缓存,紧随其后的替换只核对身份戳。读不回就按未校验处理,照常完整验包。 + try: + verified["metadata"] = _load_tmp_metadata() + except PendingTmpError: + pass except (OSError, PendingTmpError) as e: if mobile_changed: _LAST_MOBILE_STATUS = {"status": "skipped-error", "detail": str(e)} print(L(f"待替换包生成失败,未替换:{e}", f"Pending package preparation failed; not replaced: {e}")) return False - verified = {} if client_running(): try: _replace_pending("install", verified=verified) @@ -1787,14 +1885,20 @@ def _remove(): cleanup_legacy_bak() return True print(L("重打包(剥离注入行,约需十几秒)...", "repacking (stripping the injection line, takes ~10-20 seconds)...")) + verified = {} try: _prepare_tmp({"/" + ENTRY: stripped}, operation="remove", source=source) + # 同 _install:本进程刚生成并完整校验过,替换前只核对身份戳 + try: + verified["metadata"] = _load_tmp_metadata() + except PendingTmpError: + pass except (OSError, PendingTmpError) as e: print(L(f"卸载待替换包生成失败:{e}", f"Remove pending package preparation failed: {e}")) return False running = client_running() try: - _replace_pending("remove") + _replace_pending("remove", verified=verified) except PendingTmpError as e: print(L(f"卸载待替换包已失效,未替换:{e}", f"Remove pending package invalidated; not replaced: {e}")) return False diff --git a/plugins/zcode-token-usage-statusbar/renderer_bridge.py b/plugins/zcode-token-usage-statusbar/renderer_bridge.py index 3ba21b0db..b9151e81e 100644 --- a/plugins/zcode-token-usage-statusbar/renderer_bridge.py +++ b/plugins/zcode-token-usage-statusbar/renderer_bridge.py @@ -1028,6 +1028,24 @@ def _inspect_deploy(asar_path): asset_path, original, modified) +def plan_deploy(asar_path): + """loader 安装事务的并入钩子(patch_install.install(extra_modify=...) 的数据来源): + 只读判定目标 asar 是否缺桥,缺则给出改写后的渲染资产与判定时的整包指纹。返回 None = + 不并入(已带桥、布局无法验证或任何读档失败)——桥是旁路增强,绝不影响 loader 安装。 + 调用方只有在本指纹与其重打包来源一致时才并入(specs/asar-single-transaction.md)。""" + try: + asar_path = Path(asar_path) + kind, payload = _inspect_deploy(asar_path) + if kind != "patch": + return None + before, _base, _nodes, _header, _version, _auto, _derived, asset_path, _original, modified = payload + if not isinstance(asset_path, str) or not isinstance(modified, bytes) or not modified: + return None + return {"source": before, "modify": {asset_path: modified}} + except Exception: + return None + + def ensure_deployed(asar_path): """插件安装/更新链专用:确认目标 asar 带桥,没有则就地补打。 diff --git a/renderer_bridge.py b/renderer_bridge.py index 3ba21b0db..b9151e81e 100644 --- a/renderer_bridge.py +++ b/renderer_bridge.py @@ -1028,6 +1028,24 @@ def _inspect_deploy(asar_path): asset_path, original, modified) +def plan_deploy(asar_path): + """loader 安装事务的并入钩子(patch_install.install(extra_modify=...) 的数据来源): + 只读判定目标 asar 是否缺桥,缺则给出改写后的渲染资产与判定时的整包指纹。返回 None = + 不并入(已带桥、布局无法验证或任何读档失败)——桥是旁路增强,绝不影响 loader 安装。 + 调用方只有在本指纹与其重打包来源一致时才并入(specs/asar-single-transaction.md)。""" + try: + asar_path = Path(asar_path) + kind, payload = _inspect_deploy(asar_path) + if kind != "patch": + return None + before, _base, _nodes, _header, _version, _auto, _derived, asset_path, _original, modified = payload + if not isinstance(asset_path, str) or not isinstance(modified, bytes) or not modified: + return None + return {"source": before, "modify": {asset_path: modified}} + except Exception: + return None + + def ensure_deployed(asar_path): """插件安装/更新链专用:确认目标 asar 带桥,没有则就地补打。 diff --git a/specs/asar-install.md b/specs/asar-install.md index cc4f56e21..49acb0891 100644 --- a/specs/asar-install.md +++ b/specs/asar-install.md @@ -18,6 +18,8 @@ - 独立安装与插件 CLI 的手机输出:`patched` 打印「已写入」确认(客户端运行中要求完全退出并重开后生效);`pending` 打印已排定、完全退出后自动完成;独立安装在手机布局无法验证而状态条安装成功时,先说明「布局无法验证,保留原代码」再输出完成。`pending`、`deferred`、`skipped-error` 不得输出「全部完成」式承诺。 - 已登记手机目标必须在剥离本项目已知注入和 loader 尾缀后同时满足原始资产 SHA 与两个锚点;锚点仍唯一但其它字节漂移也拒绝写入。表外目标仍按原有唯一结构推导,不因版本未知而拒绝结构可验证的往返。 +渲染桥并入同一笔归档提交、以及重打包期间的整包读写收敛,见[归档单事务规格](asar-single-transaction.md)。 + ## 验收 | 场景 | 可观察结果 | diff --git a/specs/asar-single-transaction.md b/specs/asar-single-transaction.md new file mode 100644 index 000000000..17fb34ee5 --- /dev/null +++ b/specs/asar-single-transaction.md @@ -0,0 +1,47 @@ +# 归档单事务:读盘收敛与渲染桥并入 + +## 目标与边界 + +`patch_install.py` 的完整安装与卸载对 `app.asar`(现为数百 MB)的整包读取与写入做收敛,并让插件链的首次归档提交同时带上渲染桥。状态所有者不变:loader、手机钩子与待替换/监控链仍归 `patch_install.py`,渲染桥的指纹表与改写规则仍归 `renderer_bridge.py`,两者的编排只在 `overlay_install.py`。 + +不在范围:手机补装链(`install(mobile_only=True)`)的校验序列、监控进程的验包、卸载时的桥剥离,以及根 `install.py` 独立链的编排(它不补桥)均保持原样。 + +## 读盘收敛 + +- 来源归档的整包指纹仍在读取入口与重打包之前取得(`source_fingerprint(ASAR)`),这条不变。 +- `repack()` 改为逐文件边读边写,不再把整包数据拼在内存里;产物字节与此前实现逐字节相同(头、对齐、偏移与 integrity 一致)。 +- 重打包写 stage 时同步计算整包 SHA256。只有喂入的字节数等于 stage 大小才采用这份摘要;`repack` 被替身替换或没写满时回退为整包回读。 +- stage 的身份戳取在 `chown`/`chmod` 之后;此后身份戳对不上即按既有 `PendingTmpError` 语义失败,不替换归档。 +- stage 经同目录 rename 成为待替换包后,身份戳(体积、mtime、dev、ino)不变时沿用摘要,只换戳;对不上则回退整包回读。外部构建的桥 stage 没有写入期摘要,照旧整包回读,行为不变。 +- 完整安装与卸载在同一把目标锁内刚生成并完整校验过待替换包时,把 sidecar 登记进本进程的校验缓存;紧随其后的替换只核对身份戳与 sidecar,不再整包重读来源与待替换包。监控是另一个进程,照常完整验包。 +- 复用磁盘上已有待替换包(`_reusable_pending_install`)或走「已安装」早退时不登记缓存:前者不是本进程生成的包,替换前照旧完整验包。 + +## 渲染桥并入 + +- `install()` 新增可选关键字参数 `extra_modify`:无参可调用对象,返回 `None` 或 `{"source": <计算改写时的归档指纹>, "modify": {<归档内路径>: }}`。钩子自己取指纹(整包哈希),`patch_install` 不把来源指纹交给它,免得「回显即通过」。 +- 只在本次确实要生成新包时调用(已安装早退与复用待替换包两条路径都不调用),返回的改写与入口改写并入同一次重打包、同一次待替换包、同一次替换。 +- 不并入的情形一律静默退回原两段式(安装完成后再由 `ensure_renderer_bridge` 独立补桥):未提供钩子;钩子抛异常;返回形态不符;`source` 与本次来源指纹不一致;改写路径不在归档内、是外置(unpacked)或链接项、内容为空;改写触碰主入口 `out/main/index.js`。桥是旁路增强,任何情形都不得让 loader 安装失败。 +- 并入后重启标记沿用主安装的 `pending-install` 标记(`entryHash` 仍是最终入口的 SHA256),桥不再单独写标记。 +- 替换完成后,`ensure_renderer_bridge` 的只读判定应得到 `present`;不并入时其行为与此前一致。 +- `renderer_bridge.plan_deploy(asar_path)` 是并入钩子的数据来源:只读,复用 `_inspect_deploy` 的判定与改写;已带桥、布局无法验证或读档失败返回 `None`。 +- `overlay_install._install_overlay` 只在已加载的 `patch_install` 模块声明了并入能力(模块常量 `EXTRA_MODIFY`)时才传钩子;旧运行目录模块或测试替身没有该常量时调用形状不变。 +- 卸载不并入桥剥离;独立安装链不并入桥。 + +## 验收 + +| 场景 | 可观察结果 | +|---|---| +| `repack()` 改写任意条目 | 产物与旧实现逐字节相同 | +| 生成待替换包 | `source_fingerprint` 只对来源归档调用一次;sidecar 的 `tmp.sha256` 等于待替换包实际字节摘要 | +| `repack` 被不经过写入期摘要的替身顶替 | 回退整包回读,安装照常成功,摘要正确 | +| 重打包后 stage 被外部触碰 | 安装失败、不替换归档、不留 sidecar | +| 客户端未运行时完整安装(本进程替换) | 来源归档只整读两次(指纹一次、重打包一次),整写一次;归档含注入行 | +| 复用已有待替换包后替换 | 替换前仍完整验包 | +| 钩子给出与来源一致的桥改写 | 一次重打包后 `ensure_renderer_bridge` 判定 `present`;全程只有一次整写 | +| 钩子异常 / 形态不符 / 来源指纹不符 / 路径不在归档 / 触碰主入口 | 不并入,loader 照常安装,不抛出 | +| 已安装早退与复用待替换包 | 不调用钩子 | +| 待替换包含桥(客户端占用归档) | 重启标记与主安装同语义;监控收尾后桥判定 `present` | +| 已加载模块无并入能力 | `install()` 调用形状与此前一致 | +| 手机补装链、卸载桥剥离、监控验包 | 行为与此前一致 | + +自动化验收使用 `tests/test_pending_asar.py`、`tests/test_renderer_bridge.py`、`tests/test_plugin_runtime.py`;Windows 上「首次安装由两次完全退出收敛为一次」需实机验收。 diff --git a/tests/test_pending_asar.py b/tests/test_pending_asar.py index ae55bc0e9..775e2e199 100644 --- a/tests/test_pending_asar.py +++ b/tests/test_pending_asar.py @@ -1200,5 +1200,269 @@ def test_syntax_check_on_protected_here_dir_skips_without_unbounded_retry(self): self.assertIn("syntax check failed to run", buf.getvalue()) +ASSET = "/renderer/assets/styles-abc.js" +ASSET_BYTES = b"original renderer asset" + + +class SingleTransactionTests(unittest.TestCase): + """归档单事务(specs/asar-single-transaction.md):写入期摘要、进程内校验复用与旁路改写并入。""" + + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name).resolve() # macOS 的 /var 是符号链接,set_target 会 resolve + self.home = self.root / "home" + self.home.mkdir() + env = mock.patch.dict(os.environ, {"HOME": str(self.home), "USERPROFILE": str(self.home), + "ZUSAGE_NO_MONITOR": "1", "ZUSAGE_MONITOR_QUIET": ""}) + env.start() + self.addCleanup(env.stop) + spec = importlib.util.spec_from_file_location("single_transaction_test", ROOT / "patch_install.py") + self.pi = importlib.util.module_from_spec(spec) + spec.loader.exec_module(self.pi) + self.asar = self.root / "app.asar" + make_asar(self.asar, files={"out/main/index.js": b"console.log('official v1');", + ASSET.lstrip("/"): ASSET_BYTES}) + self.runtime = self.root / "runtime" + self.runtime.mkdir() + (self.runtime / "inject-main.cjs").write_text("// fixture", encoding="utf-8") + self.pi.set_target(self.asar) + self.pi.set_runtime(self.runtime) + self.pi._LANG = "en" + output = contextlib.redirect_stdout(io.StringIO()) + output.__enter__() + self.addCleanup(output.__exit__, None, None, None) + for target, kwargs in (("client_running", {"return_value": False}), + ("syntax_check", {"return_value": True}), + ("launch_monitor", {"return_value": None})): + patched = mock.patch.object(self.pi, target, **kwargs) + patched.start() + self.addCleanup(patched.stop) + + def reset(self, files=None, unpacked=False): + """还原成未注入的夹具归档:mtime 显式前移,免得同尺寸重写逃过身份戳比对。""" + for leftover in self.root.glob("app.asar.zusage.tmp*"): + leftover.unlink() + make_asar(self.asar, files=files if files is not None else { + "out/main/index.js": b"console.log('official v1');", ASSET.lstrip("/"): ASSET_BYTES}, unpacked=unpacked) + st = self.asar.stat() + os.utime(self.asar, ns=(st.st_atime_ns, st.st_mtime_ns + 2_000_000_000)) + + def entry(self): + return self.pi.entry_bytes_of(self.asar) + + def packed(self, path, archive=None): + with open(archive or self.asar, "rb") as stream: + header, base = self.pi.read_header(stream) + node = dict(self.pi.iter_files(header))[path] + stream.seek(base + int(node["offset"])) + return stream.read(node["size"]) + + def plan(self, modify=None, source=None): + """与本次来源一致的合法钩子返回值。""" + return lambda: {"source": self.pi.source_fingerprint(self.asar) if source is None else source, + "modify": {ASSET: b"bridge bytes"} if modify is None else modify} + + def test_repack_streams_same_bytes_as_reference(self): + files = {"out/main/index.js": b"console.log('official v1');", "package.json": b'{"name":"@zcode/desktop"}', + "a/b/big.bin": bytes(range(256)) * 30000, # 大于 BLOCK,走分块读 + "a/small.txt": b"tiny", "z/last.js": b"export const q=1;"} + make_asar(self.asar, files=files) + modify = {"/a/small.txt": b"replaced contents", "/a/b/big.bin": b"now small"} + # 参考实现 = 改动前的算法:整包拼在内存里、头写完后一次写出 + with open(self.asar, "rb") as src: + header, base = self.pi.read_header(src) + header = json.loads(json.dumps(header)) + nodes = dict(self.pi.iter_files(header)) + parts, offset = [], 0 + for p, node in nodes.items(): + if p in modify: + data = modify[p] + node["size"] = len(data) + node["integrity"] = self.pi.compute_integrity(data) + else: + src.seek(base + int(node["offset"])) + data = src.read(node["size"]) + node["offset"] = str(offset) + parts.append(data) + offset += len(data) + raw = json.dumps(header, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + d = len(raw) + c = (d + 4 + self.pi.ALIGN - 1) // self.pi.ALIGN * self.pi.ALIGN + reference = struct.pack("<4I", 4, c + 4, c, d) + raw + b"\0" * (c - d - 4) + b"".join(parts) + out = self.root / "repacked.asar" + self.assertEqual(self.pi.repack(self.asar, modify, out), out) + self.assertEqual(out.read_bytes(), reference) + + def test_repack_digest_matches_file_without_reread(self): + out = self.root / "repacked.asar" + with self.pi._repack_digest() as sink: + self.pi.repack(self.asar, {ASSET: b"bridge bytes"}, out) + self.assertEqual(sink.size, out.stat().st_size) + self.assertEqual(sink.hash.hexdigest(), hashlib.sha256(out.read_bytes()).hexdigest()) + # 摘要接收方只在持有期间有效:其后的 repack 不再喂 + with self.pi._repack_digest() as second: + pass + self.pi.repack(self.asar, {}, self.root / "second.asar") + self.assertEqual(second.size, 0) + + def test_prepare_hashes_only_the_source_archive(self): + with mock.patch.object(self.pi, "source_fingerprint", wraps=self.pi.source_fingerprint) as hashes: + meta = self.pi.prepare_tmp({"/" + self.pi.ENTRY: self.entry() + self.pi.INJECT_LINE.encode()}) + self.assertEqual([Path(call.args[0]) for call in hashes.call_args_list], [self.asar]) + digest = hashlib.sha256(self.pi.TMP.read_bytes()).hexdigest() + self.assertEqual(meta["tmp"]["sha256"], digest) + sidecar = json.loads(self.pi.TMP_META.read_text()) + self.assertEqual(sidecar["tmp"]["sha256"], digest) + self.assertEqual(sidecar["tmp"]["ino"], self.pi.TMP.stat().st_ino, "身份戳须是 rename 之后的 TMP") + + def test_digest_falls_back_when_repack_is_a_stand_in(self): + real = self.pi.repack + prebuilt = self.root / "prebuilt.asar" + real(self.asar, {"/" + self.pi.ENTRY: self.entry() + self.pi.INJECT_LINE.encode()}, prebuilt) + + def stand_in(src, modify, dst): # 不经写入期摘要:直接搬一份预先生成好的包 + shutil.copyfile(prebuilt, dst) + with mock.patch.object(self.pi, "repack", side_effect=stand_in), \ + mock.patch.object(self.pi, "source_fingerprint", wraps=self.pi.source_fingerprint) as hashes: + meta = self.pi.prepare_tmp({"/" + self.pi.ENTRY: self.entry() + self.pi.INJECT_LINE.encode()}) + hashed = [Path(call.args[0]) for call in hashes.call_args_list] + self.assertEqual(len(hashed), 3, "来源、stage、落成后的 TMP 各整包回读一次") + self.assertIn(self.pi.TMP, hashed) + self.assertEqual(meta["tmp"]["sha256"], hashlib.sha256(self.pi.TMP.read_bytes()).hexdigest()) + + def test_stage_touched_after_digest_is_rejected(self): + real_stage = self.pi._repack_stage + + def stage_then_touch(stage, modify): + fingerprint = real_stage(stage, modify) + with open(stage, "ab") as stream: + stream.write(b"\0") + return fingerprint + with mock.patch.object(self.pi, "_repack_stage", side_effect=stage_then_touch), \ + mock.patch.object(self.pi.os, "replace") as replace: + with self.assertRaises(self.pi.PendingTmpError): + self.pi.prepare_tmp({"/" + self.pi.ENTRY: self.entry() + self.pi.INJECT_LINE.encode()}) + replace.assert_not_called() + self.assertFalse(self.pi.TMP.exists()) + self.assertFalse(self.pi.TMP_META.exists()) + self.assertNotIn(self.pi.INJECT_LINE.encode(), self.entry()) + + def test_install_hashes_source_once_and_repacks_once(self): + with mock.patch.object(self.pi, "source_fingerprint", wraps=self.pi.source_fingerprint) as hashes, \ + mock.patch.object(self.pi, "repack", wraps=self.pi.repack) as repack, \ + mock.patch.object(self.pi.os, "replace", wraps=os.replace) as replace: + self.assertTrue(self.pi.install()) + self.assertEqual([Path(call.args[0]) for call in hashes.call_args_list], [self.asar]) + self.assertEqual(repack.call_count, 1) + self.assertEqual((Path(replace.call_args.args[0]), Path(replace.call_args.args[1])), (self.pi.TMP, self.asar)) + self.assertIn(self.pi.INJECT_LINE.encode(), self.entry()) + self.assertFalse(self.pi.TMP_META.exists()) + + def test_reused_pending_package_is_fully_verified_before_replace(self): + self.pi.prepare_tmp({"/" + self.pi.ENTRY: self.entry() + self.pi.INJECT_LINE.encode()}) + with mock.patch.object(self.pi, "source_fingerprint", wraps=self.pi.source_fingerprint) as hashes, \ + mock.patch.object(self.pi, "repack", side_effect=AssertionError("must not repack")): + self.assertTrue(self.pi.install()) + # 复用的包不是本进程生成的:来源指纹之外,替换前仍整包验来源与 TMP + self.assertEqual([Path(call.args[0]) for call in hashes.call_args_list], + [self.asar, self.asar, self.pi.TMP]) + self.assertIn(self.pi.INJECT_LINE.encode(), self.entry()) + + def test_remove_hashes_source_once_after_a_fresh_package(self): + self.assertTrue(self.pi.install()) + with mock.patch.object(self.pi, "source_fingerprint", wraps=self.pi.source_fingerprint) as hashes, \ + mock.patch.object(self.pi, "repack", wraps=self.pi.repack) as repack: + self.assertTrue(self.pi.remove()) + self.assertEqual([Path(call.args[0]) for call in hashes.call_args_list], [self.asar]) + self.assertEqual(repack.call_count, 1) + self.assertNotIn(self.pi.INJECT_LINE.encode(), self.entry()) + + def test_install_merges_extra_modify_into_the_same_repack(self): + with mock.patch.object(self.pi, "repack", wraps=self.pi.repack) as repack: + self.assertTrue(self.pi.install(extra_modify=self.plan())) + self.assertEqual(repack.call_count, 1) + modify = repack.call_args.args[1] + self.assertEqual(modify[ASSET], b"bridge bytes") + self.assertEqual(modify["/" + self.pi.ENTRY].count(self.pi.INJECT_LINE.encode()), 1) + self.assertEqual(self.packed(ASSET), b"bridge bytes") + self.assertIn(self.pi.INJECT_LINE.encode(), self.entry()) + + def test_install_ignores_extra_modify_it_cannot_trust(self): + entry = "/" + self.pi.ENTRY + other = self.pi.source_fingerprint(self.asar) + + def raises(): + raise RuntimeError("bridge planner exploded") + cases = { + "no plan": lambda: None, + "not a dict": lambda: [ASSET], + "raises": raises, + "modify not a dict": lambda: {"source": other, "modify": "nope"}, + "modify empty": lambda: {"source": other, "modify": {}}, + "source missing": lambda: {"modify": {ASSET: b"bridge bytes"}}, + "source sha differs": lambda: {"source": dict(other, sha256="0" * 64), "modify": {ASSET: b"bridge bytes"}}, + "source is another file": self.plan(source=self.pi.source_fingerprint(self.runtime / "inject-main.cjs")), + "path missing from archive": self.plan(modify={"/nope/styles.js": b"bridge bytes"}), + "path touches the entry": self.plan(modify={entry: b"evil entry"}), + "entry smuggled next to a good path": self.plan(modify={ASSET: b"bridge bytes", entry: b"evil entry"}), + "content is not bytes": self.plan(modify={ASSET: "text"}), + "content is empty": self.plan(modify={ASSET: b""}), + } + for label, hook in cases.items(): + with self.subTest(label=label): + self.reset() + with mock.patch.object(self.pi, "repack", wraps=self.pi.repack) as repack: + self.assertTrue(self.pi.install(extra_modify=hook)) + modify = repack.call_args.args[1] + self.assertEqual(set(modify), {entry}, "只有入口改写进入重打包") + self.assertIn(self.pi.INJECT_LINE.encode(), modify[entry]) + self.assertEqual(self.packed(ASSET), ASSET_BYTES) + self.assertIn(self.pi.INJECT_LINE.encode(), self.entry()) + + def test_extra_modify_skips_unpacked_paths(self): + self.reset(files={"out/main/index.js": b"console.log('official v1');", "package.json": b'{"name":"x"}'}, + unpacked=True) + with mock.patch.object(self.pi, "repack", wraps=self.pi.repack) as repack: + self.assertTrue(self.pi.install(extra_modify=self.plan(modify={"/package.json": b"{}"}))) + self.assertEqual(set(repack.call_args.args[1]), {"/" + self.pi.ENTRY}) + + def test_extra_modify_not_consulted_on_early_return_or_reuse(self): + forbidden = mock.Mock(side_effect=AssertionError("must not plan")) + self.pi.prepare_tmp({"/" + self.pi.ENTRY: self.entry() + self.pi.INJECT_LINE.encode()}) + with mock.patch.object(self.pi, "repack", side_effect=AssertionError("must not repack")): + self.assertTrue(self.pi.install(extra_modify=forbidden)) # 复用磁盘上的待替换包 + forbidden.assert_not_called() + self.assertTrue(self.pi.install()) # 落盘后再次安装 + with mock.patch.object(self.pi, "repack", side_effect=AssertionError("must not repack")): + self.assertTrue(self.pi.install(extra_modify=forbidden)) # 已安装早退 + forbidden.assert_not_called() + # 手机补装只处理手机钩子(夹具没有 package.json,按布局无法验证返回 False),同样不问钩子 + self.pi.install(mobile_only=True, extra_modify=forbidden) + forbidden.assert_not_called() + + def test_merged_package_becomes_pending_while_the_client_holds_the_archive(self): + real_replace = os.replace + + def locked(src, dst): + if Path(dst) == self.asar: + raise PermissionError(13, "The process cannot access the file") + return real_replace(src, dst) + with mock.patch.object(self.pi, "client_running", return_value=True), \ + mock.patch.object(self.pi.os, "replace", side_effect=locked), \ + mock.patch.object(self.pi, "repack", wraps=self.pi.repack) as repack: + self.assertFalse(self.pi.install(extra_modify=self.plan())) + self.assertEqual(repack.call_count, 1) + meta = self.pi.pending_tmp("install") + self.assertEqual(self.packed(ASSET, self.pi.TMP), b"bridge bytes") + self.assertIn(self.pi.INJECT_LINE.encode(), self.pi.entry_bytes_of(self.pi.TMP)) + self.assertTrue(meta["validated"]) + # 客户端退出后收尾:监控所在的另一进程完整验包,一次替换同时落下 loader 与桥 + self.assertTrue(self.pi.install(finalize=True)) + self.assertEqual(self.packed(ASSET), b"bridge bytes") + self.assertIn(self.pi.INJECT_LINE.encode(), self.entry()) + self.assertFalse(self.pi.TMP.exists()) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_plugin_runtime.py b/tests/test_plugin_runtime.py index 2feb26230..f224c7cd6 100644 --- a/tests/test_plugin_runtime.py +++ b/tests/test_plugin_runtime.py @@ -472,6 +472,49 @@ def test_install_still_syncs_installs_and_clears_markers(self): self.assertFalse((self.runtime / ".plugin-overlay-optout").exists()) self.assertFalse((self.runtime / ".plugin-overlay-nudge").exists()) + def test_install_passes_the_bridge_hook_only_to_capable_modules(self): + # 旧运行目录模块/替身没有 EXTRA_MODIFY=True:install() 的调用形状保持不变 + for capable, extra in ((False, {}), (True, {"extra_modify": mock.ANY})): + with self.subTest(capable=capable): + patch_install = self.patch_install_stub() + patch_install.install.return_value = True + if capable: + patch_install.EXTRA_MODIFY = True + with mock.patch.object(installer, "resolve_paths", return_value=(self.runtime, patch_install)): + with self.assertRaises(SystemExit) as exit_code: + self.run_main("install") + self.assertEqual(exit_code.exception.code, 0) + patch_install.install.assert_called_once_with(before_publish=mock.ANY, **extra) + + def test_bridge_hook_is_wired_to_plan_deploy_and_deferred_to_the_installer(self): + patch_install = self.patch_install_stub() + patch_install.EXTRA_MODIFY = True + patch_install.install.return_value = True + with mock.patch.object(installer, "resolve_paths", return_value=(self.runtime, patch_install)), \ + mock.patch.object(installer, "_plan_bridge", return_value={"planned": True}) as plan: + self.assertTrue(installer._install_overlay(self.runtime, patch_install)) + plan.assert_not_called() # 只有确需生成新包时 patch_install 才调用钩子 + hook = patch_install.install.call_args.kwargs["extra_modify"] + self.assertEqual(hook(), {"planned": True}) + plan.assert_called_once_with(patch_install) + + def test_bridge_plan_failures_never_break_the_install(self): + planner = mock.Mock(side_effect=RuntimeError("planner exploded")) + for label, outcome in (("raises", planner), ("no plan", mock.Mock(return_value=None))): + with self.subTest(label=label): + patch_install = self.patch_install_stub() + patch_install.EXTRA_MODIFY = True + patch_install.install.return_value = True + errors = io.StringIO() + with mock.patch.dict(sys.modules, {"renderer_bridge": mock.Mock(plan_deploy=outcome)}), \ + mock.patch.object(installer, "resolve_paths", + return_value=(self.runtime, patch_install)), \ + contextlib.redirect_stderr(errors): + self.assertTrue(installer._install_overlay(self.runtime, patch_install)) + hook = patch_install.install.call_args.kwargs["extra_modify"] + self.assertIsNone(hook()) + self.assertEqual("renderer bridge plan failed" in errors.getvalue(), label == "raises") + def test_install_deploys_renderer_bridge_and_remove_strips_it(self): bridge = mock.Mock() bridge.ensure_deployed.return_value = {"status": "patched", "version": "3.16.1", "detail": ""} diff --git a/tests/test_renderer_bridge.py b/tests/test_renderer_bridge.py index c68ce9a2a..18a36832a 100644 --- a/tests/test_renderer_bridge.py +++ b/tests/test_renderer_bridge.py @@ -1,5 +1,9 @@ +import contextlib import hashlib +import importlib.util +import io import json +import os from pathlib import Path import re import shutil @@ -1013,5 +1017,117 @@ def test_asset_drift_for_pinned_version_fails_closed(self): '''.replace('setTimeout(resolve,0)', 'Promise.resolve().then(resolve)') -if __name__ == '__main__': +class PlanDeployTests(unittest.TestCase): + """并入钩子 renderer_bridge.plan_deploy(specs/asar-single-transaction.md):loader 与桥 + 落进同一次重打包,桥在任何不利情形下都只是不并入。""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory(prefix='bridge-plan-') + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name).resolve() + self.target = self.root / 'app.asar' + archive(self.target, extra={'/out/main/index.js': b"console.log('official');"}) + self.pin = patch.object(bridge, 'HOST_TARGETS', [synthetic_target(bridge.NEWEST, MINI)]) + self.pin.start() + self.addCleanup(self.pin.stop) + # 私有模块实例:不动全局 patch_install 的 ASAR/RUNTIME 状态 + spec = importlib.util.spec_from_file_location( + 'plan_deploy_patch_install', Path(__file__).resolve().parents[1] / 'patch_install.py') + self.pi = importlib.util.module_from_spec(spec) + spec.loader.exec_module(self.pi) + runtime = self.root / 'runtime' + runtime.mkdir() + (runtime / 'inject-main.cjs').write_text('// fixture', encoding='utf-8') + self.pi.set_target(self.target) + self.pi.set_runtime(runtime) + self.pi._LANG = 'en' + environment = patch.dict(os.environ, {'ZUSAGE_NO_MONITOR': '1', 'ZUSAGE_MONITOR_QUIET': '1'}) + environment.start() + self.addCleanup(environment.stop) + for target, kwargs in (('client_running', {'return_value': False}), + ('syntax_check', {'return_value': True}), + ('launch_monitor', {'return_value': None})): + patched = patch.object(self.pi, target, **kwargs) + patched.start() + self.addCleanup(patched.stop) + quiet = contextlib.redirect_stdout(io.StringIO()) + quiet.__enter__() + self.addCleanup(quiet.__exit__, None, None, None) + + def rebuild(self): + """换一份内容不同的归档(mtime 显式前移,身份戳必然变)。""" + archive(self.target, extra={'/out/main/index.js': b"console.log('official v2');"}) + st = self.target.stat() + os.utime(self.target, ns=(st.st_atime_ns, st.st_mtime_ns + 2_000_000_000)) + + def install_with_plan(self, repack): + return self.pi.install(extra_modify=lambda: bridge.plan_deploy(self.target)) + + def test_missing_bridge_is_planned_without_touching_the_archive(self): + before, mtime = self.target.read_bytes(), self.target.stat().st_mtime_ns + planned = bridge.plan_deploy(self.target) + self.assertEqual(sorted(planned), ['modify', 'source']) + self.assertEqual(planned['source'], asar.source_fingerprint(self.target)) + self.assertEqual(list(planned['modify']), [bridge.ASSET]) + self.assertEqual(planned['modify'][bridge.ASSET], patched_module(MINI, bridge.NEWEST)) + self.assertNotIn(bridge.MARKER, read(self.target)) + self.assertEqual((self.target.read_bytes(), self.target.stat().st_mtime_ns), (before, mtime), + 'plan_deploy 只读') + + def test_present_bridge_is_not_planned(self): + self.assertEqual(bridge.ensure_deployed(self.target)['status'], 'patched') + self.assertIsNone(bridge.plan_deploy(self.target)) + + def test_unknown_host_layout_is_not_planned(self): + archive(self.target, module=b'console.log("no renderer shape here");') + self.assertIsNone(bridge.plan_deploy(self.target)) + + def test_unreadable_archive_is_not_planned(self): + self.assertIsNone(bridge.plan_deploy(self.root / 'missing.asar')) + + def test_loader_install_and_bridge_land_in_one_repack(self): + with patch.object(self.pi, 'repack', wraps=self.pi.repack) as repack: + self.assertTrue(self.install_with_plan(repack)) + self.assertEqual(bridge.ensure_deployed(self.target)['status'], 'present') + self.assertEqual(repack.call_count, 1, 'loader 与桥只重打包一次') + self.assertIn(self.pi.INJECT_LINE.encode(), self.pi.entry_bytes_of(self.target)) + self.assertIn(bridge.MARKER, read(self.target)) + self.assertEqual(read(self.target, '/other.txt'), b'third party bytes\0\xff', '第三方资产原样保留') + self.assertEqual(metadata(self.target)['/alias'], {'link': 'other.txt'}, '链接项原样保留') + self.assertTrue(metadata(self.target)['/external'].get('unpacked'), '外置项原样保留') + + def test_stale_plan_falls_back_to_the_separate_bridge_pass(self): + planned = bridge.plan_deploy(self.target) + self.rebuild() + with patch.object(self.pi, 'repack', wraps=self.pi.repack) as repack, \ + patch.object(bridge, '_rewrite_to', wraps=bridge._rewrite_to) as bridge_writes: + self.assertTrue(self.pi.install(extra_modify=lambda: planned)) + self.assertEqual(bridge.ensure_deployed(self.target)['status'], 'patched', + '过期计划没有并入:桥由事后的独立补装落下') + self.assertEqual(repack.call_count, 1, 'loader 只重打包一次,且这次不带桥') + self.assertNotIn(bridge.MARKER, self.pi.entry_bytes_of(self.target)) + self.assertEqual(bridge_writes.call_count, 1, '桥走原来的独立写入') + + def test_merged_package_survives_a_pending_swap(self): + real_replace = os.replace + + def locked(src, dst): + if Path(dst) == self.target: + raise PermissionError(13, 'The process cannot access the file') + return real_replace(src, dst) + with patch.object(self.pi, 'client_running', return_value=True), \ + patch.object(self.pi.os, 'replace', side_effect=locked), \ + patch.object(self.pi, 'repack', wraps=self.pi.repack) as repack: + self.assertFalse(self.install_with_plan(repack)) + self.assertEqual(self.pi.pending_tmp('install')['operation'], 'install') + self.assertIn(bridge.MARKER, read(self.pi.TMP)) + # 客户端退出后收尾(client_running 回到夹具默认的 False):监控所在的另一进程完整验包 + with patch.object(self.pi, 'repack', wraps=self.pi.repack) as repack: + self.assertTrue(self.pi.install(finalize=True)) + self.assertEqual(bridge.ensure_deployed(self.target)['status'], 'present') + self.assertEqual(repack.call_count, 0, '排定与收尾之间没有第二次重打包') + self.assertIn(self.pi.INJECT_LINE.encode(), self.pi.entry_bytes_of(self.target)) + + +if __name__ == "__main__": unittest.main() diff --git a/tests/test_session_start_channels.py b/tests/test_session_start_channels.py index ad4d3621b..4b4bd2f6f 100644 --- a/tests/test_session_start_channels.py +++ b/tests/test_session_start_channels.py @@ -171,7 +171,7 @@ def test_corrupt_config_still_attempts_auto_install(self): self.assertEqual(json.loads(self.config.read_text())["plugin_auto_install_overlay"], "false") def test_unfinished_auto_install_nudge_restores_monitor_flags_and_redirects_logs(self): - def unfinished(before_publish): + def unfinished(before_publish, extra_modify): self.assertEqual(os.environ["ZUSAGE_NO_MONITOR"], "1") self.assertEqual(os.environ["ZUSAGE_MONITOR_QUIET"], "1") print("fixture install unfinished") @@ -190,7 +190,7 @@ def test_pending_install_failure_nudges_full_quit_instead_of_retry(self): # issue #120:客户端运行中、待收尾包已排定的失败,重试 /install-overlay 无法 # 前进(只会再 repack 一次再失败);提示必须指向「完全退出 ZCode 等自动收尾」, # 并保留卸载豁免出口,不能继续引导无效重试。 - self.install.side_effect = lambda before_publish: False + self.install.side_effect = lambda before_publish, extra_modify: False with mock.patch.object(self.pi, "pending_tmp", return_value={"operation": "install"}) as pending, \ mock.patch.object(self.pi, "client_running", return_value=True): output, _ = self.invoke() @@ -208,7 +208,7 @@ def test_pending_install_failure_nudges_full_quit_instead_of_retry(self): def test_pending_nudge_names_host_incompatibility_when_build_unregistered(self): # issue #247:已装版本未登记适配当前宿主 build 时,反复「已排定」必须讲清为什么 # 排定也修不好(需要升级插件),且自动更新绕过 1h 限频立即尝试。 - self.install.side_effect = lambda before_publish: False + self.install.side_effect = lambda before_publish, extra_modify: False with mock.patch.object(self.installer, "_host_build", return_value="3.17.2"), \ mock.patch.object(self.installer, "_host_registered", return_value=False), \ mock.patch.object(self.pi, "pending_tmp", return_value={"operation": "install"}), \ @@ -221,7 +221,7 @@ def test_pending_nudge_names_host_incompatibility_when_build_unregistered(self): def test_protected_dir_nudge_also_carries_the_compat_note(self): # issue #247 review:受保护目录提示分支同样要补兼容性说明 - self.install.side_effect = lambda before_publish: False + self.install.side_effect = lambda before_publish, extra_modify: False with mock.patch.object(self.installer, "_host_build", return_value="3.17.2"), \ mock.patch.object(self.installer, "_host_registered", return_value=False), \ mock.patch.object(self.pi, "pending_tmp", return_value={"operation": "install"}), \ @@ -234,7 +234,7 @@ def test_protected_dir_nudge_also_carries_the_compat_note(self): def test_generic_retry_nudge_also_carries_the_compat_note(self): # issue #247 review:普通安装失败提示分支同样要补兼容性说明 - self.install.side_effect = lambda before_publish: False + self.install.side_effect = lambda before_publish, extra_modify: False with mock.patch.object(self.installer, "_host_build", return_value="3.17.2"), \ mock.patch.object(self.installer, "_host_registered", return_value=False): output, _ = self.invoke() @@ -266,7 +266,7 @@ def test_session_record_carries_bridge_status_when_injected(self): def test_pending_without_running_client_keeps_retry_hint(self): # 待收尾包有效但客户端未在跑(如杀软瞬时占用的 POSIX 场景):重试仍然有意义, # 维持原有提示。 - self.install.side_effect = lambda before_publish: False + self.install.side_effect = lambda before_publish, extra_modify: False with mock.patch.object(self.pi, "pending_tmp", return_value={"operation": "install"}), \ mock.patch.object(self.pi, "client_running", return_value=False): output, _ = self.invoke() @@ -297,7 +297,9 @@ def test_installed_no_session_text_notice_and_marker_untouched(self): def test_successful_auto_install_stays_silent(self): # v172:自动安装成功同样不注入文字(红点由 marker → restartRequired 推送驱动)。 - def install(before_publish): + def install(before_publish, extra_modify): + # 真实 patch_install 模块带并入能力:hook 链会把桥钩子交给安装器(specs/asar-single-transaction.md) + self.assertTrue(callable(extra_modify), "支持并入能力的模块应收到桥钩子") import runtime_lock installation = {"asar": str(self.asar), "entryHash": "a" * 64} before_publish(installation) From 6dd617a6bab9284e5dcd98c320c77b0e2d808965 Mon Sep 17 00:00:00 2001 From: tanranran Date: Thu, 26 Nov 2026 12:15:39 +0800 Subject: [PATCH 2/4] =?UTF-8?q?feat(install):=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E5=8F=AA=E8=AF=BB=E4=BD=93=E6=A3=80=E5=91=BD=E4=BB=A4=20/zusag?= =?UTF-8?q?e-doctor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 状态条、工具栏 chip 或回答末尾的速率行不显示时,把开放式的多轮排查收敛成一次命令。 - overlay_install.py 新增 doctor 子命令:逐项报告插件安装与启用、市场登记、客户端归档与注入、待替换包与收尾监控、运行目录、更新情况,按优先级给出建议动作 - 只读取各模块的既有判定;落盘动作只有安装器的可写性探针与监控去重锁的试取,不读凭据文件 - 安装已排定、在等客户端退出时不再建议重跑 /install-overlay(重跑只会复用同一个待替换包) - 新增命令文件 commands/zusage-doctor.md,并登记到同步清单、发布打包清单、解包白名单与两份插件清单 规格:specs/zusage-doctor.md。 --- .../.claude-plugin/plugin.json | 1 + .../.zcode-plugin/plugin.json | 1 + .../commands/zusage-doctor.md | 24 ++ .../overlay_install.py | 313 ++++++++++++++++ .../release_unpack.py | 1 + release_tool.py | 3 +- release_unpack.py | 1 + specs/zusage-doctor.md | 60 +++ sync_plugin.py | 1 + tests/test_zusage_doctor.py | 349 ++++++++++++++++++ 10 files changed, 753 insertions(+), 1 deletion(-) create mode 100644 plugins/zcode-token-usage-statusbar/commands/zusage-doctor.md create mode 100644 specs/zusage-doctor.md create mode 100644 tests/test_zusage_doctor.py diff --git a/plugins/zcode-token-usage-statusbar/.claude-plugin/plugin.json b/plugins/zcode-token-usage-statusbar/.claude-plugin/plugin.json index 10fd7c302..f5f73fff8 100644 --- a/plugins/zcode-token-usage-statusbar/.claude-plugin/plugin.json +++ b/plugins/zcode-token-usage-statusbar/.claude-plugin/plugin.json @@ -28,6 +28,7 @@ "plugins/zcode-token-usage-statusbar/README.md", "plugins/zcode-token-usage-statusbar/commands/install-overlay.md", "plugins/zcode-token-usage-statusbar/commands/uninstall-overlay.md", + "plugins/zcode-token-usage-statusbar/commands/zusage-doctor.md", "plugins/zcode-token-usage-statusbar/commands/usage.md", "plugins/zcode-token-usage-statusbar/engine-patch.cjs", "plugins/zcode-token-usage-statusbar/mobile-relay.cjs", diff --git a/plugins/zcode-token-usage-statusbar/.zcode-plugin/plugin.json b/plugins/zcode-token-usage-statusbar/.zcode-plugin/plugin.json index 10fd7c302..f5f73fff8 100644 --- a/plugins/zcode-token-usage-statusbar/.zcode-plugin/plugin.json +++ b/plugins/zcode-token-usage-statusbar/.zcode-plugin/plugin.json @@ -28,6 +28,7 @@ "plugins/zcode-token-usage-statusbar/README.md", "plugins/zcode-token-usage-statusbar/commands/install-overlay.md", "plugins/zcode-token-usage-statusbar/commands/uninstall-overlay.md", + "plugins/zcode-token-usage-statusbar/commands/zusage-doctor.md", "plugins/zcode-token-usage-statusbar/commands/usage.md", "plugins/zcode-token-usage-statusbar/engine-patch.cjs", "plugins/zcode-token-usage-statusbar/mobile-relay.cjs", diff --git a/plugins/zcode-token-usage-statusbar/commands/zusage-doctor.md b/plugins/zcode-token-usage-statusbar/commands/zusage-doctor.md new file mode 100644 index 000000000..920cf57bf --- /dev/null +++ b/plugins/zcode-token-usage-statusbar/commands/zusage-doctor.md @@ -0,0 +1,24 @@ +--- +description: 只读体检 ZCode 用量状态条插件:安装登记、注入状态、待替换包、运行目录与更新,逐项给出修法 +--- +帮助用户排查 zcode-token-usage-statusbar 的状态条、工具栏 chip 或回答末尾速率行不显示的问题。本命令只做诊断,不修改客户端、运行目录、配置或插件登记;状态条正常时不需要运行。 + +执行:用 Bash 运行体检脚本(插件根目录 = 本命令文件所在目录的上一级): + + python3 "<插件根目录>/overlay_install.py" doctor + +Windows 上 `python3` 可能是 Microsoft Store 存根(静默失败),依次改用 `python`、`py -3`;macOS/Linux 用 `python3`。 + +结果处理: + +- 把输出原样转述给用户:`[OK]` 正常,`[WARN]` 需要注意,`[FAIL]` 异常;再按「建议动作」的编号逐条说明。 +- 「建议动作」里涉及修改客户端文件、提权、重启 ZCode 或卸载的,先征得用户同意再执行;不要自行重启 ZCode。 +- 输出以「体检未能完成」开头时,说明体检脚本自身出错:原样转述,不要猜测原因或声称已修复。 +- 不要凭退出码下结论:体检跑完恒为 0,结论只看输出里的状态标签与建议动作。 + +补充说明(用户问起时再展开,不必每次输出): + +- 体检只读取插件登记、归档入口、运行目录与诊断文件,不读取也不输出任何凭据。唯一的落盘动作是在客户端安装目录做一次「建后即删」的可写性探针,与安装器用的是同一个。 +- 状态条未注入时 `/install-overlay` 可手动安装;自动安装始终开启,新建或恢复会话也会自动修复。 + +用户附加要求:$ARGUMENTS diff --git a/plugins/zcode-token-usage-statusbar/overlay_install.py b/plugins/zcode-token-usage-statusbar/overlay_install.py index 508d451c5..a86daafe3 100644 --- a/plugins/zcode-token-usage-statusbar/overlay_install.py +++ b/plugins/zcode-token-usage-statusbar/overlay_install.py @@ -6,6 +6,7 @@ python3 overlay_install.py install # 同步运行时文件 + 写入 asar 注入行(幂等) python3 overlay_install.py remove # 剥离注入行,并写豁免标记(hook 不再提示/自动安装) python3 overlay_install.py check # 查看注入状态、运行时目录与开关 + python3 overlay_install.py doctor # 只读体检:安装登记、注入、待替换、运行目录与更新,给出修法 hook 用法:hooks/session-start.py 调 run_hook(),stdout 只输出 hook 协议 JSON。 @@ -95,6 +96,9 @@ def default_runtime(): # 插件渠道已经提供 MCP,这里只清指向本插件脚本的遗留条目,绝不改用户其它 MCP 服务。 LEGACY_MCP_NAMES = ("zcode-token-usage-statusbar", "token-usage", "zusage") LEGACY_MCP_ENTRY_KEYS = frozenset(("command", "args", "type", "enabled")) +# 宿主里的插件与市场身份(与 plugin-updater.cjs 的 PLUGIN_ID、根 marketplace.json 的 name 同值) +PLUGIN_ID = "zcode-token-usage-statusbar@zusage-marketplace" +MARKETPLACE_ID = "zusage-marketplace" def host_cli_config(): @@ -1380,6 +1384,307 @@ def run_hook(): return out +def _doctor_json(path): + """读一个 JSON 文件:返回 (对象, 错误文案)。文件不存在时两者都是 None。""" + try: + value = json.loads(Path(path).read_text(encoding="utf-8")) + except FileNotFoundError: + return None, None + except (OSError, ValueError) as e: + return None, f"无法解析({e.__class__.__name__})" + return (value, None) if isinstance(value, dict) else (None, "不是 JSON 对象") + + +def _doctor_storage(): + """宿主插件存储根(…/cli/plugins),取值顺序同宿主:ZCODE_STORAGE_DIR、宿主 CLI 配置的 + storage.dir、默认 ~/.zcode。项目级配置不参与,体检在任何工作目录下结果一致。""" + home = real_home() + directory = os.environ.get("ZCODE_STORAGE_DIR", "").strip() + if not directory: + config, _ = _doctor_json(host_cli_config()) + storage = config.get("storage") if config else None + if isinstance(storage, dict) and isinstance(storage.get("dir"), str): + directory = storage["dir"].strip() + root = home / ".zcode" + if directory: + root = home / directory[2:] if directory.startswith("~/") else Path(directory).expanduser() + root = root if root.is_absolute() else home / root + return (root if root.name == "cli" else root / "cli") / "plugins" + + +def _doctor_channel(source): + """市场登记的来源形态换算成更新渠道说明。""" + if not isinstance(source, dict): + return "无法识别" + kind, url = source.get("source"), str(source.get("url") or "") + if kind == "directory": + return "本地目录市场(宿主按目录内容直接更新)" + if kind == "url": + return "清单直链" + if kind in ("github", "git"): + ref = source.get("ref") + if ref == "plugin-releases": + return "正式 Release 渠道(GitHub)" + if ref == "plugin-releases-gitcode": + return "正式 Release 渠道(GitCode)" + where = "GitCode" if url.startswith("https://gitcode.com/") else "GitHub" + return f"仓库源码(跟随 {ref or '默认分支'},{where},不经发布包校验)" + return "无法识别" + + +def doctor(runtime, pi): + """只读体检(/zusage-doctor 背后就是它,specs/zusage-doctor.md):逐项给出 + [OK]/[WARN]/[FAIL] 与建议动作。返回 (文本, 统计);任何一项出错都只记成该组的 FAIL。""" + lines, counts, ranked = [], {"OK": 0, "WARN": 0, "FAIL": 0}, [] + facts = {} + + def add(level, item, detail, action=None, rank=4): + counts[level] += 1 + lines.append(f" [{level}] {item}: {detail}") + if action is not None and all(action != text for _, text in ranked): + ranked.append((rank, action)) + + def section(title, body): + lines.extend(("", title)) + try: + body() + except Exception as e: # noqa: BLE001 — 一组检查出错不挡其余各组 + add("FAIL", title, f"这一组检查没能完成({e.__class__.__name__}: {e})") + + restart = "完全退出 ZCode(从托盘退出,只关窗口不算)再重新打开" + reinstall = ("插件没有装上:按 README「安装方法」重新安装;GitHub 连不上时改用 " + "https://gitcode.com/tanranran/zcode-token-usage-statusbar.git#plugin-releases-gitcode") + + def environment(): + add("OK", "Python", f"{sys.version_info[0]}.{sys.version_info[1]}({PYEXE})") + add("OK", "平台与运行目录", f"{sys.platform};{runtime}" + + ("(已存在)" if runtime.is_dir() else "(尚未创建,首次安装时生成)")) + + def registration(): + version = _plugin_version() + add("OK", "当前插件版本", version or "读不到 manifest") + storage = _doctor_storage() + inventory, error = _doctor_json(storage / "installed_plugins.json") + record = next((item for item in (inventory or {}).get("plugins", []) + if isinstance(item, dict) and item.get("id") == PLUGIN_ID), None) + if error or record is None: + add("FAIL", "插件安装登记", f"{storage} 里没有本插件的安装记录" if not error + else f"installed_plugins.json {error}", reinstall, rank=1) + else: + installed = Path(str(record.get("installPath") or "")) + present = installed.is_dir() + add("OK" if present else "FAIL", "插件安装登记", + f"v{record.get('version')}({record.get('scope')}){installed}" if present + else f"登记的安装目录不存在:{installed}", None if present else reinstall, rank=1) + if record.get("version") != version: + add("WARN", "插件版本", f"宿主登记 v{record.get('version')},正在运行的副本 v{version}", + restart + ",让宿主加载新版本") + config, error = _doctor_json(host_cli_config()) + if error: + add("FAIL", "插件启用状态", f"宿主 CLI 配置 {error},判断不了是否启用", + f"修复或移走 {host_cli_config()} 后重跑本命令", rank=1) + return + plugins = config.get("plugins") if config else None + plugins = plugins if isinstance(plugins, dict) else {} + enabled = plugins.get("enabledPlugins") + enabled = enabled.get(PLUGIN_ID) if isinstance(enabled, dict) else None + if plugins.get("enabled") is False: + add("FAIL", "插件启用状态", "宿主的插件总开关已关闭", + "在 ZCode 设置的插件管理里打开插件总开关,然后新建会话", rank=1) + elif enabled is False: + add("FAIL", "插件启用状态", "本插件已被禁用", + "在 ZCode 设置的插件管理里启用 ZCode Token Usage Statusbar,然后新建会话", rank=1) + else: + add("OK", "插件启用状态", "已启用" if enabled is True else "未显式设置,按默认启用") + known, error = _doctor_json(storage / "known_marketplaces.json") + market = next((item for item in (known or {}).get("marketplaces", []) + if isinstance(item, dict) and item.get("id") == MARKETPLACE_ID), None) + if error or market is None: + add("WARN", "市场登记", "没有 zusage-marketplace 的登记,更新时找不到来源", reinstall) + return + channel = _doctor_channel(market.get("source")) + add("WARN" if channel.startswith("仓库源码") else "OK", "市场登记", channel, + "想跟随正式版时,在 ZCode 设置的插件管理里把市场来源换成 " + "https://github.com/ByteRax/zcode-token-usage-statusbar#plugin-releases" + "(国内 https://gitcode.com/tanranran/zcode-token-usage-statusbar.git#plugin-releases-gitcode)" + if channel.startswith("仓库源码") else None) + failure = market.get("lastRefreshFailure") + if isinstance(failure, dict) and failure.get("message"): + add("WARN", "市场刷新", f"最近一次刷新失败:{str(failure['message'])[:200]}", + "检查网络后重新打开 ZCode 再试") + + def client_and_injection(): + if pi.ASAR is None: + facts["missing"] = True + add("FAIL", "客户端归档", "没有找到 ZCode 的 app.asar", + "确认 ZCode 桌面客户端的安装位置;装在非常见位置时,用环境变量 ZCODE_ASAR 指定 " + "app.asar 的完整路径后重跑本命令", rank=1) + return + add("OK", "客户端归档", str(pi.ASAR)) + facts["version"] = _host_build(pi) + add("OK" if facts["version"] else "WARN", "客户端版本", + facts["version"] or "读不到归档内的 package.json") + entry = pi.entry_bytes_of(pi.ASAR) + loader_lines = [match.group() for match in pi.ZUSAGE_LINE_RE.finditer(entry)] + if loader_lines == [pi.INJECT_LINE.encode()]: + add("OK", "状态条注入", "已注入,指向当前运行目录") + elif loader_lines: + add("WARN", "状态条注入", "已注入,但指向另一个目录(下次安装会替换到当前运行目录)", + "运行 /install-overlay") + else: + # 安装已排定时重跑 /install-overlay 只会复用同一个待替换包(issue #120):注入行只报 + # 事实,该做的事由「待替换包」那一行给出 + staged = pi.pending_operation() == "install" + add("FAIL", "状态条注入", "未注入(安装已排定,在等客户端退出,见下方待替换包)" if staged + else "未注入", None if staged else "运行 /install-overlay;新建或恢复会话也会自动安装", rank=2) + if pi.target_writable(): + add("OK", "安装目录可写", "可写") + else: + add("FAIL" if not loader_lines else "WARN", "安装目录可写", + "当前身份写不了客户端安装目录(受保护目录)", + "运行 /install-overlay,权限不足时按它的提示以管理员身份或 sudo 重跑同一条命令", rank=2) + mobile = pi._mobile_check_status(pi.ASAR, entry) + add("OK" if mobile == "已注入" else "WARN", "手机远控补丁", mobile) + from renderer_bridge import _inspect_deploy + kind, payload = _inspect_deploy(pi.ASAR) + if kind == "patch": + add("WARN", "逐问速率行补丁", f"未打上(客户端 {payload[4]})", + "运行 /install-overlay;状态条已注入时,新建或恢复会话也会自动补装") + elif payload.get("status") == "present": + add("OK", "逐问速率行补丁", "已部署") + else: + add("WARN", "逐问速率行补丁", f"{payload.get('status')}:{payload.get('detail')}") + # 宿主版本没进指纹表、但桥已按结构推导打上时不算是问题(与 hook 的兼容性提示同口径: + # 只在桥也打不上时才提醒) + registered = _host_registered(facts["version"]) + adapted = registered or (kind != "patch" and payload.get("status") == "present") + add("OK" if adapted else "WARN", "客户端版本适配", + "当前插件已登记这个客户端版本" if registered else + "当前插件按结构推导适配这个客户端版本(未登记指纹表)" if adapted else + f"当前插件 v{_plugin_version() or '?'} 还没有登记 ZCode {facts['version']}", + None if adapted else "检查插件更新(状态条设置面板的「插件更新」);宿主刚升级时等插件发适配版") + + def pending_work(): + running = pi.client_running() + add("OK", "客户端进程", "在运行" if running else "没检测到(按进程名探测,可能漏检)") + operation = pi.pending_operation() + if operation not in ("install", "remove"): + add("OK", "待替换包", "无") + else: + try: + pi.pending_tmp(operation) + validity = "待替换包有效" + except Exception: # noqa: BLE001 — 校验没过的原因交给重跑安装解决 + validity = "待替换包校验没通过,重跑安装会重建" + with pi.monitor_instance_lock() as free: + monitored = not free + if operation == "install": + add("FAIL", "待替换包", f"{validity},安装在等客户端退出(收尾监控" + f"{'在运行' if monitored else '没在运行'})", + "安装已排定:完全退出 ZCode(从托盘退出,只关窗口不算)让收尾监控完成替换," + "再重新打开;不需要重跑安装" if monitored else + "安装已排定,但现在没有收尾监控:重新打开 ZCode 并新建会话会自动补拉;" + "仍不生效时完全退出 ZCode 后,按 /install-overlay 输出里的命令手动收尾", rank=3) + else: + add("WARN", "待替换包", f"{validity},卸载在等客户端退出", + "完全退出 ZCode(从托盘退出,只关窗口不算)让收尾监控完成卸载", rank=3) + marker, error = _doctor_json(runtime / ".plugin-restart-required") + if error: + add("WARN", "待重启改动", f"标记读不出({error})", restart, rank=3) + elif marker: + version = f" v{marker['version']}" if isinstance(marker.get("version"), str) else "" + add("WARN", "待重启改动", f"有({marker.get('state')}{version})", restart, rank=3) + else: + add("OK", "待重启改动", "无") + + def runtime_state(): + record, error = _doctor_json(runtime / "plugin-runtime.json") + if error: + add("WARN", "同步记录", f"plugin-runtime.json {error}") + elif record: + add("OK", "同步记录", f"版本 {record.get('version')},来源 {record.get('plugin_root')}") + else: + add("WARN", "同步记录", "还没有(运行目录尚未同步过)", "运行 /install-overlay") + missing, differ = [], [] + for name in RUNTIME_FILES: + target, source = runtime / name, PLUGIN_ROOT / name + if not target.is_file(): + missing.append(name) + elif not source.is_file() or target.read_bytes() != source.read_bytes(): + differ.append(name) + if missing or differ: + detail = ";".join(part for part in ( + f"缺失 {', '.join(missing)}" if missing else "", + f"与插件来源不同 {', '.join(differ)}" if differ else "") if part) + add("WARN", "运行文件", detail, "运行 /install-overlay 重新同步运行目录") + else: + add("OK", "运行文件", f"{len(RUNTIME_FILES)} 个文件与插件来源一致") + if (runtime / "config.json").exists() and load_runtime_config(runtime) is None: + add("FAIL", "配置文件", "config.json 损坏或不是 JSON 对象", + f"修复或移走 {runtime / 'config.json'} 后重跑本命令", rank=2) + else: + add("OK", "配置文件", "可解析" if (runtime / "config.json").exists() + else "使用默认值(还没有 config.json)") + if optout_marker(runtime).exists(): + add("WARN", "自动安装豁免", "存在 .plugin-overlay-optout:不会再自动安装状态条", + "需要状态条时运行 /install-overlay") + else: + add("OK", "自动安装豁免", "无") + record, error = _doctor_json(runtime / "plugin-session-start.json") + if error: + add("WARN", "会话启动记录", f"plugin-session-start.json {error}") + elif record: + result = record.get("result") if isinstance(record.get("result"), dict) else {} + context = result.get("hookSpecificOutput") if isinstance(result.get("hookSpecificOutput"), dict) else {} + message = context.get("additionalContext") or result.get("systemMessage") + when = (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(record["time"])) + if type(record.get("time")) in (int, float) else "时间未知") + if isinstance(message, str) and message: + add("WARN", "会话启动记录", f"{when}({record.get('source') or '?'})带着故障提示:{message}") + else: + host = record.get("host") if isinstance(record.get("host"), dict) else {} + add("OK", "会话启动记录", + f"{when}({record.get('source') or '?'})宿主 {host.get('hostBuild')}," + f"插件 v{host.get('pluginVersion')},注入 {host.get('injected')},桥 {host.get('bridge')}") + else: + add("OK", "会话启动记录", "还没有(插件装好后第一次会话启动才写)") + + def updates(): + config = load_runtime_config(runtime) + automatic = isinstance(config, dict) and config.get("plugin_auto_update", True) is True + add("OK" if automatic else "WARN", "自动更新", "开启" if automatic else "已显式关闭", + None if automatic else "需要自动更新时在状态条设置面板里打开") + state, error = _doctor_json(runtime / "plugin-update.json") + if error: + add("WARN", "更新记录", f"plugin-update.json {error}") + elif not state: + add("OK", "更新记录", "还没有(第一次检查更新后才有)") + else: + failure = state.get("lastError") + if isinstance(failure, dict) and failure.get("message"): + add("WARN", "更新记录", f"最近一次检查或安装失败:{str(failure['message'])[:200]}", + "检查网络(GitHub 连不上时可改用 GitCode 渠道地址)后,在状态条设置面板手动检查更新") + else: + add("OK", "更新记录", f"当前 v{state.get('currentVersion')},最新 v{state.get('latestVersion')}" + if state.get("currentVersion") else "尚无版本记录") + + lines.append(f"zcode-token-usage-statusbar 体检(只读) {time.strftime('%Y-%m-%d %H:%M:%S')}") + section("运行环境", environment) + section("插件登记", registration) + section("客户端与注入", client_and_injection) + section("待替换与重启", pending_work) + section("运行目录", runtime_state) + section("更新", updates) + lines.extend(("", f"体检结果: OK {counts['OK']} / WARN {counts['WARN']} / FAIL {counts['FAIL']}")) + if ranked: + ranked.sort(key=lambda pair: pair[0]) + lines.append("建议动作:") + lines.extend(f" {number}. {text}" for number, (_, text) in enumerate(ranked, 1)) + else: + lines.append("未发现需要处理的问题。") + return "\n".join(lines), counts + + def main(): cmd = sys.argv[1] if len(sys.argv) > 1 else "check" if cmd == "sync": @@ -1392,6 +1697,14 @@ def main(): print(json.dumps(result, ensure_ascii=False)) return runtime, pi = resolve_paths() + if cmd == "doctor": + try: + report, _ = doctor(runtime, pi) + except Exception as e: # noqa: BLE001 — 体检自身出错必须可辨,不能带着半份报告正常退出 + print(f"[zusage-plugin] 体检未能完成:{e.__class__.__name__}: {e}", file=sys.stderr) + sys.exit(1) + print(report) + return if cmd == "install": sync_runtime(runtime, pi.ASAR) if pi.ASAR is None: diff --git a/plugins/zcode-token-usage-statusbar/release_unpack.py b/plugins/zcode-token-usage-statusbar/release_unpack.py index b142719d8..68fcafb39 100644 --- a/plugins/zcode-token-usage-statusbar/release_unpack.py +++ b/plugins/zcode-token-usage-statusbar/release_unpack.py @@ -35,6 +35,7 @@ ".zcode-plugin/plugin.json", ".claude-plugin/plugin.json", "hooks/hooks.json", "hooks/session-start.py", "hooks/prompt-submit.py", "commands/usage.md", "commands/install-overlay.md", "commands/uninstall-overlay.md", + "commands/zusage-doctor.md", "skills/zcode-token-usage/SKILL.md", ) ALLOWED_FILES = frozenset(("marketplace.json", "LICENSE") + diff --git a/release_tool.py b/release_tool.py index 541db7c59..5e0dc52fc 100644 --- a/release_tool.py +++ b/release_tool.py @@ -34,7 +34,8 @@ "restart_notice.py", ".mcp.json", "README.md", ".zcode-plugin/plugin.json", ".claude-plugin/plugin.json", "hooks/hooks.json", "hooks/session-start.py", "hooks/prompt-submit.py", "commands/usage.md", "commands/install-overlay.md", - "commands/uninstall-overlay.md", "skills/zcode-token-usage/SKILL.md") + "commands/uninstall-overlay.md", "commands/zusage-doctor.md", + "skills/zcode-token-usage/SKILL.md") NAMES = tuple(sorted(("LICENSE", "marketplace.json", *(PREFIX + p for p in SOURCES)))) RELEVANT = ("LICENSE", "marketplace.json", "plugins", "release_tool.py", "sync_plugin.py", *SYNC_FILES) diff --git a/release_unpack.py b/release_unpack.py index b142719d8..68fcafb39 100644 --- a/release_unpack.py +++ b/release_unpack.py @@ -35,6 +35,7 @@ ".zcode-plugin/plugin.json", ".claude-plugin/plugin.json", "hooks/hooks.json", "hooks/session-start.py", "hooks/prompt-submit.py", "commands/usage.md", "commands/install-overlay.md", "commands/uninstall-overlay.md", + "commands/zusage-doctor.md", "skills/zcode-token-usage/SKILL.md", ) ALLOWED_FILES = frozenset(("marketplace.json", "LICENSE") + diff --git a/specs/zusage-doctor.md b/specs/zusage-doctor.md new file mode 100644 index 000000000..ab0fd543d --- /dev/null +++ b/specs/zusage-doctor.md @@ -0,0 +1,60 @@ +# 插件体检命令 /zusage-doctor + +## 目标与边界 + +状态条、chip 或回答末尾的速率行不显示时,把开放式的多轮排查收敛成一次命令。命令只做诊断,输出每项检查的事实、等级和对应的修法;修复动作仍由用户或其后的 `/install-overlay` 等既有入口执行。 + +- 入口是插件命令 `commands/zusage-doctor.md`,它调用 `overlay_install.py doctor`。不新增运行目录文件,`doctor` 逻辑只在插件目录的 `overlay_install.py` 里。 +- 状态所有者不变:注入、待替换与可写性判定归 `patch_install.py`,渲染桥归 `renderer_bridge.py`,运行目录同步记录归 `overlay_install.py`,插件安装与市场登记归宿主。体检只读取这些既有判定,不另写一套判据。 +- 体检不修改客户端、运行目录、配置或插件登记。两处例外沿用安装器已有的做法:`target_writable()` 在归档同目录做一次「建后即删」的写入探针;监控存活探测用 `monitor_instance_lock()` 试取那把常驻的去重锁。 +- 不读取也不输出任何凭据文件。`config.json` 只报告能否解析和少数非敏感开关,不回显内容。 + +## 输出契约 + +- stdout 只有体检文本:标题、按组的检查行、汇总行 `体检结果: OK n / WARN n / FAIL n`、以及「建议动作」编号列表;没有需要处理的问题时写「未发现需要处理的问题」。 +- 每条检查行形如 `[级别] 项目: 事实`。`OK` 表示正常,`WARN` 表示需要注意但不挡主功能,`FAIL` 表示状态条或速率行当前无法工作。 +- 退出码:体检跑完恒为 0,有无问题都一样,结论只看文本;体检脚本自身出错时非 0,并以「体检未能完成」开头。 +- 某一项检查抛异常只把这一组记成 `FAIL`,其余各组照常执行。 +- 建议动作按优先级排列并去重;涉及修改客户端文件、提权、重启或卸载的动作只写进文本,由命令说明要求执行者先征得用户同意。 + +## 检查项 + +| 组 | 检查 | 数据来源 | 判定 | +|---|---|---|---| +| 运行环境 | Python 版本与平台 | `sys.version_info` | 恒 `OK` | +| 插件登记 | 当前插件副本版本 | `PLUGIN_ROOT` 下的 manifest | 恒 `OK` | +| 插件登记 | 安装记录 | 宿主插件存储的 `installed_plugins.json` | 无记录 `FAIL`;记录的安装目录不存在 `FAIL`;与当前副本版本不同 `WARN` | +| 插件登记 | 启用状态 | 宿主 CLI 配置的 `plugins.enabled` 与 `plugins.enabledPlugins` | 总开关关闭或本插件被禁用 `FAIL`;未显式设置按默认启用 `OK` | +| 插件登记 | 市场登记 | 宿主插件存储的 `known_marketplaces.json` | `#plugin-releases` / `.git#plugin-releases-gitcode` 为正式渠道 `OK`;裸 GitHub 地址为「仓库源码」`WARN`;带刷新失败记录 `WARN` | +| 客户端 | 归档位置、客户端版本、是否在运行 | `patch_install` 的目标探测、`read_asar_package`、`client_running` | 找不到归档 `FAIL`;其余如实报告(进程名探测可能漏检,输出里注明) | +| 注入 | 状态条注入行 | `injected_state` 与注入行比对 | 未注入或归档读不出 `FAIL`;指向别的目录 `WARN` | +| 注入 | 手机远控补丁 | `_mobile_check_status` | 「已注入」`OK`,其余 `WARN` | +| 注入 | 逐问速率行补丁(渲染桥) | `renderer_bridge._inspect_deploy` | `present` `OK`;缺桥或无法验证 `WARN` | +| 注入 | 客户端版本适配 | `_host_registered` | 未登记 `WARN` | +| 待替换 | 待替换包与收尾监控 | `pending_operation`、`pending_tmp`、`monitor_instance_lock` | 安装待替换 `FAIL`(客户端退出后才生效);卸载待替换 `WARN`;输出注明监控是否在运行 | +| 待替换 | 待重启改动 | 运行目录的 `.plugin-restart-required` | 存在 `WARN` | +| 运行目录 | 同步记录、运行文件与插件来源是否一致、配置可解析、卸载豁免、最近一次会话启动记录 | `plugin-runtime.json`、`RUNTIME_FILES` 逐文件比对、`load_runtime_config`、`.plugin-overlay-optout`、`plugin-session-start.json` | 配置损坏 `FAIL`;文件缺失或不一致 `WARN`;存在卸载豁免 `WARN`;启动记录带故障提示 `WARN` | +| 更新 | 自动更新开关与最近一次更新结果 | `config.json` 的 `plugin_auto_update`、`plugin-update.json` | 关闭 `WARN`;最近检查或安装失败 `WARN` | + +宿主插件存储根的解析与宿主一致取三处:环境变量 `ZCODE_STORAGE_DIR`,其次宿主 CLI 配置的 `storage.dir`,都没有则用 `~/.zcode`;再拼到 `cli/plugins`。项目级配置(`zcode.json`、`.zcode/config.json`)不参与,保证体检在任何工作目录下结果一致。 + +## 建议动作 + +每条 `FAIL` 与多数 `WARN` 带一条对应动作,按固定优先级排列:先解决「没装上、被禁用、归档找不到」,再解决「未注入、目录不可写」,然后是「待替换待退出、无监控收尾、待重启」,最后是「桥缺失、版本未适配、运行目录不一致、渠道与更新」。安装已排定、在等客户端退出时,注入行只报事实、不再建议运行 `/install-overlay`(重跑只会复用同一个待替换包),该做的事由待替换包那一行给出。重启一律写成「完全退出 ZCode(从托盘退出,只关窗口不算)再重新打开」,不替用户重启。 + +## 验收 + +| 场景 | 可观察结果 | +|---|---| +| 全部正常 | 没有 `FAIL`,没有建议动作 | +| 归档未注入且客户端未运行 | 注入行 `FAIL`,建议动作含 `/install-overlay` | +| 安装已排定、客户端在运行 | 待替换 `FAIL`;注入行只报事实。建议动作只有「完全退出」这一条,监控未运行时换成补拉收尾的办法,都不含 `/install-overlay` | +| 插件被禁用 / 没有安装记录 / 安装目录不存在 | 对应行 `FAIL` 并给出修法 | +| 市场登记是裸 GitHub 地址 | `WARN` 并写明「仓库源码」 | +| 运行目录文件缺失或与来源不一致、配置损坏、存在卸载豁免、启动记录带故障提示 | 对应行 `WARN` 或 `FAIL` | +| 某一项检查抛异常 | 该组记 `FAIL`,后续各组照常输出,退出码仍为 0 | +| 运行目录里放一个带哨兵串的 `quota-secrets.json` | 输出不含该串 | +| 体检前后 | 运行目录、归档、宿主插件存储的文件清单与字节不变 | +| 归档找不到 | 仍输出完整报告与 `FAIL`,退出码 0 | + +自动化验收使用 `tests/test_zusage_doctor.py`、`tests/test_command_frontmatter.py` 与分发清单检查;真实故障机上各修法是否对症需实机验收。 diff --git a/sync_plugin.py b/sync_plugin.py index f47ea3703..8b54b7cdd 100644 --- a/sync_plugin.py +++ b/sync_plugin.py @@ -59,6 +59,7 @@ "commands/usage.md", "commands/install-overlay.md", "commands/uninstall-overlay.md", + "commands/zusage-doctor.md", "skills/zcode-token-usage/SKILL.md", ) diff --git a/tests/test_zusage_doctor.py b/tests/test_zusage_doctor.py new file mode 100644 index 000000000..ef6bf8df1 --- /dev/null +++ b/tests/test_zusage_doctor.py @@ -0,0 +1,349 @@ +# -*- coding: utf-8 -*- +"""/zusage-doctor 只读体检的隔离测试(specs/zusage-doctor.md):临时归档、临时运行目录、 +临时宿主存储,不读真机安装、不写用户目录。""" +import contextlib +import importlib.util +import io +import json +import os +from pathlib import Path +import re +import shutil +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from tests.helpers.py_test_support import load_module, make_asar # noqa: E402 + +PLUGIN = ROOT / "plugins" / "zcode-token-usage-statusbar" +INSTALLER = load_module("doctor_overlay_install", PLUGIN / "overlay_install.py") +REPO_ASAR = load_module("doctor_repo_patch_install", ROOT / "patch_install.py") +PLUGIN_ASAR = load_module("doctor_plugin_patch_install", PLUGIN / "patch_install.py") +ID = INSTALLER.PLUGIN_ID + + +def snapshot(root): + """目录下全部文件的名字与字节(含隐藏文件),用来证明体检前后没有任何落盘改动。""" + return {str(path.relative_to(root)): path.read_bytes() + for path in sorted(Path(root).rglob("*")) if path.is_file()} + + +class DoctorTests(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory(prefix="zusage-doctor-") + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name).resolve() + self.home = self.home_dir("home") + self.runtime = self.home / ".zcode" / "zcode-token-usage-statusbar" + self.runtime.mkdir(parents=True) + self.storage = self.home_dir("storage") / "cli" / "plugins" + self.storage.mkdir(parents=True) + self.config = self.home_dir("host") / "config.json" + self.config.write_text(json.dumps({"plugins": {"enabledPlugins": {ID: True}}}), encoding="utf-8") + env = mock.patch.dict(os.environ, {"HOME": str(self.home), "USERPROFILE": str(self.home), + "ZCODE_STORAGE_DIR": str(self.storage.parents[1]), + "ZUSAGE_PLUGIN_HOST_CONFIG": str(self.config), + "ZUSAGE_PLUGIN_RUNTIME": str(self.runtime), + "ZUSAGE_PLUGIN_ASAR": str(self.root / "app.asar"), + "ZCODE_ASAR": "", "ZUSAGE_NO_MONITOR": "1"}) + env.start() + self.addCleanup(env.stop) + self.asar = self.root / "app.asar" + self.write_host(record=True, market={"id": INSTALLER.MARKETPLACE_ID, + "source": {"source": "git", "ref": "plugin-releases", + "url": "https://github.com/ByteRax/x.git"}}) + for name in INSTALLER.RUNTIME_FILES: + shutil.copyfile(PLUGIN / name, self.runtime / name) + (self.runtime / "plugin-runtime.json").write_text(json.dumps( + {"version": INSTALLER._plugin_version(), "plugin_root": str(PLUGIN)}), encoding="utf-8") + self.loader_line = (self.runtime / "inject-main.cjs").as_uri() + self.injected_entry = b"console.log('official');\n;import(\"%s\").then(() => null, " \ + b"(e) => console.error(\"[zusage] load failed\", e));" % self.loader_line.encode() + # 带宿主包身份(版本取指纹表里登记过的一个),让客户端版本与适配判定走真实分支 + self.host_package = json.dumps({"name": "@zcode/desktop", "version": "3.19.0", + "type": "module"}).encode() + make_asar(self.asar, files={"out/main/index.js": self.injected_entry, "package.json": self.host_package}) + quiet = contextlib.redirect_stdout(io.StringIO()) + quiet.__enter__() + self.addCleanup(quiet.__exit__, None, None, None) + for module in (REPO_ASAR, PLUGIN_ASAR): + patched = mock.patch.object(module, "client_running", return_value=False) + patched.start() + self.addCleanup(patched.stop) + bridge = mock.Mock() + bridge._inspect_deploy.return_value = ("result", {"status": "present", "detail": "deployed"}) + modules = mock.patch.dict(sys.modules, {"renderer_bridge": bridge, + "patch_install": PLUGIN_ASAR}) + modules.start() + self.addCleanup(modules.stop) + self.bridge = bridge + + def home_dir(self, name): + path = self.root / name + path.mkdir(exist_ok=True) + return path + + def write_host(self, record=None, market=None): + """record:None=没有安装记录,True=正常记录,dict=正常记录再加覆盖项。""" + plugins = [] + if record is not None: + item = {"id": ID, "name": "zcode-token-usage-statusbar", "marketplace": INSTALLER.MARKETPLACE_ID, + "scope": "user", "version": INSTALLER._plugin_version(), "installPath": str(PLUGIN)} + item.update(record if isinstance(record, dict) else {}) + plugins.append(item) + (self.storage / "installed_plugins.json").write_text( + json.dumps({"version": 1, "plugins": plugins}), encoding="utf-8") + markets = [] if market is None else [market] + (self.storage / "known_marketplaces.json").write_text( + json.dumps({"version": 1, "marketplaces": markets}), encoding="utf-8") + + def run_doctor(self): + runtime, pi = INSTALLER.resolve_paths() + self.assertIs(pi, PLUGIN_ASAR) + return INSTALLER.doctor(runtime, pi) + + def assertLine(self, report, level, item, detail=None): + for line in report.splitlines(): + if line.strip().startswith(f"[{level}] {item}:") and (detail is None or detail in line): + return line + self.fail(f"没有找到 [{level}] {item}: …{detail or ''}\n{report}") + + @staticmethod + def actions(report): + return [line.strip() for line in report.splitlines() if re.match(r"^\d+\. ", line.strip())] + + def test_healthy_install_reports_no_failure_and_no_action(self): + report, counts = self.run_doctor() + self.assertEqual(counts["FAIL"], 0, report) + self.assertEqual(self.actions(report), [], report) + self.assertIn("未发现需要处理的问题。", report) + self.assertRegex(report, r"体检结果: OK \d+ / WARN \d+ / FAIL 0") + self.assertLine(report, "OK", "状态条注入", "指向当前运行目录") + self.assertLine(report, "OK", "插件安装登记", str(PLUGIN)) + self.assertLine(report, "OK", "市场登记", "正式 Release 渠道") + self.assertLine(report, "OK", "运行文件", "与插件来源一致") + self.assertLine(report, "OK", "客户端版本", "3.19.0") + self.assertLine(report, "OK", "客户端版本适配", "已登记") + + def test_doctor_changes_nothing_on_disk(self): + (self.runtime / "quota-secrets.json").write_text('{"token":"SECRET-SENTINEL-123"}', encoding="utf-8") + before = {name: snapshot(path) for name, path in (("runtime", self.runtime), + ("asar", self.root), ("storage", self.storage), + ("host", self.config.parent))} + report, _ = self.run_doctor() + after = {name: snapshot(path) for name, path in (("runtime", self.runtime), + ("asar", self.root), ("storage", self.storage), + ("host", self.config.parent))} + self.assertEqual(after, before) + self.assertNotIn("SECRET-SENTINEL-123", report) + self.assertNotIn("quota-secrets", report) + + def test_missing_injection_asks_for_install(self): + make_asar(self.asar, files={"out/main/index.js": b"console.log('official');", + "package.json": self.host_package}) + report, counts = self.run_doctor() + self.assertGreaterEqual(counts["FAIL"], 1) + self.assertLine(report, "FAIL", "状态条注入", "未注入") + self.assertEqual(self.actions(report), ["1. 运行 /install-overlay;新建或恢复会话也会自动安装"], report) + + def test_loader_pointing_elsewhere_is_a_warning(self): + elsewhere = (self.root / "old-runtime" / "inject-main.cjs").as_uri() + entry = self.injected_entry.replace(self.loader_line.encode(), elsewhere.encode()) + make_asar(self.asar, files={"out/main/index.js": entry}) + report, counts = self.run_doctor() + self.assertLine(report, "WARN", "状态条注入", "指向另一个目录") + self.assertNotIn("FAIL", "".join(line for line in report.splitlines() if "状态条注入" in line)) + + def test_unwritable_target_is_fatal_only_while_not_injected(self): + make_asar(self.asar, files={"out/main/index.js": b"console.log('official');"}) + with mock.patch.object(PLUGIN_ASAR, "target_writable", return_value=False): + report, _ = self.run_doctor() + self.assertLine(report, "FAIL", "安装目录可写", "受保护目录") + self.assertIn("管理员身份或 sudo", report) + make_asar(self.asar, files={"out/main/index.js": self.injected_entry}) + with mock.patch.object(PLUGIN_ASAR, "target_writable", return_value=False): + report, _ = self.run_doctor() + self.assertLine(report, "WARN", "安装目录可写", "受保护目录") + + def test_pending_install_wants_a_full_quit(self): + make_asar(self.asar, files={"out/main/index.js": b"console.log('official');", + "package.json": self.host_package}) + REPO_ASAR.set_target(self.asar) + REPO_ASAR.set_runtime(self.runtime) + with contextlib.ExitStack() as stack: + stack.enter_context(mock.patch.object(REPO_ASAR, "syntax_check", return_value=True)) + stack.enter_context(mock.patch.object(REPO_ASAR, "launch_monitor", return_value=None)) + REPO_ASAR.prepare_tmp({"/" + REPO_ASAR.ENTRY: self.injected_entry}) + with mock.patch.object(PLUGIN_ASAR, "monitor_instance_lock", + side_effect=lambda: contextlib.nullcontext(True)): + report, counts = self.run_doctor() + self.assertLine(report, "FAIL", "待替换包", "收尾监控没在运行") + self.assertLine(report, "FAIL", "状态条注入", "安装已排定") + # 重跑 /install-overlay 只会复用同一个待替换包:建议动作里不能出现它 + self.assertEqual(self.actions(report), [ + "1. 安装已排定,但现在没有收尾监控:重新打开 ZCode 并新建会话会自动补拉;" + "仍不生效时完全退出 ZCode 后,按 /install-overlay 输出里的命令手动收尾"], report) + with mock.patch.object(PLUGIN_ASAR, "monitor_instance_lock", + side_effect=lambda: contextlib.nullcontext(False)): + report, counts = self.run_doctor() + self.assertLine(report, "FAIL", "待替换包", "收尾监控在运行") + self.assertEqual(self.actions(report), [ + "1. 安装已排定:完全退出 ZCode(从托盘退出,只关窗口不算)让收尾监控完成替换," + "再重新打开;不需要重跑安装"], report) + + def test_disabled_plugin_and_missing_record_are_fatal(self): + self.config.write_text(json.dumps({"plugins": {"enabledPlugins": {ID: False}}}), encoding="utf-8") + report, _ = self.run_doctor() + self.assertLine(report, "FAIL", "插件启用状态", "已被禁用") + self.assertRegex(report, r"1\. 在 ZCode 设置的插件管理里启用") + self.config.write_text("{not json", encoding="utf-8") + report, _ = self.run_doctor() + self.assertLine(report, "FAIL", "插件启用状态", "判断不了是否启用") + self.write_host() + report, _ = self.run_doctor() + self.assertLine(report, "FAIL", "插件安装登记", "没有本插件的安装记录") + self.write_host(record={"installPath": str(self.root / "gone")}) + report, _ = self.run_doctor() + self.assertLine(report, "FAIL", "插件安装登记", "安装目录不存在") + + def test_master_switch_off_is_fatal_and_default_is_enabled(self): + self.config.write_text(json.dumps({"plugins": {"enabled": False}}), encoding="utf-8") + report, _ = self.run_doctor() + self.assertLine(report, "FAIL", "插件启用状态", "总开关已关闭") + self.config.write_text("{}", encoding="utf-8") + report, _ = self.run_doctor() + self.assertLine(report, "OK", "插件启用状态", "按默认启用") + + def test_source_marketplace_is_flagged(self): + self.write_host(market={"id": INSTALLER.MARKETPLACE_ID, + "source": {"source": "git", + "url": "https://github.com/ByteRax/x.git"}}) + report, _ = self.run_doctor() + self.assertLine(report, "WARN", "市场登记", "仓库源码") + self.assertIn("#plugin-releases", report) + self.write_host(market={"id": INSTALLER.MARKETPLACE_ID, + "source": {"source": "git", "ref": "plugin-releases-gitcode", + "url": "https://gitcode.com/tanranran/x.git"}}) + report, _ = self.run_doctor() + self.assertLine(report, "OK", "市场登记", "GitCode") + self.write_host() + report, _ = self.run_doctor() + self.assertLine(report, "WARN", "市场登记", "没有 zusage-marketplace") + + def test_runtime_drift_and_optout_and_restart_marker(self): + (self.runtime / "overlay.js").write_text("// drifted", encoding="utf-8") + (self.runtime / "turn-stats.js").unlink() + (self.runtime / ".plugin-overlay-optout").write_text("", encoding="utf-8") + (self.runtime / ".plugin-restart-required").write_text( + json.dumps({"state": "installed", "version": "9.9.9"}), encoding="utf-8") + report, _ = self.run_doctor() + self.assertLine(report, "WARN", "运行文件", "缺失 turn-stats.js") + self.assertLine(report, "WARN", "运行文件", "与插件来源不同 overlay.js") + self.assertLine(report, "WARN", "自动安装豁免", ".plugin-overlay-optout") + self.assertLine(report, "WARN", "待重启改动", "installed v9.9.9") + + def test_corrupt_runtime_config_and_faulty_session_record(self): + (self.runtime / "config.json").write_text("{broken", encoding="utf-8") + (self.runtime / "plugin-session-start.json").write_text(json.dumps({ + "time": 1700000000, "source": "startup", + "result": {"hookSpecificOutput": {"additionalContext": "状态条自动安装未完成"}}, + "host": {"hostBuild": "1.2.3", "injected": False}}), encoding="utf-8") + report, _ = self.run_doctor() + self.assertLine(report, "FAIL", "配置文件", "config.json 损坏") + self.assertLine(report, "WARN", "会话启动记录", "状态条自动安装未完成") + + def test_update_state_is_summarised(self): + (self.runtime / "plugin-update.json").write_text( + json.dumps({"lastError": {"message": "api.github.com unreachable"}}), encoding="utf-8") + report, _ = self.run_doctor() + self.assertLine(report, "WARN", "更新记录", "api.github.com unreachable") + (self.runtime / "config.json").write_text(json.dumps({"plugin_auto_update": False}), encoding="utf-8") + report, _ = self.run_doctor() + self.assertLine(report, "WARN", "自动更新", "已显式关闭") + + def test_missing_bridge_and_unregistered_host_are_warnings(self): + self.bridge._inspect_deploy.return_value = ("patch", (None, None, None, None, "9.9.9", + False, False, "/a.js", b"", b"patched")) + with mock.patch.object(INSTALLER, "_host_registered", return_value=False): + report, counts = self.run_doctor() + self.assertLine(report, "WARN", "逐问速率行补丁", "未打上") + self.assertLine(report, "WARN", "客户端版本适配", "还没有登记 ZCode 3.19.0") + + def test_derived_bridge_counts_as_adapted(self): + with mock.patch.object(INSTALLER, "_host_registered", return_value=False): + report, _ = self.run_doctor() + self.assertLine(report, "OK", "客户端版本适配", "按结构推导适配") + + def test_one_failing_section_does_not_hide_the_rest(self): + with mock.patch.object(INSTALLER, "_host_build", side_effect=OSError("boom")): + report, counts = self.run_doctor() + self.assertLine(report, "FAIL", "客户端与注入", "这一组检查没能完成") + self.assertLine(report, "OK", "待替换包", "无") + self.assertLine(report, "OK", "插件启用状态", "已启用") + + def test_actions_are_ranked_and_deduplicated(self): + make_asar(self.asar, files={"out/main/index.js": b"console.log('official');"}) + (self.runtime / "overlay.js").write_text("// drifted", encoding="utf-8") + self.config.write_text(json.dumps({"plugins": {"enabledPlugins": {ID: False}}}), encoding="utf-8") + report, _ = self.run_doctor() + actions = self.actions(report) + self.assertRegex(actions[0], r"^1\. 在 ZCode 设置的插件管理里启用") + self.assertRegex(actions[1], r"^2\. 运行 /install-overlay") + self.assertRegex(actions[2], r"^3\. 运行 /install-overlay 重新同步运行目录") + self.assertEqual(len(actions), 3) + self.assertEqual(len(actions), len(set(actions))) + + def test_storage_dir_resolution_follows_the_host(self): + with mock.patch.dict(os.environ, {"ZCODE_STORAGE_DIR": ""}): + self.assertEqual(INSTALLER._doctor_storage(), self.home / ".zcode" / "cli" / "plugins") + self.config.write_text(json.dumps({"storage": {"dir": "~/elsewhere"}}), encoding="utf-8") + self.assertEqual(INSTALLER._doctor_storage(), self.home / "elsewhere" / "cli" / "plugins") + self.config.write_text(json.dumps({"storage": {"dir": "/abs/cli"}}), encoding="utf-8") + self.assertEqual(INSTALLER._doctor_storage(), Path("/abs/cli/plugins")) + self.config.write_text("{broken", encoding="utf-8") + self.assertEqual(INSTALLER._doctor_storage(), self.home / ".zcode" / "cli" / "plugins") + + def test_main_prints_only_the_report_and_exits_cleanly_without_an_asar(self): + # 探测不到任何归档(候选清空、测试接缝撤销):仍输出完整报告,正常返回 + self.asar.unlink() + out, errors = io.StringIO(), io.StringIO() + with mock.patch.dict(os.environ), mock.patch.object(sys, "argv", ["overlay_install.py", "doctor"]), \ + mock.patch.object(INSTALLER, "asar_candidates", return_value=[]), \ + contextlib.redirect_stdout(out), contextlib.redirect_stderr(errors): + for name in ("ZUSAGE_PLUGIN_ASAR", "ZCODE_ASAR"): + os.environ.pop(name, None) + self.assertIsNone(INSTALLER.main()) + report = out.getvalue() + self.assertEqual(errors.getvalue(), "") + self.assertTrue(report.startswith("zcode-token-usage-statusbar 体检(只读)"), report) + self.assertLine(report, "FAIL", "客户端归档", "没有找到 ZCode 的 app.asar") + self.assertRegex(report, r"FAIL [1-9]") + self.assertRegex(report, r"1\. 确认 ZCode 桌面客户端的安装位置") + + def test_main_fails_loudly_when_the_doctor_itself_breaks(self): + out, errors = io.StringIO(), io.StringIO() + with mock.patch.object(sys, "argv", ["overlay_install.py", "doctor"]), \ + mock.patch.object(INSTALLER, "doctor", side_effect=RuntimeError("exploded")), \ + contextlib.redirect_stdout(out), contextlib.redirect_stderr(errors): + with self.assertRaises(SystemExit) as exit_code: + INSTALLER.main() + self.assertEqual(exit_code.exception.code, 1) + self.assertEqual(out.getvalue(), "") + self.assertIn("体检未能完成", errors.getvalue()) + + def test_command_file_is_registered_for_packaging(self): + command = PLUGIN / "commands" / "zusage-doctor.md" + text = command.read_text(encoding="utf-8") + self.assertIn('overlay_install.py" doctor', text) + for rel in (".zcode-plugin/plugin.json", ".claude-plugin/plugin.json"): + self.assertIn("plugins/zcode-token-usage-statusbar/commands/zusage-doctor.md", + json.loads((PLUGIN / rel).read_text(encoding="utf-8"))["packageLayout"]["files"]) + tool = load_module("doctor_release_tool", ROOT / "release_tool.py") + self.assertIn("plugins/zcode-token-usage-statusbar/commands/zusage-doctor.md", tool.NAMES) + + +if __name__ == "__main__": + unittest.main() From 1b3f84f9cb1389af82d11c059827152164af7e45 Mon Sep 17 00:00:00 2001 From: tanranran Date: Thu, 26 Nov 2026 12:16:35 +0800 Subject: [PATCH 3/4] =?UTF-8?q?feat(release):=20=E6=B8=A0=E9=81=93?= =?UTF-8?q?=E5=88=86=E6=94=AF=E7=B2=BE=E7=AE=80=E6=8F=90=E4=BA=A4=E4=B8=8E?= =?UTF-8?q?=E6=8C=89=E5=86=85=E5=AE=B9=E5=AF=B9=E8=B4=A6=E7=9A=84=E8=A1=A5?= =?UTF-8?q?=E6=8E=A8=E5=B7=A5=E5=85=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - release_tool.py channel-commit:把渠道清单做成只含 marketplace.json 与 LICENSE 的提交对象,不动工作区、不推送;缺省孤儿提交用于一次性把存量渠道分支换成精简分支,给定 --parent 时是快进提交 - release_tool.py reconcile:补推前把重建包与线上发布包逐成员对账,字节不同但内容相同时照常通过,并把清单绑定到线上资产的 sha256 - 发版收尾文档、发布技能与协作规则同步:渠道分支只放清单,存量分支的切换是须单独授权的带 lease 强推;补镜像时传线上发布包而不是重建包 规格:specs/release-channel-slim.md。线上渠道分支本次不动。 --- .zcode/rules/repo-workflow.md | 2 +- .zcode/skills/zcode-github-release/SKILL.md | 1 + .../references/post-release.md | 34 +++- docs/maintaining.md | 2 +- release_tool.py | 93 +++++++++++ specs/release-channel-slim.md | 28 ++++ tests/test_release_tool.py | 147 ++++++++++++++++++ 7 files changed, 304 insertions(+), 3 deletions(-) create mode 100644 specs/release-channel-slim.md diff --git a/.zcode/rules/repo-workflow.md b/.zcode/rules/repo-workflow.md index 8dd2836b3..170eaac41 100644 --- a/.zcode/rules/repo-workflow.md +++ b/.zcode/rules/repo-workflow.md @@ -22,7 +22,7 @@ - `--theirs` 前核对删除行归属;从共享工作树导出补丁后先过一遍全部变更行再 apply。 - `.gitignore` 对 `.zcode/` 是**白名单制**(`.zcode/*` + 逐目录 `!` 例外):`.zcode/skills/` 下新建技能目录若不加 `!.zcode/skills/<名>/` 会被静默忽略、永远进不了提交(git status 看不见、新会话也不报错),新建项目技能后先补例外再写内容。 - 并行活跃期跑 `sync_plugin.py` 会把他人未提交的根文件改动扫进插件副本与运行目录(详见 [install-release.md](install-release.md));且它只构建并同步**所在工作树**的 `src/` 分片→根文件→插件副本(同时执行 `--verify-manifests` 校验 6 处分发清单):共享文件改在哪个 worktree,就要在那个 worktree 内跑它的 `sync_plugin.py`——在主工作区跑既同步不到你的改动,还会把主工作区他人的未提交改动扫进副本。 -- 渠道分支按设计**直接推送、绝不开 PR 进 main**(PR 会用 ZIP URL 清单覆盖源码相对路径市场入口):常驻的 `plugin-releases`,与发过 GitCode 渠道才有的 `plugin-releases-gitcode`(`--gitcode-repo` 在 D 内建 GitCode Release 并上传资产;对渠道分支只是把清单生成到本地资产目录,推成 `plugin-releases-gitcode` 分支是阶段 E 另行授权的动作;未发过则该分支不存在);GitHub 的 "Compare & pull request" 提示忽略。detached worktree 推渠道分支必须写完整 ref:`git push fork HEAD:refs/heads/plugin-releases`(推本地分支名会因为落后的同名本地分支报 non-FF;写短名 `HEAD:plugin-releases` 在目标分支只在一端不存在时,缺该分支的那一端报 `not a full refname`,有该分支的一端照常更新,两台主机从此不一致)。 +- 渠道分支按设计**直接推送、绝不开 PR 进 main**(PR 会用 ZIP URL 清单覆盖源码相对路径市场入口):常驻的 `plugin-releases`,与发过 GitCode 渠道才有的 `plugin-releases-gitcode`(`--gitcode-repo` 在 D 内建 GitCode Release 并上传资产;对渠道分支只是把清单生成到本地资产目录,推成 `plugin-releases-gitcode` 分支是阶段 E 另行授权的动作;未发过则该分支不存在);GitHub 的 "Compare & pull request" 提示忽略。detached worktree 推渠道分支必须写完整 ref:`git push fork HEAD:refs/heads/plugin-releases`(推本地分支名会因为落后的同名本地分支报 non-FF;写短名 `HEAD:plugin-releases` 在目标分支只在一端不存在时,缺该分支的那一端报 `not a full refname`,有该分支的一端照常更新,两台主机从此不一致)。渠道分支按设计只含 `marketplace.json` 与 `LICENSE`,提交对象用 `release_tool.py channel-commit` 生成([渠道分支精简与重建对账](../../specs/release-channel-slim.md)),不从源码树提交;把存量分支换成精简分支的孤儿提交须带 `--force-with-lease=<分支>:<远端旧提交>`,这是渠道分支唯一允许的非快进推送,且须单独授权。 ## 3. PR 工作流 diff --git a/.zcode/skills/zcode-github-release/SKILL.md b/.zcode/skills/zcode-github-release/SKILL.md index 1cbe8431e..ab1a274f2 100644 --- a/.zcode/skills/zcode-github-release/SKILL.md +++ b/.zcode/skills/zcode-github-release/SKILL.md @@ -145,6 +145,7 @@ python3 -B -m unittest discover -s tests -p 'test_*.py' - 正式 Release 验收通过后,默认接着(默认全链已含本阶段,用户调用时排除 E 的才跳过)将生成清单作为 `marketplace.json` 发布到同一仓库明确 ref `plugin-releases`,GitCode 版清单发布到 `plugin-releases-gitcode`;预演只展示动作。 - 在项目根用独立 worktree 操作,不切换或清理脏开发工作区;已有分支从远端 tip 派生,新分支从已验证 tag 派生;仅提交清单。正常推送,禁止强推;推送前先核对清单 sha256 等于 Release 资产的 digest,推送后从远端读取并核对版本、完整 ZIP URL/hash/path 与本次资产(推送后的多主机/多分支回读与真实下载资产的升级链复验可同轮并行派发只读 subagent 执行)。渠道未成功时不能声称远端更新可用。 - 新用户注册 `OWNER/REPO#plugin-releases`;已有注册不会自动切换,不修改用户市场注册。完整命令(detached worktree 的推送写法、GitCode 渠道、更新端验证)见 [发布后收尾](references/post-release.md)。 +- 渠道分支只放 `marketplace.json` 与 `LICENSE`(宿主每次刷新市场都整份下载该分支):提交对象用 `release_tool.py channel-commit` 生成,不从源码树提交。把存量分支换成精简分支是一次性的带 lease 强推,默认全链不含强推,须用户针对这个动作明确授权;步骤见 [发布后收尾](references/post-release.md#渠道分支精简)。 ## 发布后合并源码 PR diff --git a/.zcode/skills/zcode-github-release/references/post-release.md b/.zcode/skills/zcode-github-release/references/post-release.md index 776b74584..76d6ba92a 100644 --- a/.zcode/skills/zcode-github-release/references/post-release.md +++ b/.zcode/skills/zcode-github-release/references/post-release.md @@ -50,7 +50,39 @@ python3 .worktrees/rebuild-vX.Y.Z/release_tool.py build \ --out /tmp/zusage-rebuild-vX.Y.Z --version X.Y.Z ``` -重建后先对账再推送:重建 ZIP 的 sha256 必须等于 Release 资产 digest(上一节第二段命令的 `.digest`),`release-manifest.json` 应与线上资产逐字节一致。不一致说明检出或工具有变,停止并报告,不得把可疑清单推上渠道。对账通过后,把 `/tmp/zusage-rebuild-vX.Y.Z` 当作上面的 `/new/artifact-directory` 走同一推送与回读流程。GitCode 渠道欠账时先补镜像(直接调用 `gitcode_mirror`,见 [发布失败与回退](publish-failures.md#已公开但核验不符)),再用其生成的 `marketplace-release-gitcode.json` 推 `plugin-releases-gitcode`。 +重建后先对账再推送。对账用工具做([渠道分支精简与重建对账](../../../../specs/release-channel-slim.md)):重建包与线上包各自通过 `verify` 且身份一致;字节相同直接通过,字节不同(打包机或压缩实现不同)时逐成员比对内容;通过后把清单重新生成并绑定到**线上资产**的 sha256。任一步不一致都停止并报告,不得把可疑清单推上渠道: + +```bash +OUT=$(mktemp -d) +gh release download vX.Y.Z --repo OWNER/REPO -D "$OUT" -p 'zcode-token-usage-statusbar-vX.Y.Z.zip' -p 'release-manifest.json' +python3 release_tool.py reconcile --repo OWNER/REPO \ + --zip /tmp/zusage-rebuild-vX.Y.Z/zcode-token-usage-statusbar-vX.Y.Z.zip \ + --manifest /tmp/zusage-rebuild-vX.Y.Z/release-manifest.json \ + --published-zip "$OUT/zcode-token-usage-statusbar-vX.Y.Z.zip" \ + --published-manifest "$OUT/release-manifest.json" \ + --catalog-out /tmp/zusage-rebuild-vX.Y.Z/marketplace-release.json +``` + +对账通过后,把 `/tmp/zusage-rebuild-vX.Y.Z` 当作上面的 `/new/artifact-directory` 走同一推送与回读流程。GitCode 渠道欠账时先补镜像(直接调用 `gitcode_mirror`,见 [发布失败与回退](publish-failures.md#已公开但核验不符)),再用其生成的 `marketplace-release-gitcode.json` 推 `plugin-releases-gitcode`;补镜像时传 `$OUT` 里的线上发布包与线上 manifest,不要传重建包——两台主机必须托管同一份字节,否则同一版本在两条渠道上的 sha256 不一致。 + +## 渠道分支精简 + +渠道分支是全体用户的更新入口:宿主每次添加市场、每次刷新市场都按 ref 下载整份归档,所以分支里只放 `marketplace.json`(和 `LICENSE`),不带源码树。提交对象由 `release_tool.py channel-commit` 生成,它不动工作区、不推送;快进推送属于阶段 E,授权范围以发布技能为准。 + +存量分支换成精简分支是一次性动作,要强推,默认全链不含强推,须用户针对这个动作明确授权: + +```bash +git fetch -q fork plugin-releases +git show fork/plugin-releases:marketplace.json # 远端原清单的版本:新清单版本不得低于它 +OLD=$(git rev-parse fork/plugin-releases) +python3 release_tool.py channel-commit --catalog /new/artifact-directory/marketplace-release.json --version X.Y.Z +git push --force-with-lease=plugin-releases:"$OLD" fork <上一步输出的 commit>:refs/heads/plugin-releases +``` + +- 不给 `--parent` 时生成的是孤儿提交,与旧分支没有共同祖先,必须带 `--force-with-lease=<分支>:<远端旧提交>` 推送;远端在核对之后被别人更新过就会拒绝,被拒就重新读取远端并停止。 +- 两台主机上的旧提交不同时 `fork` 的双推送会在其中一段被拒:按 [仓库协作流程规则](../../../rules/repo-workflow.md) §3 的做法用显式仓库 URL 分别推送,不要去掉 lease 强推。 +- 精简分支上之后的每次发版不必再建 worktree:`python3 release_tool.py channel-commit --catalog … --version X.Y.Z --parent fork/plugin-releases`,再普通推送 `:refs/heads/plugin-releases`(快进,禁止强推);上一节带 worktree 的写法在精简分支上照样可用。 +- GitCode 渠道分支同理:清单换成 `marketplace-release-gitcode.json`,分支名换成 `plugin-releases-gitcode`,远端 refspec 写法与「分支只在部分主机存在」的处理见下一节。 ## GitCode 渠道 diff --git a/docs/maintaining.md b/docs/maintaining.md index 983179df5..e81501346 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -144,7 +144,7 @@ python3 release_tool.py verify --repo OWNER/REPO \ 正式发布还需明确 `--publish` 与 `--confirm OWNER/REPO/v版本号`,先上传草稿并核验下载字节,再发布。提交、tag 推送、Release 和渠道清单推送分别需要授权;用户调用[发布技能](../.zcode/skills/zcode-github-release/SKILL.md)发版时按该技能的默认全链执行(提交与 tag 推送、GitHub Release 与 GitCode 镜像、两个渠道清单、源码 PR 合并,不再逐项询问),此外默认不替用户执行。 -GitHub 自动更新要求已注册市场的 `marketplace.json` 指向同一个 Release ZIP/hash。维护者应将生成的 `marketplace-release.json` 作为渠道分支上的 `marketplace.json` 发布。[ByteRax 的 `plugin-releases` 渠道](https://github.com/ByteRax/zcode-token-usage-statusbar/tree/plugin-releases) 已发布 `v1.4.0` 一致清单,新用户注册 `ByteRax/zcode-token-usage-statusbar#plugin-releases`。未来发版须同步更新该清单,不能只上传 Release(`publish` 结束时会输出 `channelLag` 并在 stderr 警告清单滞后;发布目录已清理时可从正式 tag 确定性重建清单,见发布技能的[发布后收尾](../.zcode/skills/zcode-github-release/references/post-release.md));不要擅自切换用户已有来源。 +GitHub 自动更新要求已注册市场的 `marketplace.json` 指向同一个 Release ZIP/hash。维护者应将生成的 `marketplace-release.json` 作为渠道分支上的 `marketplace.json` 发布。[ByteRax 的 `plugin-releases` 渠道](https://github.com/ByteRax/zcode-token-usage-statusbar/tree/plugin-releases) 已发布 `v1.4.0` 一致清单,新用户注册 `ByteRax/zcode-token-usage-statusbar#plugin-releases`。未来发版须同步更新该清单,不能只上传 Release(`publish` 结束时会输出 `channelLag` 并在 stderr 警告清单滞后;发布目录已清理时可从正式 tag 确定性重建清单,见发布技能的[发布后收尾](../.zcode/skills/zcode-github-release/references/post-release.md));渠道分支只放清单与 `LICENSE`,提交对象由 `release_tool.py channel-commit` 生成(不推送),补推时用 `release_tool.py reconcile` 按成员内容对账而不要求重建包与线上包字节相同;不要擅自切换用户已有来源。 ### GitCode 更新渠道 diff --git a/release_tool.py b/release_tool.py index 5e0dc52fc..73a3232f2 100644 --- a/release_tool.py +++ b/release_tool.py @@ -4,6 +4,7 @@ import base64 import hashlib import importlib.util +import io import json import os from pathlib import Path, PurePosixPath @@ -215,6 +216,82 @@ def run(root, *args): return result.stdout +def run_input(root, args, data): + result = subprocess.run(args, cwd=root, input=data, capture_output=True, check=False) + require(result.returncode == 0, f"command failed: {' '.join(args)}\n" + + result.stderr.decode("utf-8", errors="replace")) + return result.stdout + + +def zip_members(path): + with zipfile.ZipFile(io.BytesIO(read_file(path, MAX_ASSET))) as archive: + return [(member.filename, archive.read(member)) for member in archive.infolist()] + + +def release_catalog(repo, version, asset_name, sha256, marketplace): + catalog = json.loads(marketplace) + require(isinstance(catalog, dict) and isinstance(catalog.get("plugins"), list) + and len(catalog["plugins"]) == 1, "marketplace catalog shape disagrees") + catalog["plugins"][0]["source"] = { + "source": "url", "type": "zip", "url": + f"https://github.com/{repo}/releases/download/v{version}/{asset_name}", + "sha256": sha256, "path": "plugins/" + PLUGIN, "stripRoot": False} + return json.dumps(catalog, indent=2, sort_keys=True) + "\n" + + +def reconcile(repo, asset, manifest_path, published_asset, published_manifest_path, catalog_out): + """补推前的对账(specs/release-channel-slim.md):重建包与线上发布包各自通过 verify 且身份 + 一致;字节相同直接通过,字节不同(打包机或压缩实现不同)时逐成员比对内容。渠道清单 + 必须指向真正托管的那份包,所以 sha256 恒取线上发布清单的值。""" + repo = repository(repo) + rebuilt = verify(asset, manifest_path, repo) + published = verify(published_asset, published_manifest_path, repo) + for key in ("repository", "version", "tag", "pluginId"): + require(rebuilt[key] == published[key], f"rebuilt release {key} disagrees with the published release") + require(rebuilt["asset"]["name"] == published["asset"]["name"], "rebuilt asset name disagrees") + rebuilt_bytes, published_bytes = read_file(asset, MAX_ASSET), read_file(published_asset, MAX_ASSET) + byte_identical = rebuilt_bytes == published_bytes + require(byte_identical or zip_members(asset) == zip_members(published_asset), + "rebuilt package differs from the published release") + catalog = release_catalog(repo, published["version"], published["asset"]["name"], + published["asset"]["sha256"], dict(zip_members(published_asset))["marketplace.json"]) + catalog_out.write_text(catalog, encoding="utf-8") + return {"byteIdentical": byte_identical, "version": published["version"], + "sha256": published["asset"]["sha256"], "rebuiltSha256": rebuilt["asset"]["sha256"], + "catalog": str(catalog_out.resolve())} + + +def channel_commit(root, catalog_path, version, parent=None): + """把渠道清单做成只含 marketplace.json 与 LICENSE 的提交对象(specs/release-channel-slim.md)。 + 不动工作区与索引、不推送:推送由发布技能按独立授权执行。缺省是孤儿提交,用于把存量 + 渠道分支一次性换成精简分支;给定 parent 时是快进提交。""" + root = Path(root).resolve() + require(isinstance(version, str) and re.fullmatch(SEMVER, version), "stable SEMVER required") + catalog = read_file(Path(catalog_path), MAX_MANIFEST) + parsed = json.loads(catalog) + plugins = parsed.get("plugins") if isinstance(parsed, dict) else None + entry = plugins[0] if isinstance(plugins, list) and plugins else None + require(isinstance(entry, dict) and entry.get("name") == PLUGIN and entry.get("version") == version, + "channel catalog plugin/version disagrees") + source = entry.get("source") + require(isinstance(source, dict) and re.fullmatch("[0-9a-f]{64}", str(source.get("sha256", ""))) + and str(source.get("url", "")).startswith("https://"), "channel catalog asset disagrees") + parent_sha = None + if parent: + parent_sha = run(root, "git", "rev-parse", "--verify", "--quiet", parent + "^{commit}").decode().strip() + entries = {"LICENSE": read_file(root / "LICENSE", MAX_MANIFEST), "marketplace.json": catalog} + tree_lines = [] + for name in sorted(entries): + oid = run_input(root, ["git", "hash-object", "-w", "--stdin"], entries[name]).decode().strip() + tree_lines.append(f"100644 blob {oid}\t{name}") + tree = run_input(root, ["git", "mktree"], ("\n".join(tree_lines) + "\n").encode("utf-8")).decode().strip() + command = ["git", "commit-tree", tree, "-m", f"chore: 更新渠道清单 {version}"] + if parent_sha: + command[3:3] = ["-p", parent_sha] + return {"commit": run(root, *command).decode().strip(), "tree": tree, "parent": parent_sha, + "files": sorted(entries), "version": version} + + def gh_json(root, endpoint, *flags): return json.loads(run(root, "gh", "api", endpoint, "--hostname", "github.com", "--method", "GET", *flags)) @@ -579,6 +656,17 @@ def main(argv=None): group.add_argument("--publish", action="store_true") group.add_argument("--dry-run", action="store_true") p.add_argument("--confirm", help="exact owner/repo/vVERSION; required with --publish") + p = sub.add_parser("reconcile", help="compare a rebuilt package with the published release and " + "emit the channel catalog bound to the published asset") + p.add_argument("--repo", required=True) + for name in ("zip", "manifest", "published-zip", "published-manifest", "catalog-out"): + p.add_argument("--" + name, dest=name.replace("-", "_"), type=Path, required=True) + p = sub.add_parser("channel-commit", help="create a commit holding only marketplace.json and LICENSE " + "(never pushes, never touches the worktree)") + p.add_argument("--root", type=Path, default=Path.cwd()) + p.add_argument("--catalog", type=Path, required=True) + p.add_argument("--version", required=True) + p.add_argument("--parent", help="commit to build on; omitted = orphan commit for the one-time switch") args = parser.parse_args(argv) try: if args.command == "build": @@ -586,6 +674,11 @@ def main(argv=None): elif args.command == "verify": result = {"zip": str(args.asset.resolve()), "manifest": str(args.manifest.resolve()), **verify(args.asset, args.manifest, args.repo)} + elif args.command == "reconcile": + result = reconcile(args.repo, args.zip, args.manifest, args.published_zip, + args.published_manifest, args.catalog_out) + elif args.command == "channel-commit": + result = channel_commit(args.root, args.catalog, args.version, args.parent) else: result = publish(args.root.resolve(), args.repo, args.asset, args.manifest, args.publish, args.confirm, notes_file=args.notes_file, gitcode_repo=args.gitcode_repo) diff --git a/specs/release-channel-slim.md b/specs/release-channel-slim.md new file mode 100644 index 000000000..85188c520 --- /dev/null +++ b/specs/release-channel-slim.md @@ -0,0 +1,28 @@ +# 渠道分支精简与重建对账 + +## 目标与边界 + +- 渠道分支 `plugin-releases` 与 `plugin-releases-gitcode` 只承载渠道清单 `marketplace.json`(外加 `LICENSE`),不再携带源码树。宿主每次添加市场、每次刷新市场都按 ref 下载整份归档,整树分支让每次更新检查多下载与安装无关的内容。 +- 清单的内容、身份与校验语义不变:仍是 `build` 输出的 `marketplace-release*.json`,仍指向正式 Release 的 ZIP 与它的 sha256。 +- 补推(Release 已发、渠道清单未更新)时的对账从「字节相同」放宽到「内容相同」。发布包的字节可能随打包机与压缩实现变化,内容不变才是对账要守的不变量;渠道清单里的 sha256 必须是线上资产的摘要,不是重建产物的摘要。 +- 工具只生成提交对象与清单文件,不推送、不动工作区。快进推送属于发布技能的阶段 E,授权范围以该技能为准;把存量分支换成精简分支要强推,发布技能的默认全链不含强推,须用户针对这个动作明确授权。 + +## 规则 + +- `release_tool.py reconcile`:重建包与线上包各自通过 `verify`,仓库、版本、tag、插件身份与资产名一致;字节相同直接通过;字节不同则逐成员比对名称与内容,任一成员不同即失败。通过后把渠道清单写到 `--catalog-out`,清单以线上发布包内的 `marketplace.json` 为底,`source.sha256` 取线上发布清单的值。 +- `release_tool.py channel-commit`:读入渠道清单,校验插件名、版本与资产的 sha256、URL 形态;生成只含 `marketplace.json` 与 `LICENSE` 的提交对象并输出提交哈希。`--parent` 给出时是快进提交,缺省是孤儿提交。 +- 存量渠道分支换成精简分支是一次性动作:先确认远端原清单的版本不高于新清单,再用孤儿提交带 `--force-with-lease=<分支>:<远端旧提交>` 推送。之后的每次发版用 `--parent` 做快进推送,不强推。 + +## 验收 + +| 场景 | 可观察结果 | +|---|---| +| 重建包与线上包字节相同 | 对账通过,清单的 sha256 等于线上资产摘要 | +| 重建包与线上包字节不同、逐成员内容相同 | 对账通过并注明不是字节相同,清单的 sha256 仍等于线上资产摘要 | +| 重建包任一成员内容不同,或版本、仓库不一致 | 对账失败,不写出清单 | +| 渠道清单的版本或资产形态不合法 | 不生成提交 | +| 不给 `--parent` | 生成没有父提交的提交,树里恰好是 `marketplace.json` 与 `LICENSE` | +| 给 `--parent` | 生成以它为唯一父提交的提交 | +| 任意一次 `channel-commit` | 工作区与索引没有变化,没有任何推送 | + +自动化验收使用 `tests/test_release_tool.py`;线上渠道分支的实际替换需维护者按发布技能授权执行。 diff --git a/tests/test_release_tool.py b/tests/test_release_tool.py index 78b8afc6d..e7c9a075c 100644 --- a/tests/test_release_tool.py +++ b/tests/test_release_tool.py @@ -3,6 +3,7 @@ import contextlib import hashlib import importlib.util +import io import json import os from pathlib import Path @@ -1229,6 +1230,152 @@ def test_gitcode_api_errors_never_leak_token(self): self.run_gitcode_publish(fail=fail) self.assertNotIn(sentinel, str(caught.exception)) + # ---- 渠道分支精简与重建对账(specs/release-channel-slim.md)---- + + def published(self): + out = self.base / "out" + return out / self._asset_name, out / "release-manifest.json", out / "marketplace-release.json" + + def rebuilt(self, name, alter=None): + """把已构建的包换成另一种压缩方式重写:字节不同、成员内容相同;alter 可改写一个成员。""" + asset, manifest_path, _ = self.published() + manifest = json.loads(manifest_path.read_text()) + target = self.base / name + target.mkdir() + with zipfile.ZipFile(asset) as original, zipfile.ZipFile( + target / self._asset_name, "w", zipfile.ZIP_DEFLATED) as rebuilt_zip: + for member in original.infolist(): + method = (zipfile.ZIP_DEFLATED if member.compress_type == zipfile.ZIP_STORED + else zipfile.ZIP_STORED) + info = zipfile.ZipInfo(member.filename, date_time=(1980, 1, 1, 0, 0, 0)) + info.create_system = 3 + info.external_attr = member.external_attr + content = original.read(member) + rebuilt_zip.writestr(info, alter(member.filename, content) if alter else content, + compress_type=method) + payload = (target / self._asset_name).read_bytes() + manifest["asset"].update(size=len(payload), sha256=hashlib.sha256(payload).hexdigest()) + (target / "release-manifest.json").write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n") + return target / self._asset_name, target / "release-manifest.json" + + def git(self, *args): + return subprocess.check_output(["git", *args], cwd=self.root, stderr=subprocess.PIPE).decode() + + def test_reconcile_passes_when_the_rebuild_is_byte_identical(self): + asset, manifest_path, catalog_path = self.published() + out = self.base / "reconciled.json" + result = tool.reconcile(REPO, asset, manifest_path, asset, manifest_path, out) + self.assertTrue(result["byteIdentical"]) + self.assertEqual(result["sha256"], json.loads(manifest_path.read_text())["asset"]["sha256"]) + self.assertEqual(out.read_bytes(), catalog_path.read_bytes(), "再生清单与 build 输出逐字节一致") + + def test_reconcile_accepts_same_contents_packaged_with_different_bytes(self): + asset, manifest_path, catalog_path = self.published() + rebuilt_asset, rebuilt_manifest = self.rebuilt("rebuilt") + self.assertNotEqual(rebuilt_asset.read_bytes(), asset.read_bytes()) + out = self.base / "reconciled.json" + result = tool.reconcile(REPO, rebuilt_asset, rebuilt_manifest, asset, manifest_path, out) + self.assertFalse(result["byteIdentical"]) + self.assertNotEqual(result["rebuiltSha256"], result["sha256"]) + self.assertEqual(result["sha256"], json.loads(manifest_path.read_text())["asset"]["sha256"], + "清单必须指向线上托管的那份包") + self.assertEqual(out.read_bytes(), catalog_path.read_bytes()) + + def test_reconcile_rejects_content_drift_and_writes_no_catalog(self): + asset, manifest_path, _ = self.published() + rebuilt_asset, rebuilt_manifest = self.rebuilt( + "rebuilt", alter=lambda name, content: b"tampered\n" if name == "LICENSE" else content) + out = self.base / "reconciled.json" + with self.assertRaisesRegex(tool.ReleaseError, "differs from the published release"): + tool.reconcile(REPO, rebuilt_asset, rebuilt_manifest, asset, manifest_path, out) + self.assertFalse(out.exists()) + + def test_reconcile_requires_both_sides_to_verify(self): + asset, manifest_path, _ = self.published() + forged = self.base / "forged" + forged.mkdir() + shutil.copyfile(asset, forged / self._asset_name) + manifest = json.loads(manifest_path.read_text()) + manifest["pluginId"] = "someone-else@evil" + (forged / "release-manifest.json").write_text(json.dumps(manifest)) + out = self.base / "reconciled.json" + with self.assertRaisesRegex(tool.ReleaseError, "identity disagrees"): + tool.reconcile(REPO, forged / self._asset_name, forged / "release-manifest.json", + asset, manifest_path, out) + self.assertFalse(out.exists()) + + def test_channel_commit_creates_a_minimal_orphan_commit_without_touching_the_worktree(self): + _, _, catalog_path = self.published() + before = (self.git("status", "--porcelain"), self.git("rev-parse", "HEAD"), + self.git("for-each-ref"), self.git("count-objects", "-v")) + result = tool.channel_commit(self.root, catalog_path, "1.2.3") + after = (self.git("status", "--porcelain"), self.git("rev-parse", "HEAD"), + self.git("for-each-ref"), self.git("count-objects", "-v")) + self.assertEqual(result["files"], ["LICENSE", "marketplace.json"]) + self.assertIsNone(result["parent"]) + tree = self.git("ls-tree", result["commit"]).splitlines() + self.assertEqual([line.split("\t")[1] for line in tree], ["LICENSE", "marketplace.json"]) + self.assertEqual(subprocess.check_output(["git", "show", result["commit"] + ":marketplace.json"], + cwd=self.root), catalog_path.read_bytes()) + self.assertEqual(subprocess.check_output(["git", "show", result["commit"] + ":LICENSE"], + cwd=self.root), (self.root / "LICENSE").read_bytes()) + self.assertEqual(self.git("rev-list", "--count", result["commit"]).strip(), "1") + self.assertEqual(after[:3], before[:3], "工作区、HEAD 与引用都不变") + self.assertNotEqual(after[3], before[3], "只往对象库写入新对象") + self.assertIn("更新渠道清单 1.2.3", self.git("log", "-1", "--format=%B", result["commit"])) + + def test_channel_commit_with_parent_builds_a_fast_forward_commit(self): + _, _, catalog_path = self.published() + head = self.git("rev-parse", "HEAD").strip() + result = tool.channel_commit(self.root, catalog_path, "1.2.3", parent="HEAD") + self.assertEqual(result["parent"], head) + self.assertEqual(self.git("rev-list", "--count", result["commit"]).strip(), "2") + self.assertEqual(self.git("rev-parse", result["commit"] + "^").strip(), head) + self.assertEqual([line.split("\t")[1] for line in self.git("ls-tree", result["commit"]).splitlines()], + ["LICENSE", "marketplace.json"], "精简分支上每次都是只有这两个文件") + + def test_channel_commit_rejects_catalogs_it_cannot_trust(self): + _, _, catalog_path = self.published() + catalog = json.loads(catalog_path.read_text()) + bad = self.base / "bad.json" + objects = self.git("count-objects", "-v") + for label, mutate, version in ( + ("version", lambda c: None, "9.9.9"), + ("sha256", lambda c: c["plugins"][0]["source"].update(sha256="zz"), "1.2.3"), + ("url", lambda c: c["plugins"][0]["source"].update(url="http://evil.invalid/x.zip"), "1.2.3"), + ("plugin", lambda c: c["plugins"][0].update(name="someone-else"), "1.2.3"), + ("not a catalog", lambda c: c.clear(), "1.2.3")): + with self.subTest(label=label): + data = json.loads(json.dumps(catalog)) + mutate(data) + bad.write_text(json.dumps(data)) + with self.assertRaises(tool.ReleaseError): + tool.channel_commit(self.root, bad, version) + self.assertEqual(self.git("count-objects", "-v"), objects, "被拒的清单不留下任何对象") + + def test_reconcile_and_channel_commit_cli_print_json(self): + asset, manifest_path, catalog_path = self.published() + out, errors = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(errors): + code = tool.main(["reconcile", "--repo", REPO, "--zip", str(asset), "--manifest", str(manifest_path), + "--published-zip", str(asset), "--published-manifest", str(manifest_path), + "--catalog-out", str(self.base / "cli.json")]) + committed = tool.main(["channel-commit", "--root", str(self.root), "--catalog", str(catalog_path), + "--version", "1.2.3"]) + rejected = tool.main(["channel-commit", "--root", str(self.root), "--catalog", str(catalog_path), + "--version", "9.9.9"]) + self.assertEqual((code, committed, rejected), (0, 0, 1)) + # 输出是多行缩进 JSON:按对象逐个解码 + text, reports = out.getvalue().lstrip(), [] + while text: + report, end = json.JSONDecoder().raw_decode(text) + reports.append(report) + text = text[end:].lstrip() + self.assertEqual([sorted(report) for report in reports], + [["byteIdentical", "catalog", "rebuiltSha256", "sha256", "version"], + ["commit", "files", "parent", "tree", "version"]]) + self.assertIn("channel catalog plugin/version disagrees", errors.getvalue()) + if __name__ == "__main__": unittest.main() From 90194caff22571497915578c84e2382b09715f21 Mon Sep 17 00:00:00 2001 From: tanranran Date: Thu, 26 Nov 2026 12:16:35 +0800 Subject: [PATCH 4/4] =?UTF-8?q?docs:=20=E5=AE=89=E8=A3=85=E6=96=87?= =?UTF-8?q?=E6=A1=88=E5=90=88=E5=B9=B6=E4=B8=BA=E8=87=AA=E5=8A=A8=E9=99=8D?= =?UTF-8?q?=E7=BA=A7=E7=89=88=EF=BC=8C=E5=90=8C=E6=AD=A5=E5=BD=92=E6=A1=A3?= =?UTF-8?q?=E5=8D=95=E4=BA=8B=E5=8A=A1=E4=B8=8E=E4=BD=93=E6=A3=80=E5=91=BD?= =?UTF-8?q?=E4=BB=A4=E7=9A=84=E8=AF=B4=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 三份 README 的安装文案由「GitHub 版 + 国内版两段」合并为一段:GitHub 连不上时自动改用 GitCode 渠道重试,不再要用户重发 - 写明宿主的来源判定规则:只有以 .git 结尾的地址才被当作仓库来源,否则会被当成清单直链下载 - 故障排查入口先引导 /zusage-doctor;插件 README 与用户指南同步 - 维护指南与规则文件补上归档单事务、只读体检的长期约束,测试对照表登记新增测试文件 --- .zcode/rules/bridge-remote.md | 1 + .zcode/rules/install-release.md | 3 +++ AGENTS.md | 6 +++--- README.en.md | 16 +++++----------- README.md | 16 +++++----------- README.zh-CN.md | 16 +++++----------- docs/user-guide.md | 2 ++ plugins/zcode-token-usage-statusbar/README.md | 4 +++- plugins/zcode-token-usage-statusbar/README_CN.md | 4 +++- 9 files changed, 30 insertions(+), 38 deletions(-) diff --git a/.zcode/rules/bridge-remote.md b/.zcode/rules/bridge-remote.md index 1b058c1f0..8489553e1 100644 --- a/.zcode/rules/bridge-remote.md +++ b/.zcode/rules/bridge-remote.md @@ -10,6 +10,7 @@ - 客户端版本登记表是 `HOST_TARGETS`(以源码为准,不在文档写版本清单):表内版本资产哈希漂移(宿主对同版本号重 build,issue:升级宿主后更新插件报「不在支持名单」)先走 `derive_target` 结构推导兜底,通过则按推导指纹打桥;幂等识别与卸载对称走「`_strip_auto_bridge` 剥桥→`derive_target` 验证→按推导指纹重打整模块逐字节等于现状(覆盖属性串与桥块)」(桥在而 pinned 校验不过即此形态,推导不过或字节不等维持 tampered 语义上抛);已装兜底桥的资产字节再次变化(原地篡改/局部热修致锚点轮换或内容不可推导)后剥桥推导不过,卸载也 skipped-error——「能拆自己装的桥」不变式在该边界失效,属刻意 fail-closed,等登记跟上后可卸载;表外版本先走 `derive_target` 严格推导(唯一锚点、registry/key/topic 绑定、store 形状与 import 目标——引擎 bundle 里 `new Map` 前的 registry 名、`workspaceIdentity?.trim()` 的 KEY 函数、跨 chunk 的 topic 绑定、全文件唯一的 ``"data-session-id":t??`draft`,`` 锚点,draft 是反引号模板字面量不是字符串),校验不过拒绝补丁并降级 DB 轮询。`python3 renderer_bridge.py derive ` 直接打印可粘贴的登记条目;新客户端版本升级=HOST_TARGETS 加一行。登记时 `tests/test_renderer_bridge.py` 三处随动:props 夹具补新锚点包装/testid 别名桩(漏补则 VM 测试 ReferenceError);sourcemap 夹具 map 名写 `bridge.ASSET + '.map'` 跟随、不写死资产名(写死则 NEWEST 切换后拒绝逻辑不再触发、假失败);SessionPane 参数映射随版本轮换(先例:3.17.x 起 c/l/u/e→l/u/d/e),期望值用实现同款 `bridge.pane_attributes(target)` 推导,不硬编码属性串与形参签名。 - 宿主契约锚点(引擎侧,混淆名随版本轮换):连接 key 无 sessionId 维度(同 workspace 新老会话共用 layer);draft 预热=pane 挂载即后台 createSession,`data-session-id` 可为字面量 `"draft"`,store 在首发消息前已 cold 创建。引擎 bundle grep 必须 `LC_ALL=C grep -a`(NUL 被当 binary 会静默丢结果);kebab-case 字段要同时搜 camelCase。 - asar 原子替换后 `os.chmod(stage, S_IMODE(...))` 保留权限位;`_output_path` 对 `is_symlink()`/`resolve()` 须捕获 `OSError`(防受限沙箱或 `/Applications/ZCode.app` 权限拦截抛 `PermissionError`)。手工部署桥前先 `cp` 一份 `app.asar.backup-pre-bridge--`(`ensure_deployed` 代码不备份)。表外版本的 `remove_deployed` 按 BEGIN/END 标记字节还原。 +- 插件链的完整安装把桥改写并入 loader 的同一次重打包([归档单事务规格](../../specs/asar-single-transaction.md)):`plan_deploy` 返回判定时的整包指纹与改写后的资产,`patch_install._extra_modifications` 只在指纹与重打包来源一致、路径在归档内且不触碰主入口时并入;其余情形(钩子异常、布局无法验证、过期计划)一律静默退回安装后的 `ensure_deployed` 独立补桥。并入后的包同时含 loader 与桥,客户端占用归档时一次待替换就够,Windows 首次安装不再需要两次完全退出;卸载仍单独剥桥。 - `ensure_deployed` 发布被系统拒绝(Windows 客户端运行中持有 asar 不带 FILE_SHARE_DELETE、目标目录 ACL 只读)时返回 `replace-failed` 并移交**完整 stage**,不得静默吞成 skipped:调用方转 `patch_install.publish_external_pending`(TMP + sidecar + monitor 收尾链)或删除 stage,不能留原地;`PermissionError` 单独标 `permission`(Windows `os.access` 看不见 ACL,不能靠 `target_writable` 判权限);入口清扫超时残留的崩溃孤儿 stage(新 stage 处在移交窗口内绝不能删);用户 remove 待收尾时让位,锁内拒绝以 install 覆盖 pending remove。 - 对本机 asar 的整文件哈希断言先检测并剥离本项目 BRIDGE 标记再校验(已部署机器必失配)。`tests/test_renderer_bridge.py` 用最新登记项的 names 推导夹具,不写死混淆名。 - **桥模板内容变更必须升 `BRIDGE_GEN` 代际**(issue #307 教训):`_original_module` 剥桥时要求桥块逐字节等于当前代或显式登记的遗留代(`BRIDGE_TEMPLATE_V1`/`BRIDGE_TEMPLATE_V2`)——只改内容不升代际,已部署旧桥的机器升级时识别失败(`Unknown renderer asset hash`)。遗留代保留原字节永不改动;`MARKER` 前缀判定(已带桥检测)跨代兼容不用动。守卫是隔离测试 `BridgeGenerationTests`(各代正文 SHA256 钉值 + 每个遗留代的识别/升级/还原),不依赖本机 asar:真机测试只在本机桥恰是旧代时才走这条路径,桥一升级即失效。 diff --git a/.zcode/rules/install-release.md b/.zcode/rules/install-release.md index 900b8bf8f..9609c0f12 100644 --- a/.zcode/rules/install-release.md +++ b/.zcode/rules/install-release.md @@ -28,6 +28,8 @@ - `patch_install.client_running()` 用 `pgrep -x ZCode`,本机进程名可能是 `zcode-cli` 而漏检;它只决定走安全路径,无害,但**测试时不要靠它判断客户端是否在跑**。asar 被占用的收尾必须由宿主以外的监控进程执行,不能依赖 ZCode 自己的定时任务。 - 热/冷清单:`overlay.js`、`turn-stats.js` 热重载(主桥 mtime 监听:`hot_reload:true`=2s/缺省 5s/`false` 关);`zusage.py` 常驻进程由 loader 按 mtime 自动重启;`inject-main.cjs` 是唯一冷文件(ipcMain/监听器注册与常驻泵都在它体内,只能随客户端完全重启生效);八个子模块 `quota-client.cjs`、`model-puller.cjs`、`plugin-updater/release/storage.cjs`、`engine-patch.cjs`(六者自 v258 起)、`sysmon-client.cjs`(v356 起)与 `mobile-relay.cjs`(v331 起)由 loader 的 `hotReloadMainModules` 同拍热换(mtime 轮询→语法预检→dispose→清 require.cache→按依赖方向重建:quota 先落并联动重装 modelPuller 的 decryptValue 注入、release/storage 联动重建 updater 与 notes→`_hotLoadedAt` 销账→广播;updater 组 busy 在途顺延;watcher/定时器一次注册不得在热换路径重建;启动时缺文件后来补齐的也进 changed,sysmon 重建后按现存订阅重放并回放最近 cfg/projectPath);`hot_reload:false` 时整链短路——mtime 轮询与更新链 `onRuntimeSynced` 两条路径都被入口门挡住,回退为待完全重启。**冷文件结论只在旧版 loader(未含热换循环)上成立**;新 loader 部署并重启一次后,上述八个模块更新即零重启生效。更新链的重启标记清单与此同源两处:`overlay_install.py` 的 `cold_files` 与 `plugin-updater.cjs` `recordRestart` 的 `cold` 判定(后者只服务旧包同步报告缺 `restartRecorded` 的回退路径),两处不许漂移(`tests/plugin-updater.test.cjs` 的 legacy fallback cold list 用例锁定),改清单必须两处同改。 - **手机中继归档补丁**:沿用 `patch_install.py install`、`remove`、`check`,不新增子命令。loader 与手机 stash/uplink 从同一份 `out/main/index.js` 变换,随现有归档 stage 和替换流程一起提交;`check` 追加只读手机诊断。渲染桥仍走独立流程。已有 loader 的 SessionStart 先处理渲染桥,再尝试手机补装;已有待替换包或 sidecar 时让位,不改写待替换文件或重定向当前 loader。归档安装、待替换与手机清理边界见 [app.asar 安装规格](../../specs/asar-install.md),宿主钩子兼容与升级见 [上行队列与补丁代际](../../specs/mobile-relay.md#上行队列与补丁代际)。 +- **归档单事务([规格](../../specs/asar-single-transaction.md))**:完整安装/卸载的待替换包在重打包时边写边算整包摘要,stage 与落成后的 TMP 不再整包回读(`repack` 被替身顶替或没喂满时自动回退回读);同一次持锁内刚生成并校验过的包,替换前只核对身份戳。复用磁盘上已有的待替换包仍完整验包,监控是另一进程也照常完整验包——这两条不要跟着省。插件链的完整安装经 `install(extra_modify=...)` 把渲染桥改写并入同一次重打包:钩子只在确需生成新包时调用,任何不满足都静默退回独立补桥;`overlay_install` 只在已加载的 `patch_install` 模块满足 `EXTRA_MODIFY is True` 时才传钩子,旧运行目录模块的调用形状不变。手机补装链与卸载时的桥剥离不在并入范围。 +- **只读体检([规格](../../specs/zusage-doctor.md))**:`overlay_install.py doctor`(`/zusage-doctor`)只读取各模块的既有判定;落盘动作只有 `target_writable` 的建后即删探针与监控去重锁的试取,不读凭据文件。改判定口径时同步 `tests/test_zusage_doctor.py`:安装已排定时不得再建议重跑 `/install-overlay`(重跑只会复用同一个待替换包)。 - **手机补装反馈**:只有 `mobile_relay` 对象内的显式布尔 `enabled:true` 允许 SessionStart 输出手机补丁会话提示;否则静默且不读写 `.mobile-deferred-notice.json`。门控不改归档安装、让位、重启标记或显式安装输出;提示分流、限频和兼容性提示优先级见 [安装与会话提示](../../specs/mobile-relay.md#安装与会话提示)。持久钩子需完全重启生效,`asarPatch:true` 仍阻止纯热销账;`hot_reload:false` 时 `mobile-relay.cjs` 变更写入 restart hashes。改动提示或重启标记时核对 `tests/test_mobile_relay_install.py`、`tests/test_bridge_pending.py`、`tests/test_plugin_runtime.py` 的 hook 用例与 `tests/test_restart_notice.py`。 - **marker 热销账(v258)**:`ack_restart` 对启动后才写入的 marker 默认不动,唯一例外=loaded 顶层 `_hotLoadedAt`(键=文件名、值=热替换完成毫秒)覆盖全部 hash 条目且每条 `loaded[key]==digest` 且时间戳≥createdAt 且不含 `inject-main.cjs`(loader 自身只能随重启生效)→ 整单销账。`_hotLoadedAt` 是 loaded 顶层键,**绝不进 marker 的 `hashes`**(restart_notice 白名单会拒绝、`_hashes()` 会剥 `_` 前缀);pending-install/installation 发布门控不受热时间戳影响。更新器 `syncInstalled` 落盘后先 `await options.onRuntimeSynced()`(宿主热换+销账)再算 `restartRequired`,红点零闪烁;旧主进程装配新包时无该回调,行为不变。**孤儿 marker 防御(2026-11-21,3.19.1 实机红点常亮;runtime_lock 域无代际,编号留给 overlay 批次)**:`hashes` 保留进 remaining 前核对盘上现状——digest 已不等于运行文件当前字节(记录后被 preserved 保护的开发部署/第三方覆盖超越)即从待办剔除;目标重启也加载不到该字节,保留只会让 ⚙ 红点永亮。盘上字节==digest(等重启加载)照常保留。剔除前按键形状校验(含分隔符/盘符/`..`/NUL 的损坏 marker 键不拼路径读盘、直接剔除);文件已消失或目标路径被目录占位(Windows 抛 PermissionError,靠 `is_dir` 归一)同按不等剔除,其余瞬态读失败无法判定时保守保留待办、下次 ack 再核(宁红勿漏)。双实例同跑存在 record-before-write 毫秒级窗口,可能把刚记录、尚未写盘的条目提前剔除(盘检引入前同窗口保守保留)——单实例因 createdAt 守卫恒不可达,属已知取舍。排查此类红点常亮的判据=三方比对(运行目录 hash / 插件缓存来源 hash / marker digest)。 标记文件自身读不到(瞬态 `OSError`)一律保留不销——读失败 ≠ 没有待办;`publishedAt` 为 NaN 等非法数值时 pending-install 门同样不销账(v445)。写入侧同理:`record_restart` 读不到标记(`OSError`)时抛错、不改写——按空合并会把盘上旧通知整份覆盖;文件不存在才是空标记(v445)。 - 插件→运行目录同步有 hash 基线/mtime 热修保护(`preserved`);根 `install.py` 的运行文件复制是直接覆盖,不能承诺同等保护。插件版本记录前进不代表每个文件的 hash 基线都前进:被保护的文件可保留旧基线。排查时逐文件比较运行文件、记录 hash 与实际插件来源;同步只有在运行文件与来源字节一致时才可按该路径更新基线,开发工作树与插件缓存不一致时重跑安装不能保证归位。安装/同步涉及全名单,仍须先核实来源身份和全部待同步差异,不能为修基线盲目执行。向运行目录覆盖任何文件前先 diff 运行目录与来源基(运行时可能领先所有工作树,直接 cp 曾静默降级);并行会话活跃时 `sync_plugin.py` 会把他人未提交的根文件改动扫进副本与运行目录——浮层/更新器异常先排查这条路径。 @@ -81,6 +83,7 @@ - 本地同步 ≠ 打包 ≠ 校验 ≠ 发布预演 ≠ 提交/tag/Release/渠道推送;源码改版、正式渠道发布、用户安装副本升级是不同步骤。 - 两份 `plugin.json` 与根 `marketplace.json` 的插件身份/版本须一致;正式渠道清单是生成的 `marketplace-release.json`,不要覆盖源码市场入口。`release_tool.py build` 的输出目录须尚不存在,包只含枚举分发文件;`verify` 校验身份、文件集、SHA256 与安全解包。 +- 渠道分支只放渠道清单与 `LICENSE`,补推对账按内容而不是按字节:`release_tool.py channel-commit` 生成提交对象(不动工作区、不推送),`release_tool.py reconcile` 把重建包与线上包逐成员对账、并把清单绑定到线上资产的 sha256([渠道分支精简与重建对账](../../specs/release-channel-slim.md))。发布包的字节可能随打包机与压缩实现变化,对账不能再要求重建包与线上包字节相同;补 GitCode 镜像时传线上发布包,不传重建包。 - `publish --dry-run` 不是离线检查:仍有 GitHub 只读 preflight,要求已提交源码、本地/远端 tag 与目标提交一致、Release 不存在及非空 UTF-8 更新说明;预演不授予发布权限。`publish --gitcode-repo`(需 `GITCODE_TOKEN`)在 GitHub 发布验收后生成 `plugin-releases-gitcode` 清单与同 tag 资产,镜像上须先有同一个 tag 且指向发布提交(创建 Release 的请求不带 `target_commitish`,见发布技能的 GitCode tag 闸门);GitCode 段认证未配置时该段失败属预期,不代表 GitHub 段失败。 - 覆盖/删除已有 Release 需用户明确指令,删除前 `gh release view --json body,assets` 存快照。`--publish`/`--confirm` 是工具安全门不是授权替代;提交、推送、tag、Release、渠道写入按当前明确授权执行。 - 配置、数据库、诊断、本地热修不是发布素材;可信同步保护用户改动,解包保留路径穿越、链接、重复项与文件集限制。本地统计只读数据库不上传;远端查询用配置/宿主连接通道、插件更新联网下载代码,不能笼统宣称"不联网"。 diff --git a/AGENTS.md b/AGENTS.md index b68f01e32..965c69812 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -55,7 +55,7 @@ | `renderer_bridge.py` | 渲染桥:按客户端版本指纹(HOST_TARGETS 登记 + derive 推导)向 SessionPane 节点写 scope 身份属性 | | `inject-main.cjs` | 主进程加载、窗口/工作区 IPC、查询泵、文件监听、快照推送、受限写操作与八个子模块热换循环(唯一冷文件) | | `install.py` | 独立安装/卸载、运行文件、配置、独立 MCP 与 `/usage` 注册 | -| `patch_install.py` | 统一 app.asar 安装/卸载;loader 与手机 stash/uplink 使用同一入口、同一 stage 和一次替换;提供 install/remove/check,自检、归档校验与待替换处理(specs/asar-install.md) | +| `patch_install.py` | 统一 app.asar 安装/卸载;loader 与手机 stash/uplink 使用同一入口、同一 stage 和一次替换;提供 install/remove/check,自检、归档校验与待替换处理(specs/asar-install.md);完整安装经可选 `extra_modify` 钩子把渲染桥并入同一次重打包,待替换包摘要边写边算、同一次持锁内复用校验(specs/asar-single-transaction.md) | | `pending_zip_patch.py` | macOS pending 更新包清理自愈(v339/issue #298):按改写账本 sha256 对账删除旧版预注入改写的 pending zip(宿主自动重下官方包);无记录 zip 绝不碰,update-info.json 恒不读写(宿主缓存有效性判据)。旧「Squirrel 取包前改写预注入」已废除——改写改变包大小,与 MacUpdater 本地代理按下载完成时固化的官方 Content-Length 拉流冲突,导致更新静默失败 | | `install_monitor.py` | 重启提醒、加载诊断和 Windows 待替换收尾 | | `plugin-updater.cjs` / `plugin-release.cjs` | 宿主插件更新调度、正式 GitHub Release 与渠道校验、更新日志(Release 说明)拉取与缓存 | @@ -78,7 +78,7 @@ - 工作区/任务 IPC、活动 SID IPC 与配置/更新写操作的校验不同;不能概括全部桥接同等可信,写操作保留本地窗口验证和固定动作白名单。 - MCP 与 CLI 使用查询库;插件 `.mcp.json` 经宿主预置 `zcode-python` 直接拉起包内 `usage_mcp.py`,不是统一 `run.py` 入口。 - `hooks/session-start.py` 负责运行文件同步、更新/自动安装(恒开)与故障提示;正常安装/待重启不再注入会话文字,由 ⚙ 齿轮红点承载(v172);`hooks/prompt-submit.py` 记录本会话提问时间并注入「上一条回复」背景行,**不再向模型下达统计指令**——逐问统计行由前端确定性渲染(依赖 renderer 桥),会话末尾经主桥 `turn-text` 通道调用包内 `token_rate.py --turn --current` 回推富文本;子代理窗格(`sess_subagent_*` 只读分栏,v458)由 03 分片的伪 owner 观察器认领,请求带页面轮号走 `--turn-ref`(specs/subagent-turn-stats-line.md)。 -- 专有入口是 `overlay_install.py`、`plugin_auto_update.py`、`restart_notice.py` 等;改变 hook 返回值应检查宿主 CLI 契约,不以手工执行代替自然事件验收。 +- 专有入口是 `overlay_install.py`、`plugin_auto_update.py`、`restart_notice.py` 等;改变 hook 返回值应检查宿主 CLI 契约,不以手工执行代替自然事件验收。`overlay_install.py doctor` 是只读体检(`/zusage-doctor` 背后就是它,specs/zusage-doctor.md):只读取各模块的既有判定并给出修法,安装已排定时不再建议重跑安装。 ## 3. 源文件、副本与正在运行的文件 @@ -232,7 +232,7 @@ python3 sync_plugin.py --check | 浮层/主桥 | `overlay-*.test.cjs`、`inject-*.test.cjs`、`plugin-loader.test.cjs`、`plugin-restart-boot.test.cjs`;语法检查,布局/多窗口需桌面验收 | | 桥/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_test_file_layout.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 一致性;涉及默认值/协议时加对应契约测试 | 宿主真实 CLI 沙箱测试和交互演示见 [测试说明](tests/README.md)。它们使用真实 ZCode、认证和模型,可能联网/消耗 token,不属于默认纯隔离测试;测试对象必须指向自有临时 HOME、插件库存与夹具。 diff --git a/README.en.md b/README.en.md index c3ae7a083..f78510cde 100644 --- a/README.en.md +++ b/README.en.md @@ -29,27 +29,20 @@ Promotional image with staged UI and demonstration data; the actual interface va ### Installation -Send this to ZCode to install or update the plugin: +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): ```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. ``` -If GitHub is unreachable, use this instead (keep `.git` in the URL; this route requires local [Git](https://git-scm.com/downloads)): - -```text -Please install or update and enable this ZCode plugin: https://gitcode.com/tanranran/zcode-token-usage-statusbar.git#plugin-releases-gitcode -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. -``` - -Keep `#plugin-releases` / `#plugin-releases-gitcode` in the URLs: they select the project's stable release channels. +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. > **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. -If the bar is still missing after a successful installation and full restart, send this to ZCode: +If the bar is still missing after a successful installation and full restart, run the read-only check-up `/zusage-doctor` in a new session and follow its suggested actions; to investigate further, send this to ZCode: ```text Please investigate why the status bar or toolbar chips from https://github.com/ByteRax/zcode-token-usage-statusbar are missing. Check whether the plugin is enabled, installation succeeded, the actual loaded path is correct, and the relevant switches are on. Ask for my confirmation before modifying client files. If a report is needed, prepare redacted reproduction steps and a diagnostic summary, then wait for my approval before submitting to https://github.com/ByteRax/zcode-token-usage-statusbar/issues. Do not upload credentials or complete local logs. @@ -66,6 +59,7 @@ The install link serves a published snapshot from the root of `main`, which can Client upgrades can overwrite injection patches. Keep the plugin enabled and **start or resume a session** to trigger automatic installation/repair; sending another message in an already-open session does not guarantee a trigger. Confirm repair succeeded, then fully quit and reopen ZCode if a restart is required. Insufficient permissions or changes to the host's structure can still prevent repair. - **Plugin install/update**: `/install-overlay`: open ZCode, start a new session, type `/install-overlay` and press Enter to re-trigger the repair injection; after confirming success, fully restart as instructed. +- **Plugin check-up**: `/zusage-doctor`: when the status bar, toolbar chips or the per-answer rate line are missing, start a new session and type `/zusage-doctor`. It is read-only, changes no files, and lists what is wrong together with the fix for each item. - **Plugin uninstall**: ① turn off auto-update in ⚙ → ② run `/uninstall-overlay` in chat and confirm success → ③ open **Settings → Plugins → Installed → ZCode Token Usage Statusbar → ⋯ → Uninstall** → ④ fully quit and reopen ZCode. Never uninstall only the plugin and leave the bar injected; for configuration and cache cleanup, see the [full uninstall guide](docs/user-guide.md#彻底卸载) (Chinese). - [Installation guide](docs/user-guide.md#插件安装) (Chinese) diff --git a/README.md b/README.md index b9c1eba5e..6506ff1c1 100644 --- a/README.md +++ b/README.md @@ -31,27 +31,20 @@ A community toolkit for ZCode desktop: generation speed, token usage, context tr ### 安装方法 -把下面这段话发给 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(仅关闭窗口不算),不要自动重启。 若安装失败,请说明原因;若当前会话无法执行该命令,请提示我手动执行,不要跳过这一步或声称安装成功。 ``` -国内访问 GitHub 受限时,换成下面这段(地址中的 `.git` 不能省,本机需安装 [Git](https://git-scm.com/downloads)): - -```text -请安装或更新并启用 ZCode 插件:https://gitcode.com/tanranran/zcode-token-usage-statusbar.git#plugin-releases-gitcode -完成后,在 ZCode 对话中执行 /install-overlay;确认状态条安装成功后,提醒我完全退出并重新打开 ZCode(仅关闭窗口不算),不要自动重启。 -若安装失败,请说明原因;若当前会话无法执行该命令,请提示我手动执行,不要跳过这一步或声称安装成功。 -``` - -保留地址中的 `#plugin-releases` / `#plugin-releases-gitcode`,它们选择正式发布的稳定渠道。 +保留地址里的 `#plugin-releases` 与 `.git#plugin-releases-gitcode`,它们选择正式发布的稳定渠道。国内源要求本机装有 [Git](https://git-scm.com/downloads)(宿主通过 git 拉取渠道清单),而且地址里的 `.git` 不能省:宿主只把以 `.git` 结尾的地址当作仓库来源,否则会把它当成清单文件的直链去下载。 > **注意**:状态条安装会修改 ZCode 的程序文件(`app.asar`),请先确认信任本项目。**首次注入成功后,须完全退出并重开 ZCode**(仅关闭窗口或重开会话不算),再检查状态条是否出现;安装失败或权限不足时,先排查原因,重启不能替代安装。 -如果安装成功并完全重启后仍看不到状态条,可把这句话发给 ZCode: +如果安装成功并完全重启后仍看不到状态条,先新开一个会话运行只读体检 `/zusage-doctor`,按输出里的「建议动作」处理;需要进一步排查时,可把这句话发给 ZCode: ```text 请排查 https://github.com/ByteRax/zcode-token-usage-statusbar 插件的状态条或工具栏 chip 未显示的原因,先检查插件启用状态、安装结果、实际加载路径及相关开关。修改客户端文件前先征求我确认;需要反馈时,整理脱敏后的复现步骤与诊断摘要,待我确认后再提交到 https://github.com/ByteRax/zcode-token-usage-statusbar/issues,不要上传凭据或完整本地日志。 @@ -68,6 +61,7 @@ A community toolkit for ZCode desktop: generation speed, token usage, context tr 客户端升级可能覆盖注入补丁。保持插件启用,**新建或恢复会话**可触发自动安装/修复;仅在已打开的会话里发消息不保证触发。确认修复成功后,如提示待重启,再完全退出并重开 ZCode。权限不足或宿主结构变化仍可能使修复失败。 - **插件安装/更新**:`/install-overlay`:打开 ZCode ,新开一个会话,输入 `/install-overlay`,然后回车,即可重新触发修复注入,确认成功后按提示完全重启。 +- **插件体检**:`/zusage-doctor`:状态条、工具栏 chip 或回答末尾的速率行不显示时,新开一个会话输入 `/zusage-doctor`;它只读、不改任何文件,逐项报告哪里不对并给出对应的修法。 - **插件卸载**:① 在 ⚙ 关闭自动更新 → ② 在对话中执行 `/uninstall-overlay` 并确认成功 → ③ 打开 **设置 → 插件 → 已安装 → ZCode Token Usage Statusbar → ⋯ → 卸载** → ④ 完全退出并重开 ZCode。切勿直接卸载插件而把状态条留在客户端中;清理配置与缓存残留见[彻底卸载指南](docs/user-guide.md#彻底卸载)。 diff --git a/README.zh-CN.md b/README.zh-CN.md index b9c1eba5e..6506ff1c1 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -31,27 +31,20 @@ A community toolkit for ZCode desktop: generation speed, token usage, context tr ### 安装方法 -把下面这段话发给 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(仅关闭窗口不算),不要自动重启。 若安装失败,请说明原因;若当前会话无法执行该命令,请提示我手动执行,不要跳过这一步或声称安装成功。 ``` -国内访问 GitHub 受限时,换成下面这段(地址中的 `.git` 不能省,本机需安装 [Git](https://git-scm.com/downloads)): - -```text -请安装或更新并启用 ZCode 插件:https://gitcode.com/tanranran/zcode-token-usage-statusbar.git#plugin-releases-gitcode -完成后,在 ZCode 对话中执行 /install-overlay;确认状态条安装成功后,提醒我完全退出并重新打开 ZCode(仅关闭窗口不算),不要自动重启。 -若安装失败,请说明原因;若当前会话无法执行该命令,请提示我手动执行,不要跳过这一步或声称安装成功。 -``` - -保留地址中的 `#plugin-releases` / `#plugin-releases-gitcode`,它们选择正式发布的稳定渠道。 +保留地址里的 `#plugin-releases` 与 `.git#plugin-releases-gitcode`,它们选择正式发布的稳定渠道。国内源要求本机装有 [Git](https://git-scm.com/downloads)(宿主通过 git 拉取渠道清单),而且地址里的 `.git` 不能省:宿主只把以 `.git` 结尾的地址当作仓库来源,否则会把它当成清单文件的直链去下载。 > **注意**:状态条安装会修改 ZCode 的程序文件(`app.asar`),请先确认信任本项目。**首次注入成功后,须完全退出并重开 ZCode**(仅关闭窗口或重开会话不算),再检查状态条是否出现;安装失败或权限不足时,先排查原因,重启不能替代安装。 -如果安装成功并完全重启后仍看不到状态条,可把这句话发给 ZCode: +如果安装成功并完全重启后仍看不到状态条,先新开一个会话运行只读体检 `/zusage-doctor`,按输出里的「建议动作」处理;需要进一步排查时,可把这句话发给 ZCode: ```text 请排查 https://github.com/ByteRax/zcode-token-usage-statusbar 插件的状态条或工具栏 chip 未显示的原因,先检查插件启用状态、安装结果、实际加载路径及相关开关。修改客户端文件前先征求我确认;需要反馈时,整理脱敏后的复现步骤与诊断摘要,待我确认后再提交到 https://github.com/ByteRax/zcode-token-usage-statusbar/issues,不要上传凭据或完整本地日志。 @@ -68,6 +61,7 @@ A community toolkit for ZCode desktop: generation speed, token usage, context tr 客户端升级可能覆盖注入补丁。保持插件启用,**新建或恢复会话**可触发自动安装/修复;仅在已打开的会话里发消息不保证触发。确认修复成功后,如提示待重启,再完全退出并重开 ZCode。权限不足或宿主结构变化仍可能使修复失败。 - **插件安装/更新**:`/install-overlay`:打开 ZCode ,新开一个会话,输入 `/install-overlay`,然后回车,即可重新触发修复注入,确认成功后按提示完全重启。 +- **插件体检**:`/zusage-doctor`:状态条、工具栏 chip 或回答末尾的速率行不显示时,新开一个会话输入 `/zusage-doctor`;它只读、不改任何文件,逐项报告哪里不对并给出对应的修法。 - **插件卸载**:① 在 ⚙ 关闭自动更新 → ② 在对话中执行 `/uninstall-overlay` 并确认成功 → ③ 打开 **设置 → 插件 → 已安装 → ZCode Token Usage Statusbar → ⋯ → 卸载** → ④ 完全退出并重开 ZCode。切勿直接卸载插件而把状态条留在客户端中;清理配置与缓存残留见[彻底卸载指南](docs/user-guide.md#彻底卸载)。 diff --git a/docs/user-guide.md b/docs/user-guide.md index f2ae29842..6f1daf621 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -74,6 +74,8 @@ https://gitcode.com/tanranran/zcode-token-usage-statusbar.git#plugin-releases-gi /install-overlay ``` +状态条、工具栏 chip 或回答末尾的速率行不显示时,先运行只读体检命令 `/zusage-doctor`:新开一个会话输入即可,它不修改任何文件,逐项报告插件登记、注入状态、待替换包、运行目录与更新情况,并按优先级给出对应的修法。 + 自动安装始终开启:新建或恢复会话时只要状态条未注入就会自动安装/修复,不再提供开关(旧配置里的 `plugin_auto_install_overlay` 与环境变量 `ZUSAGE_PLUGIN_AUTO_INSTALL` 已不被读取)。只需要查询工具与回答速率时,运行 `/uninstall-overlay` 移除状态条并保留卸载豁免,阻止自动重注入与提示。 Windows 找不到 `python3` 时插件 hook 会自动回退:hook 命令按 `python3` → `python` → `py -3` 依次尝试,无需改文件;候选解释器低于 Python 3.8 时会被 hook 脚本自动跳过(例如 PATH 里 `python` 是 3.7 而 `py -3` 指向 3.13,两条链都落到 `py -3`)。stdio MCP 由 ZCode 内置的 `zcode-python` 直接启动 `usage_mcp.py`:需要桌面 **3.19.0 及以上**,且预装工具已下载完成(宿主把预装工具的 bin 目录放在 MCP 子进程 PATH 首位,入口是宿主自带的 Python,带 sqlite3);不再经 `node` 中转,Windows 上每个会话省约 120–150MB。ZCode 3.18.2 及以下,或预装工具尚未就绪时,仍可用状态条与 `/usage`,但没有 `token_usage` MCP 工具(技能会退回 CLI 查询)。 diff --git a/plugins/zcode-token-usage-statusbar/README.md b/plugins/zcode-token-usage-statusbar/README.md index e2e532105..1eba1bf1c 100644 --- a/plugins/zcode-token-usage-statusbar/README.md +++ b/plugins/zcode-token-usage-statusbar/README.md @@ -23,7 +23,9 @@ See model speed, token usage, context size, plan quota, and Git status while you 2. Open (or reopen) a session. The plugin then installs / repairs the status bar automatically. **This modifies `app.asar` — only proceed if you trust this project.** 3. **Fully quit and reopen ZCode.** -Auto-install is always on (the legacy `plugin_auto_install_overlay` config key and `ZUSAGE_PLUGIN_AUTO_INSTALL` env var are no longer read); `/uninstall-overlay` leaves an opt-out marker — the only way to block re-injection. When a restart is pending or a new version is available, the status-bar gear shows a red dot (cleared by opening the ⚙ "Plugin updates" section, which also offers a "Restart ZCode" button); no in-session text notices are injected anymore (failure guidance excepted). If automatic install fails, run `/install-overlay` and follow its output; a full restart is still required. +Auto-install is always on (the legacy `plugin_auto_install_overlay` config key and `ZUSAGE_PLUGIN_AUTO_INSTALL` env var are no longer read); `/uninstall-overlay` leaves an opt-out marker — the only way to block re-injection. When a restart is pending or a new version is available, the status-bar gear shows a red dot (cleared by opening the ⚙ "Plugin updates" section, which also offers a "Restart ZCode" button); no in-session text notices are injected anymore (failure guidance excepted). If automatic install fails, run `/install-overlay` and follow its output; a full restart is still required. If the status bar, a toolbar chip or the per-answer rate line is missing, run `/zusage-doctor` in a new session: it is read-only, changes no files, and lists what is wrong together with the fix for each item. + +Where GitHub is unreachable, add the marketplace with `https://gitcode.com/tanranran/zcode-token-usage-statusbar.git#plugin-releases-gitcode` instead (same verified release; needs local Git, and the `.git` suffix cannot be dropped). ## Mobile remote page (current source feature) diff --git a/plugins/zcode-token-usage-statusbar/README_CN.md b/plugins/zcode-token-usage-statusbar/README_CN.md index ecf338c6d..ba46b534e 100644 --- a/plugins/zcode-token-usage-statusbar/README_CN.md +++ b/plugins/zcode-token-usage-statusbar/README_CN.md @@ -23,7 +23,9 @@ 2. 新建或重新打开会话,插件会自动安装 / 修复状态条。**这一步会修改 `app.asar`,请确认信任此项目。** 3. **完全退出并重开 ZCode。** -自动安装始终开启(旧配置 `plugin_auto_install_overlay` 与环境变量 `ZUSAGE_PLUGIN_AUTO_INSTALL` 已不再读取);`/uninstall-overlay` 会留下卸载豁免标记,是阻止自动重注入的唯一出口。待重启/有新版本时状态条 ⚙ 齿轮显示红点(点进 ⚙ 面板「插件更新」分区后消失),也可在该分区直接点「重启 ZCode」;不再注入会话内文字提醒(自动安装失败时的故障提示除外)。自动安装失败时执行 `/install-overlay` 按输出排查,成功后仍需完全重启。 +自动安装始终开启(旧配置 `plugin_auto_install_overlay` 与环境变量 `ZUSAGE_PLUGIN_AUTO_INSTALL` 已不再读取);`/uninstall-overlay` 会留下卸载豁免标记,是阻止自动重注入的唯一出口。待重启/有新版本时状态条 ⚙ 齿轮显示红点(点进 ⚙ 面板「插件更新」分区后消失),也可在该分区直接点「重启 ZCode」;不再注入会话内文字提醒(自动安装失败时的故障提示除外)。自动安装失败时执行 `/install-overlay` 按输出排查,成功后仍需完全重启。状态条、工具栏 chip 或回答末尾的速率行不显示时,新开一个会话运行 `/zusage-doctor`:它只读、不改任何文件,逐项报告哪里不对并给出对应的修法。 + +GitHub 访问受限时,改用 `https://gitcode.com/tanranran/zcode-token-usage-statusbar.git#plugin-releases-gitcode` 添加市场(同一份经过校验的正式 Release;需本机装有 Git,地址里的 `.git` 不能省)。 ## 手机远控页面(当前源码功能)