Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/server/library-kit/library-gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
.viewswitcher/
.viewswitcher.moved-aside-*
.DS_Store
62 changes: 62 additions & 0 deletions apps/server/src/atomic.test.ts
Original file line number Diff line number Diff line change
@@ -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([]);
});
});
8 changes: 6 additions & 2 deletions apps/server/src/atomic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> {
export async function writeAtomic(file: string, data: string | Uint8Array, { mode, plainParent }: { mode?: number; plainParent?: boolean } = {}): Promise<void> {
if (plainParent) await plainFolder(dirname(file));
await mkdir(dirname(file), { recursive: true });
const tmp = `${file}.${crypto.randomUUID().slice(0, 8)}.tmp`;
try {
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/library-kit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
42 changes: 40 additions & 2 deletions apps/server/src/library/contain.test.ts
Original file line number Diff line number Diff line change
@@ -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-"));
Expand Down Expand Up @@ -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);
});
});
56 changes: 55 additions & 1 deletion apps/server/src/library/contain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -118,6 +118,60 @@ async function plainStaging(dir: string): Promise<string> {
return at;
}

/**
* `dir` as a plain folder, or nothing there yet: a link or a file at `dir` is moved aside (kept, renamed
* `<dir>.moved-aside-<time>`) and never followed or deleted. Returns where it was moved, or null when
* there was nothing to move. A rename that fails says so plainly (a read-only library, say).
*/
/** Heals in progress, by folder: writes that find the same link at once share one move. */
const healing = new Map<string, Promise<string | null>>();

export function plainFolder(dir: string, now = new Date()): Promise<string | null> {
let heal = healing.get(dir);
if (!heal) {
heal = moveAside(dir, now).finally(() => healing.delete(dir));
healing.set(dir, heal);
}
return heal;
}

async function moveAside(dir: string, now: Date): Promise<string | null> {
const s = await lstat(dir).catch(() => null);
if (!s || s.isDirectory()) return null;
const aside = `${dir}.moved-aside-${now.toISOString().replace(/[:.]/g, "-")}-${crypto.randomUUID().slice(0, 4)}`;
try {
await rename(dir, aside);
} catch (e) {
// Another process healed it a moment ago: what's there now is its plain folder, or nothing yet.
if ((e as NodeJS.ErrnoException).code === "ENOENT") {
const now = await lstat(dir).catch(() => null);
if (!now || now.isDirectory()) return null;
}
throw new Error(`${dir} is a link or a file, and it couldn't be moved aside (${(e as Error).message}). Move or remove it, then start ViewSwitcher again.`);
}
console.error(`[library] ${basename(dir)} was a link or a file, so it was moved aside to ${aside} and a plain folder takes its place`);
return aside;
}

/**
* The library's own state folder (<library>/.viewswitcher: state.json, settings.json, devices.json,
* kit.json) as a plain folder. A cloned library can carry a link (or a file) there, and a `git pull`
* can put one there while the server runs (the local folder is gitignored, so git replaces it), and the
* switcher would write its state and pairings wherever it points. So it's checked at startup, and
* again by every state write (writeAtomic's `plainParent`) and settings read.
*/
export async function plainStateFolder(libraryRoot: string, now = new Date()): Promise<string | null> {
const dir = join(libraryRoot, ".viewswitcher");
const aside = await plainFolder(dir, now);
if (aside) {
// The person's agent setting went with the old folder (git deletes a gitignored folder it replaces).
// Fail closed: the fresh folder says agents may put nothing on air until they choose again.
await mkdir(dir, { recursive: true });
await writeFile(join(dir, "settings.json"), JSON.stringify({ agentOnAir: "never" }, null, 2) + "\n", { flag: "wx" }).catch(() => {});
}
return aside;
}

/**
* Where a library path really is (through links), as a library path, or the path itself when that
* can't be told. Synchronous, for checks that must happen at one instant (the agents' on-air guard).
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/live/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ export class LiveStore {
/** state.json: the on-air record and the sources ever placed. */
private persist(onAir: OnAir | null) {
const { missing: _, ...saved } = onAir ?? ({} as OnAir);
return writeAtomic(this.opts.file, JSON.stringify({ onAir: onAir ? saved : null, placed: [...this.placed].sort() }, null, 2));
return writeAtomic(this.opts.file, JSON.stringify({ onAir: onAir ? saved : null, placed: [...this.placed].sort() }, null, 2), { plainParent: true });
}

/** For a save nothing waits on: a failure is logged, and the next change saves again. */
Expand Down
3 changes: 3 additions & 0 deletions apps/server/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { dispatcher, type SocketData } from "./http/dispatch";
import { pairPageResponse, routes, secure } from "./http/routes";
import { pairingOrder, thisMac } from "./lan";
import { appParent, watchParent } from "./parent-watch";
import { plainStateFolder } from "./library/contain";
import { LibraryScanner } from "./library/scanner";
import { ensureLibrary } from "./library-kit";
import { createPlacer } from "./live/placement";
Expand All @@ -31,6 +32,8 @@ import { createSlotOrder } from "./slot-order";
import { startUsbBridge, usbAvailable } from "./usb-bridge";

// A new library gets the agent skill, CLAUDE.md, a git repo and a first org; an existing one is left as it is.
// The state folder must be a plain folder before anything writes state or pairings into it (contain.ts).
await plainStateFolder(config.library);
const firstRun = await ensureLibrary(config.library, { kit: config.libraryKit, starter: config.starter });
if (firstRun.copied.length || firstRun.updated.length || firstRun.org) {
const did = [
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/pairing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ export class Pairing {
let ok = true;
this.saving = this.saving.then(async () => {
try {
await writeAtomic(file, body, { mode: 0o600 });
await writeAtomic(file, body, { mode: 0o600, plainParent: true });
} catch (e) {
ok = false;
console.error("[pairing] couldn't save devices:", (e as Error).message);
Expand Down
5 changes: 4 additions & 1 deletion apps/server/src/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { readFile } from "node:fs/promises";
import { join } from "node:path";
import type { AgentOnAir } from "@viewswitcher/shared";
import { writeAtomic } from "./atomic";
import { plainStateFolder } from "./library/contain";

export type Settings = { agentOnAir: AgentOnAir };

Expand All @@ -21,6 +22,8 @@ const file = (root: string) => join(root, ".viewswitcher", "settings.json");
async function readRaw(root: string): Promise<{ saved: Record<string, unknown> } | { error: string }> {
let text: string;
try {
// A .viewswitcher that became a link (a git pull) would hand the guard someone else's settings.
await plainStateFolder(root);
text = await readFile(file(root), "utf8");
} catch (e) {
if ((e as NodeJS.ErrnoException).code === "ENOENT") return { saved: {} };
Expand Down Expand Up @@ -63,7 +66,7 @@ export function writeSettings(root: string, patch: Partial<Settings>): Promise<S
// An unreadable file is replaced: the person just chose what it should say.
const raw = await readRaw(root);
const next = { ...("saved" in raw ? raw.saved : {}), ...patch };
await writeAtomic(file(root), JSON.stringify(next, null, 2) + "\n");
await writeAtomic(file(root), JSON.stringify(next, null, 2) + "\n", { plainParent: true });
return readSettings(root);
});
queue = run.catch(() => {});
Expand Down
Loading