Preserve deferred macOS desktop host and local publisher

This commit is contained in:
2026-11-07 00:24:32 +00:00
parent f728b6c855
commit 492fb70d91
32 changed files with 1778 additions and 11 deletions
+135
View File
@@ -0,0 +1,135 @@
#!/usr/bin/env python3
"""Build, replace and open the local macOS app without restarting the server."""
import argparse
import json
import os
import platform
import re
from pathlib import Path
import shutil
import subprocess
import sys
import time
from urllib.parse import urlsplit, urlunsplit
APP = Path(__file__).resolve().parents[1]
def build_environment(universal=False):
environment = dict(os.environ)
architecture = platform.machine()
if not universal and architecture not in ("arm64", "x86_64"):
raise RuntimeError(f"Unsupported Mac architecture: {architecture}")
# Flutter forwards FLUTTER_XCODE_* as xcodebuild settings. Local installs
# need only the host architecture; Xcode 27 lipo rejects the combined check.
environment["FLUTTER_XCODE_ARCHS"] = "arm64 x86_64" if universal else architecture
environment["FLUTTER_XCODE_ONLY_ACTIVE_ARCH"] = "NO" if universal else "YES"
return environment
def default_server():
configured = os.environ.get("PIPELINES_SERVER_URL", "").strip()
if configured:
return configured
manifest = Path.home() / ".local/share/pipelines/pipelines-install.json"
if manifest.is_file():
data = json.loads(manifest.read_text())
public = data.get("opencode_env", {}).get("PIPELINES_WEB_PUBLIC_URL", "")
parsed = urlsplit(public)
if parsed.scheme in ("https", "http") and parsed.netloc:
return urlunsplit(("wss" if parsed.scheme == "https" else "ws",
parsed.netloc, "/connect", "", ""))
raise ValueError("Set PIPELINES_SERVER_URL or pass --server-url ws(s)://host/connect")
def install(source, target):
"""Stage the entire signed bundle before replacing; keep the last version."""
staging = target.with_name(target.name + ".next")
previous = target.with_name(target.name + ".previous")
target.parent.mkdir(parents=True, exist_ok=True)
if staging.exists():
shutil.rmtree(staging)
subprocess.run(["ditto", str(source), str(staging)], check=True)
if target.exists():
if previous.exists():
shutil.rmtree(previous)
target.rename(previous)
try:
staging.rename(target)
except OSError:
if previous.exists() and not target.exists():
previous.rename(target)
raise
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--server-url")
parser.add_argument("--destination", type=Path,
default=Path.home() / "Applications/Pipelines.app")
parser.add_argument("--no-open", action="store_true",
help="Install without opening; quit the existing app first")
parser.add_argument("--offline", action="store_true",
help="Resolve dependencies from the existing pub cache")
parser.add_argument("--universal", action="store_true",
help="Build for both Apple Silicon and Intel instead of this Mac")
args = parser.parse_args()
if sys.platform != "darwin":
parser.error("macOS with Xcode is required")
server = args.server_url or default_server()
parsed = urlsplit(server)
if parsed.scheme not in ("ws", "wss") or not parsed.hostname:
parser.error("server URL must be ws(s)://host/connect")
target = args.destination.expanduser().resolve()
if target.name != "Pipelines.app":
parser.error("destination must end in Pipelines.app")
source = APP / "build/macos/Build/Products/Release/Pipelines.app"
if target == source.resolve():
parser.error("destination must differ from the build output")
flutter = os.environ.get("FLUTTER", "flutter")
subprocess.run([flutter, "--suppress-analytics", "pub", "get",
*(["--offline"] if args.offline else [])], cwd=APP, check=True)
code = int(time.time()) // 60
command = [flutter, "--suppress-analytics", "build", "macos", "--release", "--no-pub",
f"--build-number={code}", f"--build-name=0.1.{code}",
f"--dart-define=PIPELINES_SERVER_URL={server}"]
updates = os.environ.get("PIPELINES_UPDATES_URL")
if updates:
command.append(f"--dart-define=PIPELINES_UPDATES_URL={updates}")
subprocess.run(command, cwd=APP, check=True, env=build_environment(args.universal))
# Close only this installed executable, never another Pipelines instance.
executable = target / "Contents/MacOS/Pipelines"
running = subprocess.run(["pgrep", "-f", "^" + re.escape(str(executable)) + "$"],
capture_output=True, text=True)
if running.returncode not in (0, 1):
raise RuntimeError("Could not check whether the installed app is running")
if running.stdout.strip():
if args.no_open:
raise RuntimeError("Quit the installed Pipelines app and retry")
subprocess.run(["osascript", "-e",
'on run argv\n tell application (item 1 of argv) to quit\nend run',
str(target)], check=True)
for _ in range(100):
if subprocess.run(["pgrep", "-f", "^" + re.escape(str(executable)) + "$"],
capture_output=True).returncode == 1:
break
time.sleep(0.1)
else:
raise RuntimeError("Pipelines is still running; quit it and retry")
install(source, target)
archive = APP / "build/desktop/Pipelines-macos.zip"
archive.parent.mkdir(parents=True, exist_ok=True)
subprocess.run(["ditto", "-c", "-k", "--sequesterRsrc", "--keepParent",
str(target), str(archive)], check=True)
if not args.no_open:
subprocess.run(["open", str(target)], check=True)
print(f"Installed: {target} (build {code})")
print(f"Archive: {archive}")
print("Run this command again to update; saved connections and settings are preserved.")
if __name__ == "__main__":
try:
main()
except (ValueError, RuntimeError, OSError, subprocess.CalledProcessError) as error:
sys.exit(str(error))
+73
View File
@@ -0,0 +1,73 @@
import importlib.util
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
from unittest.mock import patch
spec = importlib.util.spec_from_file_location(
"publish_macos", Path(__file__).with_name("publish_macos.py"))
publish = importlib.util.module_from_spec(spec)
spec.loader.exec_module(publish)
class InstallTests(unittest.TestCase):
def test_local_build_targets_only_the_host_architecture(self):
for architecture in ("arm64", "x86_64"):
with patch.object(publish.platform, "machine", return_value=architecture):
environment = publish.build_environment()
self.assertEqual(environment["FLUTTER_XCODE_ARCHS"], architecture)
self.assertEqual(environment["FLUTTER_XCODE_ONLY_ACTIVE_ARCH"], "YES")
def test_universal_build_is_explicit(self):
environment = publish.build_environment(universal=True)
self.assertEqual(environment["FLUTTER_XCODE_ARCHS"], "arm64 x86_64")
self.assertEqual(environment["FLUTTER_XCODE_ONLY_ACTIVE_ARCH"], "NO")
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.source = self.root / "release/Pipelines.app"
self.target = self.root / "installed/Pipelines.app"
self.source.mkdir(parents=True)
self.target.mkdir(parents=True)
(self.source / "version").write_text("new")
(self.target / "version").write_text("old")
@staticmethod
def copy(command, **kwargs):
shutil.copytree(command[1], command[2])
def test_replacement_keeps_previous_bundle(self):
with patch.object(publish.subprocess, "run", side_effect=self.copy):
publish.install(self.source, self.target)
self.assertEqual((self.target / "version").read_text(), "new")
self.assertEqual((self.target.with_name("Pipelines.app.previous") /
"version").read_text(), "old")
def test_failed_copy_leaves_installed_app_untouched(self):
with patch.object(publish.subprocess, "run",
side_effect=subprocess.CalledProcessError(1, "ditto")):
with self.assertRaises(subprocess.CalledProcessError):
publish.install(self.source, self.target)
self.assertEqual((self.target / "version").read_text(), "old")
def test_failed_swap_restores_installed_app(self):
rename = Path.rename
def fail_staging(path, target):
if path.name.endswith(".next"):
raise OSError("simulated rename failure")
return rename(path, target)
with patch.object(publish.subprocess, "run", side_effect=self.copy), \
patch.object(Path, "rename", fail_staging):
with self.assertRaises(OSError):
publish.install(self.source, self.target)
self.assertEqual((self.target / "version").read_text(), "old")
if __name__ == "__main__":
unittest.main()