Skip to content

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

fix(storage): migrate first-run profiles, physical archives, and Windows links (#1671)

AR30724e0e5275af3
diff --git a/apps/desktop/electron.vite.config.ts b/apps/desktop/electron.vite.config.ts
index 0e8a18548..a50651a87 100644
--- a/apps/desktop/electron.vite.config.ts
+++ b/apps/desktop/electron.vite.config.ts
@@ -66,6 +66,7 @@ export default defineConfig({
// (D387); Electron main never calls it, and its transpiled dist
// breaks the main bundle's esbuild transform.
external: [
+ "original-fs",
"electron-updater",
"jiti",
"jiti/static",
diff --git a/apps/desktop/electron/main/storage/files.ts b/apps/desktop/electron/main/storage/files.ts
index 08056a804..78613a902 100644
--- a/apps/desktop/electron/main/storage/files.ts
+++ b/apps/desktop/electron/main/storage/files.ts
@@ -1,11 +1,15 @@
import { createHash } from "node:crypto";
-import { createReadStream, createWriteStream } from "node:fs";
-import { chmod, lstat, mkdir, open, readdir, readlink, realpath, rm, statfs, symlink, writeFile, readFile, stat } from "node:fs/promises";
+import { createReadStream, createWriteStream, promises as fs } from "original-fs";
import { Transform } from "node:stream";
import { pipeline } from "node:stream/promises";
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
import type { StorageProgress } from "@pi-desktop/shared";
import { STORAGE_PREFERENCE_FILE, type StorageRoots } from "./preferences";
+import { storageLinkTypes } from "./link-types";
+
+// Profile contents are physical files, including user-owned .asar archives.
+// Do not let Electron's virtual archive filesystem reinterpret these paths.
+const { chmod, lstat, mkdir, open, readdir, readlink, realpath, rm, statfs, symlink, writeFile, readFile } = fs;
const OWNER_FILE = ".pi-storage-owner.json";
export const DATA_CACHE_PATHS = ["cache", "plugins/cache/download", "plugins/cache/backup", "openable-attachments"];
@@ -29,12 +33,16 @@ async function optionalStat(path: string) {
export async function validateTarget(path: string, source: StorageRoots, anchor: string, retryId?: string): Promise<string> {
if (!isAbsolute(path) || path.includes("\0")) throw new Error("Select an absolute directory.");
- const target = await realpath(path);
- if (!(await lstat(path)).isDirectory() || (await lstat(path)).isSymbolicLink()) throw new Error("Select a real directory, not a symbolic link.");
+ const target = await canonicalPath(path);
+ const existing = await optionalStat(path);
+ if (existing && (!existing.isDirectory() || existing.isSymbolicLink())) throw new Error("Select a real directory, not a symbolic link.");
for (const sourcePath of [source.data, source.browser, anchor]) {
const canonical = await canonicalPath(sourcePath);
if (contains(canonical, target) || contains(target, canonical)) throw new Error("The destination must be separate from the current storage directories.");
}
+ // First-run profiles and destinations chosen in the native picker may not
+ // exist yet. Check separation before creating only the selected destination.
+ if (!existing) await mkdir(path, { recursive: true, mode: 0o700 });
const names = await readdir(target);
if (names.length) {
if (!retryId) throw new Error("Select an empty destination directory.");
@@ -52,7 +60,8 @@ async function inventory(from: string, to: string, entries: Entry[], browser = f
entries.push({ from, to, kind: "directory", bytes: 0, mode: info.mode });
for (const name of await readdir(from)) {
if (browser && excluded(name)) continue;
- await inventory(join(from, name), join(to, name), entries, browser);
+ // Installation metadata is excluded only at the browser root.
+ await inventory(join(from, name), join(to, name), entries);
}
} else if (info.isFile()) {
entries.push({ from, to, kind: "file", bytes: info.size, mode: info.mode });
@@ -67,7 +76,9 @@ async function digest(path: string): Promise<string> {
}
async function canonicalPath(path: string): Promise<string> {
if (await optionalStat(path)) return realpath(path);
- return join(await realpath(dirname(path)), relative(dirname(path), path));
+ const parent = dirname(path);
+ if (parent === path) return realpath(path);
+ return join(await canonicalPath(parent), relative(parent, path));
}
async function assertClaimed(target: string, id: string, names: string[]): Promise<void> {
const owner = join(target, OWNER_FILE);
@@ -84,7 +95,9 @@ function relocatedLink(entry: Entry, mappings: Array<[string, string]>): string
return isAbsolute(link) ? next : relative(dirname(entry.to), next);
}
// A relative external link also needs adjustment because its parent moved.
- return isAbsolute(link) ? link : relative(dirname(entry.to), absolute);
+ // Windows junction targets can include a trailing separator that symlink()
+ // removes. Use the same lexical absolute path for creation and verification.
+ return isAbsolute(link) ? (process.platform === "win32" ? absolute : link) : relative(dirname(entry.to), absolute);
}
/** Cold copy only: no database, browser, plugin, or log writer may be running. */
@@ -118,6 +131,9 @@ export async function migrateFiles(input: {
await inventory(await realpath(source.browser), next.browser, entries, true);
state.totalBytes = entries.reduce((sum, entry) => sum + entry.bytes, 0);
state.totalFiles = entries.filter((entry) => entry.kind !== "directory").length;
+ const links = entries.filter((entry) => entry.kind === "link");
+ const types = await storageLinkTypes(links.map((entry) => entry.from));
+ const linkTypes = new Map(links.map((entry, index) => [entry.from, types[index]]));
const space = await statfs(target);
if (space.bavail * space.bsize < state.totalBytes + 16 * 1024 * 1024) throw new Error("Not enough free space in the destination directory.");
const mappings: Array<[string, string]> = [[source.data, next.data], [source.browser, next.browser],
@@ -125,26 +141,30 @@ export async function migrateFiles(input: {
const hashes = new Map<string, string>();
state.stage = "copying";
for (const entry of entries) {
- if (entry.kind === "directory") await mkdir(entry.to, { recursive: false, mode: 0o700 });
- else if (entry.kind === "link") {
- const kind = process.platform === "win32" && (await stat(entry.from)).isDirectory() ? "junction" : undefined;
- await symlink(relocatedLink(entry, mappings), entry.to, kind);
- state.completedFiles++;
- } else {
- const hash = createHash("sha256");
- await pipeline(createReadStream(entry.from), new Transform({
- transform(chunk: Buffer, _encoding, callback) {
- hash.update(chunk);
- state.completedBytes += chunk.length;
- progress({ ...state });
- callback(null, chunk);
- },
- }), createWriteStream(entry.to, { flags: "wx", mode: 0o600 }));
- hashes.set(entry.from, hash.digest("hex"));
- const file = await open(entry.to, "r+");
- try { await file.sync(); } finally { await file.close(); }
- await chmod(entry.to, entry.mode & 0o777);
- state.completedFiles++;
+ try {
+ if (entry.kind === "directory") await mkdir(entry.to, { recursive: false, mode: 0o700 });
+ else if (entry.kind === "link") {
+ await symlink(relocatedLink(entry, mappings), entry.to, linkTypes.get(entry.from));
+ state.completedFiles++;
+ } else {
+ const hash = createHash("sha256");
+ await pipeline(createReadStream(entry.from), new Transform({
+ transform(chunk: Buffer, _encoding, callback) {
+ hash.update(chunk);
+ state.completedBytes += chunk.length;
+ progress({ ...state });
+ callback(null, chunk);
+ },
+ }), createWriteStream(entry.to, { flags: "wx", mode: 0o600 }));
+ hashes.set(entry.from, hash.digest("hex"));
+ const file = await open(entry.to, "r+");
+ try { await file.sync(); } finally { await file.close(); }
+ await chmod(entry.to, entry.mode & 0o777);
+ state.completedFiles++;
+ }
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ throw new Error(`Storage copy failed: ${entry.from} -> ${entry.to}\n${detail}`, { cause: error });
}
progress({ ...state });
}
diff --git a/apps/desktop/electron/main/storage/link-types.ts b/apps/desktop/electron/main/storage/link-types.ts
new file mode 100644
index 000000000..61999274d
--- /dev/null
+++ b/apps/desktop/electron/main/storage/link-types.ts
@@ -0,0 +1,32 @@
+import { execFile } from "node:child_process";
+import type { symlink } from "node:fs";
+import { join } from "node:path";
+
+/** Read reparse-point attributes, not their targets, including dangling links. */
+export async function storageLinkTypes(paths: string[]): Promise<Array<symlink.Type | undefined>> {
+ if (process.platform !== "win32") return paths.map(() => undefined);
+ if (!paths.length) return [];
+ const systemRoot = process.env.SystemRoot;
+ if (!systemRoot) throw new Error("Windows system directory is unavailable.");
+ const script = [
+ "$ErrorActionPreference = 'Stop'",
+ "[Console]::InputEncoding = [Text.UTF8Encoding]::new($false)",
+ "$paths = ConvertFrom-Json ([Console]::In.ReadToEnd())",
+ "$types = @(foreach ($path in $paths) { if (([IO.File]::GetAttributes($path) -band [IO.FileAttributes]::Directory) -ne 0) { 'junction' } else { 'file' } })",
+ "ConvertTo-Json -InputObject $types -Compress",
+ ].join("; ");
+ const output = await new Promise<string>((resolve, reject) => {
+ const child = execFile(join(systemRoot, "System32/WindowsPowerShell/v1.0/powershell.exe"),
+ ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script],
+ { windowsHide: true, maxBuffer: 16 * 1024 * 1024 },
+ (error, stdout) => error ? reject(error) : resolve(stdout));
+ child.stdin?.on("error", reject);
+ child.stdin?.end(JSON.stringify(paths));
+ });
+ const types: unknown = JSON.parse(output);
+ if (!Array.isArray(types) || types.length !== paths.length
+ || !types.every((type): type is symlink.Type => type === "junction" || type === "file")) {
+ throw new Error("Could not determine Windows storage link types.");
+ }
+ return types;
+}
diff --git a/apps/desktop/test/storage-directory-migration.test.mjs b/apps/desktop/test/storage-directory-migration.test.mjs
new file mode 100644
index 000000000..2571a2364
--- /dev/null
+++ b/apps/desktop/test/storage-directory-migration.test.mjs
@@ -0,0 +1,125 @@
+import assert from "node:assert/strict";
+import { randomUUID } from "node:crypto";
+import { mkdir, mkdtemp, readFile, realpath, stat, symlink, writeFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import { join } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import test from "node:test";
+
+const root = fileURLToPath(new URL("../../../", import.meta.url));
+const artifacts = join(root, ".artifacts");
+await mkdir(artifacts, { recursive: true });
+const scratch = await realpath(await mkdtemp(join(artifacts, "storage-directory-tests-")));
+const { build } = createRequire(new URL("../../../packages/agent-runtime/package.json", import.meta.url))("esbuild");
+const bundle = join(scratch, "storage.mjs");
+await build({ entryPoints: [join(root, "apps/desktop/electron/main/storage/files.ts")], outfile: bundle, bundle: true, platform: "node", format: "esm", alias: { "original-fs": "node:fs" } });
+const storage = await import(pathToFileURL(bundle).href);
+
+async function fixture() {
+ const directory = await mkdtemp(join(scratch, "case-"));
+ const source = { data: join(directory, "data"), browser: join(directory, "browser") };
+ await mkdir(source.browser);
+ return { directory, source, target: join(directory, "new drive", "PI storage") };
+}
+
+test("first-install migration creates a selected destination that does not exist", async () => {
+ const { source, target } = await fixture();
+ const selected = await storage.validateTarget(target, source, source.browser);
+ assert.equal(selected, await realpath(target));
+ const next = await storage.migrateFiles({ source, target: selected, anchor: source.browser, id: randomUUID(), progress: () => {}, relocate: async () => { assert.fail("An absent source needs no offline relocation"); } });
+ assert.equal((await stat(next.data)).isDirectory(), true);
+ assert.equal((await stat(next.browser)).isDirectory(), true);
+ await assert.rejects(stat(source.data), { code: "ENOENT" });
+});
+
+test("first-install validation handles several missing source ancestors", async () => {
+ const value = await fixture();
+ value.source.data = join(value.directory, "not initialized", "PI", "data");
+ await mkdir(value.target, { recursive: true });
+ assert.equal(await storage.validateTarget(value.target, value.source, value.source.browser), await realpath(value.target));
+ const next = await storage.migrateFiles({ source: value.source, target: await realpath(value.target), anchor: value.source.browser,
+ id: randomUUID(), progress: () => {}, relocate: async () => { assert.fail("No old data exists to relocate"); } });
+ assert.equal((await stat(next.data)).isDirectory(), true);
+ await assert.rejects(stat(join(value.directory, "not initialized")), { code: "ENOENT" });
+});
+
+test("existing conversations migrate to a newly selected destination without changing originals", async () => {
+ const { source, target } = await fixture();
+ await mkdir(join(source.data, "sessions"), { recursive: true });
+ await writeFile(join(source.data, "sessions", "conversation.jsonl"), "existing conversation\n");
+ await writeFile(join(source.browser, "Preferences"), '{"fixture":true}');
+ const selected = await storage.validateTarget(target, source, source.browser);
+ let relocated = false;
+ const next = await storage.migrateFiles({ source, target: selected, anchor: source.browser, id: randomUUID(), progress: () => {}, relocate: async (from, to) => {
+ assert.equal(from, source.data);
+ assert.equal(await readFile(join(to, "sessions", "conversation.jsonl"), "utf8"), "existing conversation\n");
+ relocated = true;
+ } });
+ assert.equal(relocated, true);
+ assert.equal(await readFile(join(source.data, "sessions", "conversation.jsonl"), "utf8"), "existing conversation\n");
+ assert.equal(await readFile(join(next.browser, "Preferences"), "utf8"), '{"fixture":true}');
+});
+
+test("migration excludes only the browser installation lock, not user files named lockfile", async () => {
+ const { source, target } = await fixture();
+ await mkdir(source.data);
+ await mkdir(join(source.browser, "user-files"));
+ await writeFile(join(source.browser, "lockfile"), "installation lock");
+ await writeFile(join(source.data, "lockfile"), "user data");
+ await writeFile(join(source.browser, "user-files/lockfile"), "nested user data");
+ const selected = await storage.validateTarget(target, source, source.browser);
+ const next = await storage.migrateFiles({ source, target: selected, anchor: source.browser, id: randomUUID(), progress: () => {}, relocate: async () => {} });
+ await assert.rejects(stat(join(next.browser, "lockfile")), { code: "ENOENT" });
+ assert.equal(await readFile(join(source.browser, "lockfile"), "utf8"), "installation lock");
+ assert.equal(await readFile(join(next.data, "lockfile"), "utf8"), "user data");
+ assert.equal(await readFile(join(next.browser, "user-files/lockfile"), "utf8"), "nested user data");
+});
+
+test("backup cleanup preflights active-root overlap before touching another old root", async () => {
+ const { directory, source } = await fixture();
+ await mkdir(source.data);
+ const oldData = join(directory, "old-data");
+ await mkdir(oldData);
+ await writeFile(join(oldData, "history.txt"), "retained backup");
+ await assert.rejects(storage.removeBackups([{ data: oldData, browser: source.browser }], source, source.browser), /overlaps active storage/);
+ assert.equal(await readFile(join(oldData, "history.txt"), "utf8"), "retained backup");
+});
+
+test("overlapping destinations are rejected before creating folders", async () => {
+ const { source } = await fixture();
+ const target = join(source.browser, "new", "destination");
+ await assert.rejects(storage.validateTarget(target, source, source.browser), /separate/);
+ await assert.rejects(stat(join(source.browser, "new")), { code: "ENOENT" });
+});
+
+test("existing unrelated destination files remain untouched", async () => {
+ const { source, target } = await fixture();
+ await mkdir(target, { recursive: true });
+ await writeFile(join(target, "user-file.txt"), "keep me");
+ await assert.rejects(storage.validateTarget(target, source, source.browser), /empty/);
+ assert.equal(await readFile(join(target, "user-file.txt"), "utf8"), "keep me");
+});
+
+test("a missing target below a linked source still cannot overlap active storage", async () => {
+ const { directory, source } = await fixture();
+ const alias = join(directory, "browser alias");
+ await symlink(source.browser, alias, process.platform === "win32" ? "junction" : "dir");
+ await assert.rejects(storage.validateTarget(join(alias, "new target"), source, source.browser), /separate/);
+ await assert.rejects(stat(join(source.browser, "new target")), { code: "ENOENT" });
+});
+
+test("a linked destination is rejected instead of writing through the link", async () => {
+ const { directory, source, target } = await fixture();
+ await mkdir(target, { recursive: true });
+ const alias = join(directory, "destination alias");
+ await symlink(target, alias, process.platform === "win32" ? "junction" : "dir");
+ await assert.rejects(storage.validateTarget(alias, source, source.browser), /symbolic link/);
+});
+
+test("a destination that is a file is rejected without changing it", async () => {
+ const { directory, source } = await fixture();
+ const target = join(directory, "document.txt");
+ await writeFile(target, "user document");
+ await assert.rejects(storage.validateTarget(target, source, source.browser), /directory/);
+ assert.equal(await readFile(target, "utf8"), "user document");
+});
diff --git a/apps/desktop/test/storage-maintenance.test.mjs b/apps/desktop/test/storage-maintenance.test.mjs
index 3bdb5cf1c..cea6e1c78 100644
--- a/apps/desktop/test/storage-maintenance.test.mjs
+++ b/apps/desktop/test/storage-maintenance.test.mjs
@@ -12,10 +12,14 @@ const storageDirectory = fileURLToPath(new URL("../electron/main/storage/", impo
const result = await build({
stdin: { contents: ['files', 'preferences', 'bootstrap', 'ipc'].map((name) => `export * from "./${name}";`).join("\n") + '\nexport { IPC } from "@pi-desktop/shared";\nexport { catalogs } from "@pi-desktop/i18n";', resolveDir: storageDirectory, loader: "ts" },
bundle: true, platform: "node", format: "esm", write: false,
+ alias: { "original-fs": "node:fs" },
plugins: [{ name: "external-storage-boundaries", setup(builder) {
builder.onResolve({ filter: /^@pi-desktop\/shared$/ }, () => ({ path: fileURLToPath(new URL("../../../packages/shared/src/protocol.ts", import.meta.url)) }));
builder.onResolve({ filter: /^@pi-desktop\/i18n$/ }, () => ({ path: fileURLToPath(new URL("../../../packages/i18n/src/index.ts", import.meta.url)) }));
- builder.onResolve({ filter: /^(electron|node:child_process)$|host-process$/ }, (args) => ({ path: args.path, namespace: "storage-test-boundary" }));
+ builder.onResolve({ filter: /^(electron|node:child_process)$|host-process$/ }, (args) => {
+ if (args.path === "node:child_process" && args.importer.endsWith("link-types.ts")) return { path: args.path, external: true };
+ return { path: args.path, namespace: "storage-test-boundary" };
+ });
builder.onLoad({ filter: /.*/, namespace: "storage-test-boundary" }, (args) => {
if (args.path === "electron") return { contents: "export const app = globalThis.__storageHarness.app; export const dialog = globalThis.__storageHarness.dialog; export const BrowserWindow = globalThis.__storageHarness.BrowserWindow;" };
if (args.path === "node:child_process") return { contents: "export function execFile(command, args, options, callback) { globalThis.__storageHarness.execFile(command, args, options, callback); }" };
diff --git a/crates/host-core/src/data_relocation.rs b/crates/host-core/src/data_relocation.rs
index b39525389..425aec6db 100644
--- a/crates/host-core/src/data_relocation.rs
+++ b/crates/host-core/src/data_relocation.rs
@@ -26,6 +26,7 @@ pub fn run_cli() -> Result<bool> {
struct Roots {
source: PathBuf,
canonical_source: PathBuf,
+ project_source: PathBuf,
destination: PathBuf,
}
@@ -40,6 +41,7 @@ impl Roots {
let suffix = path
.strip_prefix(&self.source)
.or_else(|_| path.strip_prefix(&self.canonical_source))
+ .or_else(|_| path.strip_prefix(&self.project_source))
.ok()?;
Some(self.destination.join(suffix).to_string_lossy().into_owned())
}
@@ -256,6 +258,12 @@ pub fn relocate(source: &Path, destination: &Path) -> Result<()> {
}
let roots = Roots {
source: source.to_path_buf(),
+ // Project repositories strip Windows verbatim prefixes and normalize
+ // separators; retain that same canonical spelling when matching keys.
+ project_source: PathBuf::from(
+ crate::db::normalize_project_path(&canonical_source.to_string_lossy())
+ .context("normalize canonical relocation source")?,
+ ),
canonical_source,
destination: destination.to_path_buf(),
};
@@ -358,7 +366,13 @@ fn relocate_database(roots: &Roots) -> Result<()> {
serde_json::from_str(&text).context("parse relocation database metadata")?;
roots.structured(&mut value).then(|| value.to_string())
} else {
- roots.remap(&text)
+ roots.remap(&text).map(|path| {
+ if table == "projects" {
+ crate::db::normalize_project_path(&path).unwrap_or(path)
+ } else {
+ path
+ }
+ })
};
if let Some(next) = next {
transaction.execute(
@@ -385,7 +399,10 @@ fn relocate_database(roots: &Roots) -> Result<()> {
for (namespace, key, text) in rows {
let next_key = if matches!(namespace.as_str(), "projectMemory" | "projectInstructions")
{
- roots.remap(&key).unwrap_or_else(|| key.clone())
+ roots
+ .remap(&key)
+ .map(|path| crate::db::normalize_project_path(&path).unwrap_or(path))
+ .unwrap_or_else(|| key.clone())
} else {
key.clone()
};
diff --git a/crates/host-core/src/data_relocation/tests.rs b/crates/host-core/src/data_relocation/tests.rs
index e3ff0d3a0..8cfde59a5 100644
--- a/crates/host-core/src/data_relocation/tests.rs
+++ b/crates/host-core/src/data_relocation/tests.rs
@@ -19,6 +19,44 @@ fn read_json(path: &Path) -> Value {
serde_json::from_slice(&fs::read(path).unwrap()).unwrap()
}
+#[test]
+fn relocated_project_memory_remains_readable_through_the_repository() {
+ // Keep the synthetic profile for inspection; no user data is involved.
+ let temporary = tempfile::tempdir().unwrap().keep();
+ let source = temporary.join("old profile");
+ let destination = temporary.join("new profile");
+ let project = source.join("projects").join("saved project");
+ fs::create_dir_all(&project).unwrap();
+ let database = Database::open_in_dir(&source).unwrap();
+ database
+ .set_project_memory(&project.to_string_lossy(), "Keep project memory")
+ .unwrap();
+ drop(database);
+ copy_directory(&source, &destination);
+ // A picker can return different case from the canonical spelling stored by
+ // project repositories. Windows canonicalize also adds a verbatim prefix.
+ #[cfg(windows)]
+ let source = temporary.join("OLD PROFILE");
+ relocate(&source, &destination).unwrap();
+ let moved_project = destination.join("projects").join("saved project");
+ let database = Database::open_in_dir(&destination).unwrap();
+ assert_eq!(
+ database
+ .get_project_memory(&moved_project.to_string_lossy())
+ .unwrap()
+ .content,
+ "Keep project memory"
+ );
+ let stored: String = database
+ .conn()
+ .query_row("SELECT path FROM projects", [], |row| row.get(0))
+ .unwrap();
+ assert_eq!(
+ stored,
+ crate::db::canonical_project_path(&moved_project.to_string_lossy()).unwrap()
+ );
+}
+
#[test]
fn relocates_a_real_copied_profile_without_recovery_or_changing_user_content() {
let temporary = tempfile::tempdir().unwrap();
@@ -158,7 +196,10 @@ fn relocates_a_real_copied_profile_without_recovery_or_changing_user_content() {
row.get(0)
})
.unwrap();
- assert_eq!(inside, destination.join("project").to_string_lossy());
+ assert_eq!(
+ inside,
+ crate::db::normalize_project_path(&destination.join("project").to_string_lossy()).unwrap()
+ );
let outside: String = connection
.query_row(
"SELECT path FROM projects WHERE name='outside'",
@@ -190,7 +231,10 @@ fn relocates_a_real_copied_profile_without_recovery_or_changing_user_content() {
row.get(0)
})
.unwrap();
- assert_eq!(memory_key, destination.join("project").to_string_lossy());
+ assert_eq!(
+ memory_key,
+ crate::db::normalize_project_path(&destination.join("project").to_string_lossy()).unwrap()
+ );
let group: String = connection
.query_row(
"SELECT value_json FROM kv WHERE ns='projectGroups'",
@@ -227,6 +271,7 @@ fn exact_path_boundaries_preserve_prose_prefix_neighbors_and_traversal() {
let roots = Roots {
source: temporary.path().join("old"),
canonical_source: temporary.path().join("old"),
+ project_source: temporary.path().join("old"),
destination: temporary.path().join("new"),
};
let inside = roots.source.join("nested/file");
diff --git a/docs/project/storage-migration-fixes.md b/docs/project/storage-migration-fixes.md
new file mode 100644
index 000000000..f2de6cf1c
--- /dev/null
+++ b/docs/project/storage-migration-fixes.md
@@ -0,0 +1,157 @@
+# Storage migration fixes: upstream review notes
+
+## Purpose and baseline
+
+PI-Desktop is a local-first Electron application. Settings and preload express
+user intent; Electron Main schedules cold filesystem maintenance; Rust Host Core
+owns SQLite and structured-path relocation. The original Electron userData
+directory remains the installation lock and bootstrap-pointer anchor.
+
+This document scopes the October 15, 2026 upstream draft for storage migration.
+The preparation base is `2eb333723bfdb92c3adf6c68cdf86d0ec995ce88`.
+
+## Old behavior, defect, and new behavior
+
+| Scenario | Previous behavior and observed defect | Candidate behavior |
+| --- | --- | --- |
+| New selected directory | `realpath` required the target to exist; selection failed with ENOENT. | Resolve the nearest existing ancestor, reject overlap, then create the selected directory and parents. |
+| First-run source with missing parents | Resolving only the immediate source parent failed before migration. | Resolve missing ancestors recursively without initializing an unused old profile. |
+| Packaged application in scratch | Electron fs treated app.asar as a virtual directory; copying could fail with ENOTDIR. | Use original-fs streams and metadata APIs to copy physical archive bytes and adjacent unpacked files. |
+| Dangling Windows directory/file link | Target-following stat could fail when the target was absent. | Read the link's own attributes in one Windows batch, preserve the link, and relocate only internal targets. |
+| Windows junction target spelling | Node/Electron could disagree about a trailing separator; verification failed although the target was equivalent. | Normalize external absolute Windows link targets lexically before creation and comparison. |
+| Project memory/instructions after relocation | Mixed separators and canonical-root spelling made repository lookups miss copied keys. | Normalize remapped project paths and memory/instruction keys using existing repository helpers. |
+| Nested browser files matching installation metadata | The root keep-list was applied recursively, omitting ordinary nested files. | Apply installation exclusions only at the browser root; retain nested and host-data namesakes. |
+| Windows backup cleanup | Older fork versions attempted to unlink the held lockfile and failed with EBUSY. | Already fixed in upstream d815ef15b; preserve that code and extend native lock/retry coverage. |
+| Copy failure diagnostics | A low-level error could lack the failing copy pair. | Include source, destination and the original error; do not skip the failed entry or publish an incomplete destination. |
+
+Upstream's Windows lock fix was committed October 13, 2026. It is not new code
+contributed by this draft. The upstream existing test covers both lock names.
+This draft keeps that test and adds an actual Electron-held Windows lock case.
+
+## Implementation map
+
+- `apps/desktop/electron/main/storage/files.ts`: target resolution, physical
+ filesystem operations, root-only exclusions, junction normalization and copy
+ diagnostics. Existing copy verification and cleanup preflight are retained.
+- `apps/desktop/electron/main/storage/link-types.ts`: Windows reparse-point
+ attributes without dereferencing targets. Paths are sent as JSON on stdin,
+ not interpolated into a shell command. Other platforms keep their existing
+ symlink behavior.
+- `apps/desktop/electron.vite.config.ts`: externalize Electron's original-fs;
+ preserve the current upstream ESM dirname handling.
+- `crates/host-core/src/data_relocation.rs`: consistent project path/key spelling;
+ keep upstream worktrees.path relocation. SQLite remains exclusively Rust-owned.
+- `apps/desktop/test/storage-directory-migration.test.mjs` and
+ `crates/host-core/src/data_relocation/tests.rs`: regression coverage at the
+ public filesystem and repository interfaces.
+- `apps/desktop/test/storage-maintenance.test.mjs`,
+ `scripts/e2e-storage-bootstrap.mjs`, `scripts/e2e-storage-migration.mjs`:
+ existing Node harnesses alias original-fs to the real Node filesystem; native
+ Electron tests separately prove behavior that Node cannot reproduce.
+- `scripts/e2e-storage-directory.mjs`, `scripts/e2e-storage-files.mjs`,
+ `scripts/e2e-storage-backup-lock.mjs` and their `scripts/e2e/` fixtures:
+ Settings/cold-bootstrap and native filesystem regressions.
+- `package.json`: wire the focused scripts into the existing storage E2E command.
+
+## Reproduction and verification
+
+Use synthetic profiles only. Reuse the installed development toolchain and
+compatible dependencies; keep mutable profiles/artifacts isolated. Never point
+these fixtures at a user's installed profile.
+
+```text
+node --test apps/desktop/test/storage-directory-migration.test.mjs
+cargo test -p host-core --locked relocated_project_memory_remains_readable_through_the_repository
+node scripts/e2e-storage-files.mjs
+node scripts/e2e-storage-backup-lock.mjs
+node scripts/e2e-storage-directory.mjs
+```
+
+The Settings workflow requires built renderer CSS, current shared JS and a
+candidate Host supplied through `PI_DESKTOP_HOST_BIN`. Its production Settings
+controls, preload, storage IPC, cold bootstrap and reopened Host are real. The
+picker selection and relaunch dispatch are scripted. Each startup phase uses a
+separate Electron process. Set `PI_STORAGE_E2E_SOURCE_ROOT` to an isolated folder
+on another drive to exercise cross-volume migration.
+
+The archive suite covers opaque and valid ASAR files, adjacent unpacked data,
+dangling internal/external links, Node-created junction spelling and actionable
+copy-error reporting. The lock fixture keeps a real single-instance lock while
+retrying cleanup after the old payload is already absent. This is not a complete
+large-profile backup-deletion test. Fixtures are retained for diagnosis.
+
+## Evidence boundaries
+
+Current candidate checks ran on October 15, 2026 with Windows, Electron 43.6.0,
+Node 24.19.0 and Rust 1.90.0. The implementation was prepared against the upstream
+base above. Executable candidate 5586c50bf900f7ba6b7e9b4f8d2385db21b15e31
+passed the refreshed Host, directory, native archive/lock and Settings workflows
+after incorporating that base. The later documentation-only commit does not
+change executable sources. The local PR draft records the final branch head.
+Earlier fork results are not counted in this table.
+
+| Check actually executed | Result |
+| --- | --- |
+| Unmodified upstream reproduction | New-target ENOENT, missing-source-parent ENOENT and nested lockfile omission confirmed |
+| Focused directory regression | 10 passed |
+| Native Electron ASAR/link/copy-error suite | 6 passed |
+| Native installation-lock cleanup retry | Passed; lock, pointer and active history retained |
+| Rust repository-level project-memory regression | 1 passed; 918 other tests filtered out |
+| Candidate Host development build | Passed with locked Cargo dependencies |
+| Settings, cold maintenance and reopened Host | 3 passed; first-install and existing-profile migration D: to C:, plus backup retry |
+| Workspace TypeScript builds / Desktop typecheck | 9 package builds and Desktop typecheck passed |
+| Focused Biome / Rust fmt / style tokens / agent policy | Passed |
+| Documentation checks | 85 locale pairs and 575 pages passed |
+| Visual review | Reopened migration path/backups and post-cleanup removal of backup controls inspected |
+| Full Desktop build | Blocked: reused electron-vite cannot resolve esbuild |
+
+Settings renderer code, preload, storage IPC and Host use candidate sources.
+Only unchanged Settings CSS is reused from an earlier upstream-PR build; its
+renderer JS is not executed. The candidate Host was compiled from this worktree
+using the existing Cargo target cache.
+
+The reused DOMPurify 3.4.13 and Vitest 4.1.10 predate the current manifest minimums
+3.4.17 and 4.1.11. Neither participates in the focused storage fixtures. No fresh
+dependency installation was performed. Full exact-lockfile build/package
+qualification, full Rust/clippy, macOS/Linux, installer entry points and PR
+integration validation remain outstanding. Existing cleanup suites that delete
+fixture data were not executed; the focused fixtures retain their profiles.
+The current results therefore support review of a draft, not release approval.
+
+Historical source commits:
+
+| Source commit | Purpose |
+| --- | --- |
+| 8bdc4765a | New destinations, first-run profiles and normalized project keys |
+| a00577626 | Physical archives, dangling links and copy-error context |
+| f0002104e | Windows junction trailing-separator normalization |
+| 155141316 | Windows lock protection, root-only exclusions and cleanup retry coverage |
+
+The source fork had Windows acceptance runs. Its 0.18.2 release predates the last
+backup-lock change. A subsequent authorized local cleanup used the production
+selection logic with a Recycle Bin adapter; it does not certify the stock product
+deletion path and is not part of this source change.
+
+## Preserved behavior and limits
+
+- Cold migration, existing verification and atomic pointer publication remain.
+- Existing custom volumes must be available; this is not automatic recovery to
+ a blank profile when a configured drive disappears.
+- Originals remain backups until a separate explicit cleanup confirmation.
+- Source/target overlap, unrelated destination contents and linked destinations
+ remain rejected; external project directories are not moved.
+- No schema, protocol, version, dependency, SDK permission or release change.
+- No new compatibility layer, automatic fallback or integrity gate is added.
+- Unknown plugin-private absolute references remain the plugin owner's concern.
+- Windows link creation still requires the platform's permissions; errors remain
+ visible rather than dropping links.
+- macOS/Linux runtime and installer entry points need separate acceptance.
+
+## Handoff and publication
+
+Review the local PR body in Summary / Reproduction / Changes / Validation / Scope
+/ Review order. Before publication, refresh upstream, rerun applicable checks on
+the exact candidate, inspect the file list for unrelated fork changes and private
+artifacts, then obtain the user's approval to publish. Do not use a fork release
+branch as the upstream PR head. No integration-candidate or merge result is
+claimed until an actual upstream PR exists and its gates have run.
diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.md
index e3ce8fb17..bae26f935 100644
--- a/docs/spec/03-runtime/04-data-storage.md
+++ b/docs/spec/03-runtime/04-data-storage.md
@@ -89,6 +89,23 @@ both source and copied files. An interrupted copy may be retried only with its
matching ownership marker; nonempty/unrelated destinations and overlapping roots
are rejected. The stable installation lock prevents competing managed launches.
+Filesystem maintenance uses Electron's `original-fs`: archives such as `app.asar`
+inside session scratch or downloaded applications remain physical files, not
+virtual directories. Their bytes and adjacent `.asar.unpacked` directories migrate
+unchanged. Windows link types are read from the link's own filesystem attributes
+in one batch, not by following its target; dangling directory/file links remain
+links, and internal targets are relocated without requiring them to exist.
+Windows absolute link targets are lexically normalized before creation and
+verification, so trailing separators from junctions do not cause false failures. Copy
+failures include the source and destination paths in the existing local error
+detail. They never skip an entry or publish the destination as the active profile.
+
+Confirming a directory selected in Settings creates it when it does not exist,
+including missing parent directories. Overlap checks run before creating anything.
+A first-install data root may be absent together with its parents; validation
+resolves the nearest existing ancestor without creating an unused old profile.
+This does not recreate an unavailable custom storage volume during startup.
+
Rust's offline `--relocate-data <old-root> <copied-root>` mode owns structured
path relocation in the copied SQLite index, transcripts/revisions/checkpoints,
outbox, installed plugin registry and agent capability metadata. It does not boot
@@ -98,6 +115,11 @@ narrative text, commands, source code, secrets, and arbitrary plugin-private for
are preserved. Credentials and their machine key migrate as bytes with their
permissions. SQLite ownership stays exclusively in Rust.
+Relocated project database paths and project-memory/instruction keys retain the
+repository's normalized project-path spelling. In particular, Windows migration
+must not turn slash-normalized lookup keys into mixed-separator keys that make
+existing project memory appear empty after reopening the Host.
+
Only after validation/relocation succeeds is the flushed bootstrap pointer
atomically replaced. Errors keep the old profile active and visible in settings;
retrying the same destination uses the failed job's ownership identity. A crash
@@ -107,6 +129,13 @@ Original directories remain explicit backups. Deleting these requires a separate
settings confirmation after checking new-location functionality, including plugins
that may own absolute references the host cannot safely rewrite. Backup cleanup
preflights every root and protects active storage and bootstrap/lock files.
+The stable anchor retains Chromium's Windows `lockfile` alongside `Singleton*`
+and `storage-location.json`; these installation files are also excluded from
+browser-profile copies. Cleanup never releases the live single-instance lock.
+The exclusion applies only to the browser root, not same-named nested user files
+or files inside the host data root.
+Retry after a partially completed cleanup tolerates already-absent old roots,
+then clears the backup list only after the remaining cleanup succeeds.
Cache cleanup is a separate confirmed cold-restart operation. Its filesystem
allowlist is `cache/`, `plugins/cache/download/`, `plugins/cache/backup/`,
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index b4972377c..243bb8cc7 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -44,6 +44,26 @@
- **Preconditions:** Dedicated request worktree, current remote-main base, shared
compatible host toolchain, built host-core and desktop, isolated temporary data
and Chromium profiles. No user's running desktop, provider, or network is used.
+- **First-install / new-directory regression:** Run
+ `node scripts/e2e-storage-directory.mjs` with `PI_DESKTOP_HOST_BIN` pointing
+ to the candidate Host. The production storage controls and preload invoke real
+ Main handlers through native mouse clicks, schedule cold maintenance, and reopen
+ the migrated Electron profile and Host. Cover an absent data root with missing
+ parents and an existing conversation with attachments, settings and project
+ memory. The chosen destination initially does not exist. Set
+ `PI_STORAGE_E2E_SOURCE_ROOT` to a temporary folder on a different drive for
+ cross-volume coverage. Verify browser localStorage, conversation/attachment
+ reads, project-memory lookup, original backups and the displayed new path.
+ Only native picker selection and relaunch dispatch are scripted; each startup
+ phase is a separate real Electron process. Keep screenshots and synthetic
+ profiles under `.artifacts/` for inspection rather than deleting them.
+- **Electron filesystem regression:** Run `node scripts/e2e-storage-files.mjs`
+ in real Electron, not `ELECTRON_RUN_AS_NODE`. Seed valid and opaque `.asar`
+ files, live and dangling file/directory links, Unicode paths, and a destination
+ collision. Expect byte-preserving copies, relocated internal links, unchanged
+ external targets, and path-specific errors without mutating originals. The
+ existing-profile Settings journey also includes an archive and a dangling
+ dependency junction, then verifies history and browser state after reopening.
- **Steps:** Through the production Settings page, choose/cancel a destination,
confirm/retry migration, and confirm cache/backup cleanup. Seed a real host with
sessions, queued attachments, project metadata, credentials and a local installed
@@ -59,8 +79,20 @@
survive migration/restart. Cache cleanup preserves durable state; backup cleanup
retains active data and the stable bootstrap pointer. Filesystem regression tests
reject unsafe targets, redirecting links, wrong ownership and active-root overlap.
+- **Windows junction spelling:** The filesystem suite includes a Node-created
+ junction whose target ends with a separator. Copying it in Electron must
+ preserve the target without a false symbolic-link verification failure.
+- **Installation lock and cleanup retry:** `e2e-storage-backup-lock.mjs` holds a
+ real Electron single-instance lock while retrying cleanup with the old data
+ already absent. Verify the lock, bootstrap pointer and current history remain.
+ The Settings directory suite additionally confirms cleanup, cold-restarts and
+ reopens the active Host; backup controls disappear and current attachments and
+ browser state remain readable. These retry fixtures are not full-payload
+ deletion tests and retain their synthetic profiles.
- **Coverage:** `pnpm test:e2e:storage` runs `e2e-storage-settings.mjs`,
- `e2e-storage-migration.mjs`, and `e2e-storage-bootstrap.mjs`. The first uses the
+ `e2e-storage-migration.mjs`, `e2e-storage-bootstrap.mjs`,
+ `e2e-storage-directory.mjs`, `e2e-storage-files.mjs`, and
+ `e2e-storage-backup-lock.mjs`. The first uses the
production renderer/API with only preload mocked; the latter suites run real
host/Electron processes and production maintenance. The bootstrap harness
intercepts relaunch to inspect its result, then explicitly starts another isolated
diff --git a/package.json b/package.json
index 31d0c4aa0..18b92b401 100644
--- a/package.json
+++ b/package.json
@@ -22,7 +22,7 @@
"test:host": "cargo test -p host-core",
"test:e2e": "node scripts/e2e-smoke.mjs",
"test:e2e:jev": "node --test apps/desktop/test/jev-api-key-check.test.mjs apps/desktop/test/jev-config.test.mjs apps/desktop/test/jev-settings-user-path.test.mjs apps/desktop/test/jev-service-setup-user-path.test.mjs apps/desktop/test/jev-session-launch.test.mjs && node packages/agent-runtime/node_modules/vitest/vitest.mjs run packages/agent-runtime/src/jev-classifier-tool.test.ts packages/agent-runtime/src/runtime.test.ts -t Jev --config packages/agent-runtime/vitest.config.ts",
- "test:e2e:storage": "node scripts/e2e-storage-settings.mjs && node scripts/e2e-storage-migration.mjs && node scripts/e2e-storage-bootstrap.mjs",
+ "test:e2e:storage": "node scripts/e2e-storage-settings.mjs && node scripts/e2e-storage-migration.mjs && node scripts/e2e-storage-bootstrap.mjs && node scripts/e2e-storage-directory.mjs && node scripts/e2e-storage-files.mjs && node scripts/e2e-storage-backup-lock.mjs",
"test:e2e:asktool-card": "node scripts/e2e-asktool-card.mjs",
"test:e2e:worktree-live": "node scripts/e2e-worktree-live.mjs",
"test:e2e:question-notification": "node scripts/e2e-question-notification.mjs",
diff --git a/scripts/e2e-storage-backup-lock.mjs b/scripts/e2e-storage-backup-lock.mjs
new file mode 100644
index 000000000..5094aa2aa
--- /dev/null
+++ b/scripts/e2e-storage-backup-lock.mjs
@@ -0,0 +1,32 @@
+#!/usr/bin/env node
+/** Native installation-lock regression; retain all synthetic files after testing. */
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { createRequire } from "node:module";
+import { mkdir, mkdtemp, readFile, realpath, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { repositoryRoot, resolveElectronBinary } from "./e2e/boot.mjs";
+
+const root = repositoryRoot();
+await mkdir(join(root, ".artifacts"), { recursive: true });
+const artifacts = await realpath(await mkdtemp(join(root, ".artifacts/storage-backup-lock-")));
+for (const name of ["installation", "active-data", "active-browser"]) await mkdir(join(artifacts, name));
+await writeFile(join(artifacts, "installation/storage-location.json"), "retained pointer");
+await writeFile(join(artifacts, "active-data/history.txt"), "current history");
+const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");
+const main = join(artifacts, "main.mjs");
+await build({ entryPoints: [join(root, "scripts/e2e/storage-backup-lock-main.mjs")],
+ outfile: main, bundle: true, platform: "node", format: "esm", external: ["electron", "original-fs"] });
+const env = { ...process.env, PI_STORAGE_BACKUP_ARTIFACTS: artifacts };
+delete env.ELECTRON_RUN_AS_NODE;
+const child = spawn(resolveElectronBinary(root).electronBinary, [main], { env, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
+let output = "";
+for (const stream of [child.stdout, child.stderr]) stream.on("data", chunk => { output += chunk; });
+const timeout = setTimeout(() => child.kill(), 30000);
+let code;
+try { code = await new Promise((resolve, reject) => { child.on("error", reject); child.on("close", resolve); }); }
+finally { clearTimeout(timeout); await writeFile(join(artifacts, "electron.log"), output); }
+const report = JSON.parse(await readFile(join(artifacts, "result.json"), "utf8"));
+console.log(JSON.stringify({ artifacts, ...report }, null, 2));
+assert.equal(code, 0, report.error ?? output);
+assert(report.passed);
diff --git a/scripts/e2e-storage-bootstrap.mjs b/scripts/e2e-storage-bootstrap.mjs
index 3f083e8a1..dc8d4cc4e 100644
--- a/scripts/e2e-storage-bootstrap.mjs
+++ b/scripts/e2e-storage-bootstrap.mjs
@@ -82,7 +82,7 @@ if (process.env.STORAGE_E2E_MODE === 'seed') {
}
})().catch((error) => { console.error(error); originalExit(1); });
`, resolveDir: root, sourcefile: "storage-bootstrap-e2e.mjs", loader: "js" },
- outfile: main, bundle: true, platform: "node", format: "esm", target: "node24", external: ["electron"],
+ outfile: main, bundle: true, platform: "node", format: "esm", target: "node24", external: ["electron", "original-fs"],
alias: { "@pi-desktop/i18n": join(root, "packages/i18n/src/index.ts") },
plugins: [{ name: "host-binary-location", setup(builder) {
builder.onResolve({ filter: /host-process$/ }, () => ({ path: "host-binary", namespace: "host-binary" }));
diff --git a/scripts/e2e-storage-directory.mjs b/scripts/e2e-storage-directory.mjs
new file mode 100644
index 000000000..e296a952e
--- /dev/null
+++ b/scripts/e2e-storage-directory.mjs
@@ -0,0 +1,182 @@
+#!/usr/bin/env node
+/** Settings -> real IPC -> cold bootstrap -> reopened Host; no providers or user profiles. */
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { createRequire } from "node:module";
+import { mkdir, mkdtemp, readFile, readlink, realpath, stat, symlink, writeFile } from "node:fs/promises";
+import { dirname, join, resolve } from "node:path";
+import { Host, resolveHostBinary } from "./e2e/host.mjs";
+import { repositoryRoot, resolveElectronBinary } from "./e2e/boot.mjs";
+
+const root = resolve(repositoryRoot());
+const artifactRoot = process.env.PI_STORAGE_E2E_ARTIFACTS ?? join(root, ".artifacts");
+await mkdir(artifactRoot, { recursive: true });
+const artifacts = await realpath(await mkdtemp(join(artifactRoot, "storage-directory-e2e-")));
+const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");
+const hostBinary = resolveHostBinary();
+const electronBinary = resolveElectronBinary(root).electronBinary;
+const sourceRoot = process.env.PI_STORAGE_E2E_SOURCE_ROOT ?? artifacts;
+await mkdir(sourceRoot, { recursive: true });
+
+await build({ entryPoints: [join(root, "scripts/e2e/storage-directory.jsx")],
+ outfile: join(artifacts, "renderer.js"), bundle: true, platform: "browser", format: "esm", jsx: "automatic",
+ define: { "process.env.NODE_ENV": '"production"', "import.meta.env.DEV": "false" },
+ alias: { "@pi-desktop/shared": join(root, "packages/shared/src/index.ts"),
+ "@pi-desktop/shared/changelog-loader": join(root, "packages/shared/src/changelog-loader.ts"),
+ "@pi-desktop/i18n": join(root, "packages/i18n/src/index.ts"),
+ "@pi-desktop/voice-runtime/live": join(root, "packages/voice-runtime/src/live/index.ts"),
+ react: join(root, "apps/desktop/node_modules/react"),
+ "react-dom": join(root, "apps/desktop/node_modules/react-dom"),
+ i18next: join(root, "apps/desktop/node_modules/i18next"),
+ "react-i18next": join(root, "apps/desktop/node_modules/react-i18next") },
+ nodePaths: [join(root, "apps/desktop/node_modules")],
+});
+await build({ entryPoints: [join(root, "apps/desktop/electron/preload/index.ts")],
+ outfile: join(artifacts, "preload.cjs"), bundle: true, platform: "node", format: "cjs", external: ["electron"] });
+const builtHtml = await readFile(join(root, "apps/desktop/out/renderer/index.html"), "utf8");
+const cssPaths = [...builtHtml.matchAll(/href="([^" ]+\.css)"/g)].map(match => match[1]);
+assert(cssPaths.length, "Build Desktop before running storage directory E2E");
+const css = (await Promise.all(cssPaths.map(path => readFile(join(root, "apps/desktop/out/renderer", path), "utf8")))).join("\n");
+await writeFile(join(artifacts, "index.html"), '<!doctype html><html data-platform="win32" data-theme="dark"><head><meta charset="utf-8"><style>' + css + '</style></head><body><div id="root"></div><script type="module" src="renderer.js"></script></body></html>');
+
+const main = join(artifacts, "main.mjs");
+await build({ entryPoints: [join(root, "scripts/e2e/storage-directory-main.mjs")], outfile: main,
+ bundle: true, platform: "node", format: "esm", external: ["electron", "original-fs"],
+ alias: { "@pi-desktop/i18n": join(root, "packages/i18n/src/index.ts"), "@pi-desktop/shared": join(root, "packages/shared/src/protocol.ts") },
+ plugins: [{ name: "fixture-host-location", setup(builder) {
+ builder.onResolve({ filter: /host-process$/ }, () => ({ path: "host-location", namespace: "fixture" }));
+ builder.onLoad({ filter: /.*/, namespace: "fixture" }, () => ({ contents: "export function resolveHostBinary() { return process.env.PI_DESKTOP_HOST_BIN; }" }));
+ } }],
+});
+
+async function launch(config, mode) {
+ const result = join(config.directory, mode + ".json");
+ const env = { ...process.env, PI_DESKTOP_HOST_BIN: hostBinary, PI_STORAGE_E2E_CONFIG: JSON.stringify({ ...config, mode, result, artifacts }) };
+ delete env.ELECTRON_RUN_AS_NODE;
+ const child = spawn(electronBinary, [main], { env, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
+ let output = "";
+ for (const stream of [child.stdout, child.stderr]) stream.on("data", data => { output += data; });
+ const timer = setTimeout(() => child.kill(), 60000);
+ let code;
+ try { code = await new Promise((resolve, reject) => { child.on("error", reject); child.on("close", resolve); }); }
+ finally { clearTimeout(timer); await writeFile(join(config.directory, mode + ".log"), output); }
+ assert.equal(code, 0, output);
+ const value = JSON.parse(await readFile(result, "utf8"));
+ assert.deepEqual(value.errors, [], JSON.stringify(value));
+ return value;
+}
+async function stopHost(host) {
+ host.child.stdin.end();
+ const timer = setTimeout(() => host.child?.kill(), 15000);
+ try { const exited = await host.exitPromise; assert.equal(exited.code, 0, host.stderr); }
+ finally { clearTimeout(timer); await host.stop(); }
+}
+
+const checks = [];
+for (const name of ["first-install", "existing-profile"]) {
+ const directory = await mkdtemp(join(artifacts, name + "-"));
+ const source = await mkdtemp(join(sourceRoot, name + "-source-"));
+ const config = { directory, anchor: join(source, "browser"), data: join(source, "not initialized", "PI data"), target: join(directory, "new volume", "PI storage") };
+ await mkdir(config.anchor);
+ let sessionId;
+ const host = new Host(hostBinary, config.data);
+ try {
+ if (name === "existing-profile") {
+ await host.start();
+ const { session } = await host.call("session.create", { title: "Conversation survives storage migration" });
+ sessionId = session.id;
+ await host.call("settings.set", { language: "zh-CN", theme: "light", enterToSend: false });
+ const project = join(config.data, "projects", "saved project");
+ await mkdir(project, { recursive: true });
+ await host.call("workspace.set", { path: project });
+ await host.call("project.memory.set", { path: project, content: "Keep project instructions after moving drives" });
+ const attachment = join(config.data, "attachments", "迁移 attachment.txt");
+ await mkdir(dirname(attachment), { recursive: true }); await writeFile(attachment, "retained attachment");
+ await host.call("session.appendMessage", { sessionId, message: { id: "storage-fixture-message", role: "user", content: "Keep my conversation", createdAt: new Date().toISOString(), attachments: [{ kind: "file", name: "migration.txt", ref: attachment, mimeType: "text/plain" }] } });
+ await stopHost(host);
+ const resources = join(config.data, "scratch", "packaged-app", "resources");
+ await mkdir(resources, { recursive: true });
+ await writeFile(join(resources, "app.asar"), "opaque archive fixture");
+ await symlink(join(source, "missing dependency"), join(resources, "node_modules"), process.platform === "win32" ? "junction" : "dir");
+ }
+ assert.equal((await launch(config, "choose")).scheduled, true);
+ const migrated = await launch(config, "maintenance");
+ assert.equal(migrated.relaunched, true);
+ const pointer = JSON.parse(await readFile(join(config.anchor, "storage-location.json"), "utf8"));
+ assert.equal(pointer.roots.data, join(config.target, "data"));
+ assert.equal(pointer.pending, undefined);
+ if (sessionId) {
+ const resources = join(pointer.roots.data, "scratch", "packaged-app", "resources");
+ assert.equal(await readFile(join(resources, "app.asar"), "utf8"), "opaque archive fixture");
+ assert.equal(await readlink(join(resources, "node_modules")), join(source, "missing dependency"));
+ }
+ const reopened = await launch(config, "inspect");
+ assert.equal(reopened.sessionData, join(config.target, "browser"));
+ assert.equal(reopened.browserState, "browser state survives restart");
+ const nextHost = new Host(hostBinary, pointer.roots.data);
+ try {
+ await nextHost.start();
+ if (sessionId) {
+ const { session } = await nextHost.call("session.get", { id: sessionId });
+ assert.equal(session.messages[0].content, "Keep my conversation");
+ assert.equal(await readFile(session.messages[0].attachments[0].ref, "utf8"), "retained attachment");
+ assert.equal(await readFile(join(config.data, "attachments", "迁移 attachment.txt"), "utf8"), "retained attachment");
+ assert.equal((await nextHost.call("settings.get")).enterToSend, false);
+ const project = join(pointer.roots.data, "projects", "saved project");
+ assert.equal((await nextHost.call("project.memory.get", { path: project })).memory.content, "Keep project instructions after moving drives");
+ } else {
+ await assert.rejects(stat(config.data), { code: "ENOENT" });
+ const { session } = await nextHost.call("session.create", { title: "First conversation at the new location" });
+ assert(session.id);
+ }
+ await stopHost(nextHost);
+ } finally { await nextHost.stop(); }
+ checks.push({ name, passed: true, directory });
+ } finally { await host.stop(); }
+}
+// Retry the reported partially completed cleanup: the old payload is absent,
+// while userData still owns the bootstrap pointer and native installation lock.
+// Preserve every synthetic profile; no disposable backup payload is created.
+{
+ const directory = await mkdtemp(join(artifacts, "backup-cleanup-"));
+ const config = { directory, anchor: join(directory, "installation"), data: join(directory, "already-removed-data") };
+ const active = { data: join(directory, "active-data"), browser: join(directory, "active-browser") };
+ await mkdir(config.anchor); await mkdir(active.browser);
+ const host = new Host(hostBinary, active.data);
+ let sessionId;
+ try {
+ await host.start();
+ const { session } = await host.call("session.create", { title: "History survives backup cleanup" });
+ sessionId = session.id;
+ await mkdir(join(active.data, "attachments"));
+ const attachment = join(active.data, "attachments", "retained.txt");
+ await writeFile(attachment, "current attachment");
+ await host.call("session.appendMessage", { sessionId, message: { id: "backup-cleanup-fixture", role: "user", content: "Current history stays available", createdAt: new Date().toISOString(), attachments: [{ kind: "file", name: "retained.txt", ref: attachment, mimeType: "text/plain" }] } });
+ await stopHost(host);
+ } finally { await host.stop(); }
+ const preferenceFile = join(config.anchor, "storage-location.json");
+ await writeFile(preferenceFile, JSON.stringify({ version: 1, roots: active, backups: [{ data: config.data, browser: config.anchor }] }));
+ assert.equal((await launch(config, "backup")).scheduled, true);
+ assert.equal(JSON.parse(await readFile(preferenceFile, "utf8")).pending.kind, "backup");
+ assert.equal((await launch(config, "maintenance")).relaunched, true);
+ const pointer = JSON.parse(await readFile(preferenceFile, "utf8"));
+ assert.deepEqual(pointer.roots, active);
+ assert.deepEqual(pointer.backups, []);
+ assert.equal(pointer.pending, undefined);
+ assert.equal(pointer.lastError, undefined);
+ const reopened = await launch(config, "inspect-backup");
+ assert.equal(reopened.backupControlRemoved, true);
+ assert.equal(reopened.sessionData, active.browser);
+ assert.equal(reopened.browserState, "browser state survives restart");
+ const nextHost = new Host(hostBinary, active.data);
+ try {
+ await nextHost.start();
+ const { session } = await nextHost.call("session.get", { id: sessionId });
+ assert.equal(session.messages[0].content, "Current history stays available");
+ assert.equal(await readFile(session.messages[0].attachments[0].ref, "utf8"), "current attachment");
+ await stopHost(nextHost);
+ } finally { await nextHost.stop(); }
+ checks.push({ name: "backup-cleanup-with-installation-lock", passed: true, directory });
+}
+await writeFile(join(artifacts, "result.json"), JSON.stringify({ checks, hostBinary, artifacts }, null, 2));
+console.log(JSON.stringify({ checks, hostBinary, artifacts }, null, 2));
diff --git a/scripts/e2e-storage-files.mjs b/scripts/e2e-storage-files.mjs
new file mode 100644
index 000000000..0e76c4ee6
--- /dev/null
+++ b/scripts/e2e-storage-files.mjs
@@ -0,0 +1,40 @@
+#!/usr/bin/env node
+/** Real Electron filesystem migration; synthetic files only, retained for diagnosis. */
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { mkdir, mkdtemp, readFile, realpath, symlink, writeFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import { join } from "node:path";
+import { repositoryRoot, resolveElectronBinary } from "./e2e/boot.mjs";
+
+const root = repositoryRoot();
+await mkdir(join(root, ".artifacts"), { recursive: true });
+const artifacts = await realpath(await mkdtemp(join(root, ".artifacts/storage-files-e2e-")));
+const junctionFixture = join(artifacts, "node-created-junction");
+await mkdir(join(junctionFixture, "data"), { recursive: true });
+await mkdir(join(junctionFixture, "browser"));
+await symlink(join(junctionFixture, "missing-dependency"), join(junctionFixture, "data", "node_modules"), process.platform === "win32" ? "junction" : "dir");
+const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");
+const desktopRequire = createRequire(join(root, "apps/desktop/package.json"));
+const builderRequire = createRequire(desktopRequire.resolve("electron-builder"));
+const { createPackage } = createRequire(builderRequire.resolve("app-builder-lib"))("@electron/asar");
+const archiveSource = join(artifacts, "archive-source");
+await mkdir(archiveSource);
+await writeFile(join(archiveSource, "index.js"), "module.exports = 'synthetic archive';\n");
+await createPackage(archiveSource, join(artifacts, "fixture.asar"));
+const main = join(artifacts, "main.mjs");
+await build({ entryPoints: [join(root, "scripts/e2e/storage-files-main.mjs")],
+ outfile: main, bundle: true, platform: "node", format: "esm", external: ["electron", "original-fs"] });
+const env = { ...process.env, PI_STORAGE_FILES_ARTIFACTS: artifacts };
+delete env.ELECTRON_RUN_AS_NODE;
+const child = spawn(resolveElectronBinary(root).electronBinary, [main], { env, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
+let output = "";
+for (const stream of [child.stdout, child.stderr]) stream.on("data", data => { output += data; });
+const timeout = setTimeout(() => child.kill(), 60000);
+let code;
+try { code = await new Promise((resolve, reject) => { child.on("error", reject); child.on("close", resolve); }); }
+finally { clearTimeout(timeout); await writeFile(join(artifacts, "electron.log"), output); }
+const report = JSON.parse(await readFile(join(artifacts, "result.json"), "utf8"));
+console.log(JSON.stringify({ artifacts, ...report }, null, 2));
+assert.equal(code, 0, output);
+assert(report.cases.every(value => value.passed), JSON.stringify(report.cases));
diff --git a/scripts/e2e-storage-migration.mjs b/scripts/e2e-storage-migration.mjs
index b33c43b47..3a31bed5b 100644
--- a/scripts/e2e-storage-migration.mjs
+++ b/scripts/e2e-storage-migration.mjs
@@ -53,7 +53,7 @@ async function closeGracefully(host) {
try {
await Promise.all([mkdir(source.browser), mkdir(target), mkdir(pluginSource)]);
await build({ entryPoints: [join(root, "apps/desktop/electron/main/storage/files.ts")],
- outfile: storageBundle, bundle: true, platform: "node", format: "esm" });
+ outfile: storageBundle, bundle: true, platform: "node", format: "esm", alias: { "original-fs": "node:fs" } });
const storage = await import(pathToFileURL(storageBundle).href);
await sourceHost.start();
const { session } = await sourceHost.call("session.create", { title: "Migration survives restart" });
diff --git a/scripts/e2e/storage-backup-lock-main.mjs b/scripts/e2e/storage-backup-lock-main.mjs
new file mode 100644
index 000000000..047188e75
--- /dev/null
+++ b/scripts/e2e/storage-backup-lock-main.mjs
@@ -0,0 +1,32 @@
+import assert from "node:assert/strict";
+import { app } from "electron";
+import { promises as fs } from "original-fs";
+import { join } from "node:path";
+import { removeBackups } from "../../apps/desktop/electron/main/storage/files.ts";
+
+const directory = process.env.PI_STORAGE_BACKUP_ARTIFACTS;
+const anchor = join(directory, "installation");
+app.setPath("userData", anchor);
+const result = { electron: process.versions.electron, passed: false };
+const acquired = app.requestSingleInstanceLock();
+
+void (async () => {
+ assert(acquired, "The isolated installation lock is held");
+ if (process.platform === "win32") {
+ assert((await fs.lstat(join(anchor, "lockfile"))).isFile(), "Electron created the reported Windows lock");
+ }
+ const active = { data: join(directory, "active-data"), browser: join(directory, "active-browser") };
+ // Reproduce retry after cleanup already removed the old payload: only the
+ // stable pointer and real lock remain. No user data or disposable files exist.
+ await removeBackups([{ data: join(directory, "already-removed-data"), browser: anchor }], active, anchor);
+ assert.equal(app.hasSingleInstanceLock(), true);
+ assert.equal(await fs.readFile(join(anchor, "storage-location.json"), "utf8"), "retained pointer");
+ assert.equal(await fs.readFile(join(active.data, "history.txt"), "utf8"), "current history");
+ if (process.platform === "win32") assert((await fs.lstat(join(anchor, "lockfile"))).isFile());
+ result.passed = true;
+ result.lockRetained = true;
+ result.activeHistoryRetained = true;
+})().catch(error => { result.error = error.message; }).finally(async () => {
+ await fs.writeFile(join(directory, "result.json"), JSON.stringify(result, null, 2));
+ app.exit(result.passed ? 0 : 1);
+});
diff --git a/scripts/e2e/storage-directory-main.mjs b/scripts/e2e/storage-directory-main.mjs
new file mode 100644
index 000000000..a07406b17
--- /dev/null
+++ b/scripts/e2e/storage-directory-main.mjs
@@ -0,0 +1,86 @@
+import assert from "node:assert/strict";
+import { app, BrowserWindow, dialog, ipcMain, session } from "electron";
+import { existsSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { prepareStorage } from "../../apps/desktop/electron/main/storage/bootstrap.ts";
+import { registerStorageIpc } from "../../apps/desktop/electron/main/storage/ipc.ts";
+
+const config = JSON.parse(process.env.PI_STORAGE_E2E_CONFIG);
+app.setPath("userData", config.anchor);
+if (!app.requestSingleInstanceLock()) throw new Error("Isolated fixture lock unavailable");
+let window;
+const result = { errors: [] };
+const originalExit = app.exit.bind(app);
+app.relaunch = () => { result.relaunched = true; };
+dialog.showMessageBox = async (...args) => { result.errors.push(args.at(-1).detail); return { response: 0 }; };
+app.exit = (code = 0) => {
+ void (async () => {
+ if (window && !window.isDestroyed()) {
+ result.visibleText = await window.webContents.executeJavaScript("document.body.innerText");
+ await window.webContents.executeJavaScript("new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))");
+ writeFileSync(join(config.directory, config.mode + ".png"), (await window.webContents.capturePage()).toPNG());
+ }
+ writeFileSync(config.result, JSON.stringify(result));
+ originalExit(code);
+ })().catch(error => { console.error(error); originalExit(1); });
+};
+app.on("browser-window-created", (_event, created) => {
+ window = created;
+ created.webContents.setBackgroundThrottling(false);
+});
+
+async function pointer(selector, last = false) {
+ window.show();
+ window.focus();
+ window.webContents.focus();
+ await window.webContents.executeJavaScript("new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))");
+ const position = await window.webContents.executeJavaScript("(() => { const nodes = document.querySelectorAll(" + JSON.stringify(selector) + "); const b=nodes[" + (last ? "nodes.length-1" : "0") + "]; if (!b || b.disabled) throw new Error('Button unavailable'); b.scrollIntoView({block:'center'}); const r=b.getBoundingClientRect(); return {x:Math.round(r.x+r.width/2),y:Math.round(r.y+r.height/2)}; })()");
+ window.webContents.sendInputEvent({ type: "mouseMove", ...position });
+ window.webContents.sendInputEvent({ type: "mouseDown", button: "left", clickCount: 1, ...position });
+ window.webContents.sendInputEvent({ type: "mouseUp", button: "left", clickCount: 1, ...position });
+}
+
+void (async () => {
+ const storage = await prepareStorage(config.data, false);
+ await app.whenReady();
+ result.roots = storage.preferences.roots;
+ window = new BrowserWindow({ show: true, width: 1050, height: 760, title: "PI Storage Migration Test",
+ webPreferences: { preload: join(config.artifacts, "preload.cjs"), sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });
+ dialog.showOpenDialog = async () => ({ canceled: false, filePaths: [config.target] });
+ let finish;
+ const scheduled = new Promise(resolve => { finish = resolve; });
+ registerStorageIpc({ registrar: {
+ assertMainWindowSender: event => assert.equal(event.sender, window.webContents),
+ handleWithEvent: (channel, handler) => ipcMain.handle(channel, async (event, input) => {
+ try { return { ok: true, data: await handler(event, input) }; }
+ catch (error) { return { ok: false, error: { code: "STORAGE", message: error.message } }; }
+ }),
+ }, getMainWindow: () => window, restart: () => finish() });
+ await window.loadFile(join(config.artifacts, "index.html"));
+ await window.webContents.executeJavaScript('window.storageDirectoryWait("ready")');
+ if (config.mode === "inspect" || config.mode === "inspect-backup") {
+ result.browserState = await window.webContents.executeJavaScript('localStorage.getItem("migration-fixture")');
+ result.sessionData = app.getPath("sessionData");
+ if (config.mode === "inspect-backup") {
+ assert.equal(storage.preferences.backups.length, 0);
+ assert.equal(storage.preferences.lastError, undefined);
+ assert.equal(await window.webContents.executeJavaScript('document.querySelectorAll(".settings-storage .settings-row-control button").length'), 2);
+ result.backupControlRemoved = true;
+ }
+ app.exit(0); return;
+ }
+ await window.webContents.executeJavaScript('localStorage.setItem("migration-fixture","browser state survives restart")');
+ if (config.mode === "backup") {
+ assert.equal(storage.preferences.backups.length, 1);
+ assert.equal(app.hasSingleInstanceLock(), true);
+ if (process.platform === "win32") assert(existsSync(join(config.anchor, "lockfile")));
+ }
+ await pointer(".settings-storage .settings-row-control button", config.mode === "backup");
+ await window.webContents.executeJavaScript('window.storageDirectoryWait("confirmation")');
+ writeFileSync(join(config.directory, "confirmation.png"), (await window.webContents.capturePage()).toPNG());
+ await pointer(".settings-storage-actions button", true);
+ await scheduled;
+ session.defaultSession.flushStorageData();
+ result.scheduled = true;
+ app.exit(0);
+})().catch(error => { console.error(error); result.errors.push(error.message); app.exit(1); });
diff --git a/scripts/e2e/storage-directory.jsx b/scripts/e2e/storage-directory.jsx
new file mode 100644
index 000000000..1211186e9
--- /dev/null
+++ b/scripts/e2e/storage-directory.jsx
@@ -0,0 +1,26 @@
+import { createRoot } from "react-dom/client";
+import i18n from "i18next";
+import { initReactI18next } from "react-i18next";
+import { catalogs } from "@pi-desktop/i18n";
+import { StorageSettingsSection } from "../../apps/desktop/src/features/settings/StorageSettingsSection";
+
+await i18n.use(initReactI18next).init({
+ lng: "zh-CN", interpolation: { escapeValue: false },
+ resources: { "zh-CN": { translation: catalogs["zh-CN"] } },
+});
+createRoot(document.getElementById("root")).render(<main style={{ padding: 32 }}><StorageSettingsSection /></main>);
+
+// Observe visible completion instead of relying on arbitrary delays.
+window.storageDirectoryWait = (kind) => new Promise((resolve, reject) => {
+ const observer = new MutationObserver(check);
+ const timer = setTimeout(() => finish(new Error("Storage UI did not reach " + kind)), 15000);
+ function finish(error, value) { clearTimeout(timer); observer.disconnect(); error ? reject(error) : resolve(value); }
+ function check() {
+ const error = document.querySelector('[role="alert"]');
+ if (error) return finish(new Error(error.textContent));
+ const node = document.querySelector(kind === "ready" ? '.settings-storage button' : '.settings-storage-confirmation');
+ if (node && (kind !== "ready" || !node.disabled)) finish(null, document.querySelector('.settings-storage').textContent);
+ }
+ observer.observe(document.body, { childList: true, subtree: true, attributes: true, characterData: true });
+ check();
+});
diff --git a/scripts/e2e/storage-files-main.mjs b/scripts/e2e/storage-files-main.mjs
new file mode 100644
index 000000000..0bec9cff8
--- /dev/null
+++ b/scripts/e2e/storage-files-main.mjs
@@ -0,0 +1,96 @@
+import assert from "node:assert/strict";
+import { randomUUID } from "node:crypto";
+import { app } from "electron";
+import { promises as fs, writeFileSync } from "original-fs";
+import { join, relative, resolve } from "node:path";
+import { migrateFiles, validateTarget } from "../../apps/desktop/electron/main/storage/files.ts";
+import { storageLinkTypes } from "../../apps/desktop/electron/main/storage/link-types.ts";
+
+const artifacts = process.env.PI_STORAGE_FILES_ARTIFACTS;
+app.setPath("userData", join(artifacts, "electron-profile"));
+const cases = [];
+void (async () => {
+ for (const name of ["valid-asar", "opaque-asar", "dangling-directory-link", "trailing-directory-link", "mixed-links", "copy-error-context"]) {
+ const directory = name === "trailing-directory-link" ? join(artifacts, "node-created-junction") : await fs.mkdtemp(join(artifacts, name + "-"));
+ const source = { data: join(directory, "data"), browser: join(directory, "browser") };
+ await fs.mkdir(source.data, { recursive: true }); await fs.mkdir(source.browser, { recursive: true });
+ const file = name.endsWith("asar") ? "app.asar" : "session.jsonl";
+ const content = name === "valid-asar" ? await fs.readFile(join(artifacts, "fixture.asar"))
+ : Buffer.from("Retain opaque user bytes, not an Electron virtual directory.\n");
+ await fs.writeFile(join(source.data, file), content);
+ if (name.endsWith("asar")) {
+ await fs.mkdir(join(source.data, "app.asar.unpacked"));
+ await fs.writeFile(join(source.data, "app.asar.unpacked", "native.node"), "synthetic unpacked bytes");
+ }
+ const missing = join(directory, "missing-dependency");
+ if (name === "dangling-directory-link") await fs.symlink(missing, join(source.data, "node_modules"), process.platform === "win32" ? "junction" : "dir");
+ const linkNames = ["internal directory", "external directory", "missing 迁移-'directory", "missing file", "existing file", "blocked directory"];
+ if (name === "mixed-links") {
+ const internal = join(source.data, "z resources");
+ const external = join(directory, "external resources");
+ await fs.mkdir(internal); await fs.mkdir(external);
+ await fs.writeFile(join(internal, "payload.txt"), "retained internal data");
+ await fs.writeFile(join(external, "payload.txt"), "retained external data");
+ await fs.symlink(internal, join(source.data, linkNames[0]), process.platform === "win32" ? "junction" : "dir");
+ await fs.symlink(external, join(source.data, linkNames[1]), process.platform === "win32" ? "junction" : "dir");
+ await fs.symlink(join(directory, "missing-迁移-'folder"), join(source.data, linkNames[2]), process.platform === "win32" ? "junction" : "dir");
+ await fs.symlink(relative(source.data, join(directory, "missing-'document.txt")), join(source.data, linkNames[3]), "file");
+ await fs.symlink(relative(source.data, join(external, "payload.txt")), join(source.data, linkNames[4]), "file");
+ await fs.symlink(join(source.data, file, "not a directory"), join(source.data, linkNames[5]), process.platform === "win32" ? "junction" : "dir");
+ }
+ let progress;
+ try {
+ const target = await validateTarget(join(directory, "destination"), source, source.browser);
+ let collided = false;
+ const next = await migrateFiles({ source, target, anchor: source.browser, id: randomUUID(),
+ progress: value => {
+ progress = value;
+ if (name === "copy-error-context" && value.stage === "copying" && !collided) {
+ collided = true;
+ // A destination changed after preflight must retain the failing path.
+ writeFileSync(join(target, "data", file), "destination collision fixture", { flag: "wx" });
+ }
+ }, relocate: async () => { assert.notEqual(name, "copy-error-context"); } });
+ assert.deepEqual(await fs.readFile(join(next.data, file)), content);
+ assert.deepEqual(await fs.readFile(join(source.data, file)), content);
+ if (name.endsWith("asar")) {
+ assert((await fs.lstat(join(next.data, file))).isFile());
+ assert.equal(await fs.readFile(join(next.data, "app.asar.unpacked", "native.node"), "utf8"), "synthetic unpacked bytes");
+ }
+ if (name === "dangling-directory-link") {
+ assert((await fs.lstat(join(next.data, "node_modules"))).isSymbolicLink());
+ assert.equal(await fs.readlink(join(next.data, "node_modules")), await fs.readlink(join(source.data, "node_modules")));
+ await assert.rejects(fs.stat(join(next.data, "node_modules")), { code: "ENOENT" });
+ }
+ if (name === "trailing-directory-link") {
+ const link = join(next.data, "node_modules");
+ assert((await fs.lstat(link)).isSymbolicLink());
+ assert.equal(resolve(await fs.readlink(link)), resolve(missing));
+ await assert.rejects(fs.stat(link), { code: "ENOENT" });
+ }
+ if (name === "mixed-links") {
+ const destinationLinks = linkNames.map(link => join(next.data, link));
+ assert.deepEqual(await storageLinkTypes(destinationLinks), await storageLinkTypes(linkNames.map(link => join(source.data, link))));
+ assert.equal(await fs.readFile(join(destinationLinks[0], "payload.txt"), "utf8"), "retained internal data");
+ assert.equal(await fs.readFile(join(destinationLinks[1], "payload.txt"), "utf8"), "retained external data");
+ assert.equal(await fs.readFile(destinationLinks[4], "utf8"), "retained external data");
+ for (const index of [2, 3, 5]) {
+ assert((await fs.lstat(destinationLinks[index])).isSymbolicLink());
+ await assert.rejects(fs.stat(destinationLinks[index]), error => ["ENOENT", "ENOTDIR"].includes(error.code));
+ }
+ assert.equal(await fs.readlink(destinationLinks[0]), join(next.data, "z resources"));
+ }
+ assert.notEqual(name, "copy-error-context", "Conflicting destination must fail");
+ assert.equal(progress.stage, "complete");
+ cases.push({ name, passed: true, progress });
+ } catch (error) {
+ const expected = name === "copy-error-context" && error.message.includes("Storage copy failed:")
+ && error.message.includes(source.data) && error.message.includes(join(directory, "destination", "data"))
+ && error.cause?.code === "EEXIST";
+ if (expected) assert.deepEqual(await fs.readFile(join(source.data, file)), content);
+ cases.push({ name, passed: expected, message: error.message, code: error.code, syscall: error.syscall, progress });
+ }
+ }
+ await fs.writeFile(join(artifacts, "result.json"), JSON.stringify({ electron: process.versions.electron, cases }, null, 2));
+ app.exit(cases.every(value => value.passed) ? 0 : 1);
+})().catch(error => { console.error(error); app.exit(1); });