Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix: switch macOS versions through the normal app launch (#7552)

Ezra Ellette7f875d6f3977
diff --git a/.github/scripts/build-macos-update-recovery.sh b/.github/scripts/build-macos-update-recovery.sh
deleted file mode 100644
index e016183b9..000000000
--- a/.github/scripts/build-macos-update-recovery.sh
+++ /dev/null
@@ -1,50 +0,0 @@
-#!/usr/bin/env bash
-# screenpipe — AI that knows everything you've seen, said, or heard
-# https://screenpipe.com
-set -euo pipefail
-
-app="${1:?expected signed Screenpipe app}"
-output="${2:?expected companion output directory}"
-identity="${APPLE_SIGNING_IDENTITY:?expected signing identity}"
-script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-codesign --verify --deep --strict "$app"
-requirement="$(codesign -d -r- "$app" 2>&1 | sed -n 's/^designated => //p')"
-[[ -n "$requirement" ]] || { echo 'app has no designated signing requirement' >&2; exit 1; }
-helper="$output/Open updated Screenpipe.app"
-mkdir -p "$helper/Contents/MacOS"
-
-python3 - "$app" "$helper" "$requirement" <<'PY'
-import pathlib, plistlib, sys
-app, helper = map(pathlib.Path, sys.argv[1:3])
-source = plistlib.loads((app / 'Contents/Info.plist').read_bytes())
-plist = {
- 'CFBundleIdentifier': source['CFBundleIdentifier'] + '.update-recovery',
- 'CFBundleName': 'Open updated Screenpipe',
- 'CFBundleExecutable': 'update-recovery',
- 'CFBundlePackageType': 'APPL',
- 'CFBundleVersion': source['CFBundleVersion'],
- 'CFBundleShortVersionString': source['CFBundleShortVersionString'],
- 'LSMinimumSystemVersion': '12.0',
- 'LSUIElement': True,
- 'ScreenpipeTargetRequirement': sys.argv[3],
- 'ScreenpipeTargetBundleName': app.name,
- 'ScreenpipeManualHandoffProtocol': source['ScreenpipeManualHandoffProtocol'],
-}
-(helper / 'Contents/Info.plist').write_bytes(plistlib.dumps(plist))
-PY
-executable="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleExecutable' "$app/Contents/Info.plist")"
-architectures="$(lipo -archs "$app/Contents/MacOS/$executable")"
-objects=()
-for architecture in $architectures; do
- object="$output/update-recovery-$architecture"
- xcrun swiftc -O -swift-version 5 -target "$architecture-apple-macos12.0" \
- "$script_dir/macos-update-recovery.swift" -o "$object"
- objects+=("$object")
-done
-lipo -create "${objects[@]}" -output "$helper/Contents/MacOS/update-recovery"
-rm "${objects[@]}"
-timestamp=(--timestamp)
-# VM development certificates cannot obtain Apple's production timestamp.
-[[ "${SCREENPIPE_RECOVERY_DEVELOPMENT:-0}" == 1 ]] && timestamp=(--timestamp=none)
-codesign --force --options runtime "${timestamp[@]}" --sign "$identity" "$helper"
-codesign --verify --deep --strict "$helper"
diff --git a/.github/scripts/create-headless-dmg.sh b/.github/scripts/create-headless-dmg.sh
index 23c811932..6da4b2f43 100755
--- a/.github/scripts/create-headless-dmg.sh
+++ b/.github/scripts/create-headless-dmg.sh
@@ -5,19 +5,14 @@
set -euo pipefail
-if [[ $# -lt 3 || $# -gt 4 ]]; then
- echo "usage: create-headless-dmg.sh <app-path> <output-dmg> <volume-name> [recovery-app]" >&2
+if [[ $# -ne 3 ]]; then
+ echo "usage: create-headless-dmg.sh <app-path> <output-dmg> <volume-name>" >&2
exit 2
fi
app_path="$1"
output_dmg="$2"
volume_name="$3"
-recovery_path="${4:-}"
-if [[ -n "$recovery_path" ]]; then
- [[ -d "$recovery_path" ]] || { echo "recovery launcher missing: $recovery_path" >&2; exit 1; }
- codesign --verify --deep --strict "$recovery_path"
-fi
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
repo_root="$(cd "$script_dir/../.." && pwd)"
background_path="$repo_root/apps/screenpipe-app-tauri/src-tauri/assets/dmg-background.png"
@@ -35,6 +30,5 @@ dmgbuild \
-s "$settings_path" \
-D "app_path=$app_path" \
-D "background_path=$background_path" \
- -D "recovery_path=$recovery_path" \
"$volume_name" \
"$output_dmg"
diff --git a/.github/scripts/dmgbuild-settings b/.github/scripts/dmgbuild-settings
index 381469a46..0c2dee05b 100644
--- a/.github/scripts/dmgbuild-settings
+++ b/.github/scripts/dmgbuild-settings
@@ -21,15 +21,6 @@ icon_locations = {
"Applications": (480, 170),
}
hide_extensions = [app_name]
-recovery_path = defines.get("recovery_path")
-if recovery_path:
- recovery = Path(recovery_path).resolve()
- files.append(str(recovery))
- icon_size = 96
- icon_locations[app_name] = (180, 140)
- icon_locations["Applications"] = (480, 140)
- icon_locations[recovery.name] = (330, 250)
- hide_extensions.append(recovery.name)
show_status_bar = False
show_tab_view = False
show_toolbar = False
diff --git a/.github/scripts/finalize-macos-updater.sh b/.github/scripts/finalize-macos-updater.sh
index 614cc04dd..39a2b8844 100644
--- a/.github/scripts/finalize-macos-updater.sh
+++ b/.github/scripts/finalize-macos-updater.sh
@@ -6,8 +6,6 @@
set -euo pipefail
MACOS_DIR="${1:?expected macOS bundle directory}"
APP_PROJECT="${2:?expected Tauri project directory}"
-mode="${3:-updater}"
-[[ "$mode" == updater || "$mode" == --app-only ]] || { echo "invalid finalization mode: $mode" >&2; exit 2; }
notary_auth=(
--apple-id "$APPLE_ID"
--password "$APPLE_PASSWORD"
@@ -102,11 +100,6 @@ for app in "${apps[@]}"; do
codesign --verify --deep --strict --verbose=2 "$app"
spctl --assess --type execute --verbose "$app"
- # The recovery companion is shipped in the DMG, never as an updater payload.
- if [[ "$mode" == --app-only ]]; then
- continue
- fi
-
# Keep the offline Gatekeeper invariant from #5036: archive the validated
# app and sign these exact bytes, even when Tauri supplied the ticket.
echo "Rebuilding ${APP_NAME}.tar.gz from the finalized app"
diff --git a/.github/scripts/macos-update-recovery.swift b/.github/scripts/macos-update-recovery.swift
deleted file mode 100644
index 1f098c2b9..000000000
--- a/.github/scripts/macos-update-recovery.swift
+++ /dev/null
@@ -1,149 +0,0 @@
-// screenpipe — AI that knows everything you've seen, said, or heard
-// https://screenpipe.com
-
-import Cocoa
-import Security
-import UniformTypeIdentifiers
-
-// This companion is deliberately a separate app: Finder may send Reopen only
-// to the old Screenpipe process when its bundle was replaced at the same path.
-// It never terminates that process. The selected app owns authenticated handoff.
-private let validationFlags = SecCSFlags(rawValue: kSecCSStrictValidate | kSecCSCheckNestedCode)
-
-private func checked(_ status: OSStatus, _ operation: String) throws {
- if status != errSecSuccess {
- let message = SecCopyErrorMessageString(status, nil) as String? ?? "Unknown signing error"
- throw NSError(domain: "ScreenpipeUpdateRecovery", code: Int(status),
- userInfo: [NSLocalizedDescriptionKey: "\(operation): \(message) (\(status))"])
- }
-}
-
-private func verifiedCode(_ url: URL, requirement: SecRequirement? = nil) throws -> SecStaticCode {
- var code: SecStaticCode?
- try checked(SecStaticCodeCreateWithPath(url as CFURL, [], &code), "Read app signature")
- guard let code else { throw CocoaError(.fileReadCorruptFile) }
- try checked(SecStaticCodeCheckValidity(code, validationFlags, requirement), "Verify app signature")
- return code
-}
-
-private func signingInfo(_ code: SecStaticCode) throws -> [String: Any] {
- var info: CFDictionary?
- try checked(SecCodeCopySigningInformation(code, SecCSFlags(rawValue: kSecCSSigningInformation), &info),
- "Read signed app identity")
- return info as? [String: Any] ?? [:]
-}
-
-final class RecoveryDelegate: NSObject, NSApplicationDelegate {
- private var target = "not_selected"
- private var targetHash = "unknown"
- private var targetVersion = "unknown"
- private var source = "unknown"
- private var stage = "recovery_validation"
-
- // One bounded receipt, replaced atomically. Support collection prioritizes
- // update-recovery.log alongside update-install.log, even after log rotation.
- private func record(_ outcome: String, _ detail: String) {
- let environment = ProcessInfo.processInfo.environment
- let root = environment["SCREENPIPE_DATA_DIR"].flatMap { $0.isEmpty ? nil : URL(fileURLWithPath: $0) }
- ?? FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".screenpipe")
- let line = "\(ISO8601DateFormatter().string(from: Date())) manual_recovery: stage=\(stage); source=\(source); target=\(target); target_version=\(targetVersion); target_hash=\(targetHash); outcome=\(outcome); cause=\(detail)\n"
- do {
- try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true,
- attributes: [.posixPermissions: 0o700])
- let receipt = root.appendingPathComponent("update-recovery.log")
- // Atomic replacement cannot follow an existing receipt symlink.
- try Data(line.prefix(4096).utf8).write(to: receipt, options: .atomic)
- try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: receipt.path)
- } catch {
- NSLog("Screenpipe recovery diagnostic could not be saved: %@", error.localizedDescription)
- }
- }
-
- private func fail(_ error: Error) {
- record("selected_copy_not_started", error.localizedDescription)
- let alert = NSAlert()
- alert.messageText = "Couldn’t open this Screenpipe copy"
- alert.informativeText = error.localizedDescription
- alert.addButton(withTitle: "OK")
- alert.runModal()
- NSApp.terminate(nil)
- }
-
- func applicationDidFinishLaunching(_ notification: Notification) {
- NSApp.setActivationPolicy(.accessory)
- NSApp.activate(ignoringOtherApps: true)
- do {
- let own = try verifiedCode(Bundle.main.bundleURL)
- let ownInfo = try signingInfo(own)
- let sourceID = ownInfo[kSecCodeInfoIdentifier as String] as? String ?? "unknown"
- let sourceHash = (ownInfo[kSecCodeInfoUnique as String] as? Data)?.map { String(format: "%02x", $0) }.joined() ?? "unknown"
- source = "\(sourceID),version=\(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") ?? "unknown"),hash=\(sourceHash)"
- // This requirement is sealed into the companion when it is built
- // from the signed app. It retains the app's edition and publisher.
- guard let requirementText = Bundle.main.object(forInfoDictionaryKey: "ScreenpipeTargetRequirement") as? String else {
- throw CocoaError(.fileReadCorruptFile)
- }
- var requirement: SecRequirement?
- try checked(SecRequirementCreateWithString(requirementText as CFString, [], &requirement),
- "Read expected Screenpipe signing identity")
- guard let requirement else { throw CocoaError(.fileReadCorruptFile) }
-
- let panel = NSOpenPanel()
- panel.title = "Open updated Screenpipe"
- panel.message = "Quit Screenpipe first, then choose the updated app. It will open from its current location."
- panel.prompt = "Open update"
- panel.allowedContentTypes = [.applicationBundle]
- panel.canChooseDirectories = false
- panel.allowsMultipleSelection = false
- panel.treatsFilePackagesAsDirectories = false
- let downloadDirectory = Bundle.main.bundleURL.deletingLastPathComponent()
- let bundleName = Bundle.main.object(forInfoDictionaryKey: "ScreenpipeTargetBundleName") as? String ?? "screenpipe.app"
- let bundledApp = downloadDirectory.appendingPathComponent(bundleName)
- panel.directoryURL = FileManager.default.fileExists(atPath: bundledApp.path)
- ? downloadDirectory : URL(fileURLWithPath: "/Applications")
- guard panel.runModal() == .OK, let selected = panel.url else {
- record("cancelled", "user_cancelled")
- NSApp.terminate(nil)
- return
- }
- let url = selected.resolvingSymlinksInPath()
- target = url.path
- let info = try signingInfo(verifiedCode(url, requirement: requirement))
- let signedPlist = info[kSecCodeInfoPList as String] as? [String: Any]
- targetVersion = signedPlist?["CFBundleShortVersionString"] as? String ?? "unknown"
- guard let protocolVersion = signedPlist?["ScreenpipeManualHandoffProtocol"] as? Int,
- protocolVersion == Bundle.main.object(forInfoDictionaryKey: "ScreenpipeManualHandoffProtocol") as? Int else {
- throw NSError(domain: "ScreenpipeUpdateRecovery", code: 1, userInfo: [
- NSLocalizedDescriptionKey: "This is an older Screenpipe copy. Choose the updated app included with this download."
- ])
- }
- guard let hash = info[kSecCodeInfoUnique as String] as? Data else {
- throw CocoaError(.fileReadCorruptFile)
- }
- targetHash = hash.map { String(format: "%02x", $0) }.joined()
- let configuration = NSWorkspace.OpenConfiguration()
- configuration.createsNewApplicationInstance = true
- configuration.activates = true
- // The selected process rechecks this hash before any ownership
- // transfer, closing replacement races after the chooser verified it.
- configuration.environment = ["SCREENPIPE_MANUAL_HANDOFF_BUILD": targetHash]
- if let dataDirectory = ProcessInfo.processInfo.environment["SCREENPIPE_DATA_DIR"], !dataDirectory.isEmpty {
- configuration.environment["SCREENPIPE_DATA_DIR"] = dataDirectory
- }
- stage = "recovery_launch"
- record("launch_requested", "none")
- NSWorkspace.shared.openApplication(at: url, configuration: configuration) { app, error in
- DispatchQueue.main.async {
- if let error { self.fail(error); return }
- self.record("process_started", "pid=\(app?.processIdentifier ?? 0); authenticated_handoff_pending")
- NSApp.terminate(nil)
- }
- }
- } catch { fail(error) }
- }
-}
-
-let application = NSApplication.shared
-let delegate = RecoveryDelegate()
-application.delegate = delegate
-application.run()
diff --git a/.github/scripts/release-performance.test.ts b/.github/scripts/release-performance.test.ts
index 1f99e446f..bdc4d7555 100644
--- a/.github/scripts/release-performance.test.ts
+++ b/.github/scripts/release-performance.test.ts
@@ -143,7 +143,7 @@ esac
f.stub("codesign", 'if [[ "${REJECT_EXTRACTED:-}" == 1 && "${@: -1}" != "$ORIGINAL_APP" ]]; then exit 1; fi\n');
f.stub("spctl", ":\n");
f.stub("bunx", 'if [[ "${FAIL_SIGN:-}" == 1 ]]; then exit 1; fi\necho fixture-signature > "$4.sig"\n');
- const run = (extra = {}, args: string[] = []) => f.run("finalize-macos-updater.sh", [join(f.root, "bundle"), f.root, ...args], {
+ const run = (extra = {}) => f.run("finalize-macos-updater.sh", [join(f.root, "bundle"), f.root], {
APPLE_ID: "fixture", APPLE_PASSWORD: "fixture", APPLE_TEAM_ID: "fixture", MODE: mode, ORIGINAL_APP: app, ...extra,
});
return { ...f, app, run };
@@ -168,28 +168,16 @@ test("an invalid extracted bundle fails the gate even when the original app vali
const f = notarization("valid"); expect(f.run({ REJECT_EXTRACTED: "1" }).status).not.toBe(0);
});
-test("recovery companion is notarized and assessed without becoming an updater payload", () => {
- const f = notarization("missing");
- expect(f.run({}, ["--app-only"]).status).toBe(0);
- expect(f.calls()).toContain("notarytool submit");
- expect(f.calls()).toContain("stapler validate");
- expect(existsSync(`${f.app}.tar.gz`)).toBe(false);
- expect(existsSync(`${f.app}.tar.gz.sig`)).toBe(false);
- const rejected = notarization("rejected");
- expect(rejected.run({}, ["--app-only"]).status).not.toBe(0);
-});
-
-test("recovery companion is included in consumer and enterprise DMGs on every Mac runner", () => {
+test("consumer and enterprise DMGs open the regular app without a separate launcher", () => {
for (const name of ["release-app.yml", "release-enterprise.yml"]) {
- const workflow = Bun.YAML.parse(readFileSync(join(scripts, "../workflows", name), "utf8")) as any;
- const jobs = Object.values(workflow.jobs) as any[];
- const steps = jobs.flatMap(job => job.steps ?? []);
- const recovery = steps.find(step => step.name === "Build and notarize update recovery launcher");
- expect(recovery.run).toContain(".release-workflow/.github/scripts/build-macos-update-recovery.sh");
- expect(recovery.run).toContain("--app-only");
+ const source = readFileSync(join(scripts, "../workflows", name), "utf8");
+ const workflow = Bun.YAML.parse(source) as any;
+ const steps = (Object.values(workflow.jobs) as any[]).flatMap(job => job.steps ?? []);
const dmg = steps.find(step => step.name?.startsWith("Create headless DMG"));
expect(dmg.if ?? "").not.toContain("self-hosted");
- expect(dmg.run).toContain('"${RECOVERY_ARGS[@]}"');
+ expect(dmg.run).toContain('create-headless-dmg.sh "$APP_PATH" "$DMG_PATH"');
+ expect(source).not.toContain("build-macos-update-recovery");
+ expect(source).not.toContain("RECOVERY_ARGS");
}
});
diff --git a/.github/workflows/release-app.yml b/.github/workflows/release-app.yml
index 849bb1f20..bec36d56b 100644
--- a/.github/workflows/release-app.yml
+++ b/.github/workflows/release-app.yml
@@ -1427,7 +1427,7 @@ jobs:
fi
cd apps/screenpipe-app-tauri
- # Build the styled DMG below, including the signed recovery companion.
+ # Build the styled DMG below, with the app and Applications shortcut.
BUNDLE_ARGS=(--bundles app)
if bunx tauri build -v $TAURI_ARGS "${BUNDLE_ARGS[@]}" 2>&1 | tee /tmp/tauri-build-$attempt.log; then
echo "✅ Build succeeded on attempt $attempt"
@@ -1485,26 +1485,6 @@ jobs:
done
echo "all .app bundles pass codesign --verify --deep --strict"
- - name: Build and notarize update recovery launcher
- if: matrix.os_type == 'macos'
- shell: bash
- env:
- APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}
- APPLE_ID: ${{ secrets.APPLE_ID }}
- APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
- APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
- run: |
- set -euo pipefail
- BUNDLE_DIR="apps/screenpipe-app-tauri/src-tauri/target/${{ matrix.target }}/release/bundle"
- APP_PATH="${BUNDLE_DIR}/macos/screenpipe.app"
- # Older selected source revisions predate authenticated handoff.
- rm -rf "${BUNDLE_DIR}/recovery"
- if /usr/libexec/PlistBuddy -c 'Print :ScreenpipeManualHandoffProtocol' "$APP_PATH/Contents/Info.plist" >/dev/null 2>&1; then
- bash .release-workflow/.github/scripts/build-macos-update-recovery.sh "$APP_PATH" "${BUNDLE_DIR}/recovery"
- bash .release-workflow/.github/scripts/finalize-macos-updater.sh \
- "${BUNDLE_DIR}/recovery" "$GITHUB_WORKSPACE/apps/screenpipe-app-tauri" --app-only
- fi
-
- name: Create headless DMG (macOS)
if: matrix.os_type == 'macos'
shell: bash
@@ -1524,11 +1504,7 @@ jobs:
esac
APP_PATH="${BUNDLE_DIR}/macos/screenpipe.app"
DMG_PATH="${BUNDLE_DIR}/dmg/screenpipe_${VERSION}_${PACKAGE_ARCH}.dmg"
- RECOVERY_ARGS=()
- if [[ -d "${BUNDLE_DIR}/recovery/Open updated Screenpipe.app" ]]; then
- RECOVERY_ARGS=("${BUNDLE_DIR}/recovery/Open updated Screenpipe.app")
- fi
- bash .release-workflow/.github/scripts/create-headless-dmg.sh "$APP_PATH" "$DMG_PATH" "screenpipe" "${RECOVERY_ARGS[@]}"
+ bash .release-workflow/.github/scripts/create-headless-dmg.sh "$APP_PATH" "$DMG_PATH" "screenpipe"
- name: Notarize and staple DMGs (macOS)
if: matrix.os_type == 'macos'
diff --git a/.github/workflows/release-enterprise.yml b/.github/workflows/release-enterprise.yml
index cd47ba56d..81b04b968 100644
--- a/.github/workflows/release-enterprise.yml
+++ b/.github/workflows/release-enterprise.yml
@@ -1124,7 +1124,7 @@ jobs:
fi
cd apps/screenpipe-app-tauri
- # Build the styled DMG below, including the signed recovery companion.
+ # Build the styled DMG below, with the app and Applications shortcut.
BUNDLE_ARGS=(--bundles app)
if bunx tauri build -v --target "$TARGET" --features "${{ matrix.features }}" "${BUNDLE_ARGS[@]}" 2>&1 | tee /tmp/tauri-build-$attempt.log; then
echo "Build succeeded on attempt $attempt"
@@ -1171,25 +1171,6 @@ jobs:
done
echo "All enterprise .app bundles pass strict codesign verification"
- - name: Build and notarize update recovery launcher
- shell: bash
- env:
- APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}
- APPLE_ID: ${{ secrets.APPLE_ID }}
- APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
- APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
- run: |
- set -euo pipefail
- BUNDLE_DIR="apps/screenpipe-app-tauri/src-tauri/target/${{ matrix.target }}/release/bundle"
- APP_PATH="${BUNDLE_DIR}/macos/screenpipe enterprise.app"
- # Older selected source revisions predate authenticated handoff.
- rm -rf "${BUNDLE_DIR}/recovery"
- if /usr/libexec/PlistBuddy -c 'Print :ScreenpipeManualHandoffProtocol' "$APP_PATH/Contents/Info.plist" >/dev/null 2>&1; then
- bash .release-workflow/.github/scripts/build-macos-update-recovery.sh "$APP_PATH" "${BUNDLE_DIR}/recovery"
- bash .release-workflow/.github/scripts/finalize-macos-updater.sh \
- "${BUNDLE_DIR}/recovery" "$GITHUB_WORKSPACE/apps/screenpipe-app-tauri" --app-only
- fi
-
- name: Create headless DMG
shell: bash
run: |
@@ -1203,11 +1184,7 @@ jobs:
VERSION=$(sed -n 's/^version = "\([^"]*\)"/\1/p' apps/screenpipe-app-tauri/src-tauri/Cargo.toml | head -1)
APP_PATH="${BUNDLE_DIR}/macos/screenpipe enterprise.app"
DMG_PATH="${BUNDLE_DIR}/dmg/screenpipe enterprise_${VERSION}_${{ matrix.package_arch }}.dmg"
- RECOVERY_ARGS=()
- if [[ -d "${BUNDLE_DIR}/recovery/Open updated Screenpipe.app" ]]; then
- RECOVERY_ARGS=("${BUNDLE_DIR}/recovery/Open updated Screenpipe.app")
- fi
- bash .release-workflow/.github/scripts/create-headless-dmg.sh "$APP_PATH" "$DMG_PATH" "screenpipe enterprise" "${RECOVERY_ARGS[@]}"
+ bash .release-workflow/.github/scripts/create-headless-dmg.sh "$APP_PATH" "$DMG_PATH" "screenpipe enterprise"
- name: Notarize and staple DMG
env:
diff --git a/apps/screenpipe-app-tauri/scripts/build_macos.sh b/apps/screenpipe-app-tauri/scripts/build_macos.sh
index 686b55ed5..eb249943d 100755
--- a/apps/screenpipe-app-tauri/scripts/build_macos.sh
+++ b/apps/screenpipe-app-tauri/scripts/build_macos.sh
@@ -27,8 +27,4 @@ codesign --force --options runtime --entitlements src-tauri/entitlements.plist -
codesign --verify --deep --strict "$APP_PATH"
-APPLE_SIGNING_IDENTITY="$IDENTITY" SCREENPIPE_RECOVERY_DEVELOPMENT=1 \
- bash ../../.github/scripts/build-macos-update-recovery.sh "$APP_PATH" \
- src-tauri/target/debug-dev/bundle/recovery
-
echo "Build completed successfully!"
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/manual_handoff.rs b/apps/screenpipe-app-tauri/src-tauri/src/manual_handoff.rs
index 7e8d40298..258d14e58 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/manual_handoff.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/manual_handoff.rs
@@ -172,25 +172,16 @@ mod tests {
let report = crate::diagnostic_logs::collect_redacted_from_dirs(&[root.into()])
.await
.unwrap();
- let evidence = if std::env::var_os("HANDOFF_TEST_RECOVERY_LAUNCHER").is_some() {
- vec![
- "manual_recovery",
- "stage=recovery_validation",
- "source=",
- "target=",
- "cause=",
- "selected_copy_not_started",
- ]
- } else {
- vec![
- "manual_handoff_candidate",
- "source=",
- "target=",
- "manual_handoff_failed",
- "cannot authenticate the legacy search API",
- "selected_copy_not_started",
- ]
- };
+ let expected_cause = std::env::var("HANDOFF_TEST_EXPECTED_CAUSE")
+ .unwrap_or_else(|_| "cannot authenticate the legacy search API".into());
+ let evidence = [
+ "manual_handoff_candidate",
+ "source=",
+ "target=",
+ "manual_handoff_failed",
+ expected_cause.as_str(),
+ "selected_copy_not_started",
+ ];
for evidence in evidence {
assert!(report.contains(evidence), "support report lost {evidence}");
}
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/manual_handoff/macos.rs b/apps/screenpipe-app-tauri/src-tauri/src/manual_handoff/macos.rs
index 0a78663e4..24c74a510 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/manual_handoff/macos.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/manual_handoff/macos.rs
@@ -34,6 +34,7 @@ const EXPECTED_BUILD_ENV: &str = "SCREENPIPE_MANUAL_HANDOFF_BUILD";
static RUNTIME: OnceLock<Runtime> = OnceLock::new();
static LAUNCH_LOCK: Mutex<Option<File>> = Mutex::new(None);
static PENDING: AtomicBool = AtomicBool::new(false);
+static CAPTURE_BEFORE_HANDOFF: AtomicBool = AtomicBool::new(false);
struct Runtime {
identity: Identity,
@@ -247,7 +248,7 @@ async fn initialize_inner(root: PathBuf) -> Result<()> {
let lock = acquire(&runtime.lock).await?;
let existing = exchange(&runtime, false).await?;
if let Some(old) = existing {
- record_selection(&runtime, &old.identity);
+ record_selection(&runtime, &old.identity, &runtime.identity);
let mut replaced = false;
if manual_launch() {
match select(&old.identity, &runtime.identity) {
@@ -321,14 +322,14 @@ async fn focus_existing(old: &Identity) -> Result<()> {
Ok(())
}
-fn record_selection(runtime: &Runtime, old: &Identity) {
+fn record_selection(runtime: &Runtime, source: &Identity, target: &Identity) {
crate::update_diagnostics::append(
&runtime.root,
"manual_handoff_candidate",
&format!(
"source={}; target={}",
- serde_json::to_string(old).unwrap_or_default(),
- serde_json::to_string(&runtime.identity).unwrap_or_default()
+ serde_json::to_string(source).unwrap_or_default(),
+ serde_json::to_string(target).unwrap_or_default()
),
);
}
@@ -395,6 +396,7 @@ async fn serve(app: &tauri::AppHandle, runtime: &Runtime, stream: &mut UnixStrea
if candidate.hash != peer.hash {
bail!("incoming bundle changed during launch");
}
+ record_selection(runtime, &runtime.identity, &peer);
match prepare(app).await {
Ok(guard) => {
if !signing::is_same_process(&peer) {
@@ -440,9 +442,6 @@ async fn prepare(app: &tauri::AppHandle) -> Result<tokio::sync::RwLockWriteGuard
if crate::search_only::is_entering() {
bail!("Quit is still stopping capture; reopen this copy once Quit completes");
}
- if !crate::search_only::is_active() {
- bail!("the existing copy is still active; quit it before switching builds");
- }
let guard = crate::update_restart::RESTART_SAFETY
.prepare_restart(WAIT)
.await
@@ -450,21 +449,41 @@ async fn prepare(app: &tauri::AppHandle) -> Result<tokio::sync::RwLockWriteGuard
crate::store::persist_store_before_restart(app).map_err(anyhow::Error::msg)?;
// A manual launch must not inherit the automatic updater's hidden restart marker.
crate::search_only::prepare_manual_handoff().map_err(anyhow::Error::msg)?;
+ // Opening a verified replacement is the user's restart request. Drain
+ // the current recorder through its normal shutdown before releasing
+ // the database, whether the UI is open or Quit left search running.
+ CAPTURE_BEFORE_HANDOFF.store(
+ app.state::<crate::recording::RecordingState>()
+ .capture_intended(),
+ Ordering::SeqCst,
+ );
drain_started = true;
- match crate::recording::bounded_teardown(
- crate::recording::PRE_EXIT_TEARDOWN_TIMEOUT,
- async {
- crate::recording::stop_screenpipe(
- app.state::<crate::recording::RecordingState>(),
- app.clone(),
- )
- .await
- },
- )
- .await
- {
+ let stopping_app = app.clone();
+ // A timeout must not cancel a recorder halfway through flushing its
+ // durable writer. Recovery joins this task via the lifecycle lock.
+ let stop = tauri::async_runtime::spawn(async move {
+ crate::recording::stop_screenpipe(
+ stopping_app.state::<crate::recording::RecordingState>(),
+ stopping_app.clone(),
+ )
+ .await
+ });
+ let drain_started_at = std::time::Instant::now();
+ // The five-second forced-exit budget is too short for an active
+ // recorder (capture + durable database close took 6.5s in acceptance).
+ // Use the existing IPC reply deadline instead. Exceeding it cancels
+ // this replacement, but the owned stop task still finishes and the
+ // previous owner recovers without abandoning pending writes.
+ match wait_for_drain(stop, WAIT).await {
crate::recording::TeardownOutcome::Completed => {}
- other => bail!("search shutdown did not complete: {other:?}"),
+ crate::recording::TeardownOutcome::Failed(error) => {
+ bail!("recording and search shutdown failed: {error}");
+ }
+ crate::recording::TeardownOutcome::TimedOut => bail!(
+ "recording and search shutdown still pending; elapsed_ms={}; timeout_ms={}; remaining_work=finish_shutdown_and_restore_previous_owner; replacement_cancelled=true",
+ drain_started_at.elapsed().as_millis(),
+ WAIT.as_millis(),
+ ),
}
tokio::time::timeout(
crate::recording::PRE_EXIT_TEARDOWN_TIMEOUT,
@@ -485,9 +504,41 @@ async fn prepare(app: &tauri::AppHandle) -> Result<tokio::sync::RwLockWriteGuard
result
}
+async fn wait_for_drain(
+ stop: tauri::async_runtime::JoinHandle<Result<(), String>>,
+ timeout: Duration,
+) -> crate::recording::TeardownOutcome {
+ crate::recording::bounded_teardown(timeout, async {
+ stop.await.map_err(|error| error.to_string())?
+ })
+ .await
+}
+
fn recover(app: &tauri::AppHandle) {
- PENDING.store(false, Ordering::SeqCst);
- crate::search_only::recover_after_failed_update(app.clone());
+ app.state::<crate::recording::RecordingState>()
+ .set_capture_intent(CAPTURE_BEFORE_HANDOFF.load(Ordering::SeqCst));
+ let app = app.clone();
+ tauri::async_runtime::spawn(async move {
+ let state = app.state::<crate::recording::RecordingState>();
+ let _lifecycle = state.server_lifecycle.lock().await;
+ crate::update_diagnostics::record(
+ "manual_handoff_recovery_started",
+ "outcome=restoring_previous_owner",
+ );
+ let result = crate::recording::spawn_screenpipe_inner(&state, app.clone()).await;
+ PENDING.store(false, Ordering::SeqCst);
+ match result {
+ Ok(()) => crate::update_diagnostics::record(
+ "manual_handoff_recovery_startup_completed",
+ &format!("capture_intended={}", state.capture_intended()),
+ ),
+ Err(error) => {
+ if let Some(runtime) = RUNTIME.get() {
+ report_failure(&runtime.root, "restore_previous_owner", &error);
+ }
+ }
+ }
+ });
}
pub(crate) fn reopen(app: &tauri::AppHandle, trigger: &'static str) -> bool {
@@ -592,7 +643,7 @@ async fn legacy_takeover(runtime: &Runtime) -> Result<()> {
if old.identifier != runtime.identity.identifier {
continue;
}
- record_selection(runtime, &old);
+ record_selection(runtime, &old, &runtime.identity);
match select(&old, &runtime.identity) {
Selection::Focus => {
focus_existing(&old).await?;
@@ -720,6 +771,47 @@ async fn verify_legacy_stopped(api: &crate::recording::LocalApiContext) -> Resul
mod tests {
use super::*;
+ #[tokio::test]
+ async fn completed_drain_and_originating_failure_reach_handoff() {
+ use crate::recording::TeardownOutcome;
+ let stop = tauri::async_runtime::spawn(async { Ok(()) });
+ assert_eq!(wait_for_drain(stop, WAIT).await, TeardownOutcome::Completed);
+ let stop = tauri::async_runtime::spawn(async { Err("writer flush failed".into()) });
+ assert_eq!(
+ wait_for_drain(stop, WAIT).await,
+ TeardownOutcome::Failed("writer flush failed".into())
+ );
+ }
+
+ #[tokio::test]
+ async fn drain_deadline_retains_flush_and_excludes_recovery_until_it_finishes() {
+ use crate::recording::TeardownOutcome;
+ use std::sync::Arc;
+ let lifecycle = Arc::new(tokio::sync::Mutex::new(()));
+ let guard = lifecycle.clone().lock_owned().await;
+ let (finish, pending_write) = tokio::sync::oneshot::channel();
+ let flushed = Arc::new(AtomicBool::new(false));
+ let task_flushed = flushed.clone();
+ let stop = tauri::async_runtime::spawn(async move {
+ let _guard = guard;
+ pending_write.await.map_err(|error| error.to_string())?;
+ task_flushed.store(true, Ordering::SeqCst);
+ Ok(())
+ });
+ // At the deadline, unfinished work remains owned by the stop task.
+ assert_eq!(
+ wait_for_drain(stop, Duration::ZERO).await,
+ TeardownOutcome::TimedOut
+ );
+ assert!(lifecycle.try_lock().is_err());
+ assert!(!flushed.load(Ordering::SeqCst));
+ // Completion after the deadline still flushes before recovery can
+ // acquire the same lifecycle lock and reopen the database.
+ finish.send(()).unwrap();
+ let _recovery = lifecycle.lock().await;
+ assert!(flushed.load(Ordering::SeqCst));
+ }
+
#[tokio::test]
async fn socket_uses_os_peer_and_rejects_supplied_pid() {
let (mut left, right) = UnixStream::pair().unwrap();