diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml new file mode 100644 index 0000000..e25a7f7 --- /dev/null +++ b/.github/workflows/macos.yml @@ -0,0 +1,46 @@ +name: macOS checks + +on: + pull_request: + paths: + - 'Runway/**' + - 'RunwayWidget/**' + - 'Shared/**' + - 'RunwayTests/**' + - 'Runway.xcodeproj/**' + - 'scripts/**' + - 'script/**' + - 'tests/install-selfcheck.py' + - '.github/workflows/macos.yml' + push: + branches: [main] + paths: + - 'Runway/**' + - 'RunwayWidget/**' + - 'Shared/**' + - 'RunwayTests/**' + - 'Runway.xcodeproj/**' + - 'scripts/**' + - 'script/**' + - 'tests/install-selfcheck.py' + - '.github/workflows/macos.yml' + +permissions: + contents: read + +jobs: + test: + runs-on: macos-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Verify installer replacement and rollback + run: python3 tests/install-selfcheck.py + - name: Test macOS app + run: >- + xcodebuild -project Runway.xcodeproj -scheme Runway + -configuration Debug -destination 'platform=macOS' + CODE_SIGN_IDENTITY=- CODE_SIGN_STYLE=Manual DEVELOPMENT_TEAM= + -quiet test diff --git a/Runway/RunwayApp.swift b/Runway/RunwayApp.swift index 4e88d4d..728016d 100644 --- a/Runway/RunwayApp.swift +++ b/Runway/RunwayApp.swift @@ -37,7 +37,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate { } _ = AppUpdater.shared if BackgroundRefreshAgent.isStableInstall { - WidgetRegistration.refresh() + AppRegistration.refresh() } let hasCurrentAccess = OnboardingStateStore.hasCurrentCodexDataAccess() if OnboardingStateStore.completedCurrentVersion() { @@ -177,16 +177,33 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate { } -private enum WidgetRegistration { +enum AppRegistration { + static func obsoletePaths(currentApp: URL, registeredApps: [URL]) -> [String] { + let current = currentApp.resolvingSymlinksInPath().standardizedFileURL + return Set(registeredApps.filter { + $0.resolvingSymlinksInPath().standardizedFileURL != current + }.map { $0.standardizedFileURL.path }).sorted() + } + static func refresh() { + guard Bundle.main.bundleIdentifier == "com.codexusage.CodexUsageMonitor" else { return } let app = Bundle.main.bundleURL.path let plugin = Bundle.main.bundleURL .appendingPathComponent("Contents/PlugIns/RunwayWidget.appex").path - guard FileManager.default.fileExists(atPath: plugin) else { return } + let registered = ["com.codexusage.CodexUsageMonitor", "com.codexusage.CodexUsageMonitor.debug"] + .flatMap { NSWorkspace.shared.urlsForApplications(withBundleIdentifier: $0) } + let obsolete = obsoletePaths(currentApp: Bundle.main.bundleURL, registeredApps: registered) DispatchQueue.global(qos: .utility).async { - run("/System/Library/Frameworks/CoreServices.framework/Versions/Current/Frameworks/LaunchServices.framework/Versions/Current/Support/lsregister", ["-f", "-R", "-trusted", app]) - run("/usr/bin/pluginkit", ["-a", plugin]) + let lsregister = "/System/Library/Frameworks/CoreServices.framework/Versions/Current/Frameworks/LaunchServices.framework/Versions/Current/Support/lsregister" + for path in obsolete { + run("/usr/bin/pluginkit", ["-r", path + "/Contents/PlugIns/RunwayWidget.appex"]) + run(lsregister, ["-u", path]) + } + run(lsregister, ["-f", "-R", "-trusted", app]) + if FileManager.default.fileExists(atPath: plugin) { + run("/usr/bin/pluginkit", ["-a", plugin]) + } } } @@ -196,8 +213,12 @@ private enum WidgetRegistration { process.arguments = arguments process.standardOutput = FileHandle.nullDevice process.standardError = FileHandle.nullDevice - try? process.run() - process.waitUntilExit() + do { + try process.run() + process.waitUntilExit() + } catch { + // Registration is retried on the next normal launch. + } } } diff --git a/RunwayTests/RunwayTests.swift b/RunwayTests/RunwayTests.swift index 9048329..46c4421 100644 --- a/RunwayTests/RunwayTests.swift +++ b/RunwayTests/RunwayTests.swift @@ -6,6 +6,22 @@ import SwiftUI import Testing @testable import Runway +@Test("Install registration keeps the current app and retires duplicate build and backup paths") +func appRegistrationObsoletePaths() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: directory) } + let current = directory.appendingPathComponent("Runway.app", isDirectory: true) + try FileManager.default.createDirectory(at: current, withIntermediateDirectories: true) + let alias = directory.appendingPathComponent("CodexUsageMonitor.app") + try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: current) + let old = directory.appendingPathComponent("Build Products/Previous-Runway.app") + let debug = directory.appendingPathComponent("Debug/Runway.app") + let duplicate = directory.appendingPathComponent("Build Products/../Build Products/Previous-Runway.app") + #expect(AppRegistration.obsoletePaths(currentApp: current, + registeredApps: [current, alias, old, debug, duplicate]) == [old.path, debug.path].sorted()) + #expect(AppRegistration.obsoletePaths(currentApp: current, registeredApps: [current, alias]).isEmpty) +} + @Test("Streaming JSONL handles split UTF-8, large rows, CRLF, malformed rows and a final row", arguments: [1, 7, 65_536]) func streamingJSONLBoundaries(chunkSize: Int) throws { let url = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) diff --git a/script/build_and_run.sh b/script/build_and_run.sh index f358f0f..931f26d 100755 --- a/script/build_and_run.sh +++ b/script/build_and_run.sh @@ -22,7 +22,7 @@ xcodebuild \ build open_app() { - /usr/bin/open -n "$APP_BUNDLE" + /usr/bin/open "$APP_BUNDLE" } case "$MODE" in diff --git a/scripts/install_widget.sh b/scripts/install_widget.sh index 07e431a..734364d 100755 --- a/scripts/install_widget.sh +++ b/scripts/install_widget.sh @@ -2,13 +2,43 @@ set -euo pipefail ROOT="$(cd "$(dirname "$0")/.." && pwd)" -DERIVED_DATA="$ROOT/build/DerivedData" +DERIVED_DATA="$(mktemp -d "${TMPDIR:-/tmp}/runway-install.XXXXXX")" APP="$DERIVED_DATA/Build/Products/Release/Runway.app" DEST="/Applications/Runway.app" PLUGIN="$DEST/Contents/PlugIns/RunwayWidget.appex" AGENT="$HOME/Library/LaunchAgents/com.codexusage.Runway.refresh.plist" LEGACY_APP="/Applications/CodexUsageMonitor.app" LEGACY_AGENT="$HOME/Library/LaunchAgents/com.codexusage.CodexUsageMonitor.refresh.plist" +LSREGISTER="/System/Library/Frameworks/CoreServices.framework/Versions/Current/Frameworks/LaunchServices.framework/Versions/Current/Support/lsregister" +INSTALL_COMPLETED=0 +LOCK_ACQUIRED=0 +LOCKFILE="$HOME/Library/Caches/com.codexusage.Runway/install.lock" + +cleanup_build() { + if [[ "$INSTALL_COMPLETED" -eq 0 ]]; then + for installed in "$DEST" "$LEGACY_APP"; do + previous="$DERIVED_DATA/Previous-$(basename "$installed")" + if [[ ( -e "$previous" || -L "$previous" ) && ! -e "$installed" && ! -L "$installed" ]]; then + if mv "$previous" "$installed"; then + "$LSREGISTER" -f "$installed" >/dev/null 2>&1 || true + else + echo "Could not restore $installed; recovery copy: $previous" >&2 + fi + fi + done + fi + if [[ -d "$APP" ]]; then + pluginkit -r "$APP/Contents/PlugIns/RunwayWidget.appex" >/dev/null 2>&1 || true + "$LSREGISTER" -u "$APP" >/dev/null 2>&1 || true + fi + if [[ "$INSTALL_COMPLETED" -eq 0 && ( -e "$DERIVED_DATA/Previous-Runway.app" || -L "$DERIVED_DATA/Previous-Runway.app" || -e "$DERIVED_DATA/Previous-CodexUsageMonitor.app" || -L "$DERIVED_DATA/Previous-CodexUsageMonitor.app" ) ]]; then + echo "Previous application retained in $DERIVED_DATA" >&2 + else + rm -rf "$DERIVED_DATA" + fi + if [[ "$LOCK_ACQUIRED" -eq 1 ]]; then rm -f "$LOCKFILE"; fi +} +trap cleanup_build EXIT xcodebuild \ -project "$ROOT/Runway.xcodeproj" \ @@ -17,51 +47,70 @@ xcodebuild \ -destination 'platform=macOS' \ -derivedDataPath "$DERIVED_DATA" \ ENABLE_HARDENED_RUNTIME=NO \ + "$@" \ -quiet \ build +mkdir -p "$(dirname "$LOCKFILE")" +if ! /usr/bin/shlock -p "$$" -f "$LOCKFILE"; then + echo "Another Runway installation is running." >&2 + exit 1 +fi +LOCK_ACQUIRED=1 + for agent in "$AGENT" "$LEGACY_AGENT"; do - if [[ -f "$agent" ]]; then - launchctl bootout "gui/$(id -u)" "$agent" >/dev/null 2>&1 || true + label="$(basename "$agent" .plist)" + service="gui/$(id -u)/$label" + status=0 + launchctl print "$service" >/dev/null 2>&1 || status=$? + if [[ "$status" -eq 0 ]]; then + launchctl bootout "$service" + elif [[ "$status" -ne 113 ]]; then + echo "Could not inspect $service (launchctl $status)" >&2 + exit 1 fi + status=0 + launchctl print "$service" >/dev/null 2>&1 || status=$? + if [[ "$status" -ne 113 ]]; then + echo "Could not retire $service" >&2 + exit 1 + fi + rm -f "$agent" done pkill -f '^/Applications/(Runway|CodexUsageMonitor)[.]app/Contents/' >/dev/null 2>&1 || true -BACKUP="$ROOT/build/install-backups/$(date -u +%Y%m%dT%H%M%SZ)" +BACKUP="$ROOT/build/install-backups.noindex/$(date -u +%Y%m%dT%H%M%SZ)" mkdir -p "$BACKUP" -STAGED="$BACKUP/New-Runway.app" +STAGED="$DERIVED_DATA/New-Runway.app" ditto "$APP" "$STAGED" +for installed in "$LEGACY_APP" "$DEST"; do + if [[ -d "$installed" && ! -L "$installed" ]]; then + archive="$BACKUP/Previous-$(basename "$installed").zip" + ditto -c -k --sequesterRsrc --keepParent "$installed" "$archive" + unzip -tq "$archive" >/dev/null + fi +done if [[ -e "$LEGACY_APP" && ! -L "$LEGACY_APP" ]]; then - mv "$LEGACY_APP" "$BACKUP/Previous-CodexUsageMonitor.app" + "$LSREGISTER" -u "$LEGACY_APP" + mv "$LEGACY_APP" "$DERIVED_DATA/Previous-CodexUsageMonitor.app" fi if [[ -d "$DEST" ]]; then - mv "$DEST" "$BACKUP/Previous-Runway.app" + "$LSREGISTER" -u "$DEST" + mv "$DEST" "$DERIVED_DATA/Previous-Runway.app" fi if ! mv "$STAGED" "$DEST"; then - if [[ -d "$BACKUP/Previous-Runway.app" ]]; then - mv "$BACKUP/Previous-Runway.app" "$DEST" - fi - if [[ -d "$BACKUP/Previous-CodexUsageMonitor.app" ]]; then - mv "$BACKUP/Previous-CodexUsageMonitor.app" "$LEGACY_APP" - fi exit 1 fi -if [[ -L "$LEGACY_APP" ]]; then rm "$LEGACY_APP"; fi -ln -s Runway.app "$LEGACY_APP" -if [[ -f "$LEGACY_AGENT" ]]; then - mv "$LEGACY_AGENT" "$BACKUP/Previous-CodexUsageMonitor.refresh.plist" +INSTALL_COMPLETED=1 +if [[ -L "$LEGACY_APP" ]]; then + target="$(readlink "$LEGACY_APP")" + if [[ "$target" == Runway.app || "$target" == "$DEST" ]]; then rm "$LEGACY_APP"; fi fi -/System/Library/Frameworks/CoreServices.framework/Versions/Current/Frameworks/LaunchServices.framework/Versions/Current/Support/lsregister \ - -f -R -trusted "$DEST" +"$LSREGISTER" -f -R -trusted "$DEST" pluginkit -a "$PLUGIN" # WidgetKit keeps executable paths in existing sessions after an app rename. /usr/bin/killall chronod >/dev/null 2>&1 || true -# Resume the existing refresh schedule immediately after replacement, including -# installs where the user does not reopen the workspace window. -if [[ -f "$AGENT" ]]; then - launchctl bootstrap "gui/$(id -u)" "$AGENT" -fi /usr/bin/open "$DEST" echo "Installed $DEST" diff --git a/tests/install-selfcheck.py b/tests/install-selfcheck.py new file mode 100644 index 0000000..2e7a4cc --- /dev/null +++ b/tests/install-selfcheck.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +"""Exercise the real installer in a temporary filesystem with OS command doubles.""" +import json +import os +from pathlib import Path +import subprocess +import tempfile +import unittest +import zipfile + + +SCRIPT = Path(__file__).resolve().parents[1] / "scripts/install_widget.sh" +LSREGISTER = "/System/Library/Frameworks/CoreServices.framework/Versions/Current/Frameworks/LaunchServices.framework/Versions/Current/Support/lsregister" +SHIM = r'''#!/usr/bin/env python3 +import json, os, pathlib, subprocess, sys +name = pathlib.Path(sys.argv[0]).name +args = sys.argv[1:] +root = pathlib.Path(os.environ["RUNWAY_TEST_ROOT"]) +with (root / "commands.jsonl").open("a") as log: + log.write(json.dumps([name, args]) + "\n") +if name == "xcodebuild": + app = pathlib.Path(args[args.index("-derivedDataPath") + 1]) / "Build/Products/Release/Runway.app" + (app / "Contents/PlugIns/RunwayWidget.appex").mkdir(parents=True, exist_ok=True) + (app / "payload").write_text("new") +elif name == "launchctl": + sys.exit(113 if args[0] == "print" else 0) +elif name == "mv": + if os.environ.get("RUNWAY_TEST_FAIL_MOVE") and "New-Runway.app" in args[0]: + sys.exit(1) + sys.exit(subprocess.call(["/bin/mv"] + args)) +elif name == "ditto": + if os.environ.get("RUNWAY_TEST_FAIL_ARCHIVE") and "-c" in args: + sys.exit(1) + sys.exit(subprocess.call(["/usr/bin/ditto"] + args)) +elif name == "lsregister" and os.environ.get("RUNWAY_TEST_FAIL_UNREGISTER"): + if args == ["-u", str(root / "Applications/Runway.app")]: + sys.exit(1) +''' + + +class InstallChecks(unittest.TestCase): + def run_install(self, failure=None, legacy_real=False, lock_busy=False, app_symlink=False): + temporary = tempfile.TemporaryDirectory(prefix="runway-install-check-") + self.addCleanup(temporary.cleanup) + root = Path(temporary.name) + (root / "scripts").mkdir() + (root / "bin").mkdir() + (root / "agents").mkdir() + (root / "scratch").mkdir() + (root / "cache").mkdir() + if lock_busy: + (root / "cache/install.lock").write_text(str(os.getpid()) + "\n") + app = root / "Applications/Runway.app" + if app_symlink: + target = app.with_name("Original.app") + target.mkdir(parents=True) + app.symlink_to("Original.app") + else: + app.mkdir(parents=True) + (app / "payload").write_text("previous") + alias = app.with_name("CodexUsageMonitor.app") + if legacy_real: + alias.mkdir() + (alias / "payload").write_text("legacy") + else: + alias.symlink_to("Runway.app") + for label in ("Runway", "CodexUsageMonitor"): + (root / f"agents/com.codexusage.{label}.refresh.plist").write_text("old job") + for name in ("xcodebuild", "launchctl", "pkill", "pluginkit", "open", "killall", "lsregister", "mv", "ditto"): + command = root / "bin" / name + command.write_text(SHIM) + command.chmod(0o755) + source = SCRIPT.read_text().replace("/Applications/", str(root / "Applications") + "/") + source = source.replace("$HOME/Library/LaunchAgents", str(root / "agents")) + source = source.replace("$HOME/Library/Caches/com.codexusage.Runway", str(root / "cache")) + for original, name in ((LSREGISTER, "lsregister"), ("/usr/bin/open", "open"), ("/usr/bin/killall", "killall")): + source = source.replace(original, str(root / "bin" / name)) + fixture = root / "scripts/install_widget.sh" + fixture.write_text(source) + environment = dict(os.environ, PATH=str(root / "bin") + os.pathsep + os.environ["PATH"], + TMPDIR=str(root / "scratch") + "/", RUNWAY_TEST_ROOT=str(root)) + if failure: + environment[failure] = "1" + result = subprocess.run(["/bin/bash", str(fixture)], env=environment, capture_output=True, text=True, timeout=30) + commands = [json.loads(line) for line in (root / "commands.jsonl").read_text().splitlines()] + return root, app, alias, result, commands + + def test_success_archives_previous_app_and_removes_alias_and_agents(self): + root, app, alias, result, commands = self.run_install() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual((app / "payload").read_text(), "new") + self.assertFalse(alias.is_symlink(), "legacy app alias must not be recreated") + self.assertEqual(list((root / "agents").glob("*.plist")), []) + backups = list((root / "build/install-backups.noindex").rglob("Previous-Runway.app.zip")) + self.assertEqual(len(backups), 1) + with zipfile.ZipFile(backups[0]) as archive: + self.assertEqual(archive.read("Runway.app/payload"), b"previous") + self.assertEqual(list(backups[0].parent.rglob("*.app")), []) + actions = [args for name, args in commands if name == "lsregister"] + self.assertIn(["-u", str(app)], actions) + build = next(args for name, args in commands if name == "xcodebuild") + derived = Path(build[build.index("-derivedDataPath") + 1]) + self.assertTrue(any(args[0] == "-u" and Path(args[1]) == derived / "Build/Products/Release/Runway.app" + for args in actions)) + self.assertFalse(derived.exists(), "temporary build must not remain a discoverable app") + self.assertFalse((root / "cache/install.lock").exists()) + self.assertIn(["-f", "-R", "-trusted", str(app)], actions) + + def test_failed_replacement_restores_previous_app(self): + _, app, _, result, commands = self.run_install("RUNWAY_TEST_FAIL_MOVE") + self.assertNotEqual(result.returncode, 0) + self.assertEqual((app / "payload").read_text(), "previous") + self.assertFalse(any(name == "open" for name, _ in commands)) + + def test_failed_archiving_preserves_installed_app(self): + _, app, _, result, _ = self.run_install("RUNWAY_TEST_FAIL_ARCHIVE") + self.assertNotEqual(result.returncode, 0) + self.assertEqual((app / "payload").read_text(), "previous") + + def test_failed_retirement_restores_displaced_legacy_app(self): + _, app, legacy, result, commands = self.run_install("RUNWAY_TEST_FAIL_UNREGISTER", legacy_real=True) + self.assertNotEqual(result.returncode, 0) + self.assertEqual((app / "payload").read_text(), "previous") + self.assertEqual((legacy / "payload").read_text(), "legacy") + self.assertFalse(any(name == "open" for name, _ in commands)) + + def test_busy_installer_does_not_replace_app_or_retire_agents(self): + root, app, _, result, commands = self.run_install(lock_busy=True) + self.assertNotEqual(result.returncode, 0) + self.assertEqual((app / "payload").read_text(), "previous") + self.assertEqual(len(list((root / "agents").glob("*.plist"))), 2) + self.assertFalse(any(name in ("pkill", "mv", "open") for name, _ in commands)) + + def test_failed_replacement_restores_relative_app_symlink(self): + _, app, _, result, _ = self.run_install("RUNWAY_TEST_FAIL_MOVE", app_symlink=True) + self.assertNotEqual(result.returncode, 0) + self.assertTrue(app.is_symlink()) + self.assertEqual(os.readlink(app), "Original.app") + self.assertEqual((app / "payload").read_text(), "previous") + + +if __name__ == "__main__": + unittest.main()