From 1a1e5a62f1ac9b9bc1fdbb41202627518de3d639 Mon Sep 17 00:00:00 2001 From: agentflow-marathon Date: Tue, 10 Nov 2026 13:33:33 -0800 Subject: [PATCH] Use native browser updates in the 0.7.0 AI panel and retain legacy migration notices --- front_end/core/root/Runtime.ts | 1 + front_end/panels/ai_chat/BUILD.gn | 3 + front_end/panels/ai_chat/core/Version.ts | 4 +- .../panels/ai_chat/core/VersionChecker.ts | 6 +- front_end/panels/ai_chat/ui/ChatView.ts | 20 ++++++ .../ai_chat/ui/version/VersionBanner.ts | 21 +++++++ .../158.0.8127.18/09-native-ai-updates.patch | 56 +++++++++++++++++ scripts/freeze_chromium_release.py | 8 ++- scripts/merge_chromium_macos.py | 2 +- scripts/package_chromium_release.py | 35 ++++++++--- scripts/test_merge_chromium_macos.py | 2 +- scripts/updater/macos_smoke_scope.py | 50 ++++++++++++++- scripts/updater/publish_test_update.py | 2 +- .../test_legacy_version_notification.mjs | 63 +++++++++++++++++++ scripts/updater/test_macos_smoke_scope.py | 25 ++++++++ scripts/verify_chromium_release.mjs | 51 +++++++++++++++ 16 files changed, 330 insertions(+), 19 deletions(-) create mode 100644 patches/chromium/158.0.8127.18/09-native-ai-updates.patch create mode 100644 scripts/updater/test_legacy_version_notification.mjs diff --git a/front_end/core/root/Runtime.ts b/front_end/core/root/Runtime.ts index f3e3656280..8562f73540 100644 --- a/front_end/core/root/Runtime.ts +++ b/front_end/core/root/Runtime.ts @@ -518,6 +518,7 @@ interface DevToolsStartingStyleDebugging { * @see hostConfig */ export type HostConfig = Platform.TypeScriptUtilities.RecursivePartial<{ + browserOperatorUpdates: {enabled: boolean}, aidaAvailability: AidaAvailability, channel: Channel, devToolsConsoleInsights: HostConfigConsoleInsights, diff --git a/front_end/panels/ai_chat/BUILD.gn b/front_end/panels/ai_chat/BUILD.gn index 25944b54e7..cff8fe3d07 100644 --- a/front_end/panels/ai_chat/BUILD.gn +++ b/front_end/panels/ai_chat/BUILD.gn @@ -218,6 +218,9 @@ devtools_module("ai_chat") { deps = [ ":css_files", "../../core/common:bundle", + "../../core/host:bundle", + "../../core/platform:bundle", + "../../core/root:bundle", "../../core/i18n:bundle", "../../core/sdk:bundle", "../../generated:protocol", diff --git a/front_end/panels/ai_chat/core/Version.ts b/front_end/panels/ai_chat/core/Version.ts index 47c47daeb5..adc1f3c6c8 100644 --- a/front_end/panels/ai_chat/core/Version.ts +++ b/front_end/panels/ai_chat/core/Version.ts @@ -3,8 +3,8 @@ // found in the LICENSE file. export const VERSION_INFO = { - version: '0.5.0', - buildDate: '2025-10-05', + version: '0.7.0', + buildDate: '2026-11-10', channel: 'stable' } as const; diff --git a/front_end/panels/ai_chat/core/VersionChecker.ts b/front_end/panels/ai_chat/core/VersionChecker.ts index 6480c32e09..dc5bce93e9 100644 --- a/front_end/panels/ai_chat/core/VersionChecker.ts +++ b/front_end/panels/ai_chat/core/VersionChecker.ts @@ -17,8 +17,8 @@ export interface VersionInfo { export class VersionChecker { private static instance: VersionChecker; - private readonly GITHUB_API_URL = 'https://api.github.com/repos/tysonthomas9/browser-operator-devtools-frontend/releases/latest'; - private readonly RELEASE_URL = 'https://github.com/tysonthomas9/browser-operator-devtools-frontend/releases'; + private readonly GITHUB_API_URL = 'https://api.github.com/repos/BrowserOperator/browser-operator-core/releases/latest'; + private readonly RELEASE_URL = 'https://github.com/BrowserOperator/browser-operator-core/releases'; private readonly CHECK_INTERVAL = 24 * 60 * 60 * 1000; // 24 hours private readonly STORAGE_KEY = 'devtools-version-check'; private currentVersion: string; @@ -183,4 +183,4 @@ export class VersionChecker { logger.error('Failed to clear cache:', error); } } -} \ No newline at end of file +} diff --git a/front_end/panels/ai_chat/ui/ChatView.ts b/front_end/panels/ai_chat/ui/ChatView.ts index a06d980e13..4219c65852 100644 --- a/front_end/panels/ai_chat/ui/ChatView.ts +++ b/front_end/panels/ai_chat/ui/ChatView.ts @@ -5,6 +5,9 @@ import * as ComponentHelpers from '../../../ui/components/helpers/helpers.js'; import * as Lit from '../../../ui/lit/lit.js'; import * as SDK from '../../../core/sdk/sdk.js'; +import * as Host from '../../../core/host/host.js'; +import type * as Platform from '../../../core/platform/platform.js'; +import type * as Root from '../../../core/root/root.js'; import * as BaseOrchestratorAgent from '../core/BaseOrchestratorAgent.js'; import { TIMING_CONSTANTS } from '../core/Constants.js'; import { PromptEditDialog } from './PromptEditDialog.js'; @@ -233,6 +236,7 @@ export class ChatView extends HTMLElement { // Add version info state #versionInfo: VersionInfo | null = null; #isVersionBannerDismissed = false; + #nativeUpdaterEnabled = false; connectedCallback(): void { const sheet = new CSSStyleSheet(); @@ -1251,6 +1255,16 @@ export class ChatView extends HTMLElement { // Method to check for updates async #checkForUpdates(): Promise { try { + const hostConfig = await new Promise(resolve => { + Host.InspectorFrontendHost.InspectorFrontendHostInstance.getHostConfig(resolve); + }); + if (hostConfig.browserOperatorUpdates?.enabled) { + this.#nativeUpdaterEnabled = true; + this.#versionInfo = null; + VersionChecker.getInstance().clearCache(); + void ComponentHelpers.ScheduledRender.scheduleRender(this, this.#boundRender); + return; + } const versionChecker = VersionChecker.getInstance(); // Version is now automatically loaded from Version.ts @@ -1293,6 +1307,12 @@ export class ChatView extends HTMLElement { // Method to render version banner (delegates to component) #renderVersionBanner(): Lit.TemplateResult { + if (this.#nativeUpdaterEnabled) { + return html` Host.InspectorFrontendHost.InspectorFrontendHostInstance.openInNewTab( + 'chrome://help/' as Platform.DevToolsPath.UrlString)} + >`; + } if (!this.#versionInfo || !this.#versionInfo.isUpdateAvailable || this.#isVersionBannerDismissed || this.#messages.length > 1) { return html``; } diff --git a/front_end/panels/ai_chat/ui/version/VersionBanner.ts b/front_end/panels/ai_chat/ui/version/VersionBanner.ts index 52bf18a2d1..94db533440 100644 --- a/front_end/panels/ai_chat/ui/version/VersionBanner.ts +++ b/front_end/panels/ai_chat/ui/version/VersionBanner.ts @@ -3,6 +3,7 @@ // found in the LICENSE file. import * as Lit from '../../../../ui/lit/lit.js'; +import { CURRENT_VERSION } from '../../core/Version.js'; const {html, Decorators} = Lit; const {customElement} = Decorators as any; @@ -17,17 +18,37 @@ export class VersionBanner extends HTMLElement { // Manual properties #info: VersionInfo | null = null; #dismissed = false; + #nativeUpdater = false; get info(): VersionInfo | null { return this.#info; } set info(value: VersionInfo | null) { this.#info = value; this.#render(); } get dismissed(): boolean { return this.#dismissed; } set dismissed(value: boolean) { this.#dismissed = value; this.#render(); } + get nativeUpdater(): boolean { return this.#nativeUpdater; } + set nativeUpdater(value: boolean) { this.#nativeUpdater = value; this.#render(); } connectedCallback(): void { this.#render(); } #dismiss = () => { this.dispatchEvent(new CustomEvent('dismiss', {bubbles: true})); }; #render(): void { + if (this.#nativeUpdater) { + Lit.render(html` + +
Browser Operator ${CURRENT_VERSION} + +
+ `, this.#shadow, {host: this}); + return; + } if (!this.#info || !this.#info.isUpdateAvailable || this.#dismissed) { this.#shadow.innerHTML = ''; return; } const info = this.#info; Lit.render(html` diff --git a/patches/chromium/158.0.8127.18/09-native-ai-updates.patch b/patches/chromium/158.0.8127.18/09-native-ai-updates.patch new file mode 100644 index 0000000000..8f31ce3c5a --- /dev/null +++ b/patches/chromium/158.0.8127.18/09-native-ai-updates.patch @@ -0,0 +1,56 @@ +diff --git a/chrome/browser/devtools/devtools_ui_bindings.cc b/chrome/browser/devtools/devtools_ui_bindings.cc +index 7ab3e80be5..47a835dff5 100644 +--- a/chrome/browser/devtools/devtools_ui_bindings.cc ++++ b/chrome/browser/devtools/devtools_ui_bindings.cc +@@ -40,6 +40,7 @@ + #include "build/build_config.h" + #include "chrome/browser/about_flags.h" + #include "chrome/browser/browser_process.h" ++#include "chrome/browser/buildflags.h" + #include "chrome/browser/devtools/aida_service_handler.h" + #include "chrome/browser/devtools/devtools_file_watcher.h" + #include "chrome/browser/devtools/devtools_http_service_registry.h" +@@ -1429,6 +1430,21 @@ void DevToolsUIBindings::LoadNetworkResource(DispatchCallback callback, + + void DevToolsUIBindings::OpenInNewTab(const std::string& url) { + GURL gurl(url); ++#if BUILDFLAG(IS_MAC) && BUILDFLAG(ENABLE_UPDATER) ++ // The shipped Browser Operator panel may open only the fixed native update ++ // page. Remote/custom frontends and all other chrome:// URLs retain the ++ // standard request policy below. ++ if (is_local_frontend_ && web_contents_ && ++ gurl == GURL(chrome::kChromeUIHelpURL)) { ++ const GURL& frontend = web_contents_->GetLastCommittedURL(); ++ if (frontend.SchemeIs(content::kChromeDevToolsScheme) && ++ frontend.host() == "devtools" && ++ base::StartsWith(frontend.path(), "/bundled/")) { ++ delegate_->OpenInNewTab(gurl.spec()); ++ return; ++ } ++ } ++#endif + // Hardening: Verify that the frontend renderer is allowed to request this URL. + content::ChildProcessSecurityPolicy* policy = + content::ChildProcessSecurityPolicy::GetInstance(); +@@ -2359,7 +2375,20 @@ base::DictValue DevToolsUIBindings::GetHostConfigDictionary(Profile* profile) { + } + + void DevToolsUIBindings::GetHostConfig(DispatchCallback callback) { +- base::Value response(GetHostConfigDictionary(profile_)); ++ base::DictValue config = GetHostConfigDictionary(profile_); ++#if BUILDFLAG(IS_MAC) && BUILDFLAG(ENABLE_UPDATER) ++ if (is_local_frontend_ && web_contents_) { ++ const GURL& frontend = web_contents_->GetLastCommittedURL(); ++ if (frontend.SchemeIs(content::kChromeDevToolsScheme) && ++ frontend.host() == "devtools" && ++ base::StartsWith(frontend.path(), "/bundled/")) { ++ base::DictValue browser_operator_updates; ++ browser_operator_updates.Set("enabled", true); ++ config.Set("browserOperatorUpdates", std::move(browser_operator_updates)); ++ } ++ } ++#endif ++ base::Value response(std::move(config)); + std::move(callback).Run(&response); + } + diff --git a/scripts/freeze_chromium_release.py b/scripts/freeze_chromium_release.py index 1548a7f3a5..d3fd5c4fd5 100644 --- a/scripts/freeze_chromium_release.py +++ b/scripts/freeze_chromium_release.py @@ -7,6 +7,7 @@ import json from pathlib import Path import plistlib +import re import subprocess from chromium_build_input import inventory, load, release_targets, require_current_build, source_state, updater_trust @@ -44,14 +45,19 @@ def freeze(source, build, destination): subprocess.run(['cp', '-cR', str(build / name), str(destination / name)], check=True) subprocess.run(['cp', '-c', str(build / crypto), str(destination / 'crx3_build_action')], check=True) info = plistlib.loads((destination / 'Browser Operator.app/Contents/Info.plist').read_bytes()) + frontend_root = (source / 'third_party/devtools-frontend/src').resolve() + product_version = re.search(r"version: ['\"]([0-9]+\.[0-9]+\.[0-9]+)['\"]", (frontend_root / 'front_end/panels/ai_chat/core/Version.ts').read_text()) + if not product_version: + raise RuntimeError('Expected an explicit Browser Operator product version') patch = subprocess.check_output(['git', 'diff', '--binary', 'HEAD'], cwd=source) metadata = { 'schema': 1, 'version': info['CFBundleShortVersionString'], + 'browser_operator_version': product_version.group(1), 'source_base_revision': subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=source, text=True).strip(), 'source_has_local_changes': bool(patch), 'source_patch_sha256': hashlib.sha256(patch).hexdigest(), 'build_settings': settings, 'updater_product': product, 'mach_o_architectures': binaries, 'native_source_state': source_state(source), - 'frontend_source_state': source_state((source / 'third_party/devtools-frontend/src').resolve()), + 'frontend_source_state': source_state(frontend_root), 'updater_trust': updater_trust(source, settings), 'input_files': inventory(destination), } diff --git a/scripts/merge_chromium_macos.py b/scripts/merge_chromium_macos.py index b3f89999e3..9b9210dc03 100644 --- a/scripts/merge_chromium_macos.py +++ b/scripts/merge_chromium_macos.py @@ -16,7 +16,7 @@ def merge(source, arm, intel, output): if output.exists(): raise RuntimeError('Universal output must not exist') a, b = load(arm), load(intel) - for key in ('version', 'source_base_revision', 'source_patch_sha256', 'updater_product', + for key in ('version', 'browser_operator_version', 'source_base_revision', 'source_patch_sha256', 'updater_product', 'native_source_state', 'frontend_source_state', 'updater_trust'): if a.get(key) != b.get(key) or not a.get(key): raise RuntimeError(f'Architecture inputs differ in {key}') diff --git a/scripts/package_chromium_release.py b/scripts/package_chromium_release.py index 67de62580a..6e6b749845 100644 --- a/scripts/package_chromium_release.py +++ b/scripts/package_chromium_release.py @@ -133,7 +133,7 @@ def validate_mounted_app(app, team, evidence): return details -def smoke_test(app, artifacts, node, updater_enabled=False, cpu=None): +def smoke_test(app, artifacts, node, updater_enabled=False, cpu=None, frontend_checks=True, product_version=None): with socket.socket() as server: server.bind(('127.0.0.1', 0)) port = server.getsockname()[1] @@ -164,8 +164,10 @@ def smoke_test(app, artifacts, node, updater_enabled=False, cpu=None): raise RuntimeError('Release test app did not expose its local test endpoint') time.sleep(0.25) version = plistlib.loads((app / 'Contents/Info.plist').read_bytes())['CFBundleShortVersionString'] - run([node, scripts / 'verify_chromium_release.mjs', endpoint, version, artifacts]) - if cpu: + if frontend_checks: + run([node, scripts / 'verify_chromium_release.mjs', endpoint, version, artifacts, + *([product_version] if product_version else [])]) + if cpu and frontend_checks: from chromium_macos_arch import process_architecture report = json.loads((artifacts / 'report.json').read_text()) owned = [entry for entry in report['processInfo'] if entry['type'] in ('browser', 'renderer')] @@ -190,7 +192,7 @@ def smoke_test(app, artifacts, node, updater_enabled=False, cpu=None): process.wait() -def verify_release(source, output, app_name, version, team, settings, node, provenance=None): +def verify_release(source, output, app_name, version, team, settings, node, provenance=None, baseline_app=None): verification = output / 'verification' verification.mkdir(exist_ok=True) tests = Path(tempfile.mkdtemp(prefix='attempt-', dir=verification)) @@ -228,7 +230,12 @@ def verify_release(source, output, app_name, version, team, settings, node, prov validate_mounted_app(updater_apps[0], team, tests / 'gatekeeper-updater.txt') tested_architectures = ['arm64', 'x86_64'] if architecture == 'universal' else ['arm64'] from updater.macos_smoke_scope import UpdaterSmokeScope - scope = UpdaterSmokeScope(settings, team, tests) if updater_enabled else contextlib.nullcontext() + def restore_baseline(): + restore = tests / 'restore-installed-baseline' + restore.mkdir() + smoke_test(baseline_app, restore, node, updater_enabled=True, frontend_checks=False) + scope = UpdaterSmokeScope(settings, team, tests, baseline_app=baseline_app, + restore_baseline=restore_baseline) if updater_enabled else contextlib.nullcontext() # Native Chromium correctly refuses registration on a read-only DMG. # Exercise the actual installation path using this exact verified app, # leaving the user's /Applications and browser profile untouched. @@ -241,7 +248,8 @@ def verify_release(source, output, app_name, version, team, settings, node, prov for cpu in tested_architectures: cpu_tests = tests / cpu cpu_tests.mkdir(exist_ok=True) - smoke_test(installed_app, cpu_tests, node, updater_enabled=updater_enabled, cpu=cpu) + smoke_test(installed_app, cpu_tests, node, updater_enabled=updater_enabled, cpu=cpu, + product_version=provenance.get('browser_operator_version') if provenance else None) # This is an owned disposable installation, not the mounted app or a # user's browser. Keep failed attempts for diagnosis; retire successes. shutil.rmtree(installed) @@ -263,6 +271,8 @@ def verify_release(source, output, app_name, version, team, settings, node, prov 'mounted_app_validation': 'passed', 'installed_dmg_copy_functional_tests': 'passed'} manifest['mach_o_architectures'] = binaries + if provenance.get('browser_operator_version'): + manifest['browser_operator_version'] = provenance['browser_operator_version'] manifest['verification_evidence'] = str(tests.relative_to(output)) manifest['functional_test_architectures'] = {cpu: 'passed' for cpu in tested_architectures} if architecture == 'universal': @@ -304,6 +314,8 @@ def main(): help='Explicitly package a historical/manual-update build') parser.add_argument('--frozen-input', type=Path, help='Use hash-verified signing inputs captured from a completed native build') + parser.add_argument('--installed-updater-baseline', type=Path, + help='Explicit same-version installed app to preserve and restore through its native updater API') parser.add_argument('--verify-existing', action='store_true', help='Resume final verification of an existing signed/stapled DMG without signing or uploading again') args = parser.parse_args() @@ -352,9 +364,14 @@ def main(): from chromium_macos_arch import verify_architectures verify_architectures(app, args.architecture) identity, team = find_identity(args.identity) + if args.installed_updater_baseline: + args.installed_updater_baseline = args.installed_updater_baseline.resolve() + baseline_version = plistlib.loads((args.installed_updater_baseline / 'Contents/Info.plist').read_bytes())['CFBundleShortVersionString'] + if baseline_version != plistlib.loads((app / 'Contents/Info.plist').read_bytes())['CFBundleShortVersionString']: + raise RuntimeError('Baseline reuse requires exactly the same browser/updater version; use a dedicated clean user for version upgrades') if args.updater_enabled: from updater.macos_smoke_scope import UpdaterSmokeScope - UpdaterSmokeScope(settings, team, output).require_clean() + UpdaterSmokeScope(settings, team, output, baseline_app=args.installed_updater_baseline).require_clean() packaging = build / 'Browser Operator Packaging' if not (packaging / 'sign_chrome.py').is_file(): raise RuntimeError('Build chrome/installer/mac to generate the packaging pipeline first') @@ -362,7 +379,7 @@ def main(): if provenance and provenance['version'] != version: raise RuntimeError('Frozen input version differs from its captured build metadata') if args.verify_existing: - verify_release(source, output, app.name, version, team, settings, args.node, provenance) + verify_release(source, output, app.name, version, team, settings, args.node, provenance, args.installed_updater_baseline) return # Read-only authentication preflight; no password or private key is logged. subprocess.run([ @@ -442,7 +459,7 @@ def main(): raise print('Apple timestamp service failed transiently; retrying in 10 seconds', flush=True) time.sleep(10) - verify_release(source, output, app.name, version, team, settings, args.node, provenance) + verify_release(source, output, app.name, version, team, settings, args.node, provenance, args.installed_updater_baseline) if __name__ == '__main__': diff --git a/scripts/test_merge_chromium_macos.py b/scripts/test_merge_chromium_macos.py index 3a174788a3..6e3c7040df 100644 --- a/scripts/test_merge_chromium_macos.py +++ b/scripts/test_merge_chromium_macos.py @@ -57,7 +57,7 @@ def inputs(self, root): (directory / 'Browser Operator Packaging' / name).write_bytes(binary) for name in ('BrowserOperatorUpdaterUtil', 'crx3_build_action', 'browser_operator_update_verify'): (directory / name).write_bytes(binary) - metadata = {'schema': 1, 'version': '158.0.8127.18', 'source_base_revision': 'a' * 40, + metadata = {'schema': 1, 'version': '158.0.8127.18', 'browser_operator_version': '0.7.0', 'source_base_revision': 'a' * 40, 'source_patch_sha256': 'b' * 64, 'updater_product': 'BrowserOperatorUpdater', 'native_source_state': {'revision': 'a' * 40}, 'frontend_source_state': {'revision': 'd' * 40, 'untracked_source_files': {}}, diff --git a/scripts/updater/macos_smoke_scope.py b/scripts/updater/macos_smoke_scope.py index fa551f714b..bfe651f4b2 100644 --- a/scripts/updater/macos_smoke_scope.py +++ b/scripts/updater/macos_smoke_scope.py @@ -1,15 +1,18 @@ """Protect existing updater registrations and retire only a smoke test's helper.""" import json +import hashlib from pathlib import Path import plistlib import subprocess class UpdaterSmokeScope: - def __init__(self, settings, team, evidence, home=None): + def __init__(self, settings, team, evidence, home=None, baseline_app=None, restore_baseline=None): self.home = home or Path.home() self.team, self.evidence = team, evidence + self.baseline_app, self.restore_baseline = baseline_app, restore_baseline + self.baseline = None config = settings['browser_operator_updater_config'].strip('"') if config.endswith('/macos-production.gni'): company, self.product, self.appid = 'BrowserOperator', 'BrowserOperatorUpdater', 'com.browseroperator.Updater' @@ -25,15 +28,60 @@ def agents(self): return [p for p in directory.glob('*.plist') if p.name.lower().startswith(self.appid.lower() + '.')] def require_clean(self): + if self.baseline_app: + self.baseline = self.baseline_registration() + return if (self.controller.exists() or self.controller.is_symlink() or self.agents() or (Path('/Library') / self.relative).exists()): raise RuntimeError('Existing updater registration must be preserved; qualify releases with a clean dedicated macOS user') def __enter__(self): self.require_clean() + if self.baseline_app and not self.restore_baseline: + raise RuntimeError('An explicit baseline requires a native registration restore callback') return self + def baseline_registration(self): + if self.controller.is_symlink() or (Path('/Library') / self.relative).exists(): + raise RuntimeError('Baseline reuse requires an ordinary user controller without a system install') + app = self.baseline_app.resolve() + info = plistlib.loads((app / 'Contents/Info.plist').read_bytes()) + if info.get('CFBundleIdentifier') != 'com.browseroperator.BrowserOperator': + raise RuntimeError('Unexpected installed baseline identity') + subprocess.run(['codesign', '--verify', '--deep', '--strict', str(app)], check=True) + details = subprocess.run(['codesign', '-dv', '--verbose=4', str(app)], capture_output=True, text=True, check=True).stderr + if f'TeamIdentifier={self.team}' not in details: + raise RuntimeError('Installed baseline is from another signing team') + current = self.controller / 'Current' + if not current.is_symlink() or not current.resolve().is_relative_to(self.controller.resolve()): + raise RuntimeError('Expected an existing user updater within its own namespace') + helper = current / (self.product + '.app') + helper_info = plistlib.loads((helper / 'Contents/Info.plist').read_bytes()) + if helper_info.get('CFBundleIdentifier') != self.appid: + raise RuntimeError('Unexpected baseline updater identity') + subprocess.run(['codesign', '--verify', '--deep', '--strict', str(helper)], check=True) + helper_details = subprocess.run(['codesign', '-dv', '--verbose=4', str(helper)], capture_output=True, text=True, check=True).stderr + if f'TeamIdentifier={self.team}' not in helper_details: + raise RuntimeError('Baseline updater is from another signing team') + registration = json.loads((self.controller / 'prefs.json').read_text())['updateclientdata']['apps']['com.browseroperator.browseroperator'] + if (Path(registration['ecp']).resolve() != app or + registration['pv'] != info['CFBundleShortVersionString'] or + helper_info['CFBundleShortVersionString'] != info['CFBundleShortVersionString']): + raise RuntimeError('Baseline app, updater and registration must have the same version and path') + with (helper / 'Contents/MacOS' / self.product).open('rb') as stream: + helper_hash = hashlib.file_digest(stream, 'sha256').hexdigest() + return {'application': str(app), 'version': registration['pv'], 'helper_sha256': helper_hash} + def __exit__(self, *_exception): + if self.baseline_app: + # Restore through the installed browser's real native API. Never + # edit live updater preferences or uninstall the permanent helper. + self.restore_baseline() + if self.baseline_registration() != self.baseline: + raise RuntimeError('Installed updater baseline was not restored exactly') + (self.evidence / 'native-updater-baseline-restored.json').write_text( + json.dumps({**self.baseline, 'registration_restored': True, 'helper_uninstalled': False}) + '\n') + return if not self.controller.exists() and not self.agents(): return current = self.controller / 'Current' diff --git a/scripts/updater/publish_test_update.py b/scripts/updater/publish_test_update.py index c5058832ff..e14af481f6 100644 --- a/scripts/updater/publish_test_update.py +++ b/scripts/updater/publish_test_update.py @@ -18,7 +18,7 @@ def checked(*args): def public_release_manifest(release): """Keep build-host paths and untracked filenames in private audit evidence.""" - fields = ('version', 'architecture', 'update_channel', 'team_id', 'dmg', 'sha256', + fields = ('version', 'browser_operator_version', 'architecture', 'update_channel', 'team_id', 'dmg', 'sha256', 'notarization', 'gatekeeper', 'mounted_app_functional_tests', 'mounted_app_validation', 'installed_dmg_copy_functional_tests', 'functional_test_architectures', 'native_updater_upgrade_test', diff --git a/scripts/updater/test_legacy_version_notification.mjs b/scripts/updater/test_legacy_version_notification.mjs new file mode 100644 index 0000000000..ce87e2eeb5 --- /dev/null +++ b/scripts/updater/test_legacy_version_notification.mjs @@ -0,0 +1,63 @@ +import assert from 'node:assert/strict'; +import {after, beforeEach, test} from 'node:test'; +import {mkdtemp, readFile, rm, writeFile} from 'node:fs/promises'; +import {tmpdir} from 'node:os'; +import {join} from 'node:path'; +import {fileURLToPath, pathToFileURL} from 'node:url'; +import {createRequire} from 'node:module'; + +const require = createRequire(import.meta.url); +const ts = require('typescript'); +const directory = await mkdtemp(join(tmpdir(), 'bo-version-check-')); +await writeFile(join(directory, 'package.json'), '{"type":"module"}'); +for (const name of ['VersionChecker', 'Version']) { + const source = await readFile(new URL(`../../front_end/panels/ai_chat/core/${name}.ts`, import.meta.url), 'utf8'); + const result = ts.transpileModule(source, {compilerOptions: {target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ES2022}}); + await writeFile(join(directory, name + '.js'), result.outputText); +} +await writeFile(join(directory, 'Logger.js'), 'export const createLogger = () => ({info(){},error(){}});'); +const {VersionChecker} = await import(pathToFileURL(join(directory, 'VersionChecker.js')).href); +const originalFetch = globalThis.fetch; +const originalStorage = globalThis.localStorage; +const values = new Map(); +globalThis.localStorage = {getItem: key => values.get(key) ?? null, setItem: (key, value) => values.set(key, value), removeItem: key => values.delete(key)}; +const checker = VersionChecker.getInstance(); +const latestURL = 'https://api.github.com/repos/BrowserOperator/browser-operator-core/releases/latest'; +let calls; +beforeEach(() => { + values.clear(); calls = 0; checker.setCurrentVersion('0.5.0'); + globalThis.fetch = async url => { + calls++; assert.equal(url, latestURL); + return {ok: true, json: async () => ({tag_name: 'v0.7.0', html_url: 'https://github.com/BrowserOperator/browser-operator-core/releases/tag/v0.7.0'})}; + }; +}); +after(async () => { + globalThis.fetch = originalFetch; + if (originalStorage === undefined) delete globalThis.localStorage; + else globalThis.localStorage = originalStorage; + await rm(directory, {recursive: true}); +}); +for (const version of ['0.5.0', '0.6.0']) { + test(`${version} users see the public 0.7.0 migration release`, async () => { + checker.setCurrentVersion(version); + const result = await checker.checkForUpdates(); + assert.equal(result.latestVersion, '0.7.0'); + assert.equal(result.isUpdateAvailable, true); + assert.match(result.releaseUrl, /\/v0\.7\.0$/); + }); +} +test('dismissing 0.6.0 does not dismiss 0.7.0', async () => { + values.set('devtools-version-check-dismissed', '0.6.0'); + const result = await checker.checkForUpdates(); + assert.equal(checker.isUpdateDismissed(result.latestVersion), false); +}); +test('legacy daily refresh replaces an old cached 0.6.0 notice', async () => { + values.set('devtools-version-check-info', JSON.stringify({currentVersion: '0.5.0', latestVersion: '0.6.0', isUpdateAvailable: true})); + values.set('devtools-version-check-last-check', String(Date.now() - 25 * 60 * 60 * 1000)); + assert.equal((await checker.checkForUpdates()).latestVersion, '0.7.0'); + assert.equal(calls, 1); +}); +test('an installed 0.7.0 frontend is not told to download itself', async () => { + checker.setCurrentVersion('0.7.0'); + assert.equal((await checker.checkForUpdates()).isUpdateAvailable, false); +}); diff --git a/scripts/updater/test_macos_smoke_scope.py b/scripts/updater/test_macos_smoke_scope.py index 0b2d29c24d..6547a2425f 100644 --- a/scripts/updater/test_macos_smoke_scope.py +++ b/scripts/updater/test_macos_smoke_scope.py @@ -11,6 +11,31 @@ class ScopeTests(unittest.TestCase): + def test_existing_baseline_is_restored_even_when_qualification_fails(self): + with tempfile.TemporaryDirectory() as temp: + scope = self.scope(Path(temp)) + scope.baseline_app = Path('/Applications/Browser Operator.app') + restored = [] + scope.restore_baseline = lambda: restored.append(True) + baseline = {'application': str(scope.baseline_app), 'version': '158.0.8127.18', 'helper_sha256': 'a' * 64} + with patch.object(scope, 'baseline_registration', return_value=baseline), \ + patch('macos_smoke_scope.subprocess.run') as run: + with self.assertRaisesRegex(RuntimeError, 'qualification failed'): + with scope: + raise RuntimeError('qualification failed') + self.assertEqual(restored, [True]) + run.assert_not_called() # No uninstall or preference editing. + + def test_changed_baseline_after_restore_is_rejected(self): + with tempfile.TemporaryDirectory() as temp: + scope = self.scope(Path(temp)) + scope.baseline_app = Path('/Applications/Browser Operator.app') + scope.restore_baseline = lambda: None + with patch.object(scope, 'baseline_registration', side_effect=[{'version': '158'}, {'version': '159'}]): + with self.assertRaisesRegex(RuntimeError, 'not restored exactly'): + with scope: + pass + def scope(self, root): evidence = root / 'evidence' evidence.mkdir() diff --git a/scripts/verify_chromium_release.mjs b/scripts/verify_chromium_release.mjs index 48d0216eb8..6ecb4ee665 100644 --- a/scripts/verify_chromium_release.mjs +++ b/scripts/verify_chromium_release.mjs @@ -9,6 +9,7 @@ import {tmpdir} from 'node:os'; const endpoint = process.argv[2] ?? 'http://127.0.0.1:9445'; const expectedVersion = process.argv[3] ?? '158.0.8127.18'; const artifacts = resolve(process.argv[4] ?? join(tmpdir(), 'browser-operator-release-verification')); +const expectedProductVersion = process.argv[5]; await mkdir(artifacts, {recursive: true}); const version = await fetch(`${endpoint}/json/version`).then(r => r.json()); assert.equal(version.Browser.split('/').at(-1), expectedVersion); @@ -95,6 +96,55 @@ try { const tree = await frontend.send('Accessibility.getFullAXTree'); const names = tree.nodes.map(n => n.name?.value).filter(Boolean); assert.ok(names.some(name => /Browser Operator|AI Assistant/.test(name)), 'Expected branded frontend'); + let nativeUpdates; + if (expectedProductVersion) { + const inspected = await frontend.send('Runtime.evaluate', {expression: `(() => { + function find(root) { + const banner = root.querySelector('ai-version-banner'); + if (banner) return banner; + for (const element of root.querySelectorAll('*')) { + if (element.shadowRoot) { const found = find(element.shadowRoot); if (found) return found; } + } + } + const banner = find(document); + return {native: banner?.nativeUpdater, text: banner?.shadowRoot?.textContent}; + })()`, returnByValue: true}); + assert.ok(!inspected.exceptionDetails, JSON.stringify(inspected.exceptionDetails)); + nativeUpdates = inspected.result.value; + assert.equal(nativeUpdates.native, true, 'Expected the native updater entry, not a GitHub frontend notice'); + assert.ok(nativeUpdates.text.includes(expectedProductVersion), nativeUpdates.text); + assert.ok(nativeUpdates.text.includes('Check for updates')); + assert.ok(!/New version|View Release|0\.6\.0/.test(nativeUpdates.text)); + const before = new Set((await browser.send('Target.getTargets')).targetInfos.map(t => t.targetId)); + await frontend.send('Runtime.evaluate', {expression: `(() => { + function click(root) { + const banner = root.querySelector('ai-version-banner'); + if (banner) { banner.shadowRoot.querySelector('button').click(); return true; } + for (const element of root.querySelectorAll('*')) if (element.shadowRoot && click(element.shadowRoot)) return true; + return false; + } + if (!click(document)) throw new Error('Native updater action missing'); + })()`}); + let opened; + for (let attempt = 0; attempt < 60; attempt++) { + opened = (await browser.send('Target.getTargets')).targetInfos.find(t => !before.has(t.targetId) && t.url === 'chrome://settings/help'); + if (opened) break; + await new Promise(resolve => setTimeout(resolve, 250)); + } + assert.ok(opened, 'AI panel must open the real native About/update page'); + nativeUpdates.openedURL = opened.url; + // The narrow update-page action must not unlock arbitrary chrome:// pages. + const previous = new Set((await browser.send('Target.getTargets')).targetInfos.map(t => t.targetId)); + await frontend.send('Runtime.evaluate', {expression: "import('./core/host/host.js').then(h => h.InspectorFrontendHost.InspectorFrontendHostInstance.openInNewTab('chrome://settings/passwords'))", awaitPromise: true}); + let rejected; + for (let attempt = 0; attempt < 30; attempt++) { + rejected = (await browser.send('Target.getTargets')).targetInfos.find(t => !previous.has(t.targetId) && t.type === 'page'); + if (rejected?.url) break; + await new Promise(resolve => setTimeout(resolve, 250)); + } + assert.equal(rejected?.url, 'about:blank', 'Unrelated privileged URLs must retain stock blocking'); + nativeUpdates.otherPrivilegedURLs = 'blocked'; + } const report = { version: version.Browser, frontendURL: target.url, @@ -103,6 +153,7 @@ try { screenshotWorks: true, frontendLabels: names, processInfo: (await browser.send('SystemInfo.getProcessInfo')).processInfo, + nativeUpdates, }; await writeFile(join(artifacts, 'report.json'), JSON.stringify(report, null, 2)); console.log(JSON.stringify({...report, accessibilityTree: 'passed'}, null, 2));