diff --git a/apps/server/library-kit/library-gitignore b/apps/server/library-kit/library-gitignore index 8cadae9..e654e38 100644 --- a/apps/server/library-kit/library-gitignore +++ b/apps/server/library-kit/library-gitignore @@ -1,2 +1,3 @@ .viewswitcher/ +.viewswitcher.moved-aside-* .DS_Store diff --git a/apps/server/src/atomic.test.ts b/apps/server/src/atomic.test.ts new file mode 100644 index 0000000..e9f2f1f --- /dev/null +++ b/apps/server/src/atomic.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, test } from "bun:test"; +import { existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, symlinkSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { writeAtomic } from "./atomic"; +import { readSettings } from "./settings"; + +const scratch = (name: string) => mkdtempSync(join(tmpdir(), `vs-${name}-`)); + +describe("writeAtomic with plainParent", () => { + test("a state folder that became a link (a git pull) is moved aside, and the write lands in a plain folder", async () => { + const lib = scratch("lib"); + const elsewhere = scratch("elsewhere"); + mkdirSync(join(lib, ".viewswitcher")); + await writeAtomic(join(lib, ".viewswitcher", "state.json"), "{}", { plainParent: true }); + // The swap happens while the server runs: the plain folder is replaced by a link to another place. + const { rmSync } = await import("node:fs"); + rmSync(join(lib, ".viewswitcher"), { recursive: true }); + symlinkSync(elsewhere, join(lib, ".viewswitcher")); + + await writeAtomic(join(lib, ".viewswitcher", "devices.json"), "secret", { mode: 0o600, plainParent: true }); + expect(lstatSync(join(lib, ".viewswitcher")).isDirectory()).toBe(true); + expect(readFileSync(join(lib, ".viewswitcher", "devices.json"), "utf8")).toBe("secret"); + expect(readdirSync(elsewhere)).toEqual([]); // nothing was written through the link + expect(readdirSync(lib).some((n) => n.startsWith(".viewswitcher.moved-aside-"))).toBe(true); + }); + + test("without it, a plain write is unchanged", async () => { + const dir = scratch("plain"); + await writeAtomic(join(dir, "sub", "x.json"), "1"); + expect(readFileSync(join(dir, "sub", "x.json"), "utf8")).toBe("1"); + }); +}); + +describe("settings", () => { + test("settings that came in through a linked state folder are never read: it's moved aside first", async () => { + const lib = scratch("lib"); + const elsewhere = scratch("elsewhere"); + const { writeFileSync } = await import("node:fs"); + writeFileSync(join(elsewhere, "settings.json"), JSON.stringify({ agentOnAir: "always" })); + symlinkSync(elsewhere, join(lib, ".viewswitcher")); + // The moved-aside folder's "always" never counts, and the person's own choice went with it, so + // the fresh folder fails closed: agents may put nothing on air until it's chosen again. + expect((await readSettings(lib)).agentOnAir).toBe("never"); + expect(existsSync(join(elsewhere, "settings.json"))).toBe(true); // left where it was + }); +}); + +describe("two writes healing at once", () => { + test("both land in the one plain folder; neither fails on the other's move", async () => { + const lib = scratch("lib"); + const elsewhere = scratch("elsewhere"); + symlinkSync(elsewhere, join(lib, ".viewswitcher")); + await Promise.all([ + writeAtomic(join(lib, ".viewswitcher", "state.json"), "a", { plainParent: true }), + writeAtomic(join(lib, ".viewswitcher", "devices.json"), "b", { mode: 0o600, plainParent: true }), + ]); + expect(readFileSync(join(lib, ".viewswitcher", "state.json"), "utf8")).toBe("a"); + expect(readFileSync(join(lib, ".viewswitcher", "devices.json"), "utf8")).toBe("b"); + expect(readdirSync(elsewhere)).toEqual([]); + }); +}); diff --git a/apps/server/src/atomic.ts b/apps/server/src/atomic.ts index 93563d3..f083555 100644 --- a/apps/server/src/atomic.ts +++ b/apps/server/src/atomic.ts @@ -5,14 +5,18 @@ // still the version that was read; a new file that claims its name is an exclusive create instead.) import { chmod, mkdir, rename, rm, writeFile } from "node:fs/promises"; import { dirname } from "node:path"; +import { plainFolder } from "./library/contain"; /** * Write `data` to a temp file beside `file`, then rename it over `file`. The temp name has a random * part, so two writes in flight never share (or rename) each other's half-written copy. `mode` * (devices.json's 0o600) is set on the copy before it takes the name, so the file is never readable - * by others, even for a moment. + * by others, even for a moment. With `plainParent` (the switcher's own state in .viewswitcher/), a + * link or a file where its folder should be is moved aside first (contain.ts plainFolder), so the + * write never goes through a link that appeared since the last one. */ -export async function writeAtomic(file: string, data: string | Uint8Array, { mode }: { mode?: number } = {}): Promise { +export async function writeAtomic(file: string, data: string | Uint8Array, { mode, plainParent }: { mode?: number; plainParent?: boolean } = {}): Promise { + if (plainParent) await plainFolder(dirname(file)); await mkdir(dirname(file), { recursive: true }); const tmp = `${file}.${crypto.randomUUID().slice(0, 8)}.tmp`; try { diff --git a/apps/server/src/library-kit.ts b/apps/server/src/library-kit.ts index ee601a3..1ab79b9 100644 --- a/apps/server/src/library-kit.ts +++ b/apps/server/src/library-kit.ts @@ -77,7 +77,7 @@ export async function ensureLibrary(root: string, { kit, starter, firstOrg = FIR written[to] = sha(text); } if (JSON.stringify(written) !== JSON.stringify(state.files ?? {})) { - await writeAtomic(statePath, JSON.stringify({ files: written }, null, 2) + "\n"); + await writeAtomic(statePath, JSON.stringify({ files: written }, null, 2) + "\n", { plainParent: true }); } if (fresh && !existsSync(join(root, ".git"))) result.git = await gitInit(root).catch(() => false); diff --git a/apps/server/src/library/contain.test.ts b/apps/server/src/library/contain.test.ts index e50bf72..dab104d 100644 --- a/apps/server/src/library/contain.test.ts +++ b/apps/server/src/library/contain.test.ts @@ -1,9 +1,9 @@ // The library's one real-path rule (contain.ts), on a real folder with real links. import { afterAll, describe, expect, test } from "bun:test"; -import { chmodSync, mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { realLibraryPath, resolveInLibrary } from "./contain"; +import { plainStateFolder, realLibraryPath, resolveInLibrary } from "./contain"; const library = mkdtempSync(join(tmpdir(), "vs-contain-")); const outside = mkdtempSync(join(tmpdir(), "vs-contain-out-")); @@ -86,3 +86,41 @@ describe("a path that can't be read", () => { } }); }); + +describe("plainStateFolder", () => { + const lib = () => mkdtempSync(join(tmpdir(), "vs-state-")); + const at = new Date("2026-11-26T08:00:00.000Z"); + + test("a plain folder, or none yet, is left as it is", async () => { + const empty = lib(); + expect(await plainStateFolder(empty, at)).toBeNull(); + expect(existsSync(join(empty, ".viewswitcher"))).toBe(false); + const plain = lib(); + mkdirSync(join(plain, ".viewswitcher")); + writeFileSync(join(plain, ".viewswitcher", "state.json"), "{}"); + expect(await plainStateFolder(plain, at)).toBeNull(); + expect(readFileSync(join(plain, ".viewswitcher", "state.json"), "utf8")).toBe("{}"); + }); + + test("a link is moved aside, never followed: what it points at is untouched", async () => { + const root = lib(); + const elsewhere = mkdtempSync(join(tmpdir(), "vs-elsewhere-")); + writeFileSync(join(elsewhere, "keep.txt"), "mine"); + symlinkSync(elsewhere, join(root, ".viewswitcher")); + const aside = await plainStateFolder(root, at); + expect(aside).toStartWith(join(root, ".viewswitcher.moved-aside-2026-11-26T08-00-00-000Z-")); + expect(lstatSync(aside!).isSymbolicLink()).toBe(true); // kept, as the link it was + // A plain folder takes its place, and it fails closed: agents may put nothing on air until the person chooses again. + expect(lstatSync(join(root, ".viewswitcher")).isDirectory()).toBe(true); + expect(JSON.parse(readFileSync(join(root, ".viewswitcher", "settings.json"), "utf8"))).toEqual({ agentOnAir: "never" }); + expect(readFileSync(join(elsewhere, "keep.txt"), "utf8")).toBe("mine"); + }); + + test("a file where the folder should be is moved aside too", async () => { + const root = lib(); + writeFileSync(join(root, ".viewswitcher"), "not a folder"); + const aside = await plainStateFolder(root, at); + expect(readFileSync(aside!, "utf8")).toBe("not a folder"); + expect(lstatSync(join(root, ".viewswitcher")).isDirectory()).toBe(true); + }); +}); diff --git a/apps/server/src/library/contain.ts b/apps/server/src/library/contain.ts index 8d76a40..16885a6 100644 --- a/apps/server/src/library/contain.ts +++ b/apps/server/src/library/contain.ts @@ -11,7 +11,7 @@ // // Paths still go through inside() and plainName() (paths.ts) first; this adds what the real files say. import { closeSync, constants, existsSync, fstatSync, openSync, readFileSync, realpathSync } from "node:fs"; -import { type FileHandle, lstat, open, realpath } from "node:fs/promises"; +import { type FileHandle, lstat, mkdir, open, realpath, rename, writeFile } from "node:fs/promises"; import { basename, dirname, isAbsolute, join, relative, sep } from "node:path"; import { inside, PathError } from "../paths"; @@ -118,6 +118,60 @@ async function plainStaging(dir: string): Promise { return at; } +/** + * `dir` as a plain folder, or nothing there yet: a link or a file at `dir` is moved aside (kept, renamed + * `.moved-aside-