From 0429be2b2dc69cd32d0c9d0470f3d3805c1d2238 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A0=81=E5=86=9C=E9=98=BF=E6=A5=A0?= Date: Tue, 3 Nov 2026 22:12:44 +0800 Subject: [PATCH] =?UTF-8?q?chore(project):=20=E7=BB=9F=E4=B8=80=E5=9B=9E?= =?UTF-8?q?=E5=BD=92=E5=85=A5=E5=8F=A3=E5=B9=B6=E6=B8=85=E7=90=86=E5=AE=A1?= =?UTF-8?q?=E8=AF=84=E9=81=97=E7=95=99=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/review-fixes-plan.md | 24 ++- docs/testing.md | 18 +- kymo/App/kymoApp.swift | 2 +- .../Monitors/SystemBatteryHealthMonitor.swift | 2 +- kymo/Features/MenuBar/CPUCoreGrid.swift | 2 +- kymo/UI/Components/AppearanceStyle.swift | 3 +- kymoTests/SettingsWindowChecks.swift | 18 +- tools/check.py | 177 ++++++++++++++++++ 8 files changed, 233 insertions(+), 13 deletions(-) create mode 100644 tools/check.py diff --git a/docs/review-fixes-plan.md b/docs/review-fixes-plan.md index 286096a..ad74fa9 100644 --- a/docs/review-fixes-plan.md +++ b/docs/review-fixes-plan.md @@ -26,4 +26,26 @@ - 初始状态:工作区与暂存区干净,基线 cecd646。 - 步骤 1–2 完成:Debug 构建成功,签名包包含 sandbox / network.client;以实际 host entitlement 签名的隔离探针访问公网端点返回 HTTP 200。CPU / 内存各 1,000 轮真实采样后,host 发送权引用保持为 1。 -- 步骤 3 已实施:原始快照退出判定的过滤 / 读取失败 / 真实退出 / PID 复用检查通过,待集成构建。 +- 步骤 3–5 完成:退出提示以原始成功快照为准;公网服务使用单调时钟,成功 600 秒 / 失败 30 秒,面板任务持续刷新且取消后不缓存、不发布;编号风扇保留为当前语言环境解析的带参数 Text。对应回归及 Debug / Release 构建通过。 +- 步骤 6 完成:新增 tools/check.py,覆盖全部 25 个 Swift 检查,GUI / 真实网络显式 opt-in;更新主题文档、测试覆盖声明及外观 / 采样注释,消除 Swift 6 捕获及 Text 拼接源码警告。 + +## 最终验证(2026-11-03) + +| 命令 / 检查 | 结果与边界 | +| --- | --- | +| `python3 tools/check.py --gui --network` | Debug 全新构建成功;25 组 Swift 独立检查全部通过,含真实 NSPanel、设置窗口、已挂载宿主三语切换及签名沙盒 HTTPS 请求 | +| `python3 tools/check.py --configuration Release --network --only LocalizationChecks CodeIdentityChecks PanelAssetChecks SandboxNetworkChecks` | Release 全新构建成功;实际三语资源、主程序 / XPC 签名身份、颜色资产、网络权限及真实 HTTPS 请求通过 | +| 字符串目录 | 198 条资源三语完整性及格式参数一致性通过 | +| MachPortChecks | CPU / 内存各 1,000 次采样后 host 发送权引用保持 1 | +| PublicIPAddressChecks | 成功有效期 599/600 秒、失败重试 29/30 秒、路由切换、非法数据、HTTP 失败、模拟传输超时后恢复、可见期持续刷新、取消等待 / 在途请求后不发布均通过;不声称实际等待网络超时五秒 | +| 编译警告 | 已消除审评指出的源码警告;仍有 Xcode 的 AppIntents 元数据提取跳过提示(未依赖 AppIntents.framework) | +| 工作区 | `git diff --check` 通过;未修改用户已有运行实例,测试副本已退出,临时构建 / 探针 / 缓存清理 | + +首次 GUI 检查中,固定 350ms 的设置窗口焦点等待出现断言失败。检查改为等待实际可见 / key / 非最小化条件(上限 3 秒),统一脚本也按检查类型生成常规或 accessory 测试包;之后顺序运行整套检查通过。 + +## 尚未自动验收的交互 + +- 原生自动化按路径和 bundle ID 绑定隔离菜单栏副本均超时;这不是权限缺失的证据。因没有取得可操作的应用绑定,真实菜单栏 AX 点击、坐标点击、搜索输入、Esc 关闭及局部截图均未验证,不将原生窗口方法检查当作事件投递验证。 +- 三语编号风扇已检查实际编译资源,已挂载宿主的即时 locale 更新另有原生检查;未读取到实际风扇标签的渲染文本。 +- 人工补验:打开面板,选中存活进程后输入不匹配的搜索词,确认不提示“已退出”;清空搜索并按 Esc 验证关闭层次。单风扇或三风扇以上布局切换三语,确认编号文案同步更新。 +- 多显示器 / 刘海屏及长期资源占用仍需相应真实环境;本轮短时采样不证明长期能耗达标。 diff --git a/docs/testing.md b/docs/testing.md index f9e2d86..146de55 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -6,6 +6,22 @@ 本页保留当前检查入口和验收边界,不沿用旧阶段报告中的“通过”结论。源码存在、命令可编译、独立程序通过、正式应用实测是不同层次的证据,每轮应记录实际执行项。 +## 统一入口 + +```bash +python3 tools/check.py +python3 tools/check.py --configuration Release +# 额外启动真实原生窗口检查,并发起一次公网 HTTPS 请求 +python3 tools/check.py --gui --network +# 使用已有构建包,只跑指定回归(仍检查资源目录和签名权限) +python3 tools/check.py --app /absolute/path/to/kymo.app --only MachPortChecks ProcessSelectionChecks PublicIPAddressChecks +python3 tools/check.py --list +``` + +默认构建 Debug,运行全部非 GUI / 非真实网络检查,显式列出跳过项;任一编译、运行或断言失败时返回非零退出码。脚本核对新增 Swift 检查是否已登记,并在退出时清理自己的临时构建、测试包、缓存和日志。`--app` 指定的用户已有构建产物不清理。GUI 检查以独立标识的完整签名应用逐个启动(面板检查为 accessory,设置检查为常规应用),使用自身窗口,不操作用户已有应用;不等于实际菜单栏鼠标 / 键盘事件已投递。`--network` 将实际主应用的 entitlement 应用到隔离探针,访问与产品相同的 HTTPS 端点,不输出公网地址;服务不可达也会使该检查失败。 + +新增回归:`MachPortChecks` 对 CPU / 内存各采样 1,000 轮,直接核对 host 发送权引用数无增长;`ProcessSelectionChecks` 验证搜索过滤、失败枚举、真实退出及 PID 复用。`LocalizationChecks` 另检查编译后的三语编号风扇格式,`LanguageScopeChecks` 检查已挂载宿主即时切换语言。前者不等于读取了实际风扇标签的渲染文本。 + ## 构建与人工验收 ```bash @@ -236,7 +252,7 @@ swiftc -parse-as-library kymo/Core/Models/*.swift kymo/Core/Monitors/*.swift kym ## 公网地址 -服务检查使用隔离 URLProtocol,不发送真实请求: +服务检查使用隔离 URLProtocol,不发送真实请求。可控单调时钟检查 600 秒成功缓存 / 30 秒失败重试边界;模拟 `URLError.timedOut` 检查错误恢复,短周期运行面板实际调用的持续刷新逻辑并核对取消请求 / 等待后不再发布。这不等于真实传输等待 5 秒超时: ```bash swiftc -parse-as-library kymo/Core/Services/PublicIPAddressService.swift kymoTests/PublicIPAddressChecks.swift -o /private/tmp/kymo-ip-checks diff --git a/kymo/App/kymoApp.swift b/kymo/App/kymoApp.swift index cfee0dd..44ceaa9 100644 --- a/kymo/App/kymoApp.swift +++ b/kymo/App/kymoApp.swift @@ -39,7 +39,7 @@ import AppKit AppLocalization.string("status." + key, locale: language.locale, table: "StatusItem") }, openSettings: { [weak self] in self?.settingsCommand() }) { [self] panel in AppLanguageScope(preferences: language) { - MenuPanelView(metrics: metrics, preferences: appearance, keepAwake: awake, settingsPresentation: presentation, + MenuPanelView(metrics: self.metrics, preferences: self.appearance, keepAwake: self.awake, settingsPresentation: self.presentation, presentation: panel, onOpenSettings: { [weak self] in self?.menuBar?.hide() settings.environment.openSettings() diff --git a/kymo/Core/Monitors/SystemBatteryHealthMonitor.swift b/kymo/Core/Monitors/SystemBatteryHealthMonitor.swift index d5330c7..9772b44 100644 --- a/kymo/Core/Monitors/SystemBatteryHealthMonitor.swift +++ b/kymo/Core/Monitors/SystemBatteryHealthMonitor.swift @@ -1,7 +1,7 @@ import Foundation /// Uses the System Information report's own maximum-capacity field. -/// Slow-changing data is cached independently of the two-second resource samples. +/// Slow-changing data has its own cache, independent of the configurable resource interval. actor SystemBatteryHealthMonitor { private var cached: Double? private var nextRead: TimeInterval = 0 diff --git a/kymo/Features/MenuBar/CPUCoreGrid.swift b/kymo/Features/MenuBar/CPUCoreGrid.swift index 18aa316..9114364 100644 --- a/kymo/Features/MenuBar/CPUCoreGrid.swift +++ b/kymo/Features/MenuBar/CPUCoreGrid.swift @@ -100,7 +100,7 @@ struct CPUCoreGrid: View { .frame(width: diameter, height: diameter) .frame(width: proxy.size.width, height: proxy.size.height) } - .help((kind.map { label($0) + Text(verbatim: " · ") } ?? Text("cpu.core")) + Text(verbatim: "\(index + 1): \(MetricFormat.percent(value))")) + .help(Text("\(kind.map { label($0) } ?? Text("cpu.core")) · \(index + 1): \(MetricFormat.percent(value))")) .accessibilityLabel(kind.map { label($0) } ?? Text("cpu.core")) .accessibilityValue("\(index + 1): \(MetricFormat.percent(value))") } diff --git a/kymo/UI/Components/AppearanceStyle.swift b/kymo/UI/Components/AppearanceStyle.swift index c79c3a6..bf37392 100644 --- a/kymo/UI/Components/AppearanceStyle.swift +++ b/kymo/UI/Components/AppearanceStyle.swift @@ -34,7 +34,8 @@ struct AppearanceStyle: ViewModifier { } } -/// Explicitly clear the NSWindow override when returning to system appearance. +/// Apply the resolved light/dark choice to native hosts and child windows. +/// AppearanceStyle observes the system independently and reapplies its resolved choice. private struct WindowAppearanceBridge: NSViewRepresentable { let choice: AppAppearance func makeNSView(context: Context) -> AppearanceView { AppearanceView() } diff --git a/kymoTests/SettingsWindowChecks.swift b/kymoTests/SettingsWindowChecks.swift index 97e9008..0d278b5 100644 --- a/kymoTests/SettingsWindowChecks.swift +++ b/kymoTests/SettingsWindowChecks.swift @@ -25,26 +25,26 @@ import SwiftUI view.onClose = { closed = true } view.title = "Settings checks" window.contentView = view - await settle() - precondition(window.isVisible && window.isKeyWindow) + await settle { window.isVisible && window.isKeyWindow && !window.isMiniaturized } + precondition(window.isVisible && window.isKeyWindow, "visible=\(window.isVisible) key=\(window.isKeyWindow) active=\(NSApp.isActive) policy=\(NSApp.activationPolicy().rawValue)") precondition(window.level == .normal) let other = NSWindow(contentRect: window.frame, styleMask: [.titled], backing: .buffered, defer: false) other.isReleasedWhenClosed = false other.makeKeyAndOrderFront(nil) precondition(other.isKeyWindow) view.requestID = request.requestID - await settle() + await settle { window.isVisible && window.isKeyWindow && !window.isMiniaturized } precondition(window.isKeyWindow) window.orderOut(nil) precondition(!window.isVisible) request.request() view.requestID = request.requestID - await settle() + await settle { window.isVisible && window.isKeyWindow && !window.isMiniaturized } precondition(window.isVisible && window.isKeyWindow) window.miniaturize(nil) request.request() view.requestID = request.requestID - await settle() + await settle { window.isVisible && window.isKeyWindow && !window.isMiniaturized } precondition(!window.isMiniaturized && window.isKeyWindow) window.close() precondition(closed) @@ -53,7 +53,11 @@ import SwiftUI print("PASS: request sequence, first presentation, key-window recovery, hidden reopen, miniaturized recovery, normal level and close lifecycle") } - @MainActor private static func settle() async { - try? await Task.sleep(for: .milliseconds(350)) + @MainActor private static func settle(_ ready: () -> Bool) async { + // Native activation is asynchronous; a fixed 350ms sleep is not a readiness condition. + let deadline = ContinuousClock.now.advanced(by: .seconds(3)) + while !ready(), ContinuousClock.now < deadline { + try? await Task.sleep(for: .milliseconds(20)) + } } } diff --git a/tools/check.py b/tools/check.py new file mode 100644 index 0000000..2384473 --- /dev/null +++ b/tools/check.py @@ -0,0 +1,177 @@ +#!/usr/bin/env python3 +"""Build and run the repository's independent checks; GUI/network checks are opt-in.""" +import argparse +import os +import signal +from pathlib import Path +import plistlib +import shutil +import subprocess +import sys +import tempfile +import uuid + +ROOT = Path(__file__).resolve().parents[1] +CORE = sorted(str(p.relative_to(ROOT)) for folder in ("Models", "Monitors", "Services", "Extensions") + for p in (ROOT / "kymo/Core" / folder).glob("*.swift")) +CHECKS = {name: list(CORE) for name in ( + "SamplingChecks", "SamplingIntervalChecks", "UnifiedPanelChecks", "MemoryChecks", + "GPUStatisticsChecks", "StageCChecks", "MachPortChecks")} +CHECKS.update({ + "TrendScrollChecks": CORE + ["kymo/UI/Charts/TrendScroll.swift"], + "CPUCoreGridChecks": ["kymo/Features/MenuBar/CPUCoreGrid.swift", "kymo/Core/Services/CPUCoreTopology.swift", + "kymo/Core/Extensions/MetricFormat.swift", "kymo/UI/Components/MetricProgressBar.swift"], + "CPUTemperatureChecks": ["kymo/Core/Monitors/CPUTemperatureMonitor.swift"], + "DiskHealthChecks": ["kymo/Core/Models/DiskHealthMetrics.swift", "kymo/Core/Monitors/DiskHealthReport.swift"], + "PublicIPAddressChecks": ["kymo/Core/Services/PublicIPAddressService.swift"], + "ProcessSelectionChecks": ["kymo/Core/Models/ProcessMetrics.swift", "kymo/Features/MenuBar/ProcessTableProjection.swift"], + "PanelLayoutChecks": ["kymo/Core/Models/ProcessMetrics.swift", "kymo/Features/MenuBar/PanelLayout.swift", + "kymo/Features/MenuBar/ProcessTableProjection.swift"], + "PanelCurveChecks": ["kymo/UI/Charts/PanelCurveGeometry.swift", "kymo/UI/Charts/PanelCurveFrame.swift"], + "FanChecks": ["kymo/Core/Models/FanMetrics.swift", "kymo/Core/Monitors/CPUTemperatureMonitor.swift", + "kymo/UI/Components/FanSpeedIndicator.swift", "kymo/UI/Components/AnimatedMetricText.swift"], + "KeepAwakeChecks": ["kymo/Core/Services/KeepAwakeService.swift"], + "LocalizationChecks": ["kymo/Core/Services/LanguagePreferences.swift", "kymo/UI/Components/AppLocalization.swift"], + "CodeIdentityChecks": ["kymo/Core/Services/CodeIdentity.swift"], + "PanelAssetChecks": [], + "PresentationChecks": ["kymo/Core/Services/AppearancePreferences.swift", "kymo/Core/Services/LanguagePreferences.swift", + "kymo/UI/Components/AppearanceStyle.swift", "kymo/UI/Components/DetailPlacement.swift", + "kymo/UI/Components/AppLocalization.swift"], + "LanguageScopeChecks": ["kymo/Core/Services/LanguagePreferences.swift", "kymo/UI/Components/AppLanguageScope.swift"], + "SettingsWindowChecks": ["kymo/Core/Services/SettingsPresentation.swift", "kymo/Features/Settings/SettingsWindowLifecycle.swift"], + "PanelWindowChecks": ["kymo/Features/MenuBar/MenuPanelController.swift", "kymo/Features/MenuBar/PanelLayout.swift", + "kymo/UI/Components/IntervalControl.swift"], + "SandboxNetworkChecks": [], +}) +GUI = {"LanguageScopeChecks", "SettingsWindowChecks", "PanelWindowChecks"} +NETWORK = {"SandboxNetworkChecks"} + + +def run(command, *, timeout=120): + result = subprocess.run([str(v) for v in command], cwd=ROOT, capture_output=True, text=True, timeout=timeout) + if result.stdout.strip(): + print(result.stdout.strip(), flush=True) + if result.returncode: + raise RuntimeError(f"{' '.join(map(str, command))}\n{result.stderr[-8000:]}") + if result.stderr.strip(): + print(result.stderr.strip(), flush=True) + return result + + +def entitlements(app): + result = subprocess.run(["codesign", "-d", "--entitlements", ":-", str(app)], capture_output=True, check=True) + value = plistlib.loads(result.stdout) + for key in ("com.apple.security.app-sandbox", "com.apple.security.network.client"): + if value.get(key) is not True: + raise RuntimeError(f"Missing built entitlement: {key}") + print("PASS: built host has sandbox and network client entitlements", flush=True) + return value + + +def test_bundle(work, name, executable, host_entitlements=None): + app = work / (name + ".app") + contents = app / "Contents" + (contents / "MacOS").mkdir(parents=True) + shutil.copy2(executable, contents / "MacOS" / name) + (contents / "Info.plist").write_bytes(plistlib.dumps({ + "CFBundleIdentifier": "cn.airnan.kymo.checks." + uuid.uuid4().hex, + "CFBundleExecutable": name, "CFBundlePackageType": "APPL", + "LSUIElement": name in {"PanelWindowChecks", "SandboxNetworkChecks"}, + })) + command = ["codesign", "--force", "--sign", "-"] + if host_entitlements: + path = work / "network.entitlements" + path.write_bytes(plistlib.dumps(host_entitlements)) + command += ["--entitlements", path] + run(command + [app]) + return app + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--app", type=Path, help="Use an already built app instead of building") + parser.add_argument("--configuration", choices=["Debug", "Release"], default="Debug") + parser.add_argument("--gui", action="store_true", help="Also launch temporary native test apps") + parser.add_argument("--network", action="store_true", help="Also make a real sandboxed HTTPS request") + parser.add_argument("--only", nargs="+", choices=sorted(CHECKS), help="Run selected Swift checks") + parser.add_argument("--list", action="store_true") + args = parser.parse_args() + unknown = {p.stem for p in (ROOT / "kymoTests").glob("*.swift")} - CHECKS.keys() + if unknown: + parser.error("Checks missing from runner: " + ", ".join(sorted(unknown))) + if args.list: + for name in sorted(CHECKS): + print(name + (" [GUI]" if name in GUI else " [network]" if name in NETWORK else "")) + return + requested = args.only or list(CHECKS) + selected = [] + for name in requested: + disabled = (name in GUI and not args.gui) or (name in NETWORK and not args.network) + if disabled and args.only: + parser.error(f"{name} requires {'--gui' if name in GUI else '--network'}") + if disabled: + print(f"SKIP: {name} (opt-in {'--gui' if name in GUI else '--network'})", flush=True) + else: + selected.append(name) + with tempfile.TemporaryDirectory(prefix="kymo-checks-") as temp: + work = Path(temp) + if args.app: + app = args.app.expanduser().resolve() + if not (app / "Contents/MacOS/kymo").is_file(): + parser.error("--app must point to a built kymo.app") + else: + result = subprocess.run(["xcodebuild", "-project", "kymo.xcodeproj", "-scheme", "kymo", + "-configuration", args.configuration, "-derivedDataPath", str(work / "build"), "build"], + cwd=ROOT, capture_output=True, text=True, timeout=180) + if result.returncode: + raise RuntimeError(result.stdout[-10000:] + result.stderr[-3000:]) + for line in result.stdout.splitlines(): + if "warning:" in line or "BUILD SUCCEEDED" in line: + print(line, flush=True) + app = work / "build/Build/Products" / args.configuration / "kymo.app" + host_entitlements = entitlements(app) + run([sys.executable, "kymoTests/LocalizationCatalogChecks.py"]) + for index, name in enumerate(selected, 1): + print(f"[{index}/{len(selected)}] {name}", flush=True) + executable = work / name + run(["swiftc", "-parse-as-library", "-module-cache-path", work / "cache", *CHECKS[name], + f"kymoTests/{name}.swift", "-o", executable]) + if name in GUI: + bundle = test_bundle(work, name, executable) + # Open the complete app for native activation semantics, while collecting its output. + output = work / (name + ".out") + error = work / (name + ".err") + try: + run(["open", "-n", "-W", "--stdout", output, "--stderr", error, bundle], timeout=30) + finally: + # A timed-out open waiter may leave its child app running. Only stop this exact test binary. + processes = subprocess.run(["ps", "-axo", "pid=,comm="], capture_output=True, text=True, check=True) + target = (bundle / "Contents/MacOS" / name).resolve() + for line in processes.stdout.splitlines(): + fields = line.strip().split(None, 1) + if len(fields) == 2 and Path(fields[1]).resolve() == target: + try: + os.kill(int(fields[0]), signal.SIGTERM) + except ProcessLookupError: + pass + text = output.read_text() if output.exists() else "" + print(text.strip(), flush=True) + if "PASS:" not in text: + raise RuntimeError(f"{name} did not report success\n" + (error.read_text() if error.exists() else "")) + elif name in NETWORK: + bundle = test_bundle(work, name, executable, host_entitlements) + run([bundle / "Contents/MacOS" / name], timeout=15) + else: + extra = [app] if name in {"LocalizationChecks", "PanelAssetChecks"} else [] + if name == "CodeIdentityChecks": + extra = [app, app / "Contents/XPCServices/SMARTService.xpc"] + run([executable, *extra], timeout=45) + print(f"PASS: {len(selected)} Swift checks + catalog + host entitlements; temporary files cleaned on exit", flush=True) + + +if __name__ == "__main__": + try: + main() + except (RuntimeError, subprocess.SubprocessError, OSError) as error: + print(f"FAIL: {error}", file=sys.stderr) + sys.exit(1)