diff --git a/.github/workflows/reload-build.yml b/.github/workflows/reload-build.yml index 5414474e3eab..008d6323dbfc 100644 --- a/.github/workflows/reload-build.yml +++ b/.github/workflows/reload-build.yml @@ -29,6 +29,21 @@ on: options: - macos - ios + - ios-video + - sync-video + test_filter: + description: iOS UI test class or class/method used to drive ios-video + required: false + default: "cmuxUITests/cmuxUITests/testStackAuthEntryUsesStableIdentifiers" + type: string + device_family: + description: Simulator family used by ios-video + required: false + default: iphone + type: choice + options: + - iphone + - ipad runner: description: >- macOS runner label to build on. Blacksmith (blacksmith-6vcpu-macos-26), @@ -93,7 +108,7 @@ jobs: run: ./scripts/install-zig-ci.sh - name: Provision GhosttyKit (macOS) - if: ${{ inputs.platform == 'macos' }} + if: ${{ inputs.platform == 'macos' || inputs.platform == 'sync-video' }} run: ./scripts/download-prebuilt-ghosttykit.sh || ./scripts/ensure-ghosttykit.sh - name: Mark deps-ready @@ -160,6 +175,224 @@ jobs: mkdir -p artifact ( cd "$out" && ditto -c -k --keepParent "$(basename "$archive")" "$GITHUB_WORKSPACE/artifact/archive.zip" ) + # --- real sync video: launch real macOS+iOS apps, attach, record both screens --- + - name: Grant TCC screen recording permission + if: ${{ inputs.platform == 'sync-video' }} + run: | + set -euo pipefail + FFMPEG_BIN="$(command -v ffmpeg || true)" + if [ -z "$FFMPEG_BIN" ]; then + brew install ffmpeg + FFMPEG_BIN="$(command -v ffmpeg)" + fi + SYS_TCC="/Library/Application Support/com.apple.TCC/TCC.db" + if [ -f "$SYS_TCC" ]; then + for client in "$FFMPEG_BIN" /opt/homebrew/bin/ffmpeg /usr/local/bin/ffmpeg /usr/sbin/screencapture; do + sudo sqlite3 "$SYS_TCC" \ + "INSERT OR REPLACE INTO access (service, client, client_type, auth_value, auth_reason, auth_version, csreq, policy_id, indirect_object_identifier_type, indirect_object_identifier, indirect_object_code_identity, flags, last_modified) VALUES ('kTCCServiceScreenCapture', '$client', 1, 2, 4, 1, NULL, NULL, 0, 'UNUSED', NULL, 0, $(date +%s));" 2>&1 || true + done + fi + USER_TCC="$HOME/Library/Application Support/com.apple.TCC/TCC.db" + if [ -f "$USER_TCC" ]; then + for client in "$FFMPEG_BIN" /opt/homebrew/bin/ffmpeg /usr/local/bin/ffmpeg; do + sqlite3 "$USER_TCC" \ + "INSERT OR REPLACE INTO access (service, client, client_type, auth_value, auth_reason, auth_version, csreq, policy_id, indirect_object_identifier_type, indirect_object_identifier, indirect_object_code_identity, flags, last_modified) VALUES ('kTCCServiceScreenCapture', '$client', 1, 2, 4, 1, NULL, NULL, 0, 'UNUSED', NULL, 0, $(date +%s));" 2>&1 || true + done + fi + APPROVALS_PLIST="$HOME/Library/Group Containers/group.com.apple.replayd/ScreenCaptureApprovals.plist" + if [ -d "$(dirname "$APPROVALS_PLIST")" ]; then + defaults write "$APPROVALS_PLIST" "$FFMPEG_BIN" -date "3000-01-01T00:00:00Z" 2>&1 || true + fi + + - name: Record real macOS and iOS sync video + if: ${{ inputs.platform == 'sync-video' }} + env: + BUILD_TAG: ${{ inputs.tag }} + DEVICE_FAMILY: ${{ inputs.device_family }} + ARTIFACT_DIR: ${{ github.workspace }}/artifact + SYNC_MARKER: real-cmux-left-right-cloud-demo + run: scripts/ci/record-real-sync-video.sh + + # --- iOS video: run a real simulator UI test while recording the screen --- + - name: Record iOS simulator video + if: ${{ inputs.platform == 'ios-video' }} + env: + BUILD_TAG: ${{ inputs.tag }} + DEVICE_FAMILY: ${{ inputs.device_family }} + TEST_FILTER: ${{ inputs.test_filter }} + PLATFORM: ${{ inputs.platform }} + run: | + set -euo pipefail + + ios_ready() { xcrun simctl runtime list 2>/dev/null | grep -qiE "iOS [0-9].*\(Ready\)"; } + if ! ios_ready; then + echo "iOS platform not registered; installing via downloadPlatform iOS" + xcodebuild -downloadPlatform iOS 2>&1 | tr '\r' '\n' | grep -ivE 'Preparing to download|registering download' | tail -8 || true + ios_ready || { echo "iOS platform still not registered; simulator video would fail" >&2; exit 1; } + fi + + ./scripts/ensure-ghosttykit.sh + + SIMULATOR_ENV="${RUNNER_TEMP:-$PWD/.tmp}/simulator-${DEVICE_FAMILY}.env" + mkdir -p "$(dirname "$SIMULATOR_ENV")" + python3 - <<'PY' > "$SIMULATOR_ENV" + import json + import os + import shlex + import subprocess + import sys + + family = os.environ["DEVICE_FAMILY"] + data = json.loads(subprocess.check_output(["xcrun", "simctl", "list", "devices", "available", "-j"])) + devices = [ + device + for runtimes in data.get("devices", {}).values() + for device in runtimes + if device.get("isAvailable", True) + ] + prefix = "iPad" if family == "ipad" else "iPhone" + preferred = ["iPad Pro 13-inch (M4)", "iPad Air 13-inch (M3)"] if family == "ipad" else ["iPhone 17", "iPhone 16"] + selected = next((d for name in preferred for d in devices if d.get("name") == name), None) + selected = selected or next((d for d in devices if d.get("name", "").startswith(prefix)), None) + created = False + if selected is None: + runtimes_data = json.loads(subprocess.check_output(["xcrun", "simctl", "list", "runtimes", "available", "-j"])) + runtimes = [ + runtime + for runtime in runtimes_data.get("runtimes", []) + if runtime.get("isAvailable", True) + and ( + runtime.get("platform") == "iOS" + or runtime.get("identifier", "").startswith("com.apple.CoreSimulator.SimRuntime.iOS") + ) + ] + if not runtimes: + raise SystemExit(f"No available iOS simulator runtime for {family}") + + def version_key(runtime): + return tuple(int(part) for part in runtime.get("version", "0").split(".") if part.isdigit()) + + runtime = sorted(runtimes, key=version_key, reverse=True)[0] + device_types_data = json.loads(subprocess.check_output(["xcrun", "simctl", "list", "devicetypes", "-j"])) + device_types = [ + device_type + for device_type in device_types_data.get("devicetypes", []) + if device_type.get("name", "").startswith(prefix) + ] + device_type = next((d for name in preferred for d in device_types if d.get("name") == name), None) + device_type = device_type or next(iter(device_types), None) + if device_type is None: + raise SystemExit(f"No available {prefix} simulator device type") + udid = subprocess.check_output([ + "xcrun", + "simctl", + "create", + f"cmux Video {device_type['name']}", + device_type["identifier"], + runtime["identifier"], + ], text=True).strip() + selected = {"udid": udid, "name": f"cmux Video {device_type['name']}"} + created = True + print( + f"Created {selected['name']} ({udid}) with {runtime['identifier']}", + file=sys.stderr, + ) + print(f"SIMULATOR_ID={shlex.quote(selected['udid'])}") + print(f"SIMULATOR_NAME={shlex.quote(selected['name'])}") + print(f"SIMULATOR_CREATED={'1' if created else '0'}") + PY + # shellcheck disable=SC1090 + . "$SIMULATOR_ENV" + + IOS_DERIVED_DATA="${RUNNER_TEMP:-$PWD/.tmp}/cmux-ios-video" + RESULT_BUNDLE="$GITHUB_WORKSPACE/artifact/cmux-ios-video.xcresult" + VIDEO_PATH="$GITHUB_WORKSPACE/artifact/cmux-ios-${BUILD_TAG}.mp4" + FINAL_VIDEO_PATH="$VIDEO_PATH" + SCREENSHOT_PATH="$GITHUB_WORKSPACE/artifact/cmux-ios-${BUILD_TAG}.png" + RECORD_LOG="$GITHUB_WORKSPACE/artifact/record-video.log" + TEST_LOG="$GITHUB_WORKSPACE/artifact/xcodebuild-test.log" + mkdir -p artifact "$IOS_DERIVED_DATA" + rm -rf "$RESULT_BUNDLE" "$VIDEO_PATH" "$SCREENSHOT_PATH" + + xcrun simctl shutdown "$SIMULATOR_ID" >/dev/null 2>&1 || true + xcrun simctl erase "$SIMULATOR_ID" + xcrun simctl boot "$SIMULATOR_ID" >/dev/null 2>&1 || true + xcrun simctl bootstatus "$SIMULATOR_ID" -b + xcrun simctl ui "$SIMULATOR_ID" appearance dark || true + + XCODEBUILD_BASE=( + -workspace ios/cmux.xcworkspace + -scheme cmux-ios + -destination "platform=iOS Simulator,id=$SIMULATOR_ID" + -derivedDataPath "$IOS_DERIVED_DATA" + ) + if [ -n "${TEST_FILTER:-}" ]; then + ONLY_TESTING=(-only-testing:"$TEST_FILTER") + else + ONLY_TESTING=(-only-testing:cmuxUITests/cmuxUITests/testStackAuthEntryUsesStableIdentifiers) + fi + + xcodebuild "${XCODEBUILD_BASE[@]}" "${ONLY_TESTING[@]}" build-for-testing + + recorder_pid="" + cleanup_video_run() { + if [ -n "$recorder_pid" ] && kill -0 "$recorder_pid" >/dev/null 2>&1; then + kill -INT "$recorder_pid" >/dev/null 2>&1 || true + wait "$recorder_pid" >/dev/null 2>&1 || true + fi + xcrun simctl shutdown "$SIMULATOR_ID" >/dev/null 2>&1 || true + if [ "${SIMULATOR_CREATED:-0}" = "1" ]; then + xcrun simctl delete "$SIMULATOR_ID" >/dev/null 2>&1 || true + fi + } + trap cleanup_video_run EXIT + + xcrun simctl io "$SIMULATOR_ID" recordVideo --codec=h264 --force "$VIDEO_PATH" 2> "$RECORD_LOG" & + recorder_pid="$!" + for _ in $(seq 1 80); do + grep -q "Recording started" "$RECORD_LOG" 2>/dev/null && break + sleep 0.25 + done + grep -q "Recording started" "$RECORD_LOG" 2>/dev/null || { + echo "simctl recordVideo did not report startup" >&2 + cat "$RECORD_LOG" >&2 || true + exit 1 + } + + test_rc=0 + set +e + xcodebuild "${XCODEBUILD_BASE[@]}" "${ONLY_TESTING[@]}" \ + -resultBundlePath "$RESULT_BUNDLE" \ + test-without-building 2>&1 | tee "$TEST_LOG" + test_rc="${PIPESTATUS[0]}" + set -e + if ! grep -Eq 'Executed [1-9][0-9]* tests?, with 0 failures' "$TEST_LOG"; then + echo "ios-video did not execute any selected UI tests" >&2 + test_rc=65 + fi + + xcrun simctl io "$SIMULATOR_ID" screenshot --type=png "$SCREENSHOT_PATH" || true + cleanup_video_run + trap - EXIT + + [ -s "$VIDEO_PATH" ] || { echo "video not produced: $VIDEO_PATH" >&2; exit 1; } + cat > "$GITHUB_WORKSPACE/artifact/metadata.json" <> "$GITHUB_STEP_SUMMARY" - name: Upload artifact + if: ${{ always() }} uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: name: reload-${{ inputs.tag }}-${{ inputs.platform }} diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift index 6c7ff3a98512..fd8acf1d7145 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift @@ -4,6 +4,7 @@ import CmuxMobileShell import CmuxMobileShellModel import CmuxMobileSupport import CmuxMobileWorkspace +import OSLog import SwiftUI #if os(iOS) @preconcurrency import UIKit @@ -11,6 +12,8 @@ import SwiftUI import AppKit #endif +private let mobileRootLog = Logger(subsystem: "ai.manaflow.cmux", category: "mobile.root") + struct CMUXMobileRootView: View { @Bindable var store: CMUXMobileShellStore @Environment(\.scenePhase) private var scenePhase @@ -96,6 +99,9 @@ struct CMUXMobileRootView: View { // so kick off the stored-Mac reconnect here too. Without this the // restoring gate could stay on RestoringSessionView forever because // nothing ever resolves `didFinishStoredMacReconnectAttempt`. + if connectUITestAttachURLIfNeeded() { + return + } reconnectStoredMacIfNeeded() } #if os(iOS) @@ -365,13 +371,16 @@ struct CMUXMobileRootView: View { private func connectAttachURL(_ rawURL: String) { guard !authManager.isRestoringSession else { + mobileRootLog.debug("parking attach URL while auth session restores") pendingAttachURL = rawURL return } + mobileRootLog.debug("connecting raw attach URL") didAuthenticateWithAttachTicket = true syncShellAuthentication(true) Task { let result = await store.connectPairingURLResult(rawURL) + mobileRootLog.debug("raw attach URL connection finished: \(attachResultDescription(result), privacy: .public)") if result == .needsUserApproval { isShowingAddDeviceSheet = true } @@ -464,22 +473,28 @@ struct CMUXMobileRootView: View { #if DEBUG // Auto-pair when an attach URL is supplied at launch. Two sources: // - CMUX_DOGFOOD_ATTACH_URL (UITestConfig.dogfoodAttachURL): NOT gated on - // mock data, so it fires against the real backend. The dev-launch - // tooling (scripts/mobile-dev-launch.sh, scripts/dev-setup.sh) signs in - // for real (CMUX_UITEST_STACK_* with CMUX_UITEST_MOCK_DATA=0) and wants - // the phone to auto-pair to the freshly built Mac dev app. With mock - // off, UITestConfig.attachURL is always nil, so this dedicated accessor - // is what un-breaks real-backend auto-pair. + // mock data, so it fires against the real backend. A raw attach URL is + // handled through the same temporary-auth path as `.onOpenURL`, so + // cloud/dev launches do not need Stack credentials just to consume a + // Mac-issued attach ticket. // - CMUX_UITEST_ATTACH_URL (UITestConfig.attachURL): gated on mock data, // kept intact for the XCUITest harness. // No-op unless one of those env vars is set, so normal launches are // unaffected. guard !didConsumeUITestAttachURL, - isAuthenticated, let attachURL = UITestConfig.dogfoodAttachURL ?? UITestConfig.attachURL else { return false } didConsumeUITestAttachURL = true + mobileRootLog.debug("consuming launch attach URL") + if isRawAttachURL(attachURL) { + connectAttachURL(attachURL) + return true + } + guard isAuthenticated else { + pendingAttachURL = attachURL + return true + } Task { await store.connectPairingURL(attachURL) } @@ -488,4 +503,17 @@ struct CMUXMobileRootView: View { return false #endif } + + private func attachResultDescription(_ result: MobilePairingURLConnectionResult) -> String { + switch result { + case .connected: + return "connected" + case .failed: + return "failed" + case .needsUserApproval: + return "needsUserApproval" + case .superseded: + return "superseded" + } + } } diff --git a/Packages/iOS/CmuxMobileSupport/Sources/CmuxMobileSupport/UITestConfig.swift b/Packages/iOS/CmuxMobileSupport/Sources/CmuxMobileSupport/UITestConfig.swift index 49ea7307eb9f..3cdc0e250536 100644 --- a/Packages/iOS/CmuxMobileSupport/Sources/CmuxMobileSupport/UITestConfig.swift +++ b/Packages/iOS/CmuxMobileSupport/Sources/CmuxMobileSupport/UITestConfig.swift @@ -45,7 +45,11 @@ public struct UITestConfig { /// is always `nil`, so a dedicated, not-mock-gated accessor is required for the /// real-backend auto-pair path to fire. DEBUG-only; always `nil` in release. public static var dogfoodAttachURL: String? { - dogfoodAttachURL(from: ProcessInfo.processInfo.environment) + dogfoodAttachURL( + from: ProcessInfo.processInfo.environment, + arguments: ProcessInfo.processInfo.arguments, + defaults: .standard + ) } /// The dogfood attach URL for an explicit environment, not gated on mock data. @@ -53,13 +57,29 @@ public struct UITestConfig { /// - Parameter env: The environment dictionary to read. /// - Returns: The trimmed value of `CMUX_DOGFOOD_ATTACH_URL` when present and /// non-empty; otherwise `nil`. Always `nil` in release builds. - public static func dogfoodAttachURL(from env: [String: String]) -> String? { + public static func dogfoodAttachURL( + from env: [String: String], + arguments: [String] = [] + ) -> String? { + dogfoodAttachURL(from: env, arguments: arguments, defaults: nil) + } + + static func dogfoodAttachURL( + from env: [String: String], + arguments: [String] = [], + defaults: UserDefaults? + ) -> String? { #if DEBUG // Read the env directly, NOT through the mock-gated value(for:), so the // URL is returned with CMUX_UITEST_MOCK_DATA=0 (the real-backend // dev-launch path) and iOS auto-pair actually fires. - let value = env["CMUX_DOGFOOD_ATTACH_URL"]?.trimmingCharacters(in: .whitespacesAndNewlines) - return value?.isEmpty == false ? value : nil + if let value = trimmedNonEmpty(env["CMUX_DOGFOOD_ATTACH_URL"]) { + return value + } + if let value = argumentValue(for: "--cmux-dogfood-attach-url", arguments: arguments) { + return value + } + return trimmedNonEmpty(defaults?.string(forKey: "CMUX_DOGFOOD_ATTACH_URL")) #else return nil #endif @@ -139,4 +159,17 @@ public struct UITestConfig { private static func value(for key: String) -> String? { value(for: key, env: ProcessInfo.processInfo.environment) } + + private static func trimmedNonEmpty(_ value: String?) -> String? { + let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed?.isEmpty == false ? trimmed : nil + } + + private static func argumentValue(for key: String, arguments: [String]) -> String? { + guard let index = arguments.firstIndex(of: key), + arguments.indices.contains(arguments.index(after: index)) else { + return nil + } + return trimmedNonEmpty(arguments[arguments.index(after: index)]) + } } diff --git a/Packages/iOS/CmuxMobileSupport/Tests/CmuxMobileSupportTests/UITestConfigTests.swift b/Packages/iOS/CmuxMobileSupport/Tests/CmuxMobileSupportTests/UITestConfigTests.swift index 8f97c8c970ad..e995d1188e29 100644 --- a/Packages/iOS/CmuxMobileSupport/Tests/CmuxMobileSupportTests/UITestConfigTests.swift +++ b/Packages/iOS/CmuxMobileSupport/Tests/CmuxMobileSupportTests/UITestConfigTests.swift @@ -1,4 +1,5 @@ import Testing +import Foundation @testable import CmuxMobileSupport @Suite struct UITestConfigTests { @@ -103,6 +104,89 @@ import Testing #endif } + @Test func dogfoodAttachURLCanComeFromLaunchArgument() { + let arguments = [ + "/path/cmux", + "--cmux-dogfood-attach-url", + " cmux-ios-dev://attach?v=1&payload=arg ", + ] + #if DEBUG + #expect( + UITestConfig.dogfoodAttachURL(from: [:], arguments: arguments) + == "cmux-ios-dev://attach?v=1&payload=arg" + ) + #else + #expect(UITestConfig.dogfoodAttachURL(from: [:], arguments: arguments) == nil) + #endif + } + + @Test func dogfoodAttachURLEnvironmentWinsOverLaunchArgument() { + let env = ["CMUX_DOGFOOD_ATTACH_URL": "cmux-ios://attach?v=1&payload=env"] + let arguments = [ + "/path/cmux", + "--cmux-dogfood-attach-url", + "cmux-ios-dev://attach?v=1&payload=arg", + ] + #if DEBUG + #expect( + UITestConfig.dogfoodAttachURL(from: env, arguments: arguments) + == "cmux-ios://attach?v=1&payload=env" + ) + #else + #expect(UITestConfig.dogfoodAttachURL(from: env, arguments: arguments) == nil) + #endif + } + + @Test func dogfoodAttachURLCanComeFromUserDefaults() { + let (suiteName, defaults) = temporaryDefaults() + defaults.set(" cmux-ios-dev://attach?v=1&payload=defaults ", forKey: "CMUX_DOGFOOD_ATTACH_URL") + defer { defaults.removePersistentDomain(forName: suiteName) } + + #if DEBUG + #expect( + UITestConfig.dogfoodAttachURL(from: [:], defaults: defaults) + == "cmux-ios-dev://attach?v=1&payload=defaults" + ) + #else + #expect(UITestConfig.dogfoodAttachURL(from: [:], defaults: defaults) == nil) + #endif + } + + @Test func dogfoodAttachURLLaunchArgumentWinsOverUserDefaults() { + let (suiteName, defaults) = temporaryDefaults() + defaults.set("cmux-ios-dev://attach?v=1&payload=defaults", forKey: "CMUX_DOGFOOD_ATTACH_URL") + defer { defaults.removePersistentDomain(forName: suiteName) } + let arguments = [ + "/path/cmux", + "--cmux-dogfood-attach-url", + "cmux-ios-dev://attach?v=1&payload=arg", + ] + + #if DEBUG + #expect( + UITestConfig.dogfoodAttachURL(from: [:], arguments: arguments, defaults: defaults) + == "cmux-ios-dev://attach?v=1&payload=arg" + ) + #else + #expect(UITestConfig.dogfoodAttachURL(from: [:], arguments: arguments, defaults: defaults) == nil) + #endif + } + + @Test func dogfoodAttachURLIsNilWhenLaunchArgumentValueIsMissingOrBlank() { + #expect( + UITestConfig.dogfoodAttachURL( + from: [:], + arguments: ["/path/cmux", "--cmux-dogfood-attach-url"] + ) == nil + ) + #expect( + UITestConfig.dogfoodAttachURL( + from: [:], + arguments: ["/path/cmux", "--cmux-dogfood-attach-url", " "] + ) == nil + ) + } + @Test func dogfoodAttachURLIsNilWhenAbsent() { #expect(UITestConfig.dogfoodAttachURL(from: [:]) == nil) } @@ -111,4 +195,15 @@ import Testing let env = ["CMUX_DOGFOOD_ATTACH_URL": " "] #expect(UITestConfig.dogfoodAttachURL(from: env) == nil) } + + private func temporaryDefaults() -> (String, UserDefaults) { + let name = defaultsSuiteName + let defaults = UserDefaults(suiteName: name)! + defaults.removePersistentDomain(forName: name) + return (name, defaults) + } + + private var defaultsSuiteName: String { + "UITestConfigTests.\(UUID().uuidString)" + } } diff --git a/scripts/ci/record-real-sync-video.sh b/scripts/ci/record-real-sync-video.sh new file mode 100755 index 000000000000..58f428878ace --- /dev/null +++ b/scripts/ci/record-real-sync-video.sh @@ -0,0 +1,504 @@ +#!/usr/bin/env bash +set -euo pipefail + +BUILD_TAG="${BUILD_TAG:?BUILD_TAG is required}" +DEVICE_FAMILY="${DEVICE_FAMILY:-iphone}" +ARTIFACT_DIR="${ARTIFACT_DIR:-$PWD/artifact}" +SYNC_MARKER="${SYNC_MARKER:-cmux-real-sync-video}" +DEV_STACK_AUTH_TOKEN="${CMUX_MOBILE_DEV_STACK_AUTH_TOKEN:-cmux-cloud-sync-video-token}" + +mkdir -p "$ARTIFACT_DIR" + +phase() { + echo "==> $*" +} + +run_with_timeout() { + local seconds="$1" + shift + python3 - "$seconds" "$@" <<'PY' +import subprocess +import sys + +timeout = float(sys.argv[1]) +cmd = sys.argv[2:] +try: + raise SystemExit(subprocess.run(cmd, timeout=timeout).returncode) +except subprocess.TimeoutExpired: + print(f"command timed out after {timeout:g}s: {' '.join(cmd)}", file=sys.stderr) + raise SystemExit(124) +PY +} + +sanitize_tag() { + local raw="$1" + local cleaned + cleaned="$(printf '%s' "$raw" | tr '[:upper:]' '[:lower:]' | sed -E 's/[^a-z0-9]+/-/g; s/^-+//; s/-+$//; s/-+/-/g')" + [[ -n "$cleaned" ]] || cleaned="dev" + printf '%s' "$cleaned" +} + +sanitize_bundle() { + local raw="$1" + local cleaned + cleaned="$(printf '%s' "$raw" | tr '[:upper:]' '[:lower:]' | sed -E 's/[^a-z0-9]+/./g; s/^\.+//; s/\.+$//; s/\.+/./g')" + [[ -n "$cleaned" ]] || cleaned="dev" + printf '%s' "$cleaned" +} + +TAG_SLUG="$(sanitize_tag "$BUILD_TAG")" +TAG_BUNDLE="$(sanitize_bundle "$BUILD_TAG")" +MAC_BUNDLE_ID="com.cmuxterm.app.debug.${TAG_BUNDLE}" +IOS_BUNDLE_ID="dev.cmux.ios.${TAG_SLUG}" +SOCKET_PATH="/tmp/cmux-debug-${TAG_SLUG}.sock" +MAC_RAW_VIDEO="$ARTIFACT_DIR/cmux-macos-${BUILD_TAG}.mp4" +IOS_RAW_VIDEO="$ARTIFACT_DIR/cmux-ios-${BUILD_TAG}.mp4" +FINAL_VIDEO="$ARTIFACT_DIR/cmux-real-sync-left-right-${BUILD_TAG}.mp4" +MAC_RECORD_LOG="$ARTIFACT_DIR/macos-record.log" +MAC_FRAME_DIR="$ARTIFACT_DIR/macos-frames" +IOS_RECORD_LOG="$ARTIFACT_DIR/ios-record.log" +IOS_SIMULATOR_LOG="$ARTIFACT_DIR/ios-simulator.log" +IOS_SEEDED_DEFAULTS="$ARTIFACT_DIR/ios-seeded-defaults.txt" +METADATA_PATH="$ARTIFACT_DIR/metadata.json" + +MAC_RECORDER_PID="" +IOS_RECORDER_PID="" +IOS_LOG_PID="" +SIMULATOR_ID="" +SIMULATOR_CREATED="0" + +stop_pid_bounded() { + local pid="$1" + local signal="${2:-INT}" + if [[ -z "$pid" ]] || ! kill -0 "$pid" >/dev/null 2>&1; then + return 0 + fi + kill "-$signal" "$pid" >/dev/null 2>&1 || true + for _ in $(seq 1 25); do + if ! kill -0 "$pid" >/dev/null 2>&1; then + wait "$pid" >/dev/null 2>&1 || true + return 0 + fi + sleep 0.2 + done + kill -KILL "$pid" >/dev/null 2>&1 || true + wait "$pid" >/dev/null 2>&1 || true +} + +cleanup() { + set +e + stop_pid_bounded "$MAC_RECORDER_PID" INT + stop_pid_bounded "$IOS_RECORDER_PID" INT + stop_pid_bounded "$IOS_LOG_PID" INT + if [[ -n "$SIMULATOR_ID" ]]; then + xcrun simctl terminate "$SIMULATOR_ID" "$IOS_BUNDLE_ID" >/dev/null 2>&1 || true + xcrun simctl shutdown "$SIMULATOR_ID" >/dev/null 2>&1 || true + if [[ "$SIMULATOR_CREATED" == "1" ]]; then + xcrun simctl delete "$SIMULATOR_ID" >/dev/null 2>&1 || true + fi + fi + osascript -e "tell application id \"$MAC_BUNDLE_ID\" to quit" >/dev/null 2>&1 || true + pkill -f "cmux DEV ${TAG_SLUG}.app/Contents/MacOS/cmux DEV" >/dev/null 2>&1 || true +} +trap cleanup EXIT + +require_ffmpeg() { + if ! command -v ffmpeg >/dev/null 2>&1; then + brew install ffmpeg + fi + command -v ffmpeg >/dev/null 2>&1 +} + +select_simulator() { + python3 - "$DEVICE_FAMILY" <<'PY' +import json +import shlex +import subprocess +import sys + +family = sys.argv[1] +data = json.loads(subprocess.check_output(["xcrun", "simctl", "list", "devices", "available", "-j"])) +devices = [ + device + for runtimes in data.get("devices", {}).values() + for device in runtimes + if device.get("isAvailable", True) +] +prefix = "iPad" if family == "ipad" else "iPhone" +preferred = ["iPad Pro 13-inch (M4)", "iPad Air 13-inch (M3)"] if family == "ipad" else ["iPhone 17", "iPhone 16"] +selected = next((d for name in preferred for d in devices if d.get("name") == name), None) +selected = selected or next((d for d in devices if d.get("name", "").startswith(prefix)), None) +created = False +if selected is None: + runtimes_data = json.loads(subprocess.check_output(["xcrun", "simctl", "list", "runtimes", "available", "-j"])) + runtimes = [ + runtime for runtime in runtimes_data.get("runtimes", []) + if runtime.get("isAvailable", True) + and (runtime.get("platform") == "iOS" or runtime.get("identifier", "").startswith("com.apple.CoreSimulator.SimRuntime.iOS")) + ] + if not runtimes: + raise SystemExit(f"No available iOS simulator runtime for {family}") + runtime = sorted(runtimes, key=lambda r: tuple(int(p) for p in r.get("version", "0").split(".") if p.isdigit()), reverse=True)[0] + types_data = json.loads(subprocess.check_output(["xcrun", "simctl", "list", "devicetypes", "-j"])) + types = [device_type for device_type in types_data.get("devicetypes", []) if device_type.get("name", "").startswith(prefix)] + device_type = next((d for name in preferred for d in types if d.get("name") == name), None) or next(iter(types), None) + if device_type is None: + raise SystemExit(f"No available {prefix} simulator device type") + udid = subprocess.check_output([ + "xcrun", "simctl", "create", f"cmux Real Video {device_type['name']}", + device_type["identifier"], runtime["identifier"], + ], text=True).strip() + selected = {"udid": udid, "name": f"cmux Real Video {device_type['name']}"} + created = True +print(f"SIMULATOR_ID={shlex.quote(selected['udid'])}") +print(f"SIMULATOR_NAME={shlex.quote(selected['name'])}") +print(f"SIMULATOR_CREATED={'1' if created else '0'}") +PY +} + +wait_for_socket() { + phase "waiting for tagged socket $SOCKET_PATH" + for _ in $(seq 1 120); do + if [[ -S "$SOCKET_PATH" ]]; then + phase "tagged socket is ready" + return 0 + fi + sleep 0.5 + done + echo "Tagged cmux socket did not appear: $SOCKET_PATH" >&2 + return 1 +} + +cmux_tagged() { + CMUX_QUIET=1 CMUX_TAG="$BUILD_TAG" scripts/cmux-debug-cli.sh "$@" +} + +json_field() { + python3 -c ' +import json +import sys + +key = sys.argv[1] +data = json.load(sys.stdin) +value = data.get(key) +if value is None: + value = data.get(key.replace("_id", "_ref")) +if value is None: + raise SystemExit(1) +print(value) +' "$1" +} + +mint_attach_url() { + local workspace_id="$1" + local terminal_id="$2" + local payload + local params + params="$(python3 - "$workspace_id" "$terminal_id" <<'PY' +import json +import sys +print(json.dumps({ + "ttl_seconds": 900, + "workspace_id": sys.argv[1], + "terminal_id": sys.argv[2], + "route_kind": "debug_loopback", +}, separators=(",", ":"))) +PY +)" + for _ in $(seq 1 40); do + payload="$(cmux_tagged rpc mobile.attach_ticket.create "$params" 2>/dev/null || true)" + if [[ -n "$payload" ]]; then + REPO_ROOT="$PWD" PAYLOAD="$payload" node --input-type=module <<'NODE' +import path from "node:path"; +import { pathToFileURL } from "node:url"; + +const { buildAttachURL } = await import( + pathToFileURL(path.join(process.env.REPO_ROOT, "scripts", "lib", "attach-url.mjs")).href +); +const { attachURL } = buildAttachURL(JSON.parse(process.env.PAYLOAD), { routeKind: "debug_loopback" }); +process.stdout.write(attachURL); +NODE + return 0 + fi + sleep 0.5 + done + return 1 +} + +start_macos_recording() { + rm -rf "$MAC_FRAME_DIR" + mkdir -p "$MAC_FRAME_DIR" + : > "$MAC_RECORD_LOG" + ( + set +e + i=0 + failures=0 + while true; do + frame="$(printf "%s/frame-%05d.png" "$MAC_FRAME_DIR" "$i")" + label="$(printf "sync-%05d" "$i")" + params="$(python3 - "$label" <<'PY' +import json +import sys +print(json.dumps({"label": sys.argv[1]}, separators=(",", ":"))) +PY +)" + payload="$(cmux_tagged rpc debug.window.screenshot "$params" 2>>"$MAC_RECORD_LOG")" + snapshot_path="$(printf '%s\n' "$payload" | json_field path 2>/dev/null)" + if [[ -n "$snapshot_path" && -f "$snapshot_path" ]]; then + cp "$snapshot_path" "$frame" + failures=0 + else + failures=$((failures + 1)) + echo "debug.window.screenshot failed payload=$payload" >&2 + if [[ "$failures" -ge 10 ]]; then + exit 1 + fi + fi + i=$((i + 1)) + sleep 0.25 + done + ) >"$MAC_RECORD_LOG" 2>&1 & + MAC_RECORDER_PID="$!" + for _ in $(seq 1 40); do + if [[ "$(find "$MAC_FRAME_DIR" -name 'frame-*.png' -type f | wc -l | tr -d ' ')" -ge 2 ]]; then + return 0 + fi + if ! kill -0 "$MAC_RECORDER_PID" >/dev/null 2>&1; then + tail -80 "$MAC_RECORD_LOG" >&2 || true + return 1 + fi + sleep 0.25 + done + stop_pid_bounded "$MAC_RECORDER_PID" TERM + MAC_RECORDER_PID="" + tail -80 "$MAC_RECORD_LOG" >&2 || true + return 1 +} + +start_ios_recording() { + xcrun simctl io "$SIMULATOR_ID" recordVideo --codec=h264 --force "$IOS_RAW_VIDEO" 2>"$IOS_RECORD_LOG" & + IOS_RECORDER_PID="$!" + for _ in $(seq 1 80); do + grep -q "Recording started" "$IOS_RECORD_LOG" 2>/dev/null && return 0 + sleep 0.25 + done + stop_pid_bounded "$IOS_RECORDER_PID" TERM + IOS_RECORDER_PID="" + tail -80 "$IOS_RECORD_LOG" >&2 || true + return 1 +} + +start_ios_log_capture() { + rm -f "$IOS_SIMULATOR_LOG" + xcrun simctl spawn "$SIMULATOR_ID" log stream \ + --style compact \ + --level debug \ + --predicate 'process == "cmux" OR subsystem == "ai.manaflow.cmux"' \ + >"$IOS_SIMULATOR_LOG" 2>&1 & + IOS_LOG_PID="$!" + sleep 1 +} + +stop_recorders() { + stop_pid_bounded "$IOS_RECORDER_PID" INT + IOS_RECORDER_PID="" + stop_pid_bounded "$MAC_RECORDER_PID" INT + MAC_RECORDER_PID="" + stop_pid_bounded "$IOS_LOG_PID" INT + IOS_LOG_PID="" + local frame_count + frame_count="$(find "$MAC_FRAME_DIR" -name 'frame-*.png' -type f 2>/dev/null | wc -l | tr -d ' ')" + if [[ "$frame_count" -ge 2 && ! -s "$MAC_RAW_VIDEO" ]]; then + ffmpeg -hide_banner -y -framerate 4 -pattern_type glob -i "$MAC_FRAME_DIR/frame-*.png" \ + -vf "scale=trunc(iw/2)*2:trunc(ih/2)*2" \ + -c:v libx264 -preset ultrafast -pix_fmt yuv420p "$MAC_RAW_VIDEO" >>"$MAC_RECORD_LOG" 2>&1 + fi +} + +stitch_videos() { + ffmpeg -hide_banner -y \ + -i "$MAC_RAW_VIDEO" \ + -i "$IOS_RAW_VIDEO" \ + -filter_complex "\ +[0:v]trim=duration=24,setpts=PTS-STARTPTS,scale=1280:720:force_original_aspect_ratio=decrease,pad=1280:720:(ow-iw)/2:(oh-ih)/2:color=0x101418,fps=30[mac];\ +[1:v]trim=duration=24,setpts=PTS-STARTPTS,scale=540:960:force_original_aspect_ratio=decrease,pad=540:960:(ow-iw)/2:(oh-ih)/2:color=0x101418,fps=30[ios];\ +color=c=0x0b0f14:s=1920x1080:r=30:d=24[bg];\ +[bg][mac]overlay=x=40:y=(H-h)/2[tmp];\ +[tmp][ios]overlay=x=W-w-40:y=(H-h)/2[out]" \ + -map "[out]" -an -c:v libx264 -pix_fmt yuv420p -movflags +faststart "$FINAL_VIDEO" + [[ -s "$FINAL_VIDEO" ]] +} + +phase "checking ffmpeg" +require_ffmpeg + +ios_ready() { xcrun simctl runtime list 2>/dev/null | grep -qiE "iOS [0-9].*\(Ready\)"; } +if ! ios_ready; then + phase "installing iOS simulator platform" + xcodebuild -downloadPlatform iOS 2>&1 | tr '\r' '\n' | grep -ivE 'Preparing to download|registering download' | tail -8 || true + ios_ready || { echo "iOS platform is not registered" >&2; exit 1; } +fi + +phase "selecting simulator" +eval "$(select_simulator)" +export SIMULATOR_ID SIMULATOR_NAME SIMULATOR_CREATED +phase "booting simulator $SIMULATOR_NAME ($SIMULATOR_ID)" +xcrun simctl shutdown "$SIMULATOR_ID" >/dev/null 2>&1 || true +xcrun simctl erase "$SIMULATOR_ID" +xcrun simctl boot "$SIMULATOR_ID" >/dev/null 2>&1 || true +run_with_timeout 120 xcrun simctl bootstatus "$SIMULATOR_ID" -b +xcrun simctl ui "$SIMULATOR_ID" appearance dark || true + +phase "enabling macOS mobile pairing host" +defaults write "$MAC_BUNDLE_ID" mobile.iOSPairingHost.enabled -bool true +./scripts/download-prebuilt-ghosttykit.sh || ./scripts/ensure-ghosttykit.sh + +MAC_RELOAD_LOG="$ARTIFACT_DIR/reload-macos.log" +phase "building tagged macOS cmux" +run_with_timeout 600 bash -c './scripts/reload.sh --tag "$1" --swift-frontend-workaround 2>&1 | tee "$2"' bash "$BUILD_TAG" "$MAC_RELOAD_LOG" +MAC_APP_PATH="$(awk '/^App path:/{getline; sub(/^ /,""); print; exit}' "$MAC_RELOAD_LOG")" +[[ -n "$MAC_APP_PATH" && -d "$MAC_APP_PATH" ]] || { echo "could not locate built macOS app from $MAC_RELOAD_LOG" >&2; exit 1; } + +phase "launching tagged macOS cmux" +run_with_timeout 30 open "$MAC_APP_PATH" +wait_for_socket + +phase "activating tagged macOS cmux" +run_with_timeout 15 osascript -e "tell application id \"$MAC_BUNDLE_ID\" to activate" >/dev/null 2>&1 || true + +phase "creating real cmux terminal workspace" +WORKSPACE_OUTPUT="$ARTIFACT_DIR/workspace-create-output.txt" +cmux_tagged --id-format uuids workspace create --name "iOS sync demo" --cwd "$PWD" --focus true --json > "$WORKSPACE_OUTPUT" +WORKSPACE_JSON="$(cat "$WORKSPACE_OUTPUT")" +WORKSPACE_ID="$(printf '%s\n' "$WORKSPACE_JSON" | json_field workspace_id)" +SURFACE_ID="$(printf '%s\n' "$WORKSPACE_JSON" | json_field surface_id)" + +phase "configuring debug mobile Stack auth token" +DEV_STACK_AUTH_PARAMS="$(python3 - "$DEV_STACK_AUTH_TOKEN" <<'PY' +import json +import sys + +print(json.dumps({"token": sys.argv[1]}, separators=(",", ":"))) +PY +)" +cmux_tagged rpc mobile.dev_stack_auth.configure "$DEV_STACK_AUTH_PARAMS" >/dev/null + +for _ in $(seq 1 40); do + if cmux_tagged read-screen --workspace "$WORKSPACE_ID" --surface "$SURFACE_ID" --lines 5 >/dev/null 2>&1; then + break + fi + sleep 0.25 +done + +phase "minting terminal-scoped attach URL" +ATTACH_URL="$(mint_attach_url "$WORKSPACE_ID" "$SURFACE_ID")" +[[ -n "$ATTACH_URL" ]] || { echo "Failed to mint attach URL" >&2; exit 1; } + +phase "building and installing real iOS app" +run_with_timeout 600 ios/scripts/reload.sh --tag "$BUILD_TAG" --simulator "$SIMULATOR_NAME" --no-launch +phase "seeding iOS attach launch defaults" +IOS_DATA_CONTAINER="$(run_with_timeout 30 xcrun simctl get_app_container "$SIMULATOR_ID" "$IOS_BUNDLE_ID" data)" +IOS_PREFS_PLIST="$IOS_DATA_CONTAINER/Library/Preferences/${IOS_BUNDLE_ID}.plist" +mkdir -p "$(dirname "$IOS_PREFS_PLIST")" +python3 - "$IOS_PREFS_PLIST" "$ATTACH_URL" <<'PY' +import plistlib +import sys +from pathlib import Path + +path = Path(sys.argv[1]) +attach_url = sys.argv[2] +data = {} +if path.exists(): + with path.open("rb") as handle: + data = plistlib.load(handle) +data["CMUX_DOGFOOD_ATTACH_URL"] = attach_url +with path.open("wb") as handle: + plistlib.dump(data, handle) +PY +run_with_timeout 30 xcrun simctl spawn "$SIMULATOR_ID" defaults write "$IOS_BUNDLE_ID" CMUX_DOGFOOD_ATTACH_URL "$ATTACH_URL" +run_with_timeout 30 xcrun simctl spawn "$SIMULATOR_ID" launchctl setenv CMUX_DOGFOOD_ATTACH_URL "$ATTACH_URL" +python3 - "$IOS_PREFS_PLIST" "$IOS_SEEDED_DEFAULTS" <<'PY' +import plistlib +import sys +from pathlib import Path + +path = Path(sys.argv[1]) +out = Path(sys.argv[2]) +has_attach_url = False +attach_url_length = 0 +if path.exists(): + with path.open("rb") as handle: + data = plistlib.load(handle) + value = data.get("CMUX_DOGFOOD_ATTACH_URL") + has_attach_url = isinstance(value, str) and bool(value.strip()) + attach_url_length = len(value) if isinstance(value, str) else 0 +out.write_text(f"hasAttachURL={str(has_attach_url).lower()}\nattachURLLength={attach_url_length}\n") +PY +start_ios_log_capture +phase "launching and auto-attaching real iOS app" +run_with_timeout 30 env \ + SIMCTL_CHILD_CMUX_UITEST_MOCK_DATA=0 \ + SIMCTL_CHILD_CMUX_UITEST_AUTH_FIXTURE=1 \ + SIMCTL_CHILD_CMUX_UITEST_AUTH_USER_ID=cloud-recording-user \ + SIMCTL_CHILD_CMUX_UITEST_AUTH_EMAIL=cloud-recording@cmux.local \ + "SIMCTL_CHILD_CMUX_UITEST_AUTH_NAME=Cloud Recording" \ + "SIMCTL_CHILD_CMUX_MOBILE_DEV_STACK_AUTH_TOKEN=$DEV_STACK_AUTH_TOKEN" \ + SIMCTL_CHILD_CMUX_MOBILE_SOAK_OPEN_SELECTED_WORKSPACE=1 \ + "SIMCTL_CHILD_CMUX_DOGFOOD_ATTACH_URL=$ATTACH_URL" \ + xcrun simctl launch --terminate-running-process "$SIMULATOR_ID" "$IOS_BUNDLE_ID" \ + --cmux-dogfood-attach-url "$ATTACH_URL" +sleep 18 + +phase "starting macOS and iOS recordings" +start_macos_recording +start_ios_recording + +phase "sending synced terminal input through real macOS cmux" +cmux_tagged send --workspace "$WORKSPACE_ID" --surface "$SURFACE_ID" -- "clear\r" +sleep 1 +cmux_tagged send --workspace "$WORKSPACE_ID" --surface "$SURFACE_ID" -- "echo real cmux desktop to iOS\r" +sleep 1 +cmux_tagged send --workspace "$WORKSPACE_ID" --surface "$SURFACE_ID" -- "echo ${SYNC_MARKER}\r" +sleep 4 +cmux_tagged send --workspace "$WORKSPACE_ID" --surface "$SURFACE_ID" -- "echo same terminal, two clients\r" +sleep 6 + +cmux_tagged read-screen --workspace "$WORKSPACE_ID" --surface "$SURFACE_ID" --lines 20 > "$ARTIFACT_DIR/macos-read-screen.txt" || true +xcrun simctl io "$SIMULATOR_ID" screenshot --type=png "$ARTIFACT_DIR/ios-final.png" || true +find "$MAC_FRAME_DIR" -name 'frame-*.png' -type f | sort | tail -1 | while read -r frame; do + cp "$frame" "$ARTIFACT_DIR/macos-final.png" +done + +phase "stopping recorders" +stop_recorders + +[[ -s "$MAC_RAW_VIDEO" ]] || { echo "macOS recording missing: $MAC_RAW_VIDEO" >&2; exit 1; } +[[ -s "$IOS_RAW_VIDEO" ]] || { echo "iOS recording missing: $IOS_RAW_VIDEO" >&2; exit 1; } +phase "stitching left-right video" +stitch_videos + +phase "writing metadata" +python3 - "$METADATA_PATH" <