From f1ba762424ff9ab8d96948270826d79129cb5425 Mon Sep 17 00:00:00 2001 From: "Moshui Codex Desktop mba[bot]" <312784525+moshui-codex-desktop-mba[bot]@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:26:57 +0000 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E7=8B=AC=E7=AB=8B=E4=B8=8A?= =?UTF-8?q?=E6=8A=A5=E7=9A=84=20Mac=20=E5=8D=87=E7=BA=A7=E5=90=8E=E8=AF=AF?= =?UTF-8?q?=E5=9B=9E=E9=80=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../StatusBarController.swift | 5 +- docs/device-registration-and-upgrades.md | 4 +- src/ai_usage_widget/upgrade_apply.py | 59 ++++++++++++++----- tests/test_upgrade.py | 43 ++++++++++++++ 4 files changed, 95 insertions(+), 16 deletions(-) diff --git a/clients/macos/Sources/AIUsageMenuBarApp/StatusBarController.swift b/clients/macos/Sources/AIUsageMenuBarApp/StatusBarController.swift index 280bc84..d437dcc 100644 --- a/clients/macos/Sources/AIUsageMenuBarApp/StatusBarController.swift +++ b/clients/macos/Sources/AIUsageMenuBarApp/StatusBarController.swift @@ -77,7 +77,10 @@ final class StatusBarController: NSObject { setupPopover() bindStatusTitle() startRefreshTimer() - model.refresh() + // The updater needs a summary fetched by the newly launched app, even if its old cache is fresh. + let verifyingToday = ProcessInfo.processInfo.arguments.contains("--verify-upgrade") + && model.selection == MenuPeriodSelection(periodID: "today") + model.refresh(force: verifyingToday) if model.selection != MenuPeriodSelection(periodID: "today") { model.refreshToday() } model.prefetchCommonPeriods() collector.start() diff --git a/docs/device-registration-and-upgrades.md b/docs/device-registration-and-upgrades.md index d57085d..4d4b833 100644 --- a/docs/device-registration-and-upgrades.md +++ b/docs/device-registration-and-upgrades.md @@ -71,7 +71,9 @@ ai-usage-widget upgrade apply --root "$HOME/.local/share/ai-usage" 客户端依次完成验签、通道与前向版本检查、大小及 SHA-256 校验、安全解包和候选入口启动预检。失败产物不会成为可安装目录。Linux 继续使用已有 release/current/previous 原子切换机制,暂停原定时任务后切换;新版本须能采集并实际上报,健康检查失败回滚,再恢复定时任务。system 级多用户部署需由各 OS 用户与 Ops 协调,不能由 root 代采其他用户数据。 -Mac 使用菜单“检查 App 更新…”;更新器运行于独立复制的 helper,避免替换 App 时破坏更新器自身。候选通过 App 标识、版本、完整构建 SHA、代码签名与内置采集器启动预检后才退出旧 App、等待旧采集器退出并替换。新采集器上报与十分钟内的非空摘要缓存检查失败则恢复旧 App;成功保留一个上版本,下一次升级自动轮换。升级不改用户 token、来源身份、原始日志或 outbox。结果写入私有 `last-upgrade.json`,不得把文件切换成功当成生产回源验收。 +Mac 使用菜单“检查 App 更新…”;更新器运行于独立复制的 helper,避免替换 App 时破坏更新器自身。候选通过 App 标识、版本、完整构建 SHA、代码签名与内置采集器启动预检后才退出旧 App、等待旧采集器退出并替换。启用 App 内采集时,升级要求新版用量及额度上报成功,并有十分钟内的非空摘要。使用独立任务上报或暂停 App 内采集时,升级要求新版菜单栏成功读取一次新的非空今日摘要。健康检查失败则恢复旧 App;成功保留一个上版本,下一次升级自动轮换。升级不改用户 token、来源身份、原始日志或 outbox。结果写入私有 `last-upgrade.json`,不得把文件切换成功当成生产回源验收。 + +使用独立任务上报的 3.0.0 和 3.0.1 用户,首次切换到 3.0.2 时需要通过发布包安装。旧版菜单调用的是旧更新器,仍会等待 App 内采集上报。从含修复的版本再次使用菜单内更新时,会按当前采集方式验收。 手动触发检查与升级,不引入客户端短轮询。Linux 依赖环境须通过 `pip install .` 安装项目声明依赖;Mac 内置相同验签依赖,无需用户配置 Python。 diff --git a/src/ai_usage_widget/upgrade_apply.py b/src/ai_usage_widget/upgrade_apply.py index 3c8bc9f..4f20d11 100644 --- a/src/ai_usage_widget/upgrade_apply.py +++ b/src/ai_usage_widget/upgrade_apply.py @@ -132,7 +132,7 @@ def pids(): def launch_mac_app(app): - return subprocess.run(['open',str(app)],capture_output=True,timeout=15).returncode==0 + return subprocess.run(['open', str(app), '--args', '--verify-upgrade'], capture_output=True, timeout=15).returncode == 0 def wait_mac_collector(root): @@ -151,20 +151,51 @@ def wait_mac_collector(root): time.sleep(0.5) -def mac_health(root, manifest, started): - root=Path(root);deadline=time.monotonic()+480 - status_path=root/'collector/status.json';cache=root/'summaries/today-offset0.json' - while time.monotonic()started: - status=json.loads(status_path.read_text()) - if status.get('collector_version')==manifest['collector_version']: - jobs=[status.get(name,{}) for name in ('usage','limits')] - if any(job.get('success') is False for job in jobs):return False - if all(job.get('success') is True for job in jobs) and 0 <= time.time() - cache.stat().st_mtime <= 600: - summary=json.loads(cache.read_text()) - if isinstance(summary.get('sources'), list) and summary['sources']:return True - except (OSError,ValueError):pass + if not newer_than < cache.stat().st_mtime <= time.time(): + continue + summary = json.loads(cache.read_text()) + if isinstance(summary, dict) and isinstance(summary.get('sources'), list) and summary['sources']: + return True + except (OSError, ValueError): + continue + return False + + +def mac_health(root, manifest, started): + root = Path(root) + collector = root / 'collector' + try: + settings = json.loads((collector / 'settings.json').read_text()) + except FileNotFoundError: + settings = {} + except (OSError, ValueError): + return False + if not isinstance(settings, dict): + return False + collects_in_app = settings.get('enabled') is True + deadline = time.monotonic() + 480 + status_path = collector / 'status.json' + while time.monotonic() < deadline: + if not collects_in_app: + if mac_summary_is_healthy(root / 'summaries', newer_than=started): + return True + else: + try: + status = json.loads(status_path.read_text()) if status_path.stat().st_mtime > started else {} + if status.get('collector_version') == manifest['collector_version']: + jobs = [status.get(name, {}) for name in ('usage', 'limits')] + if any(job.get('success') is False for job in jobs): + return False + if all(job.get('success') is True for job in jobs) and mac_summary_is_healthy( + root / 'summaries', newer_than=time.time() - 600 + ): + return True + except (OSError, ValueError): + pass time.sleep(1) return False diff --git a/tests/test_upgrade.py b/tests/test_upgrade.py index 2a4ad88..273fdd5 100644 --- a/tests/test_upgrade.py +++ b/tests/test_upgrade.py @@ -84,6 +84,8 @@ def test_mac_health_reads_nonempty_mobile_owner_sources(self): with tempfile.TemporaryDirectory() as folder: root = Path(folder) (root / 'summaries').mkdir() + (root / 'collector').mkdir() + (root / 'collector/settings.json').write_text('{"enabled": true}') cache = root / 'summaries/today-offset0.json' shutil.copyfile(fixture, cache) write_status(root, {'usage': {'success': True}, 'limits': {'success': True}}) @@ -102,6 +104,8 @@ def test_mac_health_accepts_recent_owner_cache_without_forcing_another_read(self with tempfile.TemporaryDirectory() as folder: root = Path(folder) (root / 'summaries').mkdir() + (root / 'collector').mkdir() + (root / 'collector/settings.json').write_text('{"enabled": true}') cache = root / 'summaries/today-offset0.json' shutil.copyfile(fixture, cache) started = time.time() @@ -113,6 +117,45 @@ def test_mac_health_accepts_recent_owner_cache_without_forcing_another_read(self with patch('ai_usage_widget.upgrade_apply.time.monotonic', side_effect=[0, 0, 500]), patch('ai_usage_widget.upgrade_apply.time.sleep'): self.assertFalse(mac_health(root, {'collector_version': version_contract.COLLECTOR_VERSION}, started)) + def test_mac_without_app_collection_uses_new_nonempty_summary(self): + import os + import shutil + import time + + from ai_usage_widget.mac_app_collector import write_status + from ai_usage_widget.upgrade_apply import mac_health + + fixture = Path(__file__).parent / 'fixtures/verify_cloud/healthy/mobile_summary.json' + manifest = {'collector_version': version_contract.COLLECTOR_VERSION} + cases = ( + ('no settings and fresh summary', None, 'today-offset0.json', True, True, None, True), + ('paused and fresh local today', False, 'client-today-Africa-Abidjan-offset0.json', True, True, False, True), + ('cached before upgrade', None, 'today-offset0.json', False, True, None, False), + ('empty sources', None, 'today-offset0.json', True, False, None, False), + ('enabled with upload failure', True, 'today-offset0.json', True, True, False, False), + ('enabled with uploads successful', True, 'client-today-Africa-Abidjan-offset0.json', True, True, True, True), + ) + for label, enabled, name, fresh, has_sources, upload_ok, expected in cases: + with self.subTest(label=label), tempfile.TemporaryDirectory() as folder: + root = Path(folder) + (root / 'summaries').mkdir() + if enabled is not None: + (root / 'collector').mkdir() + (root / 'collector/settings.json').write_text(json.dumps({'enabled': enabled})) + cache = root / 'summaries' / name + shutil.copyfile(fixture, cache) + if not has_sources: + summary = json.loads(cache.read_text()) + summary['sources'] = [] + cache.write_text(json.dumps(summary)) + started = time.time() - 1 + if not fresh: + os.utime(cache, (started - 1, started - 1)) + if upload_ok is not None: + write_status(root, {'usage': {'success': True}, 'limits': {'success': upload_ok}}) + with patch('ai_usage_widget.upgrade_apply.time.monotonic', side_effect=[0, 0, 500]), patch('ai_usage_widget.upgrade_apply.time.sleep'): + self.assertIs(mac_health(root, manifest, started), expected) + def test_mac_failed_health_restores_app_and_keeps_runtime_config(self): with tempfile.TemporaryDirectory() as folder: root=Path(folder)/'runtime';root.mkdir()