fix(desktop): verified update teardown on Windows+WSL, install integrity check, and resilient WSL readiness handshake #5998
ClosedJgratton24(GitHub profile, opens in a new tab)wants to merge 9 commits into
main fromrefs/pull/5998/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/desktop/src/backend/DesktopBackendManager.ts lines 623 to 623OutdatedResolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -573,0 +603,21 @@603+ };604+ const dedupeUrls = (urls: ReadonlyArray<URL>): ReadonlyArray<URL> =>605+ urls.filter((url, index) => urls.findIndex((other) => other.href === url.href) === index);606+ const probeCandidates = (urls: ReadonlyArray<URL>, timeout: Duration.Duration) =>607+ Effect.raceAll(608+ urls.map((url) =>609+ waitForHttpReady({ ...processContext, httpBaseUrl: url, timeout }).pipe(Effect.as(url)),610+ ),611+ );612+ const staticCandidates = dedupeUrls([613+ options.httpBaseUrl,614+ ...(options.readinessProbeUrls ?? []),615+ ]);616+ const readinessTimeout = options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT;617+ yield* probeCandidates(staticCandidates, readinessTimeout).pipe(618+ // Every static candidate timed out. Before declaring the run619+ // unreachable, recover candidate origins from the backend's persisted620+ // runtime state (when the config wired a resolver) and probe those —621+ // a ready server on a reachable port must not present as a dead one622+ // just because the advertised host heuristic was wrong.623+ Effect.catchTag("BackendReadinessTimeoutError", (error) => {apps/desktop/src/backend/DesktopBackendManager.ts lines 643 to 645OutdatedResolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -573,0 +625,21 @@625+ Effect.fail(626+ new BackendReadinessTimeoutError({627+ ...processContext,628+ readinessUrl: error.readinessUrl,629+ timeoutMs: error.timeoutMs,630+ probedUrls,631+ cause: error.cause,632+ }),633+ );634+ return (options.resolveReadinessFallbackUrls ?? Effect.succeed<ReadonlyArray<URL>>([])).pipe(635+ Effect.flatMap((fallbackUrls) => {636+ const fresh = dedupeUrls(fallbackUrls).filter(637+ (url) => !staticCandidates.some((candidate) => candidate.href === url.href),638+ );639+ if (fresh.length === 0) {640+ return failWithProbed(staticCandidates);641+ }642+ return probeCandidates(fresh, READINESS_FALLBACK_PROBE_TIMEOUT).pipe(643+ Effect.catchTag("BackendReadinessTimeoutError", () =>644+ failWithProbed([...staticCandidates, ...fresh]),645+ ),
- apps/desktop/src/wsl/DesktopWslEnvironment.ts lines 863 to 863OutdatedResolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -716,4 +844,20 @@844+ }),845+ ).pipe(846+ Effect.timeoutOption(WSLINFO_TIMEOUT),716847 Effect.map(Option.flatten),717- Effect.orElseSucceed(() => Option.none<string>()),848+ Effect.orElseSucceed(() => Option.none<WslServerRuntimeState>()),718849 );719850851+// Finds every Linux process holding the target directory via cwd, exe, an852+// open fd, or a mapped file; SIGTERMs, then SIGKILLs stragglers, then853+// reports. `cd /` first so the probe shell itself (spawned with the854+// desktop's install-dir cwd mapped through /mnt) never counts as a holder.855+export const buildEnsurePathReleasedScript = (quotedLinuxPath: string): string => `cd /856+dir=${quotedLinuxPath}857+self=$$858+find_holders() {859+ for p in /proc/[0-9]*; do860+ pid=\${p#/proc/}861+ [ "$pid" = "$self" ] && continue862+ [ "$pid" = "1" ] && continue863+ if { readlink "$p/cwd"; readlink "$p/exe"; ls -l "$p/fd" 2>/dev/null; cat "$p/maps" 2>/dev/null; } 2>/dev/null | grep -qF "$dir"; thenapps/desktop/src/updates/DesktopUpdates.ts line 565Resolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -480,0 +533,21 @@533+ // dir> blocks file replacement on the Windows side, which is exactly534+ // how a half-applied update happens. Verify release instead of535+ // assuming it.536+ if (environment.isPackaged && environment.platform === "win32") {537+ const installDir = environment.path.dirname(environment.resourcesPath);538+ for (const result of stopResults) {539+ const instanceConfig = Option.getOrUndefined(result.instanceConfig);540+ if (instanceConfig?.executablePath !== "wsl.exe") {541+ continue;542+ }543+ const released = yield* wslEnvironment.ensureWindowsPathReleased({544+ distro: instanceConfig.runningDistro ?? null,545+ windowsPath: installDir,546+ });547+ if (released === "busy") {548+ return yield* abortInstall(549+ instances,550+ `Update install aborted: processes inside WSL (${result.instance.id}) still hold files under ${installDir}. Close them (or run "wsl --shutdown") and try the update again.`,551+ );552+ }553+ if (released === "unknown") {apps/desktop/src/wsl/DesktopWslEnvironment.ts line 821Resolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -715,0 +787,21 @@787+ stderr: "ignore",788+ killSignal: "SIGTERM",789+ forceKillAfter: PROCESS_TERMINATE_GRACE,790+ },791+ );792+ const handle = yield* spawner.spawn(command);793+ const stdoutBytes = yield* Stream.runCollect(handle.stdout);794+ const exitCode = yield* handle.exitCode;795+ if ((exitCode as unknown as number) !== 0) return "unknown" as WslNetworkingMode;796+ const raw = decodeUtf8(concatChunks(stdoutBytes)).trim().toLowerCase();797+ if (raw === "mirrored") return "mirrored" as WslNetworkingMode;798+ if (raw === "nat") return "nat" as WslNetworkingMode;799+ return "unknown" as WslNetworkingMode;800+ }),801+ ).pipe(802+ Effect.timeoutOption(WSLINFO_TIMEOUT),803+ Effect.map(Option.getOrElse((): WslNetworkingMode => "unknown")),804+ Effect.orElseSucceed((): WslNetworkingMode => "unknown"),805+ );806+807+// The backend runs with the distro user's own $HOME (the bootstrap omits
- apps/desktop/src/app/DesktopInstallIntegrity.ts lines 72 to 75OutdatedResolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -0,0 +55,21 @@55+56+export const checkInstallIntegrity: Effect.Effect<57+ DesktopInstallIntegrityResult,58+ never,59+ DesktopEnvironment.DesktopEnvironment | FileSystem.FileSystem60+> = Effect.gen(function* () {61+ const environment = yield* DesktopEnvironment.DesktopEnvironment;62+ const fileSystem = yield* FileSystem.FileSystem;63+64+ if (!environment.isPackaged) {65+ return { _tag: "Skipped", reason: "not a packaged build" } as const;66+ }67+68+ const manifestPath = environment.path.join(69+ environment.resourcesPath,70+ ...DESKTOP_BUILD_MANIFEST_RELATIVE_PATH.split("/"),71+ );72+ const raw = yield* fileSystem.readFileString(manifestPath, "utf-8").pipe(Effect.option);73+ if (Option.isNone(raw)) {74+ return { _tag: "Skipped", reason: `no build manifest at ${manifestPath}` } as const;75+ }apps/desktop/src/updates/DesktopUpdates.ts lines 553 to 558OutdatedResolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -480,0 +538,21 @@538+ for (const result of stopResults) {539+ const instanceConfig = Option.getOrUndefined(result.instanceConfig);540+ if (instanceConfig?.executablePath !== "wsl.exe") {541+ continue;542+ }543+ const released = yield* wslEnvironment.ensureWindowsPathReleased({544+ distro: instanceConfig.runningDistro ?? null,545+ windowsPath: installDir,546+ });547+ if (released === "busy") {548+ return yield* abortInstall(549+ instances,550+ `Update install aborted: processes inside WSL (${result.instance.id}) still hold files under ${installDir}. Close them (or run "wsl --shutdown") and try the update again.`,551+ );552+ }553+ if (released === "unknown") {554+ // wsl.exe unavailable or the check timed out. An unreachable WSL555+ // VM cannot hold 9p handles open either, so proceed — but leave556+ // a trace in case an apply failure still follows.557+ yield* logUpdaterWarning(558+ "could not verify WSL released the install directory; proceeding with install",apps/desktop/src/wsl/DesktopWslEnvironment.ts line 863OutdatedResolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -716,4 +844,20 @@844+ }),845+ ).pipe(846+ Effect.timeoutOption(WSLINFO_TIMEOUT),716847 Effect.map(Option.flatten),717- Effect.orElseSucceed(() => Option.none<string>()),848+ Effect.orElseSucceed(() => Option.none<WslServerRuntimeState>()),718849 );719850851+// Finds every Linux process holding the target directory via cwd, exe, an852+// open fd, or a mapped file; SIGTERMs, then SIGKILLs stragglers, then853+// reports. `cd /` first so the probe shell itself (spawned with the854+// desktop's install-dir cwd mapped through /mnt) never counts as a holder.855+export const buildEnsurePathReleasedScript = (quotedLinuxPath: string): string => `cd /856+dir=${quotedLinuxPath}857+self=$$858+find_holders() {859+ for p in /proc/[0-9]*; do860+ pid=\${p#/proc/}861+ [ "$pid" = "$self" ] && continue862+ [ "$pid" = "1" ] && continue863+ if { readlink "$p/cwd"; readlink "$p/exe"; ls -l "$p/fd" 2>/dev/null; cat "$p/maps" 2>/dev/null; } 2>/dev/null | grep -qF "$dir"; then
- apps/desktop/src/backend/DesktopBackendManager.ts line 1146Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -937,0 +1050,21 @@1050+ // A process that spawns fine but never answers any probe URL1051+ // is not going to heal by silently cycling — surface the1052+ // reason (dialog + Windows fallback on the primary, inline1053+ // error on the WSL secondary) exactly like an exhausted1054+ // preflight failure.1055+ yield* logInstanceError(1056+ "backend never became reachable; surfacing readiness failure",1057+ { reason: error.message, attempt: attempt.value },1058+ );1059+ const shouldRestart = yield* (1060+ spec.onPreflightFailed?.({1061+ reason: error.message,1062+ fatal: false,1063+ retryLimit: MAX_READINESS_FAILURE_ATTEMPTS,1064+ }) ?? Effect.succeed(false)1065+ );1066+ yield* Ref.update(state, (latest) => ({1067+ ...latest,1068+ readinessFailureAttempt: 0,1069+ ...(shouldRestart ? {} : { desiredRunning: false }),1070+ }));apps/desktop/src/updates/DesktopUpdates.ts line 485Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -453,0 +462,21 @@462+ // The install cannot proceed: a backend process (or a Linux-side process463+ // holding /mnt handles into the install directory) survived teardown, so464+ // running the installer now would half-apply the update and corrupt the465+ // install. Restart the backends so the app stays usable, surface the466+ // failure through the update state machine, and leave the downloaded467+ // update in place so the user can retry.468+ const abortInstall = (469+ stoppedInstances: ReadonlyArray<DesktopBackendPool.DesktopBackendInstance>,470+ message: string,471+ ) =>472+ Effect.gen(function* () {473+ yield* logUpdaterError(message, { stage: "pre-install-teardown" });474+ yield* Effect.forEach(475+ stoppedInstances,476+ (instance) => instance.start.pipe(Effect.ignore),477+ { concurrency: "unbounded" },478+ );479+ yield* resetInstallAction;480+ yield* updateState((current) => reduceDesktopUpdateStateOnInstallFailure(current, message));481+ return { accepted: true, completed: false };482+ });
- apps/desktop/src/app/DesktopInstallIntegrity.ts line 78OutdatedResolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -0,0 +58,21 @@58+59+const { logWarning: logIntegrityWarning, logError: logIntegrityError } =60+ DesktopObservability.makeComponentLogger("desktop-install-integrity");61+62+export const checkInstallIntegrity: Effect.Effect<63+ DesktopInstallIntegrityResult,64+ never,65+ DesktopEnvironment.DesktopEnvironment | FileSystem.FileSystem66+> = Effect.gen(function* () {67+ const environment = yield* DesktopEnvironment.DesktopEnvironment;68+ const fileSystem = yield* FileSystem.FileSystem;69+70+ if (!environment.isPackaged) {71+ return { _tag: "Skipped", reason: "not a packaged build" } as const;72+ }73+74+ const manifestPath = environment.path.join(75+ environment.resourcesPath,76+ ...DESKTOP_BUILD_MANIFEST_RELATIVE_PATH.split("/"),77+ );78+ const raw = yield* fileSystem.readFileString(manifestPath, "utf-8").pipe(Effect.option);
- apps/desktop/src/wsl/DesktopWslEnvironment.ts line 937OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -719,0 +917,21 @@917+ // Script goes via stdin: wsl.exe re-escapes command-line args on the918+ // way into Linux, which mangles quoted paths with spaces.919+ const command = ChildProcess.make("wsl.exe", [...buildDistroArgs(input.distro), "--", "sh"], {920+ stdin: Stream.encodeText(921+ Stream.make(buildEnsurePathReleasedScript(shellQuote(linuxPath.value))),922+ ),923+ stdout: "pipe",924+ stderr: "ignore",925+ killSignal: "SIGTERM",926+ forceKillAfter: PROCESS_TERMINATE_GRACE,927+ });928+ const spawnResult = yield* spawner.spawn(command).pipe(929+ Effect.match({930+ onFailure: () => ({ _tag: "Failure" }) as const,931+ onSuccess: (handle) => ({ _tag: "Success", handle }) as const,932+ }),933+ );934+ if (spawnResult._tag === "Failure") {935+ // wsl.exe itself would not start — no running VM, so nothing can936+ // be holding /mnt handles either.937+ return "unavailable" as WslPathReleaseResult;
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/desktop/src/backend/DesktopBackendManager.ts line 1153OutdatedResolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -937,0 +1133,21 @@1133+ { reason: error.message, attempt: attempt.value },1134+ );1135+ const shouldRestart = yield* (1136+ spec.onPreflightFailed?.({1137+ reason: error.message,1138+ fatal: false,1139+ retryLimit: MAX_READINESS_FAILURE_ATTEMPTS,1140+ }) ?? Effect.succeed(false)1141+ );1142+ yield* Ref.update(state, (latest) => ({1143+ ...latest,1144+ readinessFailureAttempt: 0,1145+ ...(shouldRestart ? {} : { desiredRunning: false }),1146+ }));1147+ }1148+ // Terminate this run instead of leaving it in limbo (alive,1149+ // never ready, never restarted). Closing the run scope kills1150+ // the child; finalizeRun then schedules a restart when1151+ // desiredRunning is still set. The close is forked into the1152+ // parent scope because this fiber lives inside the run scope1153+ // being closed.
- apps/desktop/src/backend/DesktopBackendManager.ts line 959Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -859,6 +943,17 @@859- wasReady: latest.ready,943+ isCurrentRun: false,944+ nextState: latest,945+ pid: Option.none<number>(),946+ exitObserved: false,947+ stopRequested: false,948+ wasReady: false,949+ exitFailureAttempt: Option.none<number>(),860950 },861- next,951+ latest,862952 ] as const;863- },864- );953+ }954+955+ const countsTowardExitCap =956+ currentRun.exitObserved &&957+ !currentRun.stopRequested &&958+ !latest.ready &&959+ latest.desiredRunning;
- apps/desktop/src/backend/DesktopBackendPool.ts line 239OutdatedResolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -235,3 +235,5 @@235235 function* (failure: DesktopBackendManager.PreflightFailure) {236236 const { reason, fatal } = failure;237237 if (!fatal) {238+ const settings = yield* appSettings.get;239+ if (!settings.wslOnly) {
shivamhwp(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
e310a9a5-be8d-496e-b0cb-2823e06b141cYou can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share