Skip to content

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

fix(storage): preserve link kinds through Windows migration (#1688)

Liu Zixiange53abd031f3f
diff --git a/apps/desktop/electron/main/storage/link-types.ts b/apps/desktop/electron/main/storage/link-types.ts
index 61999274d..09c70b2e8 100644
--- a/apps/desktop/electron/main/storage/link-types.ts
+++ b/apps/desktop/electron/main/storage/link-types.ts
@@ -2,17 +2,26 @@ 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. */
+/**
+ * Classify each path as a junction, a directory symlink, or a file symlink,
+ * reading the reparse point — not its target — so dangling links classify
+ * too. A directory attribute alone cannot tell these apart (#1686): a
+ * directory symlink carries it just like a junction does, which used to
+ * rewrite every `mklink /D` link into a junction and wedged the migration on
+ * UNC-targeted links that junctions cannot point at.
+ */
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.");
+ // One statement: -Command joins on semicolons, and a semicolon between an
+ // `if` and its `elseif` breaks PowerShell's statement structure.
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' } })",
+ "$types = @(foreach ($path in $paths) { $type = 'file'; try { $item = Get-Item -LiteralPath $path -Force; if ($item.LinkType -eq 'Junction') { $type = 'junction' } elseif ($item.LinkType -eq 'SymbolicLink') { $target = [string]$item.Target; if ($target -and -not [IO.Path]::IsPathRooted($target)) { $target = Join-Path $item.DirectoryName $target }; if ($target -and (Test-Path -LiteralPath $target -ErrorAction SilentlyContinue)) { if (([IO.File]::GetAttributes($target) -band [IO.FileAttributes]::Directory) -ne 0) { $type = 'dir' } else { $type = 'file' } } elseif (($item.Attributes -band [IO.FileAttributes]::Directory) -ne 0) { $type = 'dir' } else { $type = 'file' } } else { if (([IO.File]::GetAttributes($path) -band [IO.FileAttributes]::Directory) -ne 0) { $type = 'junction' } else { $type = 'file' } } } catch { $type = if (([IO.File]::GetAttributes($path) -band [IO.FileAttributes]::Directory) -ne 0) { 'dir' } else { 'file' } }; $type })",
"ConvertTo-Json -InputObject $types -Compress",
].join("; ");
const output = await new Promise<string>((resolve, reject) => {
@@ -25,7 +34,7 @@ export async function storageLinkTypes(paths: string[]): Promise<Array<symlink.T
});
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")) {
+ || !types.every((type): type is symlink.Type => type === "junction" || type === "dir" || 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
index 2571a2364..13a0fb7e1 100644
--- a/apps/desktop/test/storage-directory-migration.test.mjs
+++ b/apps/desktop/test/storage-directory-migration.test.mjs
@@ -1,8 +1,9 @@
import assert from "node:assert/strict";
+import { execFile } from "node:child_process";
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 { basename, join } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import test from "node:test";
@@ -15,6 +16,31 @@ 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);
+import { register } from "node:module";
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url).href);
+const { storageLinkTypes } = await import("../electron/main/storage/link-types.ts");
+
+function windowsLinkType(path) {
+ return new Promise((resolve, reject) => {
+ execFile(join(process.env.SystemRoot, "System32/WindowsPowerShell/v1.0/powershell.exe"),
+ ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command",
+ `(Get-Item -LiteralPath @'
+${path}
+'@ -Force).LinkType`],
+ { windowsHide: true }, (error, stdout) => error ? reject(error) : resolve(stdout.trim()));
+ });
+}
+
+async function createSymlinkOrSkip(t, target, link, type) {
+ try {
+ await symlink(target, link, type);
+ return true;
+ } catch (error) {
+ if (error.code === "EPERM") { t.skip(`requires the Windows symlink privilege (${type})`); return false; }
+ throw error;
+ }
+}
+
async function fixture() {
const directory = await mkdtemp(join(scratch, "case-"));
const source = { data: join(directory, "data"), browser: join(directory, "browser") };
@@ -123,3 +149,50 @@ test("a destination that is a file is rejected without changing it", async () =>
await assert.rejects(storage.validateTarget(target, source, source.browser), /directory/);
assert.equal(await readFile(target, "utf8"), "user document");
});
+
+
+test("a junction entry is classified as junction and rebuilt as a junction", async (t) => {
+ if (process.platform !== "win32") return t.skip("Windows link classification");
+ const { source, target } = await fixture();
+ const outside = join(await realpath(await mkdtemp(join(scratch, "outside-"))), "kept");
+ await mkdir(outside, { recursive: true });
+ await mkdir(source.data, { recursive: true });
+ if (!(await createSymlinkOrSkip(t, outside, join(source.data, "linked"), "junction"))) return;
+ {
+ assert.equal((await storageLinkTypes([join(source.data, "linked")]))[0], "junction");
+ 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 () => {} });
+ assert.equal(await windowsLinkType(join(next.data, "linked")), "Junction");
+ }
+});
+
+test("a directory symlink survives migration as a symlink, including a UNC target", async (t) => {
+ if (process.platform !== "win32") return t.skip("Windows link classification");
+ const { source, target } = await fixture();
+ // The #1686 wedge: a dir symlink to a UNC path cannot be rebuilt as a
+ // junction, which used to abort the migration and every retry.
+ const uncTarget = "\\\\localhost\\c$\\" + basename(scratch);
+ await mkdir(source.data, { recursive: true });
+ if (!(await createSymlinkOrSkip(t, uncTarget, join(source.data, "netlinked"), "dir"))) return;
+ {
+ assert.equal((await storageLinkTypes([join(source.data, "netlinked")]))[0], "dir");
+ 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 () => {} });
+ assert.equal(await windowsLinkType(join(next.data, "netlinked")), "SymbolicLink", "the dir symlink must not become a junction");
+ }
+});
+
+test("a file symlink pointing at a directory is rebuilt as a directory symlink", async (t) => {
+ if (process.platform !== "win32") return t.skip("Windows link classification");
+ const { source, target } = await fixture();
+ const outside = join(await realpath(await mkdtemp(join(scratch, "outside-"))), "dir-target");
+ await mkdir(outside, { recursive: true });
+ await mkdir(source.data, { recursive: true });
+ if (!(await createSymlinkOrSkip(t, outside, join(source.data, "filelink"), "file"))) return;
+ {
+ assert.equal((await storageLinkTypes([join(source.data, "filelink")]))[0], "dir", "the target's kind decides dir vs file");
+ 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 () => {} });
+ assert.equal(await windowsLinkType(join(next.data, "filelink")), "SymbolicLink");
+ }
+});
diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.md
index bae26f935..5bc3b9fcc 100644
--- a/docs/spec/03-runtime/04-data-storage.md
+++ b/docs/spec/03-runtime/04-data-storage.md
@@ -92,9 +92,12 @@ 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.
+unchanged. Windows links are classified in one batch by their reparse-point
+kind, preserving junctions as junctions and symbolic links as symbolic links.
+For a symbolic link whose target exists, the target's kind determines whether
+it is recreated as a directory or file link; for dangling or unavailable
+targets, the link's own directory attribute determines that type. 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