Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(updater): relocate Windows update cache

vastsad61bdbbb731f
diff --git a/apps/desktop/electron/main/bootstrap/startup.ts b/apps/desktop/electron/main/bootstrap/startup.ts
index fae7ef296..4caf0754e 100644
--- a/apps/desktop/electron/main/bootstrap/startup.ts
+++ b/apps/desktop/electron/main/bootstrap/startup.ts
@@ -357,7 +357,11 @@ export function registerApplicationStartup(deps: StartupDependencies): void {
// GitHub discovery is delayed and time-bounded. Never start it before the
// first window exists: a hung feed used to sit in "checking" for ~60s and
// compete with boot for the net stack.
- updater.startAutoCheck();
+ // Adopt legacy NSIS baselines before the delayed feed check can start. The
+ // filesystem work runs after the first window exists and never blocks boot.
+ void updater
+ .reclaimRelocatedUpdateCache()
+ .finally(() => updater.startAutoCheck());
// createWindow awaits the initial load (loadFile resolves on
// did-finish-load), so the page is up; give React a beat to mount its
// event subscriptions before pushing the boot outcome.
diff --git a/apps/desktop/electron/main/update-cache-maintenance.ts b/apps/desktop/electron/main/update-cache-maintenance.ts
new file mode 100644
index 000000000..55970982f
--- /dev/null
+++ b/apps/desktop/electron/main/update-cache-maintenance.ts
@@ -0,0 +1,98 @@
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import {
+ adoptRelocatedUpdateCache,
+ discardDownloadedUpdate,
+ readUpdaterCacheDirName,
+ updateCacheDirFor,
+} from "./update-cache";
+import type { Logger } from "./logger";
+
+export type UpdateCacheMaintenanceOptions = {
+ resourcesPath: string;
+ activeBasePath: string;
+ legacyBasePath: string | null;
+ logger: Logger;
+};
+
+/**
+ * Operations that reclaim update download staging and adopt a relocated cache.
+ * The controller owns the updater state; this service owns cache filesystem work.
+ */
+export class UpdateCacheMaintenance {
+ private readonly resourcesPath: string;
+ private readonly activeBasePath: string;
+ private readonly legacyBasePath: string | null;
+ private readonly logger: Logger;
+
+ constructor(options: UpdateCacheMaintenanceOptions) {
+ this.resourcesPath = options.resourcesPath;
+ this.activeBasePath = options.activeBasePath;
+ this.legacyBasePath = options.legacyBasePath;
+ this.logger = options.logger;
+ }
+
+ /** Remove the staged installer after the feed confirms the running version is current. */
+ async discardDownloadedInstaller(): Promise<void> {
+ const dirs = this.cacheDirs();
+ if (!dirs) return;
+ try {
+ await discardDownloadedUpdate(dirs.active);
+ } catch (error) {
+ this.logger.app(
+ "updater",
+ "warn",
+ "failed to discard the downloaded update",
+ { data: { detail: String(error) } },
+ );
+ }
+ }
+
+ /** Adopt legacy delta baselines and pending update staging after relocation. */
+ async reclaimLegacyCache(): Promise<void> {
+ const dirs = this.cacheDirs();
+ if (!dirs?.legacy) return;
+ try {
+ await adoptRelocatedUpdateCache(dirs.active, dirs.legacy);
+ this.logger.app(
+ "updater",
+ "info",
+ "adopted the relocated update cache",
+ { data: { cacheDir: dirs.active } },
+ );
+ } catch (error) {
+ this.logger.app(
+ "updater",
+ "warn",
+ "failed to adopt the relocated update cache",
+ { data: { detail: String(error) } },
+ );
+ }
+ }
+
+ private cacheDirs(): { active: string; legacy: string | null } | null {
+ let feedConfig: string;
+ try {
+ feedConfig = readFileSync(
+ join(this.resourcesPath, "app-update.yml"),
+ "utf8",
+ );
+ } catch (error) {
+ this.logger.app(
+ "updater",
+ "warn",
+ "update feed configuration unavailable",
+ { data: { detail: String(error) } },
+ );
+ return null;
+ }
+ const dirName = readUpdaterCacheDirName(feedConfig);
+ if (!dirName) return null;
+ return {
+ active: updateCacheDirFor(this.activeBasePath, dirName),
+ legacy: this.legacyBasePath
+ ? updateCacheDirFor(this.legacyBasePath, dirName)
+ : null,
+ };
+ }
+}
diff --git a/apps/desktop/electron/main/update-cache.ts b/apps/desktop/electron/main/update-cache.ts
new file mode 100644
index 000000000..9b4465712
--- /dev/null
+++ b/apps/desktop/electron/main/update-cache.ts
@@ -0,0 +1,203 @@
+/**
+ * The electron-updater download cache: where it lives, and what may be reclaimed.
+ *
+ * electron-updater resolves the cache as `<base cache path>/<updaterCacheDirName>`.
+ * The base path is `%LOCALAPPDATA%` on Windows, `~/Library/Caches` on macOS,
+ * and `$XDG_CACHE_HOME` or `~/.cache` on Linux. The directory name is generated
+ * into the packaged `app-update.yml` by electron-builder. An installation on
+ * another drive therefore keeps a second full copy of every installer on the
+ * system drive, and the downloaded installer stays there for the whole life of
+ * the version (#1098).
+ *
+ * `pending/` holds the downloaded installer and must survive relocation too: the
+ * app may have been closed before the downloaded update was installed. It can be
+ * removed only once the feed reports that the running version is current. At the
+ * cache root, the installer copy and `current.blockmap` are differential-download
+ * cache even when downloads are relocated, so the next launch adopts those files.
+ * The old directory is removed only if it is empty; unrelated files are left
+ * alone rather than recursively deleted.
+ */
+import { copyFile, cp, mkdir, rename, rm, rmdir, stat } from "node:fs/promises";
+import { isAbsolute, join, resolve } from "node:path";
+
+/** Base cache directory override; an absolute path to the cache's parent. */
+export const UPDATE_CACHE_DIR_ENV = "PI_DESKTOP_UPDATE_CACHE_DIR";
+/** Download staging directory inside the cache directory. */
+export const UPDATE_DOWNLOAD_DIR_NAME = "pending";
+/** NSIS baseline copy (`CURRENT_APP_INSTALLER_FILE_NAME`). */
+export const UPDATE_INSTALLER_BASELINE_NAME = "installer.exe";
+/** Installed-version block map used alongside the differential baseline. */
+export const UPDATE_BLOCKMAP_BASELINE_NAME = "current.blockmap";
+
+export type UpdateCachePathInput = {
+ platform: NodeJS.Platform;
+ env: NodeJS.ProcessEnv;
+ home: string;
+};
+
+/** Mirror electron-updater's unexported `getAppCacheDir()` implementation. */
+export function defaultUpdateCacheBasePath(input: UpdateCachePathInput): string {
+ const { platform, env, home } = input;
+ if (platform === "win32") {
+ return env.LOCALAPPDATA || join(home, "AppData", "Local");
+ }
+ if (platform === "darwin") return join(home, "Library", "Caches");
+ return env.XDG_CACHE_HOME || join(home, ".cache");
+}
+
+/**
+ * An absolute `PI_DESKTOP_UPDATE_CACHE_DIR`, or null to keep the default.
+ * Relative paths are ignored because a packaged app's working directory is
+ * arbitrary and can change between launches.
+ */
+export function resolveUpdateCacheOverride(
+ value: string | undefined,
+): string | null {
+ const requested = value?.trim();
+ if (!requested || !isAbsolute(requested)) return null;
+ return resolve(requested);
+}
+
+/**
+ * The cache directory name from electron-builder's packaged feed configuration.
+ * Reject path separators and traversal before joining or deleting any directory.
+ */
+export function readUpdaterCacheDirName(appUpdateConfig: string): string | null {
+ const match = /^updaterCacheDirName:[ \t]*['"]?([^'"\r\n]+?)['"]?[ \t]*$/m.exec(
+ appUpdateConfig,
+ );
+ const name = match?.[1]?.trim() ?? "";
+ if (!name || name === "." || name.includes("..") || !/^[A-Za-z0-9@._-]+$/.test(name)) {
+ return null;
+ }
+ return name;
+}
+
+/** Cache directory for a given base and the packaged updater name. */
+export function updateCacheDirFor(
+ baseCachePath: string,
+ dirName: string,
+): string {
+ return join(baseCachePath, dirName);
+}
+
+/** Compare cache paths with Windows' case-insensitive path semantics. */
+export function sameUpdateCacheDir(
+ left: string,
+ right: string,
+ platform: NodeJS.Platform = process.platform,
+): boolean {
+ const resolved = [resolve(left), resolve(right)];
+ return platform === "win32"
+ ? resolved[0].toLowerCase() === resolved[1].toLowerCase()
+ : resolved[0] === resolved[1];
+}
+
+/**
+ * Redirect an updater instance without passing an AppAdapter to its constructor.
+ * electron-updater 6.8.9 sets `httpExecutor` to null when a custom adapter is
+ * passed; shadowing the base cache path on its default adapter preserves the
+ * feed transport and packaged configuration lookup.
+ */
+export function relocateUpdateCacheBasePath(
+ app: object,
+ baseCachePath: string,
+): void {
+ Object.defineProperty(app, "baseCachePath", { value: baseCachePath });
+}
+
+/** Remove downloaded installer staging, preserving differential baselines. */
+export async function discardDownloadedUpdate(cacheDir: string): Promise<void> {
+ await rm(join(cacheDir, UPDATE_DOWNLOAD_DIR_NAME), {
+ recursive: true,
+ force: true,
+ });
+}
+
+/**
+ * Adopt a relocated cache by moving its installed-version differential baselines
+ * and any pending installer out of the legacy user cache. Missing baselines are
+ * safe: electron-updater falls back to a full download. A pending update is
+ * preserved because the app may have been closed before installing it. Unknown
+ * files remain untouched, and the legacy directory is removed only when empty.
+ */
+export async function adoptRelocatedUpdateCache(
+ activeCacheDir: string,
+ legacyCacheDir: string,
+ platform: NodeJS.Platform = process.platform,
+): Promise<void> {
+ if (sameUpdateCacheDir(activeCacheDir, legacyCacheDir, platform)) return;
+ await mkdir(activeCacheDir, { recursive: true });
+ for (const name of [
+ UPDATE_INSTALLER_BASELINE_NAME,
+ UPDATE_BLOCKMAP_BASELINE_NAME,
+ ]) {
+ const legacyBaseline = join(legacyCacheDir, name);
+ const activeBaseline = join(activeCacheDir, name);
+ if ((await isFile(legacyBaseline)) && !(await exists(activeBaseline))) {
+ await moveFile(legacyBaseline, activeBaseline);
+ }
+ }
+ const legacyPending = join(legacyCacheDir, UPDATE_DOWNLOAD_DIR_NAME);
+ const activePending = join(activeCacheDir, UPDATE_DOWNLOAD_DIR_NAME);
+ if ((await isDirectory(legacyPending)) && !(await exists(activePending))) {
+ await moveDirectory(legacyPending, activePending);
+ }
+ try {
+ await rmdir(legacyCacheDir);
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ if (code !== "ENOTEMPTY" && code !== "EEXIST" && code !== "ENOENT") {
+ throw error;
+ }
+ }
+}
+
+async function exists(path: string): Promise<boolean> {
+ try {
+ await stat(path);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+async function isFile(path: string): Promise<boolean> {
+ try {
+ return (await stat(path)).isFile();
+ } catch {
+ return false;
+ }
+}
+
+async function isDirectory(path: string): Promise<boolean> {
+ try {
+ return (await stat(path)).isDirectory();
+ } catch {
+ return false;
+ }
+}
+
+/** Move a directory, falling back to recursive copy across volumes. */
+async function moveDirectory(from: string, to: string): Promise<void> {
+ try {
+ await rename(from, to);
+ return;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "EXDEV") throw error;
+ }
+ await cp(from, to, { recursive: true, errorOnExist: true, force: false });
+ await rm(from, { recursive: true, force: true });
+}
+
+/** Move a file, falling back to a copy when the directories are on different volumes. */
+async function moveFile(from: string, to: string): Promise<void> {
+ try {
+ await rename(from, to);
+ return;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "EXDEV") throw error;
+ }
+ await copyFile(from, to);
+ await rm(from, { force: true });
+}
diff --git a/apps/desktop/electron/main/updater.ts b/apps/desktop/electron/main/updater.ts
index 7eaeea770..ad7230568 100644
--- a/apps/desktop/electron/main/updater.ts
+++ b/apps/desktop/electron/main/updater.ts
@@ -12,12 +12,17 @@
* NSIS installer must not replace a no-install run.
* - Linux deb (no $APPIMAGE in env) → notify + link.
* - Unpackaged dev runs → disabled (no app-update.yml in resources).
+ *
+ * The installer download cache lives in the user cache directory rather than
+ * beside the installation; `PI_DESKTOP_UPDATE_CACHE_DIR` relocates it, and
+ * `./update-cache` owns what may be reclaimed from it (#1098).
*/
import { readFileSync } from "node:fs";
+import { homedir } from "node:os";
import { join } from "node:path";
import { app, shell } from "electron";
import electronUpdaterPkg from "electron-updater";
-import type { UpdateInfo, ProgressInfo } from "electron-updater";
+import type { AppUpdater, UpdateInfo, ProgressInfo } from "electron-updater";
import {
formatChangelogNotes,
IPC,
@@ -26,12 +31,34 @@ import {
} from "@pi-desktop/shared";
import type { Logger } from "./logger";
import { parseAllowedExternalUrl } from "./safe-open-external";
+import {
+ defaultUpdateCacheBasePath,
+ relocateUpdateCacheBasePath,
+ resolveUpdateCacheOverride,
+ UPDATE_CACHE_DIR_ENV,
+} from "./update-cache";
+import { UpdateCacheMaintenance } from "./update-cache-maintenance";
import {
raceWithTimeout,
UPDATE_CHECK_TIMEOUT_CODE,
} from "./update-timeout";
-const { autoUpdater } = electronUpdaterPkg;
+const { NsisUpdater, autoUpdater } = electronUpdaterPkg;
+
+/** Windows NSIS updater with a caller-selected cache base. */
+class RelocatedNsisUpdater extends NsisUpdater {
+ constructor(baseCachePath: string) {
+ super();
+ relocateUpdateCacheBasePath(this.app, baseCachePath);
+ }
+}
+
+function createRelocatedUpdater(
+ platform: NodeJS.Platform,
+ baseCachePath: string,
+): AppUpdater | null {
+ return platform === "win32" ? new RelocatedNsisUpdater(baseCachePath) : null;
+}
export const RELEASES_URL = "https://github.com/vastsa/PI-Desktop/releases/latest";
@@ -51,6 +78,11 @@ export type UpdaterOptions = {
* Called when attaching notes to update state; defaults to English.
*/
getLocale?: () => string | null | undefined;
+ /**
+ * `PI_DESKTOP_UPDATE_CACHE_DIR`; an absolute directory moves the updater's
+ * download cache out of the user cache directory. Empty keeps the default.
+ */
+ updateCacheDirOverride?: string | null;
/** Overrides for tests. */
platform?: NodeJS.Platform;
isPackaged?: boolean;
@@ -94,6 +126,8 @@ export class AppUpdaterController {
* is about to see is the update restart.
*/
private installRequested = false;
+ private readonly autoUpdater: AppUpdater;
+ private readonly cacheMaintenance: UpdateCacheMaintenance;
private readPackagedDistribution(
isPackaged: boolean,
@@ -139,6 +173,38 @@ export class AppUpdaterController {
process.env,
distribution,
);
+ const defaultCacheBasePath = defaultUpdateCacheBasePath({
+ platform,
+ env: process.env,
+ home: homedir(),
+ });
+ const requestedCacheBasePath =
+ options.updateCacheDirOverride ??
+ resolveUpdateCacheOverride(process.env[UPDATE_CACHE_DIR_ENV]);
+ const relocated =
+ mode !== "in-app" || !requestedCacheBasePath
+ ? null
+ : createRelocatedUpdater(platform, requestedCacheBasePath);
+ const activeBasePath =
+ relocated && requestedCacheBasePath
+ ? requestedCacheBasePath
+ : defaultCacheBasePath;
+ const legacyBasePath = relocated ? defaultCacheBasePath : null;
+ if (requestedCacheBasePath && !relocated && mode !== "disabled") {
+ this.logger.app(
+ "updater",
+ "warn",
+ "update cache relocation is not supported on this target",
+ { data: { platform } },
+ );
+ }
+ this.autoUpdater = relocated ?? autoUpdater;
+ this.cacheMaintenance = new UpdateCacheMaintenance({
+ resourcesPath: process.resourcesPath,
+ activeBasePath,
+ legacyBasePath,
+ logger: this.logger,
+ });
this.state = {
mode,
status: "idle",
@@ -158,17 +224,17 @@ export class AppUpdaterController {
if (this.listenersAttached) return;
this.listenersAttached = true;
- autoUpdater.autoDownload = this.state.mode === "in-app";
+ this.autoUpdater.autoDownload = this.state.mode === "in-app";
// electron-updater defaults allowPrerelease=true when the installed
// version has a prerelease component (e.g. 0.2.0-rc.6). That pins the
// GitHub provider to the same custom channel ("rc") and never offers a
// newer stable release such as 0.2.2. Always track GitHub's latest
// stable release so RC installs can graduate to stable.
- autoUpdater.allowPrerelease = false;
+ this.autoUpdater.allowPrerelease = false;
// Even if the user ignores the restart prompt, a downloaded update
// lands on the next normal quit.
- autoUpdater.autoInstallOnAppQuit = true;
- autoUpdater.logger = {
+ this.autoUpdater.autoInstallOnAppQuit = true;
+ this.autoUpdater.logger = {
info: (m: unknown) =>
this.logger.app("updater", "info", "updater diagnostic", {
data: { detail: String(m) },
@@ -187,10 +253,10 @@ export class AppUpdaterController {
}),
};
- autoUpdater.on("checking-for-update", () => {
+ this.autoUpdater.on("checking-for-update", () => {
this.setState({ status: "checking", error: undefined });
});
- autoUpdater.on("update-available", (info: UpdateInfo) => {
+ this.autoUpdater.on("update-available", (info: UpdateInfo) => {
this.setState({
status: this.state.mode === "in-app" ? "downloading" : "available",
availableVersion: info.version,
@@ -198,15 +264,21 @@ export class AppUpdaterController {
progressPercent: this.state.mode === "in-app" ? 0 : undefined,
});
});
- autoUpdater.on("update-not-available", () => {
+ this.autoUpdater.on("update-not-available", () => {
this.setState({
status: "up-to-date",
availableVersion: undefined,
releaseNotes: undefined,
progressPercent: undefined,
});
+ // In-app installs have no newer staged installer after the feed reports
+ // current. Keep the differential baselines for the next update. Manual
+ // delivery modes may share a cache with an installed NSIS copy.
+ if (this.state.mode === "in-app") {
+ void this.cacheMaintenance.discardDownloadedInstaller();
+ }
});
- autoUpdater.on("download-progress", (progress: ProgressInfo) => {
+ this.autoUpdater.on("download-progress", (progress: ProgressInfo) => {
this.setState({
status: "downloading",
// Preserve notes already attached when discovery advanced to download.
@@ -215,7 +287,7 @@ export class AppUpdaterController {
progressPercent: Math.round(progress.percent),
});
});
- autoUpdater.on("update-downloaded", (info: UpdateInfo) => {
+ this.autoUpdater.on("update-downloaded", (info: UpdateInfo) => {
this.setState({
status: "downloaded",
availableVersion: info.version,
@@ -223,7 +295,7 @@ export class AppUpdaterController {
progressPercent: 100,
});
});
- autoUpdater.on("error", (error: Error) => {
+ this.autoUpdater.on("error", (error: Error) => {
// Auto checks fail quietly (offline, private repo, rate limits);
// the renderer only surfaces errors when `manual` is set.
this.logger.app("updater", "warn", "updater error", { data: String(error) });
@@ -273,7 +345,7 @@ export class AppUpdaterController {
// first-window path. The race only bounds *our* wait; electron-updater
// may still finish later and emit available/up-to-date.
await raceWithTimeout(
- autoUpdater.checkForUpdates(),
+ this.autoUpdater.checkForUpdates(),
timeoutMs,
"update check",
);
@@ -310,7 +382,7 @@ export class AppUpdaterController {
if (this.state.status === "downloading" || this.state.status === "downloaded") {
return this.state;
}
- await autoUpdater.downloadUpdate();
+ await this.autoUpdater.downloadUpdate();
return this.state;
}
@@ -334,7 +406,12 @@ export class AppUpdaterController {
// the shutdown handler must already know this quit is the update restart.
this.installRequested = true;
// Fires 'before-quit' first, so host/sidecar shutdown still runs.
- autoUpdater.quitAndInstall(false, true);
+ this.autoUpdater.quitAndInstall(false, true);
+ }
+ /** Adopt legacy NSIS cache files before the first update check. */
+ reclaimRelocatedUpdateCache(): Promise<void> {
+ if (this.state.mode === "disabled") return Promise.resolve();
+ return this.cacheMaintenance.reclaimLegacyCache();
}
async openReleases(): Promise<void> {
diff --git a/apps/desktop/test/auto-update.test.mjs b/apps/desktop/test/auto-update.test.mjs
index 5593e8eef..024683a44 100644
--- a/apps/desktop/test/auto-update.test.mjs
+++ b/apps/desktop/test/auto-update.test.mjs
@@ -312,3 +312,16 @@ test("shared shipped-locale changelog is the in-app notes source of truth", () =
assert.match(stylesSource, /\.update-notice-notes/);
assert.match(stylesSource, /\.update-settings-notes/);
});
+
+test("update cache relocation and cleanup preserve the delta-update path", async () => {
+ const updateCacheSource = await read("../electron/main/update-cache.ts");
+ const maintenanceSource = await read("../electron/main/update-cache-maintenance.ts");
+ assert.match(updateCacheSource, /PI_DESKTOP_UPDATE_CACHE_DIR/);
+ assert.match(updaterSource, /new RelocatedNsisUpdater\(baseCachePath\)/);
+ assert.match(updaterSource, /relocateUpdateCacheBasePath\(this\.app, baseCachePath\)/);
+ assert.match(maintenanceSource, /readFileSync\([\s\S]*app-update\.yml/);
+ assert.match(mainSource, /reclaimRelocatedUpdateCache/);
+ assert.match(updateCacheSource, /UPDATE_INSTALLER_BASELINE_NAME/);
+ assert.match(updateCacheSource, /UPDATE_BLOCKMAP_BASELINE_NAME/);
+ assert.match(updateCacheSource, /UPDATE_DOWNLOAD_DIR_NAME/);
+});
diff --git a/apps/desktop/test/update-cache.test.mjs b/apps/desktop/test/update-cache.test.mjs
new file mode 100644
index 000000000..2cc126f11
--- /dev/null
+++ b/apps/desktop/test/update-cache.test.mjs
@@ -0,0 +1,174 @@
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+import { dirname, join as pathJoin } from "node:path";
+import { register } from "node:module";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+const here = dirname(fileURLToPath(import.meta.url));
+register(pathToFileURL(pathJoin(here, "helpers/ts-import-hooks.mjs")));
+
+const {
+ adoptRelocatedUpdateCache,
+ defaultUpdateCacheBasePath,
+ discardDownloadedUpdate,
+ readUpdaterCacheDirName,
+ resolveUpdateCacheOverride,
+ sameUpdateCacheDir,
+ updateCacheDirFor,
+} = await import("../electron/main/update-cache.ts");
+const { UpdateCacheMaintenance } = await import("../electron/main/update-cache-maintenance.ts");
+
+async function withTempDir(run) {
+ const root = await mkdtemp(join(tmpdir(), "pi-desktop-update-cache-"));
+ try {
+ await run(root);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+}
+
+test("default updater cache base mirrors electron-updater on supported platforms", () => {
+ assert.equal(
+ defaultUpdateCacheBasePath({
+ platform: "win32",
+ env: { LOCALAPPDATA: "C:/Users/A/AppData/Local" },
+ home: "C:/Users/A",
+ }),
+ "C:/Users/A/AppData/Local",
+ );
+ assert.equal(
+ defaultUpdateCacheBasePath({ platform: "win32", env: {}, home: "/home/a" }),
+ "/home/a/AppData/Local",
+ );
+ assert.equal(
+ defaultUpdateCacheBasePath({ platform: "darwin", env: {}, home: "/Users/a" }),
+ "/Users/a/Library/Caches",
+ );
+ assert.equal(
+ defaultUpdateCacheBasePath({
+ platform: "linux",
+ env: { XDG_CACHE_HOME: "/mnt/cache" },
+ home: "/home/a",
+ }),
+ "/mnt/cache",
+ );
+});
+
+test("cache override requires an absolute path and uses app-update.yml's directory name", () => {
+ assert.equal(resolveUpdateCacheOverride(undefined), null);
+ assert.equal(resolveUpdateCacheOverride(" "), null);
+ assert.equal(resolveUpdateCacheOverride("relative/cache"), null);
+ assert.equal(resolveUpdateCacheOverride("/mnt/PI cache"), "/mnt/PI cache");
+ assert.equal(
+ readUpdaterCacheDirName("provider: github\nupdaterCacheDirName: '@pi-desktopdesktop-updater'\n"),
+ "@pi-desktopdesktop-updater",
+ );
+ assert.equal(readUpdaterCacheDirName("provider: github\n"), null);
+ assert.equal(readUpdaterCacheDirName("updaterCacheDirName: ../outside"), null);
+ assert.equal(readUpdaterCacheDirName("updaterCacheDirName: nested/path"), null);
+ assert.equal(
+ updateCacheDirFor("/mnt/cache", "@pi-desktopdesktop-updater"),
+ "/mnt/cache/@pi-desktopdesktop-updater",
+ );
+ assert.equal(sameUpdateCacheDir("C:/Cache/UPDATER", "c:/cache/updater", "win32"), true);
+ assert.equal(sameUpdateCacheDir("/Cache/UPDATER", "/cache/updater", "linux"), false);
+});
+
+test("discarding a completed update removes only the pending installers", async () => {
+ await withTempDir(async (root) => {
+ const cache = join(root, "cache");
+ const pending = join(cache, "pending");
+ await mkdir(pending, { recursive: true });
+ await writeFile(join(pending, "PI-Desktop-Setup-0.15.8.exe"), "installer");
+ await writeFile(join(pending, "update-info.json"), "{}");
+ await writeFile(join(cache, "installer.exe"), "differential baseline");
+ await writeFile(join(cache, "current.blockmap"), "block map");
+
+ await discardDownloadedUpdate(cache);
+
+ assert.deepEqual(await readdir(cache), ["current.blockmap", "installer.exe"]);
+ assert.equal(await readFile(join(cache, "installer.exe"), "utf8"), "differential baseline");
+ assert.equal(await readFile(join(cache, "current.blockmap"), "utf8"), "block map");
+ });
+});
+
+test("adopting a relocated cache carries the NSIS delta baseline and removes the old cache", async () => {
+ await withTempDir(async (root) => {
+ const oldCache = join(root, "old-cache", "@pi-updater");
+ const activeCache = join(root, "D-drive", "@pi-updater");
+ await mkdir(join(oldCache, "pending"), { recursive: true });
+ await writeFile(join(oldCache, "installer.exe"), "installed version baseline");
+ await writeFile(join(oldCache, "current.blockmap"), "installed version map");
+ await writeFile(join(oldCache, "pending", "old-setup.exe"), "old installer");
+
+ await adoptRelocatedUpdateCache(activeCache, oldCache, "win32");
+
+ assert.equal(await readFile(join(activeCache, "pending", "old-setup.exe"), "utf8"), "old installer");
+ assert.equal(await readFile(join(activeCache, "installer.exe"), "utf8"), "installed version baseline");
+ assert.equal(await readFile(join(activeCache, "current.blockmap"), "utf8"), "installed version map");
+ await assert.rejects(readdir(oldCache), { code: "ENOENT" });
+ });
+});
+test("relocation does not overwrite active cache data or delete unknown legacy files", async () => {
+ await withTempDir(async (root) => {
+ const oldCache = join(root, "old-cache");
+ const activeCache = join(root, "active-cache");
+ await mkdir(join(oldCache, "pending"), { recursive: true });
+ await mkdir(join(activeCache, "pending"), { recursive: true });
+ await writeFile(join(oldCache, "installer.exe"), "legacy baseline");
+ await writeFile(join(activeCache, "installer.exe"), "active baseline");
+ await writeFile(join(oldCache, "pending", "staged.exe"), "legacy staged update");
+ await writeFile(join(activeCache, "pending", "staged.exe"), "active staged update");
+ await writeFile(join(oldCache, "user-file"), "unrecognized file");
+
+ await adoptRelocatedUpdateCache(activeCache, oldCache, "win32");
+
+ assert.equal(await readFile(join(activeCache, "installer.exe"), "utf8"), "active baseline");
+ assert.equal(await readFile(join(activeCache, "pending", "staged.exe"), "utf8"), "active staged update");
+ assert.equal(await readFile(join(oldCache, "user-file"), "utf8"), "unrecognized file");
+ });
+});
+
+test("adopting a relocated cache tolerates an absent old cache", async () => {
+ await withTempDir(async (root) => {
+ await adoptRelocatedUpdateCache(join(root, "active"), join(root, "missing"), "win32");
+ await assert.rejects(readdir(join(root, "missing")), { code: "ENOENT" });
+ });
+});
+test("cache maintenance reads the packaged updater name, adopts baselines, then discards stale staging", async () => {
+ await withTempDir(async (root) => {
+ const resources = join(root, "resources");
+ const legacyBase = join(root, "legacy-base");
+ const activeBase = join(root, "active-base");
+ const cacheName = "@pi-desktopdesktop-updater";
+ const legacyCache = join(legacyBase, cacheName);
+ const activeCache = join(activeBase, cacheName);
+ await mkdir(resources, { recursive: true });
+ await writeFile(
+ join(resources, "app-update.yml"),
+ `provider: github\nupdaterCacheDirName: '${cacheName}'\n`,
+ );
+ await mkdir(join(legacyCache, "pending"), { recursive: true });
+ await writeFile(join(legacyCache, "installer.exe"), "baseline");
+ await writeFile(join(legacyCache, "current.blockmap"), "blockmap");
+ await writeFile(join(legacyCache, "pending", "next-setup.exe"), "pending update");
+ const logs = [];
+ const maintenance = new UpdateCacheMaintenance({
+ resourcesPath: resources,
+ activeBasePath: activeBase,
+ legacyBasePath: legacyBase,
+ logger: { app: (...args) => logs.push(args) },
+ });
+
+ await maintenance.reclaimLegacyCache();
+ assert.equal(await readFile(join(activeCache, "installer.exe"), "utf8"), "baseline");
+ assert.equal(await readFile(join(activeCache, "current.blockmap"), "utf8"), "blockmap");
+ assert.equal(await readFile(join(activeCache, "pending", "next-setup.exe"), "utf8"), "pending update");
+ await maintenance.discardDownloadedInstaller();
+ assert.deepEqual((await readdir(activeCache)).sort(), ["current.blockmap", "installer.exe"]);
+ assert.equal(logs[0][2], "adopted the relocated update cache");
+ });
+});
diff --git a/docs/adr/0022-application-update-delivery.md b/docs/adr/0022-application-update-delivery.md
index e8537519f..83de9fe8d 100644
--- a/docs/adr/0022-application-update-delivery.md
+++ b/docs/adr/0022-application-update-delivery.md
@@ -89,3 +89,18 @@ builds NSIS and ZIP separately and stamps the ZIP app metadata with
even though ordinary ZIP launches do not set `PORTABLE_EXECUTABLE_FILE`. Users
extract the archive and run `PI-Desktop.exe`; the NSIS lane and existing data
directory remain unchanged.
+
+## Amendment (issue #1098)
+
+For Windows NSIS installs, `PI_DESKTOP_UPDATE_CACHE_DIR` may set an absolute,
+writable base for electron-updater's download cache. Main reads the cache's
+subdirectory name from the packaged `app-update.yml`, adopts the installer and
+block-map differential baselines plus any staged update from `%LOCALAPPDATA%`
+on startup, then removes the legacy cache directory only when empty. Unknown
+files and already-populated destinations are preserved rather than overwritten
+or recursively deleted. Once the feed confirms the running version is current,
+Main deletes only the obsolete `pending/` staging directory and keeps the
+baselines for the next differential update. The default
+cache location remains unchanged unless the variable is set. Main does not write
+to the installation directory: the NSIS script still writes its `installer.exe`
+baseline to `%LOCALAPPDATA%`, which Main adopts on the next launch.
diff --git a/docs/spec/03-runtime/07-process-model.md b/docs/spec/03-runtime/07-process-model.md
index 0039381f4..a86653b82 100644
--- a/docs/spec/03-runtime/07-process-model.md
+++ b/docs/spec/03-runtime/07-process-model.md
@@ -259,6 +259,23 @@ front of the launcher or a plugin panel (ADR 0086).
reaches `downloaded`. Electron still emits `before-quit`, so the normal
sidecar/host shutdown sequence runs before the updater replaces the app.
+For Windows NSIS installs, `PI_DESKTOP_UPDATE_CACHE_DIR` may override the
+electron-updater cache base with an absolute, writable directory. The packaged
+`app-update.yml` remains authoritative for the cache subdirectory name. On first
+startup after relocation, Main adopts the differential installer and block map
+from the legacy `%LOCALAPPDATA%` cache, preserves any staged update, then removes
+the old cache directory only when empty. Unknown files and an already-populated
+destination are preserved rather than overwritten or recursively deleted. When
+the update feed confirms the running version is current, Main removes only the
+`pending/` download staging directory; differential baselines stay available for
+the next small update. Do not point the override at an installation directory
+that requires elevation to write.
+
+The download-and-install path remains owned by Electron Main. The installer itself
+still creates `installer.exe` in `%LOCALAPPDATA%`; relocation adopts that copy on
+the next launch rather than changing the NSIS installer or writing into
+`Program Files` (issue #1098).
+
## 6. Dev vs release
### Dev
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 87f50bd4f..a6aa1745f 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -8535,6 +8535,7 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
| F — Persistence (import visibility) | E2E-257 |
| G — Plugins (import visibility) | E2E-257 |
| Quality (import visibility) | E2E-257 |
+| Quality (Windows updater cache) | E2E-260 |
| G — Plugins (Session Orchestrator) | E2E-PLUGIN-session-orchestrator-real-workers |
| Security (Session Orchestrator) | E2E-PLUGIN-session-orchestrator-real-workers |
| Quality (Session Orchestrator) | E2E-PLUGIN-session-orchestrator-real-workers |
@@ -8581,6 +8582,7 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
| M6+ (Session Orchestrator) | E2E-PLUGIN-session-orchestrator-real-workers |
| M6+ (Selected model order) | E2E-MODEL-selected-order-persists |
| M6+ (Session list responsiveness) | E2E-SESSION-list-refresh-keeps-desktop-responsive |
+| M6+ (Windows updater cache) | E2E-260 |
| M6+ (Independent session communication) | E2E-SESSION-independent-top-level-communication, E2E-SESSION-hover-card-model-and-links |
| M5 (Chat file references) | E2E-CHAT-shorthand-file-ref-opens-the-matching-file, E2E-CHAT-file-ref-opens-the-surface-that-owns-it |
| M6+ (Chat file references) | E2E-PLUGIN-file-view-collapse-persists |
@@ -15294,3 +15296,13 @@ renderer's durable transcript reads. No real model or provider is contacted.
`official-native-search.test.ts`; shared route tests reject lookalike hosts,
unsafe URLs and unknown gateways. The UI fixture does not prove Host/SQLite
persistence or live provider availability.
+
+#### E2E-260: Windows updater cache can be relocated and reclaimed safely
+
+- **Preconditions:** Packaged Windows x64 NSIS install, isolated user profile, and a writable cache directory on a non-system volume. Use a local updater-feed fixture; do not contact GitHub or a paid service.
+- **Steps:** 1) Seed the legacy `%LOCALAPPDATA%` updater cache with `installer.exe`, `current.blockmap`, and a staged update. 2) Launch with `PI_DESKTOP_UPDATE_CACHE_DIR` set to the isolated cache base. 3) Confirm Main adopts the baselines and staged update into the configured cache and removes the legacy cache. 4) Complete the staged update and launch the new version. 5) When the fixture reports no newer version, inspect the configured cache.
+- **Expected:** `app-update.yml` determines the cache subdirectory; the pending update and differential baselines survive relocation; when the running version is current only `pending/` is removed, while `installer.exe` and `current.blockmap` remain for the next delta. The default path remains unchanged when the override is unset. The app does not write the download into `Program Files`.
+- **Specs:** `03-runtime/07-process-model.md`, ADR 0022.
+- **Acceptance:** Cache-path, migration, and cleanup unit tests pass; Windows task-candidate validation confirms the updater feed transport, installer handoff, and filesystem behavior without a live release feed.
+- **Milestone:** M6+
+- **Status:** Unit and source-contract covered (`update-cache.test.mjs`, `auto-update.test.mjs`); Windows installer/E2E validation remains required.
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index 31fe676c5..632cb94c9 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -5392,6 +5392,7 @@ eleven-tool-round desktop paths are verified by
| 品质(Session Orchestrator) | E2E-PLUGIN-session-orchestrator-real-workers |
| C — 对话与流式(会话列表响应性) | E2E-SESSION-list-refresh-keeps-desktop-responsive |
| 品质(会话列表响应性) | E2E-SESSION-list-refresh-keeps-desktop-responsive |
+| 品质(Windows 更新缓存) | E2E-260 |
| 安全性(导入扩展依赖) | E2E-PLUGIN-import-extension-installs-dependencies、E2E-PLUGIN-import-extension-reports-missing-dependency |
| 品质(导入扩展依赖) | E2E-PLUGIN-import-extension-installs-dependencies、E2E-PLUGIN-import-extension-reports-missing-dependency |
| F / G / 安全性 / 品质 — 导入扩展的 npm 恢复 | E2E-PLUGIN-import-extension-recovers-missing-npm |
@@ -5427,6 +5428,7 @@ eleven-tool-round desktop paths are verified by
| M6+(Session Orchestrator) | E2E-PLUGIN-session-orchestrator-real-workers |
| M6+(已选模型顺序) | E2E-MODEL-selected-order-persists |
| M6+(会话列表响应性) | E2E-SESSION-list-refresh-keeps-desktop-responsive |
+| M6+(Windows 更新缓存) | E2E-260 |
| M6+(独立会话通信) | E2E-SESSION-independent-top-level-communication、E2E-SESSION-hover-card-model-and-links |
| M5(聊天文件引用) | E2E-CHAT-shorthand-file-ref-opens-the-matching-file、E2E-CHAT-file-ref-opens-the-surface-that-owns-it |
| M6+(聊天文件引用) | E2E-PLUGIN-file-view-collapse-persists |
@@ -8967,3 +8969,13 @@ the latest destination. These assertions measure work counts, not device FPS.
- **里程碑:** 提供商配置维护。
- **状态:** `pnpm test:e2e:provider-api-style`、`official-native-search.test.ts`;
共享路由测试覆盖伪装域名、不安全地址和未知中转站。未验证线上服务或 Host/SQLite 保存。
+
+#### E2E-260:Windows 更新缓存可安全迁移和回收
+
+- **前提:** 已打包的 Windows x64 NSIS 安装、隔离用户配置,以及非系统卷上的可写缓存目录。使用本地更新源 fixture;不得访问 GitHub 或付费服务。
+- **步骤:** 1)在旧 `%LOCALAPPDATA%` 更新缓存中准备 `installer.exe`、`current.blockmap` 和待安装更新。2)设置 `PI_DESKTOP_UPDATE_CACHE_DIR` 为隔离缓存根目录后启动。3)确认 Main 将差分基线和待安装更新迁移至配置目录,并清理旧目录。4)完成更新并启动新版本。5)fixture 报告没有更新后检查配置目录。
+- **预期:** 缓存子目录名以 `app-update.yml` 为准;迁移保留待安装更新及差分基线。确认当前版本已是最新版本后,只移除 `pending/`,`installer.exe` 和 `current.blockmap` 仍供下次增量更新使用。未设置覆盖变量时默认路径保持不变;应用不会将下载写入 `Program Files`。
+- **规格:** `03-runtime/07-process-model.md`、ADR 0022。
+- **验收:** 缓存路径、迁移和清理单测通过;Windows task-candidate 验证应覆盖更新源传输、安装器交接和文件系统行为,且不连接真实发布源。
+- **里程碑:** M6+
+- **状态:** 单测和源码契约覆盖(`update-cache.test.mjs`、`auto-update.test.mjs`);仍需 Windows 安装器/E2E 验证。