The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
import 'dart:async';
import 'dart:io';
import 'dart:isolate';
import 'package:cryptography/dart.dart' show DartSha256;
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as p;
import '../core/runtime_architecture.dart';
import '../core/runtime_platform.dart';
import '../core/app_version.dart';
import '../core/staging_build.dart';
import 'update_signature.dart';
import 'windows_update_swap.dart';
/// Published by `scripts/upload-desktop.sh` (`make upload-desktop`) — see
/// `RELEASE.md` for the full publish-side design this mirrors.
const _defaultMetadataUrl =
'https://storage.googleapis.com/s3-autonomous-upgrade-3/harness/desktop/metadata.json';
const _stagingMetadataUrl =
'https://storage.googleapis.com/s3-autonomous-upgrade-3/harness/staging/desktop/metadata.json';
/// Override for testing against a scratch manifest without touching the real one — see RELEASE.md's
/// "Rolling out safely" section. Empty (the default) means "use the real manifest".
const _metadataUrlOverride = String.fromEnvironment(
'DESKTOP_UPDATE_METADATA_URL',
);
/// Lets a DEBUG build check and install, so the update band and its percentage
/// can be exercised without cutting a release. Off unless asked for
/// (`--dart-define=DESKTOP_UPDATE_FORCE=true`), and pointless on its own: pair
/// it with [_metadataUrlOverride] pointing at a scratch manifest, or the debug
/// build will poll the real one and offer to replace itself with a release.
const _forceUpdateChecks = bool.fromEnvironment('DESKTOP_UPDATE_FORCE');
/// The macOS build every Mac can run, rendered on Skia: what an Intel Mac installs, what every install
/// from before the Intel/Apple Silicon split polls on either CPU, and what the website download
/// serves. Must match the `intel` row of scripts/publish-macos-variant.sh — RELEASE.md, "Two macOS
/// builds", has the why.
const _otaKeyMacOS = 'desktop-macos';
/// The Apple Silicon build, rendered on Impeller. Must match the `apple-silicon` row of
/// scripts/publish-macos-variant.sh.
const _otaKeyMacOSArm64 = 'desktop-macos-arm64';
const _otaKeyWindowsX64 = 'desktop-windows-x64';
const _otaKeyWindowsArm64 = 'desktop-windows-arm64';
/// `arm64` or `x64` for the CPU this process runs on: which Linux artifact to fetch, and whether the
/// Apple Silicon macOS build is on offer. An Apple Silicon Mac running this under Rosetta reports x64
/// and is offered only the Skia build — harmless, since both macOS builds are universal.
String _currentArchitecture() => runtimeArchitecture;
@visibleForTesting
String desktopUpdateMetadataUrl({
String override = _metadataUrlOverride,
bool staging = kHarnessStagingBuild,
}) => override.isNotEmpty
? override
: (staging ? _stagingMetadataUrl : _defaultMetadataUrl);
String get _metadataUrl => desktopUpdateMetadataUrl();
class UpdateInfo {
final String version;
final String url;
final String sha256;
final int size;
const UpdateInfo({
required this.version,
required this.url,
required this.sha256,
required this.size,
});
}
/// Refuses a staged update with [UpdateRefused] unless its signer is the
/// running app's: [staged] is the macOS bundle or the Windows version folder,
/// [launcher] the staged Windows `Harness.exe`, [version] the manifest's,
/// which a staged Windows app must also say it is.
typedef UpdateSignatureCheck = Future<void> Function(
String staged, {
String? launcher,
required String version,
});
enum DesktopUpdateCheckStatus { upToDate, available, disabled, failed }
/// A failed or disabled check cannot establish that the installed app is current.
class DesktopUpdateCheck {
final DesktopUpdateCheckStatus status;
final UpdateInfo? update;
const DesktopUpdateCheck.upToDate()
: status = DesktopUpdateCheckStatus.upToDate,
update = null;
const DesktopUpdateCheck.available(UpdateInfo this.update)
: status = DesktopUpdateCheckStatus.available;
const DesktopUpdateCheck.disabled()
: status = DesktopUpdateCheckStatus.disabled,
update = null;
const DesktopUpdateCheck.failed()
: status = DesktopUpdateCheckStatus.failed,
update = null;
}
/// A downloaded, sha256-verified build sitting in a temp directory, not yet swapped into place.
class StagedUpdate {
final String version;
/// On macOS: `.../Harness.app` inside [stagingDirPath], unpacked and version-confirmed. On
/// Linux: the downloaded `.AppImage` file itself (already made executable), directly inside
/// [stagingDirPath] — there is nothing to unpack.
final String bundlePath;
final String stagingDirPath;
final WindowsUpdateSwap? _windowsSwap;
const StagedUpdate({
required this.version,
required this.bundlePath,
required this.stagingDirPath,
}) : _windowsSwap = null;
const StagedUpdate._windows({
required this.version,
required this.bundlePath,
required this.stagingDirPath,
required WindowsUpdateSwap swap,
}) : _windowsSwap = swap;
}
/// Publication has begun, so a failed update may need a manual restart or repair.
class WindowsPartialUpdateException implements Exception {
const WindowsPartialUpdateException(
this.detail, {
this.launcherNeedsRepair = false,
this.publicationIncomplete = false,
});
final String detail;
final bool launcherNeedsRepair;
final bool publicationIncomplete;
@override
String toString() => detail;
}
/// Strict X.Y.Z compare, prerelease/build metadata ignored — same rule as the CLI's own
/// `semverGt` (cli/src/lib/selfUpdate.ts in the harness CLI repo), so publishing an old build can
/// never look newer than what's already running.
bool semverGt(String a, String b) {
final x = _parseSemverCore(a);
final y = _parseSemverCore(b);
if (x == null || y == null) return false;
for (var i = 0; i < 3; i++) {
if (x[i] != y[i]) return x[i] > y[i];
}
return false;
}
List<int>? _parseSemverCore(String version) {
final match = RegExp(r'^(\d+)\.(\d+)\.(\d+)').firstMatch(version);
if (match == null) return null;
return [
int.parse(match.group(1)!),
int.parse(match.group(2)!),
int.parse(match.group(3)!),
];
}
String _singleQuote(String value) => "'${value.replaceAll("'", "'\\''")}'";
/// The lowercase hex SHA-256 of [bytes], worked out on a background isolate.
///
/// A release download is ~45 MB, and the hash used to be awaited on the UI
/// isolate — but `Sha256().hash` is pure Dart and synchronous underneath
/// (`DartHashAlgorithmMixin.hash` calls `hashSync`), so every Update froze the
/// window for the whole of it: 45 MiB took 535 ms in an AOT build and ~560 ms
/// under `flutter test` (i7-10700K, 2026-10-17). Same algorithm, same digest;
/// only the isolate changes. A top-level function, so the closure carries
/// nothing but the bytes, which are copied to the worker once.
Future<String> sha256HexOffUiIsolate(List<int> bytes) =>
Isolate.run(() => _sha256Hex(bytes));
String _sha256Hex(List<int> bytes) => const DartSha256()
.hashSync(bytes)
.bytes
.map((b) => b.toRadixString(16).padLeft(2, '0'))
.join();
/// Resolves the path the running build should be swapped at.
///
/// On macOS this walks up from the running executable to the enclosing
/// `.app` bundle — `.../Harness.app/Contents/MacOS/Harness` -> `.../Harness.app`.
/// On Linux the packaged build is a single `.AppImage` file (see
/// `scripts/upload-desktop-linux.sh`), and a running AppImage executes from a temporary FUSE mount,
/// not from that file — so the file's own path comes from [appImagePath] (tests) or the `APPIMAGE`
/// environment variable the AppImage runtime sets on launch (production), never from
/// `RuntimePlatform.resolvedExecutable`.
/// On Windows it is the install root above `app/<version>/harness-desktop.exe`;
/// a development executable outside this layout has no update destination.
String? currentBundlePath({
String? executablePath,
bool? isLinux,
String? appImagePath,
bool? isWindows,
}) {
if (isWindows ?? (isLinux == null && RuntimePlatform.isWindows)) {
return windowsInstallRootOf(
executablePath ?? RuntimePlatform.resolvedExecutable,
);
}
if (isLinux ?? RuntimePlatform.isLinux) {
return appImagePath ?? RuntimePlatform.environment['APPIMAGE'];
}
final resolved = executablePath ?? RuntimePlatform.resolvedExecutable;
var dir = File(resolved).parent;
for (var i = 0; i < 6; i++) {
if (dir.path.endsWith('.app')) return dir.path;
final parent = dir.parent;
if (parent.path == dir.path) return null; // reached filesystem root
dir = parent;
}
return null;
}
Future<void> _defaultLaunchDetached(String command) async {
await Process.start(RuntimePlatform.isLinux ? '/bin/bash' : '/bin/zsh', [
'-l',
'-c',
command,
], mode: ProcessStartMode.detached);
}
/// Checks the public GCS manifest for a newer desktop build than the one currently running,
/// downloads + verifies it, and — once the caller applies it — swaps it into place and relaunches.
/// See `RELEASE.md` for the publish side and the full design (why this doesn't
/// silently auto-restart like the CLI's own self-updater does).
class DesktopUpdater {
final Dio _dio;
final Future<void> Function(String command) _launchDetached;
final String _metadataUrlForInstance;
final bool _releaseMode;
final bool _enabled;
final bool _isLinux;
final bool _isWindows;
final String _architecture;
final String? _windowsInstallRoot;
final Future<void> Function(String, List<String>)? _startDetached;
final UpdateSignatureCheck? _verifySignature;
final _checksInFlight = <String?, Future<DesktopUpdateCheck>>{};
/// How often the background poll asks the manifest.
///
/// Five minutes, not the six hours this used to be, because the offer on
/// screen has to be close to the build Update will actually install: a person
/// who leaves a notice sitting for an afternoon should not be shown a version
/// that was superseded hours ago. The request is one small GET that GCS
/// serves `no-cache`, the overlap guard in [startChecking] and the in-flight
/// map above mean a slow answer never stacks up a second one, and the CLI's
/// own self-updater polls on the same order (`cli/src/lib/selfUpdate.ts`).
static const checkInterval = Duration(minutes: 5);
bool get canCheck => !kIsWeb && _enabled && _releaseMode;
DesktopUpdater({
this._enabled = true,
Dio? dio,
Future<void> Function(String command)? launchDetached,
// Defaults to the real manifest (or the --dart-define build-time override — see RELEASE.md's
// "Rolling out safely"). Tests and any other caller that needs a different manifest (e.g. a
// scratch one) pass this directly instead.
String? metadataUrl,
// Defaults to the real Flutter build mode — see checkOnce()'s guard. `flutter test` always runs
// outside release mode, so tests that want to exercise checkOnce()'s real logic pass `true` here.
bool? releaseMode,
// Defaults to the real host OS. Tests force this to exercise the Linux packaging/relaunch branch
// (a single downloaded file, no unpacking) from any host, since that branch needs no extra
// tooling beyond the standard library, unlike ditto/plutil on macOS.
bool? isLinux,
// Defaults to the real host. A caller that names the host through [isLinux] is describing
// macOS or Linux, so it is not Windows unless it says so — which keeps every existing test of
// the macOS and Linux branches meaningful on a Windows runner.
bool? isWindows,
// Defaults to the running CPU (`arm64`/`x64`): which Linux artifact to fetch, and whether the
// Apple Silicon macOS build is on offer. Tests override it to exercise every key from any host.
String? architecture,
String? windowsInstallRoot,
Future<void> Function(String executable, List<String> arguments)?
startDetached,
// Defaults to checking against the running app's own signature. Tests
// whose fixtures are not signed pass their own.
UpdateSignatureCheck? verifySignature,
}) : _dio =
dio ??
Dio(
BaseOptions(
connectTimeout: const Duration(seconds: 10),
receiveTimeout: const Duration(seconds: 30),
),
),
_launchDetached = launchDetached ?? _defaultLaunchDetached,
_metadataUrlForInstance = metadataUrl ?? _metadataUrl,
_releaseMode = releaseMode ?? (kReleaseMode || _forceUpdateChecks),
_isLinux = isLinux ?? RuntimePlatform.isLinux,
_isWindows = isWindows ?? (isLinux == null && RuntimePlatform.isWindows),
_architecture =
architecture ??
((isWindows ?? (isLinux == null && RuntimePlatform.isWindows))
? windowsMachineArchitecture()
: _currentArchitecture()),
// Public injection names keep the fixture seam usable outside this library.
// ignore: prefer_initializing_formals
_windowsInstallRoot = windowsInstallRoot,
// ignore: prefer_initializing_formals
_startDetached = startDetached,
// ignore: prefer_initializing_formals
_verifySignature = verifySignature;
Future<void> _checkSignature(
String staged, {
String? launcher,
required String version,
}) => (_verifySignature ?? _signedLikeThisApp)(
staged,
launcher: launcher,
version: version,
);
/// Linux AppImages carry no signature, so Linux keeps the sha256 check.
Future<void> _signedLikeThisApp(
String staged, {
String? launcher,
required String version,
}) async {
if (_isWindows) {
return verifyWindowsUpdate(
stagedFolder: staged,
stagedLauncher: launcher!,
runningExe: RuntimePlatform.resolvedExecutable,
version: version,
);
}
if (_isLinux) return;
final running = currentBundlePath(isLinux: false, isWindows: false);
if (running == null) throw cannotCheckSignature;
return verifyMacUpdate(stagedBundle: staged, runningBundle: running);
}
/// The manifest entries this build may install, most preferred first — [_newestEntry] takes the
/// newest of them, an earlier key winning a tie.
List<String> get _otaKeys {
if (_isWindows) {
return _architecture == 'arm64'
? const [_otaKeyWindowsArm64, _otaKeyWindowsX64]
: const [_otaKeyWindowsX64];
}
if (_isLinux) return ['desktop-linux-$_architecture'];
// An Intel Mac reads only the Skia build: the arm64 one renders on Impeller, which is exactly
// what it must not get, however new.
if (_architecture != 'arm64') return const [_otaKeyMacOS];
return const [_otaKeyMacOSArm64, _otaKeyMacOS];
}
/// Unattended callers only need an offer. Interactive callers use [check]
/// so an unreachable service is not presented as "up to date".
Future<UpdateInfo?> checkOnce({String? currentVersion}) async =>
(await check(currentVersion: currentVersion)).update;
/// Manual and background callers share an in-flight manifest request.
/// Debug/profile and explicitly disabled builds never offer a release that
/// could replace the local development build.
Future<DesktopUpdateCheck> check({String? currentVersion}) =>
_checksInFlight.putIfAbsent(currentVersion, () async {
try {
return await _check(currentVersion: currentVersion);
} finally {
_checksInFlight.remove(currentVersion);
}
});
Future<DesktopUpdateCheck> _check({String? currentVersion}) async {
if (!canCheck) return const DesktopUpdateCheck.disabled();
try {
final running = currentVersion ?? await runningAppVersion();
if (_parseSemverCore(running) == null) {
return const DesktopUpdateCheck.failed();
}
final response = await _dio.get<Map<String, dynamic>>(
_metadataUrlForInstance,
);
final newest = _newestEntry(response.data);
if (newest == null) return const DesktopUpdateCheck.failed();
return semverGt(newest.version, running)
? DesktopUpdateCheck.available(newest)
: const DesktopUpdateCheck.upToDate();
} catch (error) {
debugPrint('DesktopUpdater.check: $error');
return const DesktopUpdateCheck.failed();
}
}
/// The newest of this host's [_otaKeys] entries, an earlier key winning a tie — so on Apple Silicon
/// a release that published both macOS builds installs the Impeller one, while a release that only
/// moved `desktop-macos` still reaches it instead of hiding behind an older arm64 entry.
UpdateInfo? _newestEntry(Map<String, dynamic>? manifest) {
UpdateInfo? newest;
for (final key in _otaKeys) {
final entry = _parseEntry(manifest?[key]);
if (entry == null) continue;
if (_isWindows && !windowsPackageVersion(entry.version)) continue;
if (newest == null || semverGt(entry.version, newest.version)) {
newest = entry;
}
}
return newest;
}
/// One manifest entry, or null when it is missing or malformed — "nothing to install from this
/// key", never an error.
static UpdateInfo? _parseEntry(Object? entry) {
if (entry is! Map) return null;
final version = entry['version'];
final url = entry['url'];
final sha256 = entry['sha256'];
final size = entry['size'];
if (version is! String ||
_parseSemverCore(version) == null ||
url is! String ||
sha256 is! String ||
size is! int) {
return null;
}
return UpdateInfo(version: version, url: url, sha256: sha256, size: size);
}
/// Checks once immediately, then every [interval] — calls [onUpdateAvailable] each time a newer
/// build is found (re-finding the same version on a later tick is harmless; the caller is expected
/// to no-op if it's already showing that version). Cancel the returned [Timer] to stop.
Timer startChecking({
Duration interval = checkInterval,
void Function(UpdateInfo info)? onUpdateAvailable,
void Function(DesktopUpdateCheck result)? onCheckCompleted,
// Forwarded to checkOnce() on every tick — tests pass this to avoid checkOnce()'s default
// runningAppVersion() call, which (via PackageInfo.fromPlatform()) needs a platform method
// channel real production code gets for free but a plain `test()` doesn't.
String? currentVersion,
}) {
var checking = false;
late final Timer timer;
Future<void> tick() async {
if (checking || !timer.isActive) return;
checking = true;
try {
final result = await check(currentVersion: currentVersion);
if (!timer.isActive) return;
onCheckCompleted?.call(result);
final info = result.update;
if (info != null) onUpdateAvailable?.call(info);
} finally {
checking = false;
}
}
timer = Timer.periodic(interval, (_) => unawaited(tick()));
unawaited(tick());
return timer;
}
/// Downloads [info] and verifies its sha256 BEFORE trusting the bytes. On macOS, unpacks the zip
/// and confirms the staged bundle's own Info.plist really carries [info].version — the archive
/// holds more than the hash alone authenticates. On Linux, the download itself is the artifact (a
/// single AppImage file), so the sha256 check already covers everything there is: it is made
/// executable and staged as-is, with nothing to unpack or recheck.
/// On macOS and Windows the unpacked build must also be signed by whoever
/// signed the running app ([UpdateSignatureCheck]); a refusal deletes what
/// was staged and throws [UpdateRefused], whose message says why.
/// Returns null (and cleans up anything partially written) on any other verification failure.
/// [onProgress] reports the DOWNLOAD only — bytes received out of
/// [UpdateInfo.size]. The manifest's size is the denominator rather than the
/// response's, because a CDN that omits `Content-Length` leaves Dio reporting
/// `-1` and the manifest is the authority the hash is checked against anyway.
/// Verifying and unpacking afterwards have no counter, so a caller showing a
/// percentage stops at 100 and keeps saying "installing" until this returns.
Future<StagedUpdate?> downloadAndStage(
UpdateInfo info, {
void Function(int received, int total)? onProgress,
}) async {
if (!_enabled) return null;
if (_isWindows && !windowsPackageVersion(info.version)) return null;
Directory? stagingDir;
try {
final response = await _dio.get<List<int>>(
info.url,
options: Options(responseType: ResponseType.bytes),
onReceiveProgress: onProgress == null
? null
: (received, _) => onProgress(received, info.size),
);
final bytes = response.data;
if (bytes == null || bytes.length != info.size) {
debugPrint(
'DesktopUpdater: unexpected download size for ${info.version}',
);
return null;
}
final actualSha = await sha256HexOffUiIsolate(bytes);
if (actualSha != info.sha256) {
debugPrint(
'DesktopUpdater: sha256 mismatch for ${info.version} — discarding download',
);
return null;
}
stagingDir = await Directory.systemTemp.createTemp('harness-update-');
if (_isWindows) {
final root = _windowsInstallRoot ?? currentBundlePath(isWindows: true);
if (root == null) {
await stagingDir.delete(recursive: true);
return null;
}
final zipPath = p.join(
stagingDir.path,
'harness-desktop-${info.version}.zip',
);
await File(zipPath).writeAsBytes(bytes, flush: true);
final swap = WindowsUpdateSwap(
installRoot: root,
start: _startDetached,
);
final error = await swap.stage(zipPath: zipPath, version: info.version);
if (error != null) {
debugPrint('DesktopUpdater: Windows staging failed: $error');
await stagingDir.delete(recursive: true);
return null;
}
try {
await _checkSignature(
swap.stagedFolder!,
launcher: swap.stagedLauncher,
version: info.version,
);
} on UpdateRefused {
await swap.discardStaged();
rethrow;
}
return StagedUpdate._windows(
version: info.version,
bundlePath: root,
stagingDirPath: stagingDir.path,
swap: swap,
);
}
if (_isLinux) {
final appImagePath =
'${stagingDir.path}/Harness-linux-$_architecture.AppImage';
await File(appImagePath).writeAsBytes(bytes, flush: true);
await Process.run('/bin/chmod', ['+x', appImagePath]);
return StagedUpdate(
version: info.version,
bundlePath: appImagePath,
stagingDirPath: stagingDir.path,
);
}
final archivePath = '${stagingDir.path}/Harness-macos.zip';
await File(archivePath).writeAsBytes(bytes, flush: true);
final unpack = await Process.run('/usr/bin/ditto', [
'-x',
'-k',
archivePath,
stagingDir.path,
]);
if (unpack.exitCode != 0) {
debugPrint('DesktopUpdater: ditto unpack failed: ${unpack.stderr}');
await stagingDir.delete(recursive: true);
return null;
}
final bundlePath = '${stagingDir.path}/Harness.app';
if (!Directory(bundlePath).existsSync()) {
debugPrint(
'DesktopUpdater: no Harness bundle inside the downloaded archive',
);
await stagingDir.delete(recursive: true);
return null;
}
final plutil = await Process.run('/usr/bin/plutil', [
'-extract',
'CFBundleShortVersionString',
'raw',
'$bundlePath/Contents/Info.plist',
]);
final stagedVersion = plutil.exitCode == 0
? (plutil.stdout as String?)?.trim()
: null;
if (stagedVersion != info.version) {
debugPrint(
'DesktopUpdater: staged bundle reports version "$stagedVersion", expected "${info.version}"',
);
await stagingDir.delete(recursive: true);
return null;
}
// The bundle's own version was compared with the manifest's above.
await _checkSignature(bundlePath, version: info.version);
return StagedUpdate(
version: info.version,
bundlePath: bundlePath,
stagingDirPath: stagingDir.path,
);
} on UpdateRefused {
await _deleteQuietly(stagingDir);
rethrow;
} catch (error) {
debugPrint('DesktopUpdater.downloadAndStage: $error');
await _deleteQuietly(stagingDir);
return null;
}
}
static Future<void> _deleteQuietly(Directory? dir) async {
try {
await dir?.delete(recursive: true);
} catch (_) {
// best-effort cleanup
}
}
/// Hands off to a detached helper that waits for THIS process (pid [selfPid]) to exit, backs the
/// running bundle up as `Harness.app.prev`, swaps [staged] into place, relaunches it, and restores
/// the backup if the relaunch doesn't stay alive a few seconds later. Returns as soon as the helper
/// has been spawned — the caller owns actually quitting (e.g. `exit(0)`) right after; this never
/// exits the app itself, and never touches anything if [runningBundlePath] can't be resolved.
Future<bool> applyStaged(
StagedUpdate staged, {
required int selfPid,
String? runningBundlePath,
}) async {
if (!_enabled) return false;
if (_isWindows) {
final swap = staged._windowsSwap;
if (swap == null ||
swap.installRoot != staged.bundlePath ||
!windowsPackageVersion(staged.version)) {
return false;
}
final error = swap.commit(version: staged.version);
try {
await Directory(staged.stagingDirPath).delete(recursive: true);
} catch (_) {
// Only the downloaded zip is here; the OS can clear this temp folder.
}
if (error != null) {
debugPrint('DesktopUpdater: Windows swap failed: $error');
if (swap.publicationStarted) {
throw WindowsPartialUpdateException(
error,
launcherNeedsRepair: swap.launcherNeedsRepair,
publicationIncomplete: true,
);
}
await swap.discardStaged();
return false;
}
try {
await swap.relaunch(selfPid);
} catch (error) {
throw WindowsPartialUpdateException(
'The new Harness files were installed, but the launcher could not start: $error',
launcherNeedsRepair: swap.launcherNeedsRepair,
);
}
return true;
}
final bundlePath =
runningBundlePath ?? currentBundlePath(isLinux: _isLinux);
if (bundlePath == null) {
debugPrint(
'DesktopUpdater: could not resolve the running bundle path — not applying',
);
return false;
}
final prevPath = '$bundlePath.prev';
// On Linux, `bundlePath` IS the AppImage file (see currentBundlePath) — there is no enclosing
// directory to exec into, so the "executable" is the swapped file itself. downloadAndStage()
// already made staged.bundlePath executable, and mv preserves that bit across the swap below.
final executableInBundle = _isLinux
? bundlePath
: '$bundlePath/Contents/MacOS/Harness';
// macOS relaunches through `open -n` (LaunchServices, so Dock/menu-bar identity stays correct).
// Linux has no such registry for a plain packaged binary — exec it directly, detached from this
// shell so it outlives the helper script.
final relaunch = _isLinux
? 'nohup ${_singleQuote(executableInBundle)} >/dev/null 2>&1 & disown'
: 'open -n ${_singleQuote(bundlePath)}';
final command =
'''
while kill -0 $selfPid 2>/dev/null; do sleep 0.2; done
rm -rf ${_singleQuote(prevPath)}
mv ${_singleQuote(bundlePath)} ${_singleQuote(prevPath)}
mv ${_singleQuote(staged.bundlePath)} ${_singleQuote(bundlePath)}
$relaunch
sleep 3
if pgrep -f ${_singleQuote(executableInBundle)} >/dev/null; then
rm -rf ${_singleQuote(prevPath)}
else
rm -rf ${_singleQuote(bundlePath)}
mv ${_singleQuote(prevPath)} ${_singleQuote(bundlePath)}
$relaunch
fi
rm -rf ${_singleQuote(staged.stagingDirPath)}
''';
await _launchDetached(command);
return true;
}
}