RuneStone 1.0.0
This commit is contained in:
@@ -0,0 +1,456 @@
|
||||
// The Background feature: the engine (ported from the Background Slideshow plugin), the per-image settings,
|
||||
// the sources, the settings section, the launch rule, and the first-start migration.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { DEFAULT_BACKGROUND, hasBackgroundSource, migrateBackground, normalizeBackground, normalizeLayout, type BackgroundMigrationHost, type BackgroundSettings } from "../../../src/lib/features/backgroundSettings.ts";
|
||||
import { LAUNCH_RULES, launchWanted, runsInWindow } from "../../../src/lib/features/launch.ts";
|
||||
import { BLUR_CACHE, RESCAN_SLIDES, Slideshow, transitionMs, type EngineSettings, type ImageSource, type Runtime } from "../../../src/lib/features/background/engine.ts";
|
||||
import { imageAppearance, imageNames, parseImageSettings, sequence } from "../../../src/lib/features/background/imageSettings.ts";
|
||||
import { folderSource, imageSource, readSavedImage } from "../../../src/lib/features/background/sources.ts";
|
||||
import type { LegacyPlugin } from "../../../src/lib/features/migration.ts";
|
||||
import type { BackgroundFrame } from "../../../src/lib/plugins/backgroundContracts.ts";
|
||||
|
||||
const settle = () => new Promise(resolve => setImmediate(resolve));
|
||||
const on: EngineSettings = { ...normalizeBackground({ source: "folder", seconds: 3, targets: ["app", "pm-all"] }) };
|
||||
|
||||
function fixture({ width = 200, height = 100 } = {}) {
|
||||
const frames = new Map<string, BackgroundFrame>();
|
||||
const released: string[] = [];
|
||||
const reads: string[] = [];
|
||||
const counts = { list: 0, sidecar: 0, blur: 0 };
|
||||
let names = ["2.png", "1.png", "10.png"];
|
||||
let sidecar: string | null = null;
|
||||
let serial = 0;
|
||||
let scheduled: { callback: () => void; delay: number } | undefined;
|
||||
const source = (key = "folder:D:\\Pictures"): ImageSource => ({
|
||||
key, timed: true,
|
||||
list: async () => { counts.list++; return names; },
|
||||
read: async name => { reads.push(name); return new Blob([name]); },
|
||||
sidecar: async () => { counts.sidecar++; return sidecar; },
|
||||
});
|
||||
const runtime: Runtime = {
|
||||
load: async blob => ({ url: `blob:${await blob.text()}-${serial++}`, width, height }),
|
||||
blur: async image => { counts.blur++; return `${image.url}-blur`; },
|
||||
release: url => { released.push(url); },
|
||||
later: (callback, delay) => { scheduled = { callback, delay }; return scheduled; },
|
||||
cancel: () => { scheduled = undefined; },
|
||||
random: () => 0,
|
||||
now: () => 0,
|
||||
};
|
||||
const engine = new Slideshow({ set: (target, frame) => { if (frame) frames.set(target, frame); else frames.delete(target); } }, runtime);
|
||||
return {
|
||||
engine, frames, released, reads, counts, runtime, source,
|
||||
names: (value: string[]) => { names = value; },
|
||||
sidecar: (value: string | null) => { sidecar = value; },
|
||||
scheduled: () => scheduled,
|
||||
/** Run the timer, then let the read of the next prepared image finish. */
|
||||
tick: async () => { await scheduled!.callback(); await settle(); await settle(); },
|
||||
};
|
||||
}
|
||||
|
||||
test("settings and names normalize, and the order is natural", () => {
|
||||
assert.equal(normalizeBackground({ seconds: NaN }).seconds, 60);
|
||||
assert.equal(normalizeBackground({ seconds: -2 }).seconds, 1);
|
||||
assert.equal(normalizeBackground({ seconds: 1e9 }).seconds, 86400);
|
||||
assert.equal(normalizeBackground({ overlay: Infinity }).overlay, 0);
|
||||
assert.equal(normalizeBackground({ overlay: -3 }).overlay, -1);
|
||||
assert.deepEqual(normalizeBackground({ targets: ["app", "app", "bogus", "pm-board:../x", "pm-board:0c18bcdc-f41e-4a31-87f4-87c369f398c1"] }).targets, ["app", "pm-board:0c18bcdc-f41e-4a31-87f4-87c369f398c1"]);
|
||||
assert.deepEqual(normalizeBackground(null), { ...DEFAULT_BACKGROUND, targets: ["app"] });
|
||||
assert.deepEqual(normalizeBackground({ source: "web", order: "shuffle", paused: "yes", position: "middle", size: "100px" }), { ...DEFAULT_BACKGROUND, targets: ["app"] });
|
||||
assert.deepEqual(normalizeLayout({ overlay: 0.5, position: "top left", size: "auto" }), { overlay: 0.5, position: "top left", size: "auto" });
|
||||
assert.deepEqual(imageNames(["10.png", "2.png", "README.md", "../bad.png", "2.png", "a.JPEG"]), ["2.png", "10.png", "a.JPEG"]);
|
||||
assert.deepEqual(sequence(["a", "b", "c"], "b", "name"), ["c", "a", "b"]);
|
||||
assert.notEqual(sequence(["a", "b", "c"], "a", "random", () => 0)[0], "a");
|
||||
assert.deepEqual(sequence(["a"], "a", "random"), ["a"]);
|
||||
});
|
||||
|
||||
test("a folder rotates, shows one frame on every target, and a pause keeps the current image", async () => {
|
||||
const f = fixture();
|
||||
await f.engine.configure(f.source(), { ...on, overlay: -0.4, position: "top left", size: "contain" });
|
||||
assert.equal(f.engine.status.image, "1.png");
|
||||
assert.equal(f.scheduled()!.delay, 3000);
|
||||
assert.equal(f.frames.get("app")!.overlay, -0.4);
|
||||
assert.equal(f.frames.get("app")!.size, "contain");
|
||||
assert.deepEqual(f.frames.get("app"), f.frames.get("pm-all"));
|
||||
await f.tick();
|
||||
assert.equal(f.engine.status.image, "2.png");
|
||||
await f.engine.next();
|
||||
assert.equal(f.engine.status.image, "10.png");
|
||||
await f.engine.configure(f.source(), { ...on, paused: true });
|
||||
assert.equal(f.engine.status.image, "10.png", "A pause keeps the image.");
|
||||
assert.equal(f.scheduled(), undefined, "A pause has no timer.");
|
||||
assert.equal(f.frames.size, 2);
|
||||
await f.engine.next();
|
||||
assert.equal(f.engine.status.image, "1.png", "Next works during a pause.");
|
||||
assert.equal(f.scheduled(), undefined);
|
||||
await f.engine.configure(null, on);
|
||||
assert.equal(f.frames.size, 0, "Without a source, the frames go away.");
|
||||
f.engine.dispose();
|
||||
});
|
||||
|
||||
test("unreadable images are skipped, and an empty folder tries again", async () => {
|
||||
const f = fixture();
|
||||
const read = f.source();
|
||||
const source: ImageSource = { ...read, read: async name => { if (name === "1.png") throw new Error("removed"); return read.read(name); } };
|
||||
await f.engine.configure(source, on);
|
||||
assert.equal(f.engine.status.image, "2.png");
|
||||
assert.match(f.engine.status.message, /skipped 1/);
|
||||
f.names([]);
|
||||
f.engine.invalidate();
|
||||
await f.engine.next();
|
||||
assert.equal(f.frames.size, 0);
|
||||
assert.equal(f.engine.status.error, true);
|
||||
assert.equal(f.scheduled()!.delay, 5000);
|
||||
f.names(["restored.png"]);
|
||||
f.engine.invalidate();
|
||||
await f.tick();
|
||||
assert.equal(f.engine.status.image, "restored.png");
|
||||
f.engine.dispose();
|
||||
});
|
||||
|
||||
test("both images of a fade stay alive, and each image is released once", async () => {
|
||||
const f = fixture();
|
||||
await f.engine.configure(f.source(), on);
|
||||
const first = f.frames.get("app")!;
|
||||
assert.equal(first.previous, undefined);
|
||||
await f.engine.next(); await settle();
|
||||
const second = f.frames.get("app")!;
|
||||
assert.deepEqual(second.previous, first);
|
||||
assert.equal(second.transitionMs, transitionMs);
|
||||
assert.equal(f.released.length, 0);
|
||||
await f.engine.next(); await settle();
|
||||
const third = f.frames.get("app")!;
|
||||
assert.deepEqual(third.previous, { url: second.url, overlay: 0, position: "center", size: "cover" });
|
||||
assert.deepEqual(f.released, [first.url]);
|
||||
f.engine.dispose();
|
||||
await settle();
|
||||
assert.equal(new Set(f.released).size, f.released.length, "No URL is released twice.");
|
||||
for (const url of [first.url, second.url, third.url]) assert.ok(f.released.includes(url), url);
|
||||
});
|
||||
|
||||
test("a settings change keeps the current image and applies the new layout without a fade", async () => {
|
||||
const f = fixture();
|
||||
await f.engine.configure(f.source(), on);
|
||||
const first = f.frames.get("app")!;
|
||||
await f.engine.configure(f.source(), { ...on, overlay: 0.4, position: "bottom", targets: ["app"] });
|
||||
const changed = f.frames.get("app")!;
|
||||
assert.equal(changed.url, first.url);
|
||||
assert.equal(changed.overlay, 0.4);
|
||||
assert.equal(changed.position, "bottom");
|
||||
assert.equal(changed.previous, undefined);
|
||||
assert.equal(f.frames.has("pm-all"), false, "A removed target loses its frame.");
|
||||
assert.equal(f.engine.status.image, "1.png");
|
||||
assert.deepEqual(f.released, []);
|
||||
f.engine.dispose();
|
||||
});
|
||||
|
||||
test("the next image is read and decoded before its fade", async () => {
|
||||
const f = fixture();
|
||||
await f.engine.configure(f.source(), on);
|
||||
await settle(); await settle();
|
||||
assert.deepEqual(f.reads, ["1.png", "2.png"], "The next image loads after the current one shows.");
|
||||
await f.tick();
|
||||
assert.equal(f.engine.status.image, "2.png");
|
||||
assert.deepEqual(f.reads, ["1.png", "2.png", "10.png"], "The timer used the prepared image without a new read.");
|
||||
// A change of order drops the prepared image when the folder no longer has it.
|
||||
f.names(["1.png", "2.png"]);
|
||||
f.engine.invalidate();
|
||||
await f.tick();
|
||||
assert.equal(f.engine.status.image, "1.png");
|
||||
assert.ok(f.released.some(url => url.startsWith("blob:10.png")), "The unused prepared image is released.");
|
||||
f.engine.dispose();
|
||||
});
|
||||
|
||||
test("a missing folder shows an error, and the folder recovers on the next try", async () => {
|
||||
const f = fixture();
|
||||
const missing: ImageSource = { ...f.source(), list: async () => { throw new Error("The background folder is missing. Choose the folder again."); } };
|
||||
await f.engine.configure(missing, on);
|
||||
assert.equal(f.engine.status.error, true);
|
||||
assert.match(f.engine.status.message, /Choose the folder again/);
|
||||
assert.equal(f.frames.size, 0);
|
||||
await f.engine.configure(f.source("folder:D:\\Other"), on);
|
||||
assert.equal(f.engine.status.error, false);
|
||||
assert.equal(f.engine.status.image, "1.png");
|
||||
f.engine.dispose();
|
||||
});
|
||||
|
||||
test("a host failure clears the published targets and releases every image", async () => {
|
||||
const f = fixture();
|
||||
let fail = false;
|
||||
const engine = new Slideshow({ set: (target, frame) => {
|
||||
if (fail && target === "pm-all" && frame) throw new Error("Background access ended.");
|
||||
if (frame) f.frames.set(target, frame); else f.frames.delete(target);
|
||||
} }, f.runtime);
|
||||
await engine.configure(f.source(), on);
|
||||
await engine.next(); await settle();
|
||||
fail = true;
|
||||
await engine.next(); await settle();
|
||||
assert.equal(engine.status.error, true);
|
||||
assert.equal(f.frames.size, 0);
|
||||
assert.equal(new Set(f.released).size, f.released.length, "No URL is released twice.");
|
||||
assert.ok(f.released.length >= 3);
|
||||
engine.dispose();
|
||||
});
|
||||
|
||||
test("another source starts again, and a late read of the old source is ignored", async () => {
|
||||
const f = fixture();
|
||||
let resolve!: (value: string[]) => void;
|
||||
const slow: ImageSource = { ...f.source("folder:D:\\Slow"), list: () => new Promise(done => { resolve = done; }) };
|
||||
const pending = f.engine.configure(slow, on);
|
||||
await settle();
|
||||
await f.engine.configure(f.source("folder:D:\\Other"), on);
|
||||
const current = f.frames.get("app")!.url;
|
||||
resolve(["stale.png"]);
|
||||
await pending;
|
||||
assert.equal(f.frames.get("app")!.url, current);
|
||||
assert.equal(f.engine.status.image, "1.png");
|
||||
f.engine.dispose();
|
||||
});
|
||||
|
||||
test("the list and the sidecar are read again only after a change, a focus, or every 10 images", async () => {
|
||||
const f = fixture();
|
||||
await f.engine.configure(f.source(), { ...on, seconds: 1 });
|
||||
assert.deepEqual([f.counts.list, f.counts.sidecar], [1, 1]);
|
||||
for (let index = 1; index < RESCAN_SLIDES; index++) await f.tick();
|
||||
assert.deepEqual([f.counts.list, f.counts.sidecar], [1, 1], "Nine timer images read nothing again.");
|
||||
await f.tick();
|
||||
assert.deepEqual([f.counts.list, f.counts.sidecar], [2, 2], "The eleventh image reads the folder again.");
|
||||
f.engine.invalidate();
|
||||
await f.tick();
|
||||
assert.deepEqual([f.counts.list, f.counts.sidecar], [3, 3], "A focus reads it again.");
|
||||
await f.engine.configure(f.source(), { ...on, seconds: 2 });
|
||||
assert.deepEqual([f.counts.list, f.counts.sidecar], [4, 4], "A settings change reads it again.");
|
||||
f.engine.dispose();
|
||||
});
|
||||
|
||||
test("a late image after disposal is released and never published", async () => {
|
||||
const f = fixture();
|
||||
let resolve!: (value: { url: string; width: number; height: number }) => void;
|
||||
f.runtime.load = () => new Promise(done => { resolve = done; });
|
||||
const pending = f.engine.configure(f.source(), on);
|
||||
await settle(); await settle();
|
||||
f.engine.dispose();
|
||||
resolve({ url: "blob:late", width: 1, height: 1 });
|
||||
await pending;
|
||||
assert.deepEqual(f.released, ["blob:late"]);
|
||||
assert.equal(f.frames.size, 0);
|
||||
assert.equal(f.scheduled(), undefined);
|
||||
});
|
||||
|
||||
test("disposal clears the targets and stops the timer", async () => {
|
||||
const f = fixture();
|
||||
await f.engine.configure(f.source(), on);
|
||||
const timer = f.scheduled()!;
|
||||
f.engine.dispose();
|
||||
timer.callback();
|
||||
await settle();
|
||||
assert.equal(f.frames.size, 0);
|
||||
assert.equal(f.scheduled(), undefined);
|
||||
});
|
||||
|
||||
test("the image source shows one image without a timer and without the portrait default", async () => {
|
||||
const f = fixture({ width: 100, height: 300 });
|
||||
const image: ImageSource = { key: "image:abc", timed: false, list: async () => ["image"], read: async () => new Blob(["saved"]), sidecar: async () => { throw new Error("not asked"); } };
|
||||
await f.engine.configure(image, { ...on, size: "cover" });
|
||||
assert.equal(f.frames.get("app")!.size, "cover");
|
||||
assert.equal(f.frames.get("app")!.blurredUrl, undefined);
|
||||
assert.equal(f.scheduled(), undefined);
|
||||
await f.engine.next();
|
||||
assert.equal(f.frames.get("app")!.previous, undefined, "Next keeps the one image.");
|
||||
assert.equal(f.counts.blur, 0);
|
||||
f.engine.dispose();
|
||||
});
|
||||
|
||||
test("the sidecar keeps file names and other data, and rejects invalid appearance", () => {
|
||||
const value = { schema: 1, owner: "personal", images: { "Portrait.png": { fit: "blurred", position: "top", overlay: -0.25 } } };
|
||||
assert.deepEqual(parseImageSettings(JSON.stringify(value)), value);
|
||||
assert.deepEqual(parseImageSettings(null), { schema: 1, images: {} });
|
||||
for (const source of ["{}", '{"schema":2,"images":{}}', '{"schema":1,"images":[]}', '{"schema":1,"images":{"../a.png":{"fit":"cover"}}}', '{"schema":1,"images":{"a.png":{"fit":"crop"}}}', '{"schema":1,"images":{"a.png":{"overlay":2}}}']) {
|
||||
assert.throws(() => parseImageSettings(source), source);
|
||||
}
|
||||
const layout = { overlay: 0.3, position: "center" as const, size: "auto" as const };
|
||||
assert.equal(imageAppearance(layout, undefined, true).fit, "blurred");
|
||||
assert.equal(imageAppearance(layout, undefined, false).fit, "auto");
|
||||
assert.equal(imageAppearance(layout, { fit: "cover", position: "bottom", overlay: -0.2 }, true).fit, "cover");
|
||||
});
|
||||
|
||||
test("a partial image override inherits every other field", () => {
|
||||
const source = { schema: 1, owner: "personal", images: { "Portrait.png": { position: "top", note: "keep" }, "Other.png": {} } };
|
||||
assert.deepEqual(parseImageSettings(JSON.stringify(source)), source);
|
||||
const layout = { overlay: 0.3, position: "center" as const, size: "auto" as const };
|
||||
assert.deepEqual(imageAppearance(layout, { position: "top" }, false), { fit: "auto", position: "top", overlay: 0.3 });
|
||||
assert.deepEqual(imageAppearance({ ...layout, size: "contain", overlay: -0.4 }, { position: "top" }, false), { fit: "contain", position: "top", overlay: -0.4 });
|
||||
assert.deepEqual(imageAppearance(layout, { overlay: 0 }, true), { fit: "blurred", position: "center", overlay: 0 });
|
||||
for (const value of [null, [], "cover", 1, { fit: null }, { position: "invalid" }, { overlay: "0" }, { overlay: null }]) {
|
||||
assert.throws(() => parseImageSettings(JSON.stringify({ schema: 1, images: { "Image.png": value } })));
|
||||
}
|
||||
});
|
||||
|
||||
test("a partial override stays while the folder layout changes", async () => {
|
||||
const f = fixture();
|
||||
f.names(["A.png"]);
|
||||
f.sidecar(JSON.stringify({ schema: 1, images: { "A.png": { position: "top" } } }));
|
||||
await f.engine.configure(f.source(), on);
|
||||
assert.equal(f.frames.get("app")!.size, "cover");
|
||||
await f.engine.configure(f.source(), { ...on, size: "contain", overlay: -0.4, position: "bottom" });
|
||||
assert.equal(f.frames.get("app")!.size, "contain");
|
||||
assert.equal(f.frames.get("app")!.overlay, -0.4);
|
||||
assert.equal(f.frames.get("app")!.position, "top");
|
||||
f.engine.dispose();
|
||||
});
|
||||
|
||||
test("a portrait image shows in full over a blurred fill that stays alive through the fade", async () => {
|
||||
const f = fixture({ width: 100, height: 300 });
|
||||
f.names(["A.png", "B.png"]);
|
||||
await f.engine.configure(f.source(), on);
|
||||
const first = f.frames.get("app")!;
|
||||
assert.equal(first.size, "contain");
|
||||
assert.equal(first.blurredUrl, `${first.url}-blur`);
|
||||
f.sidecar(JSON.stringify({ schema: 1, images: { "B.png": { fit: "cover", position: "bottom", overlay: 0.4 } } }));
|
||||
f.engine.invalidate();
|
||||
await f.engine.next(); await settle();
|
||||
const second = f.frames.get("app")!;
|
||||
assert.equal(second.size, "cover"); assert.equal(second.position, "bottom"); assert.equal(second.overlay, 0.4);
|
||||
assert.equal(second.blurredUrl, undefined);
|
||||
assert.equal(second.previous!.blurredUrl, first.blurredUrl);
|
||||
assert.equal(f.released.includes(first.blurredUrl!), false, "The fill of the fade stays.");
|
||||
f.engine.dispose(); await settle();
|
||||
for (const url of [first.url, first.blurredUrl!, second.url]) assert.ok(f.released.includes(url), url);
|
||||
});
|
||||
|
||||
test("the blurred fills of the last three images stay in the cache", async () => {
|
||||
const f = fixture({ width: 100, height: 300 });
|
||||
f.names(["A.png", "B.png", "C.png", "D.png", "E.png"]);
|
||||
await f.engine.configure(f.source(), { ...on, order: "name" });
|
||||
for (let index = 0; index < 4; index++) { await f.engine.next(); await settle(); await settle(); }
|
||||
const blurs = f.counts.blur;
|
||||
const releasedBlurs = f.released.filter(url => url.endsWith("-blur")).length;
|
||||
assert.ok(releasedBlurs >= 1, "Old fills beyond the cache are released.");
|
||||
assert.ok(blurs - releasedBlurs <= BLUR_CACHE + 1, "At most the cache and the prepared fill stay.");
|
||||
// The same image again uses the cached fill.
|
||||
const repeat = fixture({ width: 100, height: 300 });
|
||||
repeat.names(["A.png", "B.png"]);
|
||||
await repeat.engine.configure(repeat.source(), on);
|
||||
for (let index = 0; index < 4; index++) { await repeat.engine.next(); await settle(); await settle(); }
|
||||
assert.equal(repeat.counts.blur, 2, "Two images that alternate use their cached fills.");
|
||||
f.engine.dispose(); repeat.engine.dispose();
|
||||
});
|
||||
|
||||
test("a late blurred fill is released when the source goes away", async () => {
|
||||
let resolve!: (url: string) => void;
|
||||
const f = fixture({ width: 100, height: 300 });
|
||||
f.names(["A.png"]);
|
||||
f.runtime.blur = () => new Promise(done => { resolve = done; });
|
||||
const loading = f.engine.configure(f.source(), on);
|
||||
await settle(); await settle();
|
||||
await f.engine.configure(null, on);
|
||||
resolve("blob:blur");
|
||||
await loading;
|
||||
assert.equal(f.frames.size, 0);
|
||||
assert.ok(f.released.includes("blob:blur"));
|
||||
assert.ok(f.released.some(url => url.startsWith("blob:A.png")));
|
||||
f.engine.dispose();
|
||||
});
|
||||
|
||||
test("the sources have stable keys, and the saved image of an old data URL decodes", async () => {
|
||||
assert.equal(folderSource("D:\\Pictures").key, "folder:D:\\Pictures");
|
||||
assert.equal(folderSource("D:\\Pictures").timed, true);
|
||||
const id = "01234567-89ab-cdef-0123-456789abcdef";
|
||||
assert.equal(imageSource({ imageId: id }).key, `image:${id}`);
|
||||
assert.equal(imageSource({ imageId: id }).timed, false);
|
||||
assert.deepEqual(await imageSource({ imageId: id }).list(), ["image"]);
|
||||
const data = "data:image/png;base64,iVBORw0KGgo=";
|
||||
const blob = await readSavedImage({ image: data });
|
||||
assert.equal(blob.type, "image/png");
|
||||
assert.deepEqual([...new Uint8Array(await blob.arrayBuffer())], [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
||||
assert.notEqual(imageSource({ image: data }).key, imageSource({ image: data.replace("KGgo", "KGgp") }).key);
|
||||
});
|
||||
|
||||
test("Background has a source only with a folder or an existing image", () => {
|
||||
const appearance = { theme: "default" as const, mode: "dark" as const };
|
||||
const withImage = { ...appearance, newTabBackground: { imageId: "01234567-89ab-cdef-0123-456789abcdef" } };
|
||||
assert.equal(hasBackgroundSource(normalizeBackground({ source: "none" }), withImage), false);
|
||||
assert.equal(hasBackgroundSource(normalizeBackground({ source: "folder" }), appearance), true);
|
||||
assert.equal(hasBackgroundSource(normalizeBackground({ source: "image" }), appearance), false);
|
||||
assert.equal(hasBackgroundSource(normalizeBackground({ source: "image" }), withImage), true);
|
||||
});
|
||||
|
||||
test("the launch rule starts Background when it has a source, also in browser windows, but not in the settings window", () => {
|
||||
const rule = LAUNCH_RULES.background!;
|
||||
assert.equal(rule.browserWindow, true);
|
||||
assert.equal(LAUNCH_RULES.git, undefined, "Git loads at first need.");
|
||||
assert.equal(runsInWindow("background", { browserWindow: true }), true);
|
||||
assert.equal(runsInWindow("git", { browserWindow: true }), false);
|
||||
assert.equal(runsInWindow("git", { browserWindow: false }), true);
|
||||
assert.equal(launchWanted("git", { settingsWindow: false }), false);
|
||||
// In Node the settings are empty, so the source is "none".
|
||||
assert.equal(rule.wanted(), false);
|
||||
assert.equal(launchWanted("background", { settingsWindow: false }), false);
|
||||
const wanted = rule.wanted;
|
||||
rule.wanted = () => true;
|
||||
try {
|
||||
assert.equal(launchWanted("background", { settingsWindow: false }), true);
|
||||
assert.equal(launchWanted("background", { settingsWindow: true }), false);
|
||||
} finally { rule.wanted = wanted; }
|
||||
});
|
||||
|
||||
function migrationHost({ image = false, folder = true, fails = false } = {}) {
|
||||
const calls = { folder: 0 };
|
||||
const written: BackgroundSettings[] = [];
|
||||
const host: BackgroundMigrationHost = {
|
||||
missing: () => true,
|
||||
hasImage: () => image,
|
||||
migrateFolder: async () => { calls.folder++; if (fails) throw new Error("no folder"); return folder; },
|
||||
write: async value => { written.push(value); },
|
||||
};
|
||||
return { host, calls, written };
|
||||
}
|
||||
const plugin = (installed: boolean, enabled: boolean, settings: unknown): LegacyPlugin => ({ id: "runestone.bg-slideshow", installed, enabled, settings });
|
||||
const grant = "6f0c7a8e-5b1d-4c2e-9a3f-2d7b8e1c4a90";
|
||||
const kept = { grant, folder: "D:\\Pictures", seconds: 10, order: "random", enabled: true, targets: ["app", "pm-all"], overlay: 0.25, position: "top", size: "contain" };
|
||||
|
||||
test("the migration selects the folder of an installed, enabled, and running slideshow", async () => {
|
||||
const { host, calls, written } = migrationHost({ image: true });
|
||||
const value = await migrateBackground(plugin(true, true, kept), host);
|
||||
assert.equal(calls.folder, 1);
|
||||
assert.deepEqual(value, { source: "folder", seconds: 10, order: "random", paused: false, targets: ["app", "pm-all"], overlay: 0.25, position: "top", size: "contain" });
|
||||
assert.deepEqual(written, [value]);
|
||||
});
|
||||
|
||||
test("a disabled package, a stopped slideshow, or a lost folder gives the image or none, and the folder still migrates", async () => {
|
||||
for (const [legacy, folder] of [[plugin(true, false, kept), true], [plugin(true, true, { ...kept, enabled: false }), true], [plugin(false, false, kept), true], [plugin(true, true, kept), false]] as const) {
|
||||
const withImage = migrationHost({ image: true, folder });
|
||||
assert.equal((await migrateBackground(legacy, withImage.host)).source, "image");
|
||||
assert.equal(withImage.calls.folder, 1, "A kept grant always migrates its folder.");
|
||||
const without = migrationHost({ folder });
|
||||
const value = await migrateBackground(legacy, without.host);
|
||||
assert.equal(value.source, "none");
|
||||
assert.equal(value.seconds, 10, "The kept settings still give the sequence and the layout.");
|
||||
}
|
||||
});
|
||||
|
||||
test("a failed folder migration is not a failed start", async () => {
|
||||
const errors = console.error;
|
||||
console.error = () => {};
|
||||
try {
|
||||
const { host, written } = migrationHost({ image: true, fails: true });
|
||||
assert.equal((await migrateBackground(plugin(true, true, kept), host)).source, "image");
|
||||
assert.equal(written.length, 1);
|
||||
} finally { console.error = errors; }
|
||||
});
|
||||
|
||||
test("without the old plugin, an image gives the image source and nothing gives none", async () => {
|
||||
const image = migrationHost({ image: true });
|
||||
assert.deepEqual(await migrateBackground(undefined, image.host), { ...DEFAULT_BACKGROUND, targets: ["app"], source: "image" });
|
||||
assert.equal(image.calls.folder, 0, "Without a grant, no folder migrates.");
|
||||
const none = migrationHost();
|
||||
assert.deepEqual(await migrateBackground(plugin(false, false, null), none.host), { ...DEFAULT_BACKGROUND, targets: ["app"] });
|
||||
// Settings of version 0.0.10 and earlier have a path and no grant. Only a grant migrates.
|
||||
const old = migrationHost();
|
||||
assert.equal((await migrateBackground(plugin(true, true, { folder: "D:\\Pictures", enabled: true }), old.host)).source, "none");
|
||||
assert.equal(old.calls.folder, 0);
|
||||
// Invalid kept values take the defaults.
|
||||
const invalid = migrationHost();
|
||||
const value = await migrateBackground(plugin(true, true, { grant, enabled: true, seconds: "x", targets: ["bogus"], overlay: 9 }), invalid.host);
|
||||
assert.deepEqual([value.source, value.seconds, value.targets, value.overlay], ["folder", 60, [], 1]);
|
||||
});
|
||||
@@ -0,0 +1,208 @@
|
||||
// The native feature runtime: the catalog, the switches, the migration from old plugin packages, the loader, and the session.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { FEATURES, featureEntry, featureOfOwner } from "../../../src/lib/features/catalog.ts";
|
||||
import { storedSwitches, switchesFrom } from "../../../src/lib/features/state.ts";
|
||||
import { legacySwitch, migrateFeatures, type LegacyPlugin } from "../../../src/lib/features/migration.ts";
|
||||
import type { BackgroundMigrationHost, BackgroundSettings } from "../../../src/lib/features/backgroundSettings.ts";
|
||||
import type { TerminalMigrationHost } from "../../../src/lib/features/terminalSettings.ts";
|
||||
import type { ProjectManagementMigrationHost } from "../../../src/lib/features/pmSettings.ts";
|
||||
import { featureErrors, featureRequested, loadFeature } from "../../../src/lib/features/loader.ts";
|
||||
import { FeatureSession } from "../../../src/lib/features/session.ts";
|
||||
import type { FeatureContext, FeatureInstance, FeatureModule } from "../../../src/lib/features/types.ts";
|
||||
import { get } from "svelte/store";
|
||||
|
||||
test("each feature keeps the ID of its old plugin package as its owner ID", () => {
|
||||
assert.equal(featureEntry("git").owner, "runestone.git");
|
||||
assert.equal(featureOfOwner("runestone.git")?.id, "git");
|
||||
assert.equal(featureOfOwner("runestone.csv-viewer"), undefined);
|
||||
assert.equal(new Set(FEATURES.map(feature => feature.owner)).size, FEATURES.length);
|
||||
const git = featureEntry("git");
|
||||
assert.deepEqual(git.views.map(view => [view.id, view.placement]), [["source-control", "sidebar"], ["diff", "editor"], ["graph", "editor"]]);
|
||||
assert.equal(git.views[0].title(), "Source control");
|
||||
assert.deepEqual(git.commands.map(command => [command.id, command.view]), [["graph", "graph"]]);
|
||||
const background = featureEntry("background");
|
||||
assert.equal(background.owner, "runestone.bg-slideshow");
|
||||
assert.equal(featureOfOwner("runestone.bg-slideshow")?.id, "background");
|
||||
assert.deepEqual(background.views, []);
|
||||
assert.deepEqual(background.commands.map(command => [command.id, command.view, command.title()]), [["next", undefined, "Next background image"], ["pause", undefined, "Pause background"]]);
|
||||
assert.equal(background.defaultOn, true);
|
||||
assert.equal(background.followsPackage, false);
|
||||
});
|
||||
|
||||
test("switches keep known booleans only, and missing keys take the default", () => {
|
||||
assert.deepEqual(storedSwitches({ git: false, terminal: "no", csv: true, other: "yes" }), { git: false });
|
||||
assert.deepEqual(storedSwitches(null), {});
|
||||
assert.deepEqual(storedSwitches(["git"]), {});
|
||||
assert.deepEqual(switchesFrom(undefined), { git: true, background: true, terminal: true, pdf: true, pm: true });
|
||||
assert.deepEqual(switchesFrom({ git: false, background: false, terminal: false, pdf: false, pm: false }), { git: false, background: false, terminal: false, pdf: false, pm: false });
|
||||
assert.deepEqual(switchesFrom({ git: "false" }), { git: true, background: true, terminal: true, pdf: true, pm: true });
|
||||
});
|
||||
|
||||
test("an installed package gives its state, and without a package the default applies", () => {
|
||||
const git = featureEntry("git");
|
||||
const legacy = (installed: boolean, enabled: boolean): LegacyPlugin => ({ id: "runestone.git", installed, enabled, settings: null });
|
||||
assert.equal(legacySwitch(git, undefined), true);
|
||||
assert.equal(legacySwitch(git, legacy(false, false)), true);
|
||||
assert.equal(legacySwitch(git, legacy(true, false)), false);
|
||||
assert.equal(legacySwitch(git, legacy(true, true)), true);
|
||||
// Background is on for every user, also after an update with a disabled Background Slideshow package.
|
||||
const background = featureEntry("background");
|
||||
for (const [installed, enabled] of [[false, false], [true, false], [true, true]]) {
|
||||
assert.equal(legacySwitch(background, { id: "runestone.bg-slideshow", installed, enabled, settings: null }), true);
|
||||
}
|
||||
assert.equal(legacySwitch(background, undefined), true);
|
||||
});
|
||||
|
||||
/** A background host with a section already present: the migration of the section does not run. */
|
||||
function presentBackground(): BackgroundMigrationHost {
|
||||
return { missing: () => false, hasImage: () => false, migrateFolder: async () => { throw new Error("not asked"); }, write: async () => { throw new Error("not asked"); } };
|
||||
}
|
||||
|
||||
/** A terminal host with a section already present. */
|
||||
function presentTerminal(): TerminalMigrationHost {
|
||||
return { missing: () => false, legacy: () => { throw new Error("not asked"); }, write: async () => { throw new Error("not asked"); } };
|
||||
}
|
||||
|
||||
/** A Project Management host with a section already present. */
|
||||
function presentProjectManagement(): ProjectManagementMigrationHost {
|
||||
return { missing: () => false, write: async () => { throw new Error("not asked"); }, storage: { getItem: () => { throw new Error("not asked"); }, setItem: () => { throw new Error("not asked"); } } };
|
||||
}
|
||||
|
||||
test("the migration asks only for features without a switch, and keeps other keys", async () => {
|
||||
const writes: unknown[] = [];
|
||||
const asked: string[][] = [];
|
||||
const host = (stored: unknown, packages: LegacyPlugin[]) => ({
|
||||
read: () => stored,
|
||||
write: async (value: unknown) => { writes.push(value); },
|
||||
legacy: async (ids: string[]) => { asked.push(ids); return packages; },
|
||||
});
|
||||
assert.deepEqual(await migrateFeatures(host({ future: 1, background: false, terminal: true, pdf: true, pm: true }, [{ id: "runestone.git", installed: true, enabled: false, settings: null }]), presentBackground(), presentTerminal(), presentProjectManagement()), ["git"]);
|
||||
assert.deepEqual(asked, [["runestone.git"]]);
|
||||
assert.deepEqual(writes, [{ future: 1, background: false, terminal: true, pdf: true, pm: true, git: false }]);
|
||||
assert.deepEqual(await migrateFeatures(host({ git: true, background: true, terminal: true, pdf: true, pm: true }, []), presentBackground(), presentTerminal(), presentProjectManagement()), []);
|
||||
assert.equal(asked.length, 1, "A stored switch needs no package read.");
|
||||
assert.equal(writes.length, 1);
|
||||
});
|
||||
|
||||
test("a missing background section asks for the slideshow package and makes the section", async () => {
|
||||
const asked: string[][] = [];
|
||||
const switches: unknown[] = [];
|
||||
const sections: BackgroundSettings[] = [];
|
||||
const background: BackgroundMigrationHost = { missing: () => true, hasImage: () => true, migrateFolder: async () => true, write: async value => { sections.push(value); } };
|
||||
const host = { read: () => ({ git: true, background: false, terminal: true, pdf: true, pm: true }), write: async (value: unknown) => { switches.push(value); }, legacy: async (ids: string[]) => { asked.push(ids); return []; } };
|
||||
assert.deepEqual(await migrateFeatures(host, background, presentTerminal(), presentProjectManagement()), []);
|
||||
assert.deepEqual(asked, [["runestone.bg-slideshow"]]);
|
||||
assert.deepEqual(switches, [], "Stored switches stay.");
|
||||
assert.equal(sections.length, 1);
|
||||
assert.equal(sections[0].source, "image");
|
||||
// Both migrations together ask once for both packages.
|
||||
asked.length = 0;
|
||||
await migrateFeatures({ ...host, read: () => undefined }, background, presentTerminal(), presentProjectManagement());
|
||||
assert.deepEqual(asked, [["runestone.git", "runestone.bg-slideshow", "runestone.terminal", "runestone.pdf-viewer", "runestone.pm"]]);
|
||||
assert.deepEqual(switches, [{ git: true, background: true, terminal: true, pdf: true, pm: true }]);
|
||||
});
|
||||
|
||||
test("a failed package read writes nothing, so the next start tries again", async () => {
|
||||
const writes: unknown[] = [];
|
||||
const error = console.error;
|
||||
console.error = () => {};
|
||||
try {
|
||||
const background: BackgroundMigrationHost = { missing: () => true, hasImage: () => true, migrateFolder: async () => true, write: async value => { writes.push(value); } };
|
||||
const result = await migrateFeatures({ read: () => undefined, write: async value => { writes.push(value); }, legacy: async () => { throw new Error("no host"); } }, background, presentTerminal(), presentProjectManagement());
|
||||
assert.deepEqual(result, []);
|
||||
assert.deepEqual(writes, []);
|
||||
} finally { console.error = error; }
|
||||
});
|
||||
|
||||
test("the loader imports a feature one time, reports a failure, and tries again after it", async () => {
|
||||
let calls = 0;
|
||||
const module: FeatureModule = { start: () => ({ mount: () => () => {}, dispose() {} }) };
|
||||
await assert.rejects(loadFeature("git", async () => { calls++; throw new Error("chunk missing"); }), /chunk missing/);
|
||||
assert.match(get(featureErrors).git ?? "", /chunk missing/);
|
||||
assert.equal(featureRequested("git"), false);
|
||||
const first = loadFeature("git", async () => { calls++; return module; });
|
||||
const second = loadFeature("git", async () => { calls++; return module; });
|
||||
assert.equal(await first, module);
|
||||
assert.equal(await second, module);
|
||||
assert.equal(calls, 2);
|
||||
assert.equal(featureRequested("git"), true);
|
||||
assert.equal(get(featureErrors).git, undefined);
|
||||
});
|
||||
|
||||
function fakeContext(opened: string[] = []): FeatureContext {
|
||||
return { openView: id => { opened.push(id); }, openFile: async () => {}, onWorkspaceChange: () => () => {}, setViewTitle: () => {}, closeView: () => {}, replaceView: () => {} };
|
||||
}
|
||||
|
||||
test("a feature session shows its views and commands without loading the feature", async () => {
|
||||
let loads = 0;
|
||||
const opened: string[] = [];
|
||||
const session = new FeatureSession(featureEntry("git"), fakeContext(opened), async () => { loads++; throw new Error("not loaded"); });
|
||||
assert.deepEqual([...session.views.keys()], ["source-control", "diff", "graph"]);
|
||||
assert.equal(session.views.get("source-control")?.navigation, true);
|
||||
assert.equal(session.views.get("diff")?.launcher, false);
|
||||
assert.equal(session.views.get("graph")?.title, "Git graph");
|
||||
assert.equal(session.views.get("diff")?.saveTabState?.(), undefined);
|
||||
await session.run("graph");
|
||||
await session.launch("source-control");
|
||||
assert.deepEqual(opened, ["graph", "source-control"]);
|
||||
assert.equal(loads, 0, "Commands and navigation do not load the feature.");
|
||||
assert.equal(session.started, false);
|
||||
await session.stop();
|
||||
});
|
||||
|
||||
test("an action command loads the feature and runs it, and start loads it without a view", async () => {
|
||||
const runs: string[] = [];
|
||||
let starts = 0;
|
||||
const instance: FeatureInstance = { mount: () => () => {}, run: command => { runs.push(command); }, dispose() { runs.push("dispose"); } };
|
||||
const session = new FeatureSession(featureEntry("background"), fakeContext(), async () => ({ start: () => { starts++; return instance; } }));
|
||||
assert.deepEqual([...session.commands.keys()], ["next", "pause"]);
|
||||
assert.equal(session.commands.get("pause")?.title, "Pause background");
|
||||
assert.equal(session.started, false);
|
||||
await session.run("next");
|
||||
assert.equal(session.started, true);
|
||||
await session.start();
|
||||
await session.run("pause");
|
||||
assert.equal(starts, 1, "One instance runs the commands and the start.");
|
||||
await session.stop();
|
||||
assert.deepEqual(runs, ["next", "pause", "dispose"]);
|
||||
await assert.rejects(session.run("missing"), /This command is unavailable/);
|
||||
await assert.rejects(session.start(), /This feature is off/);
|
||||
});
|
||||
|
||||
test("the first mount starts one instance, and stop disposes it", async () => {
|
||||
const events: string[] = [];
|
||||
let starts = 0;
|
||||
const instance: FeatureInstance = {
|
||||
mount: (view, element) => { events.push(`mount ${view}`); element.textContent = view; return () => { events.push(`unmount ${view}`); }; },
|
||||
saveTabState: view => ({ view }),
|
||||
restoreTabState: (view, state) => { events.push(`restore ${view} ${JSON.stringify(state)}`); },
|
||||
dispose: () => { events.push("dispose"); },
|
||||
};
|
||||
const session = new FeatureSession(featureEntry("git"), fakeContext(), async () => ({ start: () => { starts++; return instance; } }));
|
||||
const element = { textContent: "", replaceChildren(this: { textContent: string }) { this.textContent = ""; } } as unknown as HTMLElement;
|
||||
const dispose = await session.mount("diff", element);
|
||||
await session.views.get("graph")!.restoreTabState!({ selectedId: "a" });
|
||||
assert.equal(starts, 1);
|
||||
assert.deepEqual(session.views.get("diff")!.saveTabState!(), { view: "diff" });
|
||||
await dispose();
|
||||
assert.equal(element.textContent, "");
|
||||
await session.stop();
|
||||
assert.deepEqual(events, ["mount diff", 'restore graph {"selectedId":"a"}', "unmount diff", "dispose"]);
|
||||
await assert.rejects(session.mount("diff", element), /This feature is off/);
|
||||
});
|
||||
|
||||
test("a failed load leaves no instance, so a later mount tries again", async () => {
|
||||
let attempt = 0;
|
||||
const instance: FeatureInstance = { mount: () => () => {}, dispose() {} };
|
||||
const session = new FeatureSession(featureEntry("git"), fakeContext(), async () => {
|
||||
if (++attempt === 1) throw new Error("offline");
|
||||
return { start: () => instance };
|
||||
});
|
||||
const element = { replaceChildren() {} } as unknown as HTMLElement;
|
||||
await assert.rejects(session.mount("graph", element), /offline/);
|
||||
await session.mount("graph", element);
|
||||
assert.equal(attempt, 2);
|
||||
await assert.rejects(session.mount("missing", element), /This view is unavailable/);
|
||||
await session.stop();
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
// The Git feature model. These tests come from the Git plugin (`RuneStone_Git/test/model.test.mjs`).
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { changeLabel, diffLineKind, graphLayout, groups, isConflict, pathsFor } from "../../../src/lib/features/git/model.ts";
|
||||
import type { GitChange, GitGraphCommit } from "../../../src/lib/git/contracts.ts";
|
||||
|
||||
const commit = (id: string, parents: string[]): GitGraphCommit => ({ id, parents, refs: [], summary: id, author: "Test", date: "2026-10-29" });
|
||||
|
||||
test("partially staged files occur in both groups, with conflicts only in working files", () => {
|
||||
const changes: GitChange[] = [
|
||||
{ path: "both.txt", index: "M", worktree: "M" },
|
||||
{ path: "new.txt", index: "?", worktree: "?" },
|
||||
{ path: "conflict.txt", index: "U", worktree: "U" },
|
||||
{ path: "deleted.txt", index: "D", worktree: " " },
|
||||
];
|
||||
assert.deepEqual(groups(changes).staged.map(change => change.path), ["both.txt", "deleted.txt"]);
|
||||
assert.deepEqual(groups(changes).working.map(change => change.path), ["both.txt", "new.txt", "conflict.txt"]);
|
||||
assert.equal(isConflict({ path: "a", index: "A", worktree: "A" }), true);
|
||||
assert.equal(changeLabel(changes[2], false), "Conflict");
|
||||
assert.equal(changeLabel(changes[1], false), "New");
|
||||
assert.equal(changeLabel(changes[3], true), "Deleted");
|
||||
assert.equal(changeLabel({ path: "x", index: "X", worktree: " " }, true), "X");
|
||||
});
|
||||
|
||||
test("rename actions include old and new paths exactly once", () => {
|
||||
assert.deepEqual(pathsFor([{ path: "new.txt", originalPath: "old.txt", index: "R", worktree: " " }, { path: "old.txt", index: "M", worktree: " " }]), ["old.txt", "new.txt"]);
|
||||
});
|
||||
|
||||
test("diff lines get their kind from the first character", () => {
|
||||
assert.deepEqual(["+add", "-remove", "+++ b/file", "--- a/file", "@@ -1 +1 @@", " same", ""].map(diffLineKind),
|
||||
["add", "remove", "context", "context", "range", "context", "context"]);
|
||||
});
|
||||
|
||||
test("graph lanes preserve merge parents, forks, and truncated history", () => {
|
||||
const layout = graphLayout({ commits: [commit("merge", ["main", "feature"]), commit("feature", ["root"]), commit("main", ["root"]), commit("root", ["older"])] });
|
||||
assert.deepEqual(layout.nodes.map(node => node.lane), [0, 1, 0, 1]);
|
||||
assert.equal(layout.edges.length, 5);
|
||||
assert.deepEqual(layout.edges.filter(edge => edge.from === "merge").map(edge => [edge.to, edge.endRow]), [["main", 2], ["feature", 1]]);
|
||||
assert.equal(layout.edges.at(-1)!.outside, true);
|
||||
assert.equal(layout.edges.at(-1)!.endRow, 4);
|
||||
assert.deepEqual(graphLayout({ commits: [] }).nodes, []);
|
||||
assert.deepEqual(graphLayout(null).nodes, []);
|
||||
});
|
||||
|
||||
test("graph track colors survive lane changes, joins, and history boundaries", () => {
|
||||
const history = { commits: [commit("merge", ["main", "feature"]), commit("feature", ["feature-old"]), commit("main", ["root"]), commit("feature-old", ["root"]), commit("root", ["older"])] };
|
||||
const layout = graphLayout(history);
|
||||
const node = (id: string) => layout.nodes.find(item => item.id === id)!;
|
||||
const edge = (from: string, to: string) => layout.edges.find(item => item.from === from && item.to === to)!;
|
||||
assert.notEqual(node("main").color, node("feature").color);
|
||||
assert.equal(node("merge").color, node("main").color);
|
||||
assert.equal(node("feature").color, node("feature-old").color);
|
||||
assert.equal(edge("merge", "feature").color, node("feature").color);
|
||||
assert.equal(edge("feature-old", "root").color, node("feature-old").color);
|
||||
assert.equal(edge("root", "older").color, node("root").color);
|
||||
assert.deepEqual(graphLayout(history), layout);
|
||||
const shifted = graphLayout({ commits: [commit("merge", ["main", "feature"]), commit("main", []), commit("feature", ["feature-old"]), commit("feature-old", [])] });
|
||||
assert.notEqual(shifted.nodes[2].lane, shifted.nodes[3].lane);
|
||||
assert.equal(shifted.nodes[2].color, shifted.nodes[3].color);
|
||||
});
|
||||
|
||||
test("six concurrent graph tracks use six colors before palette reuse", () => {
|
||||
const parents = ["a", "b", "c", "d", "e", "f"];
|
||||
const layout = graphLayout({ commits: [commit("merge", parents), ...parents.map(id => commit(id, []))] });
|
||||
assert.equal(new Set(layout.nodes.slice(1).map(node => node.color)).size, 6);
|
||||
assert.equal(new Set(layout.edges.map(edge => edge.color)).size, 6);
|
||||
});
|
||||
@@ -0,0 +1,136 @@
|
||||
// The PDF Viewer feature: the page and zoom limits, the document identification of the catalog, and the document
|
||||
// mount of a feature session. The model tests come from the PDF Viewer plugin (tests/model.test.ts).
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { featureEntry, featureOfOwner } from "../../../src/lib/features/catalog.ts";
|
||||
import { identifyPdf } from "../../../src/lib/features/pdfDocument.ts";
|
||||
import { PAGE_GAP, PAGE_MARGIN, fitZoom, mostVisiblePage, nextRotation, outputScale, pageBoxes, pageNumber, pagesInRange, zoomFromText, zoomLevel } from "../../../src/lib/features/pdf/model.ts";
|
||||
import { FeatureSession } from "../../../src/lib/features/session.ts";
|
||||
import type { FeatureContext, FeatureInstance } from "../../../src/lib/features/types.ts";
|
||||
import type { PluginDocumentContext } from "../../../src/lib/plugins/sdk.ts";
|
||||
|
||||
test("PDF identification handles uppercase extensions and distinct paths", () => {
|
||||
assert.deepEqual(identifyPdf("notes\\Report.PDF"), { id: "notes/Report.PDF" });
|
||||
assert.notDeepEqual(identifyPdf("a/report.pdf"), identifyPdf("b/report.pdf"));
|
||||
for (const path of ["report.pdf.md", "pdf", "report.png"]) assert.equal(identifyPdf(path), null);
|
||||
});
|
||||
|
||||
test("page and zoom inputs stay within supported bounds", () => {
|
||||
assert.equal(pageNumber(NaN, 20), 1);
|
||||
assert.equal(pageNumber(-3, 20), 1);
|
||||
assert.equal(pageNumber(99, 20), 20);
|
||||
assert.equal(pageNumber(2.8, 20), 2);
|
||||
assert.equal(zoomLevel(Infinity), 1);
|
||||
assert.equal(zoomLevel(0), .25);
|
||||
assert.equal(zoomLevel(10), 4);
|
||||
assert.deepEqual([0, 90, 180, 270].map(nextRotation), [90, 180, 270, 0]);
|
||||
});
|
||||
|
||||
test("a typed zoom is a percent within the limits", () => {
|
||||
assert.equal(zoomFromText("137"), 1.37);
|
||||
assert.equal(zoomFromText(" 150 % "), 1.5);
|
||||
assert.equal(zoomFromText("112,5"), 1.125);
|
||||
assert.equal(zoomFromText("9000"), 4);
|
||||
assert.equal(zoomFromText("1"), .25);
|
||||
for (const text of ["", " ", "text", "-50", "0", "1e999"]) assert.equal(zoomFromText(text), null);
|
||||
});
|
||||
|
||||
test("the pages are one column, and the scroll position gives the current page", () => {
|
||||
const sizes = [{ width: 600, height: 800 }, { width: 800, height: 600 }, { width: 600, height: 800 }];
|
||||
const boxes = pageBoxes(sizes, .5, 0);
|
||||
assert.deepEqual(boxes, [
|
||||
{ top: PAGE_MARGIN, width: 300, height: 400 },
|
||||
{ top: PAGE_MARGIN + 400 + PAGE_GAP, width: 400, height: 300 },
|
||||
{ top: PAGE_MARGIN + 700 + 2 * PAGE_GAP, width: 300, height: 400 },
|
||||
]);
|
||||
assert.deepEqual(pageBoxes(sizes, 1, 90).map(box => [box.width, box.height]), [[800, 600], [600, 800], [800, 600]]);
|
||||
assert.equal(fitZoom(sizes, 0, 400), .5);
|
||||
assert.equal(fitZoom(sizes, 90, 400), .5);
|
||||
assert.equal(fitZoom([{ width: 600, height: 900 }], 90, 450), .5);
|
||||
assert.equal(fitZoom([], 0, 400), 1);
|
||||
assert.deepEqual(pagesInRange(boxes, 0, 100), [1]);
|
||||
assert.deepEqual(pagesInRange(boxes, 400, 800), [1, 2, 3]);
|
||||
assert.deepEqual(pagesInRange(boxes, 5000, 6000), []);
|
||||
assert.equal(mostVisiblePage(boxes, 0, 300), 1);
|
||||
assert.equal(mostVisiblePage(boxes, 300, 600), 2);
|
||||
assert.equal(mostVisiblePage(boxes, 900, 1200), 3);
|
||||
assert.equal(mostVisiblePage(boxes, 0, 2000), 1, "The first page wins when several pages show in full");
|
||||
assert.equal(mostVisiblePage([], 0, 100), 1);
|
||||
});
|
||||
|
||||
test("large PDF pages respect canvas dimension and memory limits", () => {
|
||||
for (const [width, height] of [[612, 792], [20000, 500], [20000, 20000]]) {
|
||||
const scale = outputScale(width, height, 3);
|
||||
assert.ok(width * scale <= 8192);
|
||||
assert.ok(height * scale <= 8192);
|
||||
assert.ok(width * height * scale * scale <= 16_000_001);
|
||||
}
|
||||
});
|
||||
|
||||
test("the catalog gives PDF Viewer the old package ID and one binary document type", () => {
|
||||
const pdf = featureEntry("pdf");
|
||||
assert.equal(pdf.owner, "runestone.pdf-viewer");
|
||||
assert.equal(featureOfOwner("runestone.pdf-viewer")?.id, "pdf");
|
||||
assert.equal(pdf.defaultOn, true);
|
||||
assert.equal(pdf.followsPackage, true);
|
||||
assert.deepEqual(pdf.views, []);
|
||||
assert.deepEqual(pdf.commands, []);
|
||||
assert.deepEqual(pdf.documentTypes.map(type => [type.id, type.icon, type.content, [...type.extensions], type.title()]), [["pdf", "file", "binary", ["pdf"], "PDF document"]]);
|
||||
assert.deepEqual(featureEntry("git").documentTypes, []);
|
||||
});
|
||||
|
||||
function fakeContext(): FeatureContext {
|
||||
return { openView: () => {}, openFile: async () => {}, onWorkspaceChange: () => () => {}, setViewTitle: () => {}, closeView: () => {}, replaceView: () => {} };
|
||||
}
|
||||
|
||||
test("a feature session identifies PDF files without loading the feature", () => {
|
||||
let loads = 0;
|
||||
const session = new FeatureSession(featureEntry("pdf"), fakeContext(), async () => { loads++; throw new Error("not loaded"); });
|
||||
const type = session.documentTypes.get("pdf");
|
||||
assert.ok(type);
|
||||
assert.equal(type.title, "PDF document");
|
||||
assert.equal(type.content, "binary");
|
||||
assert.deepEqual(type.extensions, ["pdf"]);
|
||||
assert.deepEqual(type.identify("docs/Guide.PDF", ""), { id: "docs/Guide.PDF" });
|
||||
assert.equal(type.identify("docs/guide.md", ""), null);
|
||||
assert.equal(loads, 0, "Identification does not load the feature.");
|
||||
assert.equal(session.started, false);
|
||||
});
|
||||
|
||||
test("the first document mount starts one instance, each tab gets the document, and stop disposes it", async () => {
|
||||
const events: string[] = [];
|
||||
let starts = 0;
|
||||
const instance: FeatureInstance = {
|
||||
mount: () => { throw new Error("no views"); },
|
||||
mountDocument: (type, element, document) => {
|
||||
events.push(`mount ${type} ${document.path}`);
|
||||
element.textContent = document.id;
|
||||
return () => { events.push(`unmount ${document.path}`); };
|
||||
},
|
||||
dispose: () => { events.push("dispose"); },
|
||||
};
|
||||
const session = new FeatureSession(featureEntry("pdf"), fakeContext(), async () => ({ start: () => { starts++; return instance; } }));
|
||||
const element = () => ({ textContent: "", replaceChildren(this: { textContent: string }) { this.textContent = ""; } }) as unknown as HTMLElement;
|
||||
const first = element(), second = element();
|
||||
const a: PluginDocumentContext = { id: "a.pdf", path: "a.pdf" };
|
||||
const b: PluginDocumentContext = { id: "b/B.PDF", path: "b/B.PDF" };
|
||||
const closeA = await session.mount("pdf", first, a);
|
||||
const closeB = await session.mount("pdf", second, b);
|
||||
assert.equal(starts, 1, "Two tabs share one instance.");
|
||||
assert.equal(first.textContent, "a.pdf");
|
||||
await closeA();
|
||||
assert.equal(first.textContent, "", "The host empties the element after the dispose.");
|
||||
await assert.rejects(session.mount("missing", element(), a), /This view is unavailable/);
|
||||
await assert.rejects(session.mount("pdf", element()), /This view is unavailable/, "Without a document, the ID names a view.");
|
||||
await closeB();
|
||||
await session.stop();
|
||||
assert.deepEqual(events, ["mount pdf a.pdf", "mount pdf b/B.PDF", "unmount a.pdf", "unmount b/B.PDF", "dispose"]);
|
||||
await assert.rejects(session.mount("pdf", element(), a), /This feature is off/);
|
||||
});
|
||||
|
||||
test("a feature without a document mount refuses a document", async () => {
|
||||
const instance: FeatureInstance = { mount: () => () => {}, dispose() {} };
|
||||
const session = new FeatureSession(featureEntry("pdf"), fakeContext(), async () => ({ start: () => instance }));
|
||||
await assert.rejects(session.mount("pdf", { replaceChildren() {} } as unknown as HTMLElement, { id: "a.pdf", path: "a.pdf" }), /This view is unavailable/);
|
||||
await session.stop();
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
// An in-memory workspace for the tests of the native Project Management feature. It records each read.
|
||||
import { defaultBoard } from "../../../../src/lib/features/pm/storage/board.ts";
|
||||
import { catalogPath } from "../../../../src/lib/features/pm/storage/catalog.ts";
|
||||
import { cardPath } from "../../../../src/lib/features/pm/storage/cards.ts";
|
||||
import { newTask } from "../../../../src/lib/features/pm/storage/notes.ts";
|
||||
import { cardsMarker, privateRulesPath } from "../../../../src/lib/features/pm/storage/persistence.ts";
|
||||
import type { TaskFields, Workspace } from "../../../../src/lib/features/pm/model/model.ts";
|
||||
|
||||
export interface MemoryWorkspace extends Workspace {
|
||||
files: Map<string, string>;
|
||||
/** Each path that a read asked for, in order. A `readMany` row counts as one read. */
|
||||
reads: string[];
|
||||
/** Each folder that a listing asked for. */
|
||||
lists: string[];
|
||||
/** The number of Markdown listings. */
|
||||
markdownLists: number;
|
||||
}
|
||||
|
||||
export function memoryWorkspace(initial: Record<string, string> = {}): MemoryWorkspace {
|
||||
const files = new Map(Object.entries(initial));
|
||||
const reads: string[] = [], lists: string[] = [];
|
||||
const parent = (path: string) => path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";
|
||||
const workspace: MemoryWorkspace = {
|
||||
files, reads, lists, markdownLists: 0,
|
||||
async list(path = "") {
|
||||
lists.push(path);
|
||||
const names = new Map<string, "file" | "folder">();
|
||||
for (const file of files.keys()) {
|
||||
if (path && !file.startsWith(path + "/")) continue;
|
||||
const rest = path ? file.slice(path.length + 1) : file;
|
||||
const name = rest.split("/")[0];
|
||||
names.set(name, rest.includes("/") ? "folder" : "file");
|
||||
}
|
||||
return [...names].map(([name, kind]) => ({ name, rel_path: path ? `${path}/${name}` : name, kind }));
|
||||
},
|
||||
async listMarkdown() {
|
||||
workspace.markdownLists++;
|
||||
return [...files.keys()].filter(path => /\.(md|markdown|mdown)$/i.test(path) && !path.startsWith(".")).sort();
|
||||
},
|
||||
async read(path) {
|
||||
reads.push(path);
|
||||
if (!files.has(path)) throw new Error(`Missing file: ${path}`);
|
||||
return files.get(path)!;
|
||||
},
|
||||
async readMany(paths) {
|
||||
reads.push(...paths);
|
||||
return paths.map(path => files.has(path) ? { path, source: files.get(path) } : { path, error: "Missing file" });
|
||||
},
|
||||
async readOptional(path) {
|
||||
reads.push(path);
|
||||
return files.get(path) ?? null;
|
||||
},
|
||||
async write(path, contents, expected) {
|
||||
if (files.get(path) !== expected) throw new Error(`The file changed: ${path}`);
|
||||
files.set(path, contents);
|
||||
},
|
||||
async create(path, contents) {
|
||||
if (files.has(path)) throw new Error(`The file exists: ${path}`);
|
||||
void parent(path);
|
||||
files.set(path, contents);
|
||||
},
|
||||
};
|
||||
return workspace;
|
||||
}
|
||||
|
||||
export const fields = (extra: Partial<TaskFields> = {}): TaskFields => ({ status: "todo", tags: [], sessions: [], archived: false, ...extra });
|
||||
|
||||
/** A workspace with hidden storage: one board `board` and the given cards. */
|
||||
export function hiddenWorkspace(cards: { id: string; title: string; fields?: Partial<TaskFields> }[] = [], extra: Record<string, string> = {}) {
|
||||
const board = defaultBoard("board");
|
||||
const files: Record<string, string> = {
|
||||
[privateRulesPath]: "*\n",
|
||||
[cardsMarker]: "*\n",
|
||||
[catalogPath]: JSON.stringify({ schema: 1, boards: [{ name: "Board", value: board }] }, null, 2) + "\n",
|
||||
...extra,
|
||||
};
|
||||
for (const card of cards) files[cardPath(card.id)] = newTask(card.title, fields({ title: card.title, placements: { board: { listId: "todo" } }, ...card.fields }), "Body", card.id).source;
|
||||
return memoryWorkspace(files);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { allTaskColumns, allTaskGroups } from "../../../../src/lib/features/pm/model/all-tasks.ts";
|
||||
import { defaultBoard, type BoardDocument } from "../../../../src/lib/features/pm/storage/board.ts";
|
||||
import { newTask, readTask } from "../../../../src/lib/features/pm/storage/notes.ts";
|
||||
import type { TaskFields } from "../../../../src/lib/features/pm/model/model.ts";
|
||||
const board = (id: string): BoardDocument => ({ id, path: `${id}.md`, name: id, source: "", value: defaultBoard(id) });
|
||||
const task = (title: string, placements: TaskFields["placements"]) => {
|
||||
const note = newTask(title, { status: "todo", archived: false, tags: [], sessions: [], placements });
|
||||
return readTask(`${title}.md`, note.source)!;
|
||||
};
|
||||
|
||||
test("All tasks merges list names, preserves custom lists, and includes every matching card once", () => {
|
||||
const a = board("A"), b = board("B"), c = board("C");
|
||||
a.value.lists.push({ id: "review", name: "Review", status: null, collapsed: true });
|
||||
b.value.lists[0].name = " To Do ";
|
||||
b.value.lists[0].id = "different-id";
|
||||
c.value.lists[0].maxCards = 2;
|
||||
const shared = task("Shared", { A: { listId: "todo" }, B: { listId: "different-id" } });
|
||||
const other = task("Other", { C: { listId: "todo" } });
|
||||
const review = task("Review", { A: { listId: "review" }, C: { listId: "todo" } });
|
||||
const unlisted = task("Unlisted", { A: { listId: "removed" }, B: { listId: null } });
|
||||
const orphan = task("Orphan", { deleted: { listId: "todo" } });
|
||||
const original = JSON.stringify({ boards: [a, b, c], tasks: [shared, other, review, unlisted, orphan] });
|
||||
const columns = allTaskColumns([a, b, c], [shared, other, review, unlisted, orphan]);
|
||||
assert.equal(columns.length, 5);
|
||||
assert.deepEqual(columns.find(c => c.list?.name === "To do")?.tasks, [shared, other, review, orphan]);
|
||||
assert.deepEqual(columns.find(c => c.list?.name === "Review")?.tasks, [review]);
|
||||
assert.deepEqual(columns.find(c => !c.list)?.tasks, [unlisted]);
|
||||
assert.equal(columns.find(c => c.list?.name === "Review")?.list?.collapsed, false);
|
||||
assert.equal(columns.find(c => c.list?.name === "To do")?.list?.maxCards, undefined);
|
||||
assert.equal(columns.find(c => c.list?.name === "To do")?.allowCreate, false);
|
||||
assert.equal(JSON.stringify({ boards: [a, b, c], tasks: [shared, other, review, unlisted, orphan] }), original);
|
||||
});
|
||||
|
||||
test("matching list IDs with different names remain separate and empty lists stay visible", () => {
|
||||
const a = board("A"), b = board("B");
|
||||
b.value.lists[0].name = "Backlog";
|
||||
const columns = allTaskColumns([a, b], []);
|
||||
assert.deepEqual(columns.map(c => c.list?.name), ["To do", "In progress", "Done", "Backlog"]);
|
||||
assert.equal(new Set(columns.map(c => c.list?.id)).size, 4);
|
||||
});
|
||||
|
||||
test("cards on archived boards remain visible and empty workspaces retain default lists", () => {
|
||||
const archived = { ...board("Archived"), archived: true };
|
||||
const card = task("Archived board card", { Archived: { listId: "todo" } });
|
||||
const columns = allTaskColumns([archived], [card]);
|
||||
assert.deepEqual(columns[0].tasks, [card]);
|
||||
assert.equal(columns.length, 3);
|
||||
assert.equal(columns[0].allowCreate, true);
|
||||
assert.equal(allTaskColumns([], []).length, 3);
|
||||
});
|
||||
|
||||
test("board dividers name shared memberships once and separate cards without active boards", () => {
|
||||
const a = board("A"), b = board("B");
|
||||
a.value.lists.push({ id: "review", name: "Review", status: null, collapsed: false });
|
||||
const shared = task("Shared", { A: { listId: "todo" }, B: { listId: "todo" } });
|
||||
const separate = task("Separate", { A: { listId: "review" }, B: { listId: "todo" } });
|
||||
const orphan = task("Orphan", { deleted: { listId: "todo" } });
|
||||
const columns = allTaskColumns([a, b], [shared, separate, orphan]);
|
||||
const todo = columns.find(column => column.list?.name === "To do")!;
|
||||
assert.deepEqual(allTaskGroups([a, b], todo).map(group => [group.name, group.tasks.map(task => task.title)]), [
|
||||
["A · B", ["Shared"]], ["B", ["Separate"]], ["No active board", ["Orphan"]],
|
||||
]);
|
||||
assert.deepEqual(allTaskGroups([a, b], columns.find(column => column.list?.name === "Review")!).map(group => group.name), ["A"]);
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
|
||||
import { newTask, readTask, editTask } from "../../../../src/lib/features/pm/storage/notes.ts";
|
||||
import { cardPath } from "../../../../src/lib/features/pm/storage/cards.ts";
|
||||
import { cardsMarker, privateRulesPath } from "../../../../src/lib/features/pm/storage/persistence.ts";
|
||||
import type { Workspace } from "../../../../src/lib/features/pm/model/model.ts";
|
||||
|
||||
function fixture(count = 3) {
|
||||
const files = new Map<string, string>([[cardsMarker, "*\n"], [privateRulesPath, "*\n"]]);
|
||||
const ids = Array.from({ length: count }, () => crypto.randomUUID());
|
||||
for (const [index, id] of ids.entries()) files.set(cardPath(id), newTask(`Card ${index}`, {
|
||||
title: `Card ${index}`, status: "todo", tags: [], sessions: [], archived: false,
|
||||
...(index === 0 ? { links: [{ taskId: ids[1], relation: "blocks" }, { taskId: ids[2], relation: "relates" }] as const } : {}),
|
||||
}, "Keep body", id).source);
|
||||
let batches = 0, singleReads = 0;
|
||||
const workspace: Workspace = {
|
||||
async listMarkdown() { return []; },
|
||||
async list() { return [...files.keys()].filter(path => path.endsWith(".md")).map(path => ({ name: path.split("/").at(-1)!, rel_path: path, kind: "file" })); },
|
||||
async read(path) { singleReads++; return files.get(path)!; },
|
||||
async readOptional(path) { return files.get(path) ?? null; },
|
||||
async readMany(paths) { assert.ok(paths.length <= 64); batches++; return paths.map(path => ({ path, source: files.get(path) })); },
|
||||
async write(path, source, expected) { assert.equal(files.get(path), expected); files.set(path, source); },
|
||||
async create(path, source) { assert.equal(files.has(path), false); files.set(path, source); },
|
||||
};
|
||||
return { files, ids, workspace, counts: () => ({ batches, singleReads }) };
|
||||
}
|
||||
|
||||
test("1000 cards use 16 bounded reads and share parsed cards between board views", async t => {
|
||||
const f = fixture(1000), store = new TaskStore(f.workspace);
|
||||
let started = performance.now();
|
||||
await store.reload();
|
||||
t.diagnostic(`Initial 1000-card parse: ${Math.round(performance.now() - started)} ms`);
|
||||
assert.deepEqual(f.counts(), { batches: 16, singleReads: 0 });
|
||||
const first = store.tasks[0];
|
||||
const next = new TaskStore(f.workspace);
|
||||
started = performance.now(); await next.reload();
|
||||
t.diagnostic(`Switch with unchanged sources: ${Math.round(performance.now() - started)} ms`);
|
||||
assert.equal(next.tasks[0], first);
|
||||
started = performance.now(); await next.save(first, { body: "Changed body" });
|
||||
t.diagnostic(`Save with full conflict scan: ${Math.round(performance.now() - started)} ms`);
|
||||
assert.deepEqual(f.counts(), { batches: 48, singleReads: 0 });
|
||||
const stale = next.tasks.find(task => task.id === first.id)!;
|
||||
f.files.set(stale.path, editTask(stale, { body: "External body" }));
|
||||
await assert.rejects(next.save(stale, { body: "Overwrite" }), /changed/);
|
||||
assert.equal(readTask(stale.path, f.files.get(stale.path)!)!.body, "External body");
|
||||
});
|
||||
|
||||
test("incoming unlink preserves unrelated links and rejects stale source cards", async () => {
|
||||
const f = fixture(), store = new TaskStore(f.workspace); await store.reload();
|
||||
const source = store.tasks.find(task => task.id === f.ids[0])!;
|
||||
await store.unlinkIncoming(f.ids[1], [source]);
|
||||
const saved = readTask(source.path, f.files.get(source.path)!)!;
|
||||
assert.deepEqual(saved.links, [{ taskId: f.ids[2], relation: "relates" }]);
|
||||
assert.equal(saved.body, "Keep body");
|
||||
await store.unlinkIncoming(f.ids[1], [source]); // A retry is harmless.
|
||||
f.files.set(saved.path, editTask(saved, { body: "External change" }));
|
||||
await assert.rejects(store.unlinkIncoming(f.ids[2], [saved]), /linked card changed/);
|
||||
assert.deepEqual(readTask(saved.path, f.files.get(saved.path)!)!.links, saved.links);
|
||||
});
|
||||
@@ -0,0 +1,237 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { BoardStore, newBoardSource, parseBoard } from "../../../../src/lib/features/pm/storage/board.ts";
|
||||
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
|
||||
import { newTask, readTask } from "../../../../src/lib/features/pm/storage/notes.ts";
|
||||
import type { Workspace, TaskFields } from "../../../../src/lib/features/pm/model/model.ts";
|
||||
|
||||
const fields: TaskFields = {
|
||||
status: "todo",
|
||||
tags: [],
|
||||
sessions: [],
|
||||
archived: false,
|
||||
};
|
||||
function fixture() {
|
||||
const source = newBoardSource();
|
||||
const files = new Map<string, string>([["Board.md", source]]);
|
||||
const reference = { id: parseBoard(source).id, path: "Board.md" };
|
||||
const workspace: Workspace = {
|
||||
async readOptional(path) {
|
||||
return files.get(path) ?? null;
|
||||
},
|
||||
async read(path) {
|
||||
if (!files.has(path)) throw Error("Missing");
|
||||
return files.get(path)!;
|
||||
},
|
||||
async create(path, text) {
|
||||
if (files.has(path)) throw Error("Exists");
|
||||
files.set(path, text);
|
||||
},
|
||||
async write(path, text, expected) {
|
||||
if (files.get(path) !== expected) throw Error("Conflict");
|
||||
files.set(path, text);
|
||||
},
|
||||
async list(parent = "") {
|
||||
return [...files.keys()]
|
||||
.filter((path) => !path.startsWith("."))
|
||||
.map((path) => ({ name: path, rel_path: path, kind: "file" }));
|
||||
},
|
||||
};
|
||||
return { files, workspace, reference };
|
||||
}
|
||||
test("list names, completion mapping, order, and collapse survive reload", async () => {
|
||||
const { workspace, reference } = fixture();
|
||||
const board = new BoardStore(workspace, reference);
|
||||
await board.reload();
|
||||
await board.add("Review", null);
|
||||
const review = board.value.lists.at(-1)!;
|
||||
await board.edit(review.id, "Approved", "done");
|
||||
await board.move(review.id, 0);
|
||||
await board.collapse(review.id);
|
||||
const reopened = new BoardStore(workspace, reference);
|
||||
await reopened.reload();
|
||||
assert.deepEqual(reopened.value.lists[0], {
|
||||
id: review.id,
|
||||
name: "Approved",
|
||||
status: "done",
|
||||
collapsed: true,
|
||||
});
|
||||
await assert.rejects(reopened.add("approved", null), /already exists/);
|
||||
});
|
||||
|
||||
test("list maximum survives edits and reload, rejects invalid values, and can be removed", async () => {
|
||||
const { workspace, reference } = fixture();
|
||||
const board = new BoardStore(workspace, reference);
|
||||
await board.reload();
|
||||
await board.setLimit("todo", 2);
|
||||
await board.edit("todo", "Next", "todo");
|
||||
await board.collapse("todo");
|
||||
await board.reload();
|
||||
assert.equal(board.value.lists[0].maxCards, 2);
|
||||
for (const invalid of [0, -1, 1.5, Infinity, NaN, Number.MAX_SAFE_INTEGER + 1])
|
||||
await assert.rejects(board.setLimit("todo", invalid), /whole number/);
|
||||
const source = newBoardSource().replace("collapsed: false", "collapsed: false\n maxCards: -2");
|
||||
assert.throws(() => parseBoard(source), /invalid list/);
|
||||
await board.setLimit("todo");
|
||||
await board.reload();
|
||||
assert.equal(board.value.lists[0].maxCards, undefined);
|
||||
});
|
||||
test("deleting a populated list preserves notes and sends its cards to Unlisted", async () => {
|
||||
const { workspace, files, reference } = fixture();
|
||||
const note = newTask(
|
||||
"Keep me",
|
||||
{ ...fields, placements: { [reference.id]: { listId: "todo" } } },
|
||||
"Keep the body",
|
||||
);
|
||||
files.set("Keep me.md", note.source);
|
||||
const store = new TaskStore(workspace, reference);
|
||||
await store.reload();
|
||||
await store.changeBoard(() => store.board.remove("todo"));
|
||||
assert.equal(store.board.listFor(store.tasks[0]), undefined);
|
||||
assert.equal(files.get("Keep me.md"), note.source);
|
||||
await store.board.add("Replacement", null);
|
||||
assert.equal(store.board.listFor(store.tasks[0]), undefined);
|
||||
assert.equal(
|
||||
store.board.listFor({ status: "todo", listId: undefined }),
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
test("moving a card stores its list and completion in one guarded note write", async () => {
|
||||
const { workspace, files, reference } = fixture();
|
||||
const note = newTask("Task", fields);
|
||||
files.set("Task.md", note.source);
|
||||
const store = new TaskStore(workspace, reference);
|
||||
await store.reload();
|
||||
await store.moveTask(store.tasks[0], "done");
|
||||
const saved = readTask("Task.md", files.get("Task.md")!)!;
|
||||
assert.equal(saved.placements?.[reference.id].listId, "done");
|
||||
assert.equal(saved.status, "done");
|
||||
assert.equal(saved.id, store.tasks[0].id);
|
||||
await store.moveTask(store.tasks[0], null);
|
||||
assert.equal(store.board.listFor(store.tasks[0]), undefined);
|
||||
assert.equal(store.tasks[0].status, "todo");
|
||||
});
|
||||
test("stale list edits do not overwrite another board revision", async () => {
|
||||
const { workspace, files, reference } = fixture();
|
||||
const first = new BoardStore(workspace, reference),
|
||||
second = new BoardStore(workspace, reference);
|
||||
await first.reload();
|
||||
await second.reload();
|
||||
await first.add("Review", null);
|
||||
const saved = files.get("Board.md");
|
||||
await assert.rejects(second.add("Other", null), /changed/);
|
||||
assert.equal(files.get("Board.md"), saved);
|
||||
});
|
||||
test("malformed or future board files stay untouched", async () => {
|
||||
const { workspace, files, reference } = fixture();
|
||||
const text = newBoardSource().replace("schema: 1", "schema: 2");
|
||||
files.set("Board.md", text);
|
||||
const board = new BoardStore(workspace, reference);
|
||||
await assert.rejects(board.reload(), /unsupported/);
|
||||
await assert.rejects(board.add("Oops", null), /Open an available board/);
|
||||
assert.equal(files.get("Board.md"), text);
|
||||
});
|
||||
test("deleting all lists remains empty after reload and allows a new list", async () => {
|
||||
const { workspace, reference } = fixture();
|
||||
const board = new BoardStore(workspace, reference);
|
||||
await board.reload();
|
||||
for (const id of ["todo", "doing", "done"]) await board.remove(id);
|
||||
const next = new BoardStore(workspace, reference);
|
||||
await next.reload();
|
||||
assert.equal(next.value.lists.length, 0);
|
||||
await next.add("First", null);
|
||||
assert.equal(next.value.lists[0].name, "First");
|
||||
});
|
||||
test("All tasks cannot save board lists", async () => {
|
||||
const { workspace, reference } = fixture();
|
||||
const board = new BoardStore(workspace);
|
||||
await board.reload();
|
||||
await assert.rejects(board.add("Review", null), /Open an available board/);
|
||||
assert.equal(board.value.lists.length, 3);
|
||||
});
|
||||
|
||||
test("archiving a list scopes by board placement and preserves status, bodies, and other memberships", async () => {
|
||||
const { workspace, files, reference } = fixture();
|
||||
const sourceBoard = files.get(reference.path);
|
||||
for (const [title, placements] of [
|
||||
["Target", { [reference.id]: { listId: "todo" }, other: { listId: "doing" } }],
|
||||
["Other list", { [reference.id]: { listId: "doing" } }],
|
||||
["Other board", { other: { listId: "todo" } }],
|
||||
] as const) {
|
||||
const task = newTask(title, { ...fields, placements }, "Keep body");
|
||||
files.set(task.path, task.source);
|
||||
}
|
||||
const store = new TaskStore(workspace, reference);
|
||||
await store.reload();
|
||||
const original = store.tasks.find(task => task.title === "Target")!;
|
||||
await store.archiveList("todo");
|
||||
await store.reload();
|
||||
const archived = store.tasks.find(task => task.title === "Target")!;
|
||||
assert.equal(archived.archived, true);
|
||||
assert.equal(archived.status, original.status);
|
||||
assert.deepEqual(archived.placements, original.placements);
|
||||
assert.equal(archived.body, original.body);
|
||||
assert.equal(store.tasks.filter(task => task.archived).length, 1);
|
||||
assert.equal(files.get(reference.path), sourceBoard);
|
||||
await store.archiveList("todo");
|
||||
await assert.rejects(store.archiveList("missing"), /unavailable/);
|
||||
});
|
||||
|
||||
test("board image appearance survives legacy saves and hidden catalog saves independently", async () => {
|
||||
const { workspace, reference } = fixture();
|
||||
const board = new BoardStore(workspace, reference); await board.reload();
|
||||
const appearance = { overlay: -0.4, position: "bottom right", size: "contain" } as const;
|
||||
await board.update(value => { value.backgroundImage = "11111111-1111-4111-8111-111111111111"; value.backgroundAppearance = appearance; });
|
||||
await board.reload(); assert.equal(board.value.backgroundImage, "11111111-1111-4111-8111-111111111111"); assert.deepEqual(board.value.backgroundAppearance, appearance);
|
||||
const store = new TaskStore(workspace); await store.reload(); const hidden = await store.createBoard("Hidden");
|
||||
const managed = new BoardStore(workspace, hidden); await managed.reload();
|
||||
await managed.update(value => { value.backgroundImage = "22222222-2222-4222-8222-222222222222"; value.backgroundAppearance = { overlay: 0.7, position: "top", size: "auto" }; });
|
||||
await managed.reload(); assert.equal(managed.value.backgroundImage, "22222222-2222-4222-8222-222222222222"); assert.equal(managed.value.backgroundAppearance!.overlay, 0.7);
|
||||
await board.reload(); assert.deepEqual(board.value.backgroundAppearance, appearance);
|
||||
});
|
||||
|
||||
|
||||
test("leaving a Done rule reopens a card and neutral moves preserve manual completion", async () => {
|
||||
const { workspace, files, reference } = fixture();
|
||||
const note = newTask("Task", { ...fields, status: "done", placements: { [reference.id]: { listId: "done" } } });
|
||||
files.set("Task.md", note.source);
|
||||
const store = new TaskStore(workspace, reference); await store.reload();
|
||||
await store.changeBoard(() => store.board.add("Review", null));
|
||||
const review = store.board.value.lists.at(-1)!.id;
|
||||
await store.moveTask(store.tasks[0], review);
|
||||
await store.reload();
|
||||
assert.equal(store.tasks[0].status, "todo");
|
||||
assert.equal(store.tasks[0].placements![reference.id].listId, review);
|
||||
await store.save(store.tasks[0], { status: "done" });
|
||||
await store.moveTask(store.tasks[0], null);
|
||||
await store.reload();
|
||||
assert.equal(store.tasks[0].status, "done");
|
||||
await store.changeBoard(() => store.board.edit(review, "Review", "doing"));
|
||||
await store.moveTask(store.tasks[0], review);
|
||||
await store.reload(); assert.equal(store.tasks[0].status, "doing");
|
||||
await store.moveTask(store.tasks[0], "todo");
|
||||
await store.changeBoard(() => store.board.edit(review, "Review", null));
|
||||
await store.save(store.tasks[0], { listId: review }, true);
|
||||
await store.reload(); assert.equal(store.tasks[0].status, "todo");
|
||||
assert.equal(store.board.value.lists.find(list => list.id === review)!.status, null);
|
||||
});
|
||||
|
||||
|
||||
test("overview creation writes one assigned card and rejects stale destinations without extra cards", async () => {
|
||||
const { workspace, files, reference } = fixture();
|
||||
const store = new TaskStore(workspace);
|
||||
await store.reload();
|
||||
await store.create("Assigned card", { ...fields, listId: "doing" }, "Card body", reference.id);
|
||||
const task = store.tasks.find(task => task.title === "Assigned card")!;
|
||||
assert.equal(task.placements?.[reference.id].listId, "doing");
|
||||
assert.equal(Object.keys(task.placements ?? {}).length, 1);
|
||||
assert.equal(task.body.trim(), "Card body");
|
||||
const snapshot = new Map(files);
|
||||
await assert.rejects(store.create("Missing board", fields, "", "missing"), /active board/);
|
||||
await assert.rejects(store.create("Missing list", { ...fields, listId: "missing" }, "", reference.id), /list no longer exists/);
|
||||
assert.deepEqual(files, snapshot);
|
||||
files.delete("Board.md");
|
||||
const afterDelete = new Map(files);
|
||||
await assert.rejects(store.create("Deleted board", fields, "", reference.id), /active board/);
|
||||
assert.deepEqual(files, afterDelete);
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { newTask, readTask, editTask } from "../../../../src/lib/features/pm/storage/notes.ts";
|
||||
import { priorities, type TaskFields } from "../../../../src/lib/features/pm/model/model.ts";
|
||||
import { renderMarkdown } from "../../../../src/lib/features/pm/model/markdown.ts";
|
||||
|
||||
const fields: TaskFields = {
|
||||
status: "todo",
|
||||
tags: [],
|
||||
labels: ["high-priority"],
|
||||
sessions: [],
|
||||
archived: false,
|
||||
};
|
||||
test("priority round-trips independently of labels and survives unrelated changes", () => {
|
||||
for (const priority of [...priorities, null]) {
|
||||
const note = newTask("Priority card", { ...fields, priority });
|
||||
const task = readTask(note.path, note.source)!;
|
||||
assert.equal(task.priority, priority);
|
||||
const changed = readTask(
|
||||
note.path,
|
||||
editTask(task, { status: "doing", listId: "review", body: "Edited" }),
|
||||
)!;
|
||||
assert.equal(changed.priority, priority);
|
||||
assert.deepEqual(changed.labels, fields.labels);
|
||||
}
|
||||
});
|
||||
test("unrelated edits preserve absent priority and explicit removal writes null", () => {
|
||||
const note = newTask("Legacy", fields);
|
||||
const task = readTask(note.path, note.source)!;
|
||||
assert.doesNotMatch(editTask(task, { body: "Edit" }), /priority:/);
|
||||
const cleared = editTask(task, { priority: null });
|
||||
assert.match(cleared, /priority: null/);
|
||||
assert.deepEqual(readTask(note.path, cleared)!.labels, fields.labels);
|
||||
assert.throws(
|
||||
() => newTask("Invalid", { ...fields, priority: "urgent" as never }),
|
||||
/priority/,
|
||||
);
|
||||
});
|
||||
test("Markdown preview escapes HTML and rejects active links and external images", () => {
|
||||
const result = renderMarkdown(
|
||||
"# Heading\n\n**Bold**\n\n<script>alert(1)</script>\n\n[x](javascript:alert(1))\n\n\n\n\n\n[safe](https://example.com)",
|
||||
);
|
||||
assert.match(result, /<h1>Heading<\/h1>/);
|
||||
assert.match(result, /<strong>Bold<\/strong>/);
|
||||
assert.doesNotMatch(result, /<script|src=|href="javascript:/);
|
||||
assert.match(result, /data-pm-image="12345678-1234-1234-1234-123456789abc"/);
|
||||
assert.match(result, /rel="noopener noreferrer"/);
|
||||
});
|
||||
|
||||
test("covers, subtasks, and card links round-trip without changing other fields", () => {
|
||||
const coverImage = "12345678-1234-1234-1234-123456789abc";
|
||||
const subtasks = [{ id: "subtask", title: "Check the change", done: true }];
|
||||
const links = [{ taskId: "dependency", relation: "blocked-by" as const }];
|
||||
const note = newTask("Relationships", { ...fields, coverImage, subtasks, links });
|
||||
const task = readTask(note.path, note.source)!;
|
||||
assert.deepEqual(task.subtasks, subtasks); assert.deepEqual(task.links, links); assert.equal(task.coverImage, coverImage);
|
||||
const edited = readTask(note.path, editTask(task, { body: "Revised", priority: "lowest" }))!;
|
||||
assert.deepEqual(edited.subtasks, subtasks); assert.deepEqual(edited.links, links); assert.equal(edited.coverImage, coverImage);
|
||||
assert.throws(() => editTask(task, { coverImage: "../outside.png" }), /image/);
|
||||
assert.throws(() => editTask(task, { subtasks: [...subtasks, ...subtasks] }), /unique ID/);
|
||||
assert.throws(() => editTask(task, { links: [...links, ...links] }), /once/);
|
||||
});
|
||||
|
||||
test("attachments round-trip independently of description edits and reject duplicate or invalid IDs", () => {
|
||||
const attachments = [{ id: "12345678-1234-1234-1234-123456789abc", name: "Screenshot.png" }];
|
||||
const note = newTask("Attached image", { ...fields, attachments }, "Description");
|
||||
const task = readTask(note.path, note.source)!;
|
||||
assert.deepEqual(task.attachments, attachments);
|
||||
const changed = readTask(note.path, editTask(task, { body: "", status: "doing" }))!;
|
||||
assert.deepEqual(changed.attachments, attachments);
|
||||
assert.equal(changed.body, "");
|
||||
assert.deepEqual(readTask(note.path, editTask(changed, { attachments: [] }))!.attachments, []);
|
||||
assert.throws(() => editTask(task, { attachments: [...attachments, ...attachments] }), /unique image ID/);
|
||||
assert.throws(() => editTask(task, { attachments: [{ id: "../outside", name: "Image" }] }), /unique image ID/);
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { newTask, readTask, editTask } from "../../../../src/lib/features/pm/storage/notes.ts";
|
||||
import { validateFields, type TaskFields } from "../../../../src/lib/features/pm/model/model.ts";
|
||||
|
||||
const fields: TaskFields = {
|
||||
status: "todo",
|
||||
tags: [],
|
||||
sessions: [],
|
||||
archived: false,
|
||||
};
|
||||
|
||||
test("optional card fields survive moves and can be removed without changing other note data", () => {
|
||||
const note = newTask(
|
||||
"Customer work",
|
||||
{
|
||||
...fields,
|
||||
color: "purple",
|
||||
assignees: ["Alex", "Northwind"],
|
||||
customFields: [
|
||||
{ name: "Customer ID", value: "0012" },
|
||||
{ name: "Contact", value: "[email protected]" },
|
||||
],
|
||||
},
|
||||
"Keep **these details**.\n",
|
||||
);
|
||||
const source = note.source.replace(
|
||||
" schema: 1",
|
||||
" extra: keep-me # future property\n schema: 1",
|
||||
);
|
||||
const task = readTask(note.path, source)!;
|
||||
assert.equal(task.color, "purple");
|
||||
assert.deepEqual(task.assignees, ["Alex", "Northwind"]);
|
||||
assert.equal(task.customFields?.[0].value, "0012");
|
||||
const moved = readTask(
|
||||
note.path,
|
||||
editTask(task, { status: "done", listId: "done" }),
|
||||
)!;
|
||||
assert.deepEqual(moved.customFields, task.customFields);
|
||||
assert.equal(moved.color, "purple");
|
||||
const cleared = editTask(moved, {
|
||||
color: undefined,
|
||||
assignees: [],
|
||||
customFields: [],
|
||||
});
|
||||
assert.ok(cleared.includes("extra: keep-me # future property"));
|
||||
assert.equal(readTask(note.path, cleared)!.body, task.body);
|
||||
assert.equal(readTask(note.path, cleared)!.color, undefined);
|
||||
assert.deepEqual(readTask(note.path, cleared)!.customFields, []);
|
||||
});
|
||||
|
||||
test("invalid optional fields and duplicate names cannot enter saved notes", () => {
|
||||
for (const patch of [
|
||||
{ color: "url(bad)" },
|
||||
{ assignees: "Alex" },
|
||||
{ assignees: [1] },
|
||||
{ customFields: [null] },
|
||||
{ customFields: [{ name: "", value: "x" }] },
|
||||
{
|
||||
customFields: [
|
||||
{ name: "ID", value: "1" },
|
||||
{ name: " id ", value: "2" },
|
||||
],
|
||||
},
|
||||
])
|
||||
assert.throws(() => validateFields({ ...fields, ...patch } as TaskFields));
|
||||
const old = newTask("Basic", fields);
|
||||
assert.equal(readTask(old.path, old.source)!.color, undefined);
|
||||
});
|
||||
@@ -0,0 +1,296 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { newBoardSource, parseBoard } from "../../../../src/lib/features/pm/storage/board.ts";
|
||||
import { adoptNote, editTask, newTask, readTask } from "../../../../src/lib/features/pm/storage/notes.ts";
|
||||
import { cardOrder, orderBetween } from "../../../../src/lib/features/pm/storage/order.ts";
|
||||
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
|
||||
import { isHiddenCard } from "../../../../src/lib/features/pm/storage/persistence.ts";
|
||||
import type { TaskFields, Workspace } from "../../../../src/lib/features/pm/model/model.ts";
|
||||
|
||||
const fields: TaskFields = {
|
||||
status: "todo",
|
||||
tags: [],
|
||||
sessions: [],
|
||||
archived: false,
|
||||
};
|
||||
function fixture() {
|
||||
const board = newBoardSource();
|
||||
const files = new Map([["Board.md", board]]);
|
||||
const reads: string[] = [],
|
||||
lists: string[] = [],
|
||||
writes: string[] = [];
|
||||
const workspace: Workspace = {
|
||||
async readOptional(path) {
|
||||
return files.get(path) ?? null;
|
||||
},
|
||||
async list(parent = "") {
|
||||
lists.push(parent);
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
const prefix = parent ? parent + "/" : "";
|
||||
if (!path.startsWith(prefix)) continue;
|
||||
const parts = path.slice(prefix.length).split("/");
|
||||
entries.set(parts[0], {
|
||||
name: parts[0],
|
||||
rel_path: prefix + parts[0],
|
||||
kind: parts.length > 1 ? "folder" : "file",
|
||||
});
|
||||
}
|
||||
return [...entries.values()];
|
||||
},
|
||||
async read(path) {
|
||||
reads.push(path);
|
||||
if (!files.has(path)) throw new Error("Missing note");
|
||||
return files.get(path)!;
|
||||
},
|
||||
async write(path, source, expected) {
|
||||
assert.equal(files.get(path), expected);
|
||||
writes.push(path);
|
||||
files.set(path, source);
|
||||
},
|
||||
async create(path, source) {
|
||||
if (files.has(path)) throw new Error("Exists");
|
||||
files.set(path, source);
|
||||
},
|
||||
};
|
||||
const reference = { id: parseBoard(board).id, path: "Board.md" };
|
||||
return {
|
||||
files,
|
||||
reads,
|
||||
lists,
|
||||
writes,
|
||||
workspace,
|
||||
reference,
|
||||
store: new TaskStore(workspace, reference),
|
||||
};
|
||||
}
|
||||
|
||||
test("card creation reads one board and does not scan unrelated notes after loading", async () => {
|
||||
const { store, files, lists, reads } = fixture();
|
||||
for (let index = 0; index < 300; index++)
|
||||
files.set(`Archive/Note ${index}.md`, "Plain note");
|
||||
await store.reload();
|
||||
lists.length = reads.length = 0;
|
||||
await store.create("New card", fields, "Details");
|
||||
assert.deepEqual(lists, []);
|
||||
assert.deepEqual(reads, ["Board.md"]);
|
||||
assert.equal(store.scopedTasks[0].title, "New card");
|
||||
assert.equal(store.scopedTasks[0].body, "Details");
|
||||
await store.create("New card", fields, "Second");
|
||||
assert.equal(store.scopedTasks.length, 2);
|
||||
assert.equal(store.scopedTasks[0].body, "Details");
|
||||
});
|
||||
|
||||
test("creation checks the current list before writing a card", async () => {
|
||||
const { store, files } = fixture();
|
||||
await store.reload();
|
||||
await store.board.remove("todo");
|
||||
const snapshot = new Map(files);
|
||||
await assert.rejects(
|
||||
store.create("Missing list", { ...fields, listId: "todo" }, ""),
|
||||
/list no longer exists/,
|
||||
);
|
||||
assert.deepEqual(files, snapshot);
|
||||
assert.equal(store.tasks.length, 0);
|
||||
});
|
||||
|
||||
test("a background scan cannot replace a newly created card with an older snapshot", async () => {
|
||||
const { store, workspace } = fixture();
|
||||
await store.reload();
|
||||
const list = workspace.list;
|
||||
let release!: () => void;
|
||||
const gate = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
workspace.list = async (path) => {
|
||||
const snapshot = await list(path);
|
||||
await gate;
|
||||
return snapshot;
|
||||
};
|
||||
const pending = store.reload();
|
||||
await store.create("Keep new card", fields, "");
|
||||
release();
|
||||
await pending;
|
||||
assert.deepEqual(
|
||||
store.scopedTasks.map((task) => task.title),
|
||||
["Keep new card"],
|
||||
);
|
||||
});
|
||||
|
||||
test("title edits preserve the filename, identity, metadata, and body", async () => {
|
||||
const { store, files } = fixture();
|
||||
await store.create("Original", fields, "Keep **Markdown**.\n");
|
||||
const original = store.tasks[0];
|
||||
files.set(
|
||||
original.path,
|
||||
original.source.replace("---\n", "---\nowner: Ada # keep\n"),
|
||||
);
|
||||
await store.reload();
|
||||
await store.save(store.tasks[0], { title: "Edited: title / shared" });
|
||||
const updated = store.tasks[0];
|
||||
assert.equal(updated.title, "Edited: title / shared");
|
||||
assert.equal(updated.id, original.id);
|
||||
assert.equal(updated.path, original.path);
|
||||
assert.equal(updated.body, original.body);
|
||||
assert.match(updated.source, /owner: Ada # keep/);
|
||||
assert.equal([...files.keys()].filter(isHiddenCard).length, 1);
|
||||
await store.reload();
|
||||
assert.equal(store.tasks[0].title, updated.title);
|
||||
await assert.rejects(store.save(original, { title: "Stale" }), /changed/);
|
||||
await assert.rejects(
|
||||
store.save(store.tasks[0], { title: " " }),
|
||||
/card title/,
|
||||
);
|
||||
assert.equal(readTask(original.path, original.source)!.title, "Original");
|
||||
});
|
||||
|
||||
test("legacy notes with long filenames remain editable before a card title is set", () => {
|
||||
const path = "Long existing note ".repeat(8).trim() + ".md";
|
||||
const source = adoptNote(path, "Existing description");
|
||||
const task = readTask(path, source)!;
|
||||
assert.equal(task.title, path.slice(0, -3));
|
||||
const edited = readTask(path, editTask(task, { status: "doing" }))!;
|
||||
assert.equal(edited.title, task.title);
|
||||
assert.equal(edited.status, "doing");
|
||||
});
|
||||
|
||||
test("cards retain insertion order and can move before, between, and after other cards", async () => {
|
||||
const { store, workspace, reference, writes } = fixture();
|
||||
for (const name of ["Zulu", "Alpha", "Middle"])
|
||||
await store.create(name, fields, "");
|
||||
const names = () => store.cardsInList("todo").map((task) => task.title);
|
||||
const task = (title: string) =>
|
||||
store.tasks.find((task) => task.title === title)!;
|
||||
assert.deepEqual(names(), ["Zulu", "Alpha", "Middle"]);
|
||||
await store.save(task("Middle"), { status: "done" });
|
||||
const middle = task("Middle");
|
||||
writes.length = 0;
|
||||
await store.moveTask(middle, "todo", task("Zulu").id);
|
||||
assert.deepEqual(writes, [middle.path]);
|
||||
assert.equal(task("Middle").status, "done");
|
||||
assert.deepEqual(names(), ["Middle", "Zulu", "Alpha"]);
|
||||
await store.moveTask(task("Alpha"), "todo", task("Zulu").id);
|
||||
assert.deepEqual(names(), ["Middle", "Alpha", "Zulu"]);
|
||||
await store.moveTask(task("Middle"), "todo", null);
|
||||
assert.deepEqual(names(), ["Alpha", "Zulu", "Middle"]);
|
||||
await store.save(task("Zulu"), {
|
||||
title: "A renamed card",
|
||||
listId: "todo",
|
||||
tags: ["release"],
|
||||
});
|
||||
const reopened = new TaskStore(workspace, reference);
|
||||
await reopened.reload();
|
||||
assert.deepEqual(
|
||||
reopened.cardsInList("todo").map((task) => task.title),
|
||||
["Alpha", "A renamed card", "Middle"],
|
||||
);
|
||||
});
|
||||
|
||||
test("card order stays independent in each board and All tasks", async () => {
|
||||
const { store, files, workspace, reference } = fixture();
|
||||
const secondSource = newBoardSource();
|
||||
files.set("Second.md", secondSource);
|
||||
const second = new TaskStore(workspace, {
|
||||
id: parseBoard(secondSource).id,
|
||||
path: "Second.md",
|
||||
});
|
||||
for (const name of ["Alpha", "Beta", "Gamma"]) {
|
||||
await store.create(
|
||||
name,
|
||||
{ ...fields, due: { date: "2026-10-08" } },
|
||||
"Shared details",
|
||||
);
|
||||
await second.adopt(store.tasks.find((task) => task.title === name)!.path);
|
||||
}
|
||||
await store.reload();
|
||||
const gamma = store.tasks.find((task) => task.title === "Gamma")!;
|
||||
const secondPlacement = gamma.placements![second.board.reference!.id];
|
||||
await store.moveTask(
|
||||
gamma,
|
||||
"todo",
|
||||
store.tasks.find((task) => task.title === "Alpha")!.id,
|
||||
);
|
||||
await second.reload();
|
||||
assert.deepEqual(
|
||||
second.cardsInList("todo").map((task) => task.title),
|
||||
["Alpha", "Beta", "Gamma"],
|
||||
);
|
||||
assert.deepEqual(
|
||||
second.tasks.find((task) => task.id === gamma.id)!.placements![
|
||||
second.board.reference!.id
|
||||
],
|
||||
secondPlacement,
|
||||
);
|
||||
const all = new TaskStore(workspace);
|
||||
await all.reload();
|
||||
await all.moveTask(all.tasks[1], "todo", all.tasks[0].id);
|
||||
assert.deepEqual(
|
||||
all.cardsInList("todo").map((task) => task.title),
|
||||
["Beta", "Alpha", "Gamma"],
|
||||
);
|
||||
await store.reload();
|
||||
assert.deepEqual(
|
||||
store.cardsInList("todo").map((task) => task.title),
|
||||
["Gamma", "Alpha", "Beta"],
|
||||
);
|
||||
await store.moveTask(store.cardsInList("todo")[0], "done", null);
|
||||
const moved = store.cardsInList("done")[0];
|
||||
assert.equal(moved.status, "done");
|
||||
assert.deepEqual(moved.due, { date: "2026-10-08" });
|
||||
assert.equal(moved.body, "Shared details");
|
||||
assert.equal(moved.placements![reference.id].listId, "done");
|
||||
});
|
||||
|
||||
test("failed or stale order writes keep card data intact", async () => {
|
||||
const { store, workspace, files } = fixture();
|
||||
await store.create("Alpha", fields, "");
|
||||
await store.create("Beta", fields, "");
|
||||
const [alpha, beta] = store.cardsInList("todo");
|
||||
const snapshot = new Map(files);
|
||||
workspace.write = async () => {
|
||||
throw new Error("Disk failure");
|
||||
};
|
||||
await assert.rejects(store.moveTask(beta, "todo", alpha.id), /Disk failure/);
|
||||
assert.deepEqual(files, snapshot);
|
||||
assert.deepEqual(
|
||||
store.cardsInList("todo").map((task) => task.title),
|
||||
["Alpha", "Beta"],
|
||||
);
|
||||
await assert.rejects(
|
||||
store.moveTask(beta, "todo", "missing"),
|
||||
/target card moved/,
|
||||
);
|
||||
files.set(beta.path, editTask(beta, { body: "External change" }));
|
||||
await assert.rejects(store.moveTask(beta, "todo", alpha.id), /changed/);
|
||||
});
|
||||
|
||||
test("ordering handles repeated narrow gaps, legacy notes, and matching saved ranks", () => {
|
||||
let upper = "j";
|
||||
for (let index = 0; index < 1200; index++) {
|
||||
const rank = orderBetween("i", upper);
|
||||
assert.ok("i" < rank && rank < upper);
|
||||
assert.match(rank, /^[0-9a-z]*[1-9a-z]$/);
|
||||
upper = rank;
|
||||
}
|
||||
const alphaNote = newTask(
|
||||
"Alpha",
|
||||
fields,
|
||||
"",
|
||||
"00000000-0000-4000-8000-000000000001",
|
||||
);
|
||||
const betaNote = newTask(
|
||||
"Beta",
|
||||
fields,
|
||||
"",
|
||||
"00000000-0000-4000-8000-000000000002",
|
||||
);
|
||||
const alpha = readTask(alphaNote.path, alphaNote.source)!;
|
||||
const beta = readTask(betaNote.path, betaNote.source)!;
|
||||
assert.ok(cardOrder(alpha) < cardOrder(beta));
|
||||
assert.equal(cardOrder(alpha), cardOrder({ ...alpha, title: "Zulu" }));
|
||||
alpha.order = beta.order = "i";
|
||||
const between = orderBetween(cardOrder(alpha), cardOrder(beta));
|
||||
const inserted = cardOrder({ ...alpha, id: "new", order: between });
|
||||
assert.ok(cardOrder(alpha) < inserted && inserted < cardOrder(beta));
|
||||
assert.throws(() => editTask(alpha, { order: "invalid!" }), /order/);
|
||||
});
|
||||
@@ -0,0 +1,198 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { readTask, editTask, newTask, adoptNote } from "../../../../src/lib/features/pm/storage/notes.ts";
|
||||
import {
|
||||
addDays,
|
||||
dayDistance,
|
||||
validDate,
|
||||
type Workspace,
|
||||
type TaskFields,
|
||||
} from "../../../../src/lib/features/pm/model/model.ts";
|
||||
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
|
||||
import { isHiddenCard } from "../../../../src/lib/features/pm/storage/persistence.ts";
|
||||
|
||||
const fields: TaskFields = {
|
||||
status: "todo",
|
||||
tags: [],
|
||||
sessions: [],
|
||||
archived: false,
|
||||
};
|
||||
function memory(initial: Record<string, string> = {}) {
|
||||
const files = new Map(Object.entries(initial));
|
||||
const workspace: Workspace = {
|
||||
async readOptional(path) {
|
||||
return files.get(path) ?? null;
|
||||
},
|
||||
async list(parent = "") {
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
const prefix = parent ? `${parent}/` : "";
|
||||
if (!path.startsWith(prefix)) continue;
|
||||
const parts = path.slice(prefix.length).split("/");
|
||||
entries.set(parts[0], {
|
||||
name: parts[0],
|
||||
rel_path: `${prefix}${parts[0]}`,
|
||||
kind: parts.length > 1 ? "folder" : "file",
|
||||
});
|
||||
}
|
||||
return [...entries.values()];
|
||||
},
|
||||
async read(path) {
|
||||
const text = files.get(path);
|
||||
if (text === undefined) throw Error("Missing file");
|
||||
return text;
|
||||
},
|
||||
async write(path, text, expected) {
|
||||
assert.equal(files.get(path), expected, "Changed on disk");
|
||||
files.set(path, text);
|
||||
},
|
||||
async create(path, text) {
|
||||
if (files.has(path)) throw Error("Exists");
|
||||
files.set(path, text);
|
||||
},
|
||||
};
|
||||
return { workspace, files };
|
||||
}
|
||||
|
||||
test("tasks round trip with a stable ID, description, deadline, plan, and sessions", () => {
|
||||
const note = newTask(
|
||||
"Launch",
|
||||
{
|
||||
...fields,
|
||||
due: { date: "2026-10-30" },
|
||||
plan: { start: "2026-10-05", end: "2026-10-31" },
|
||||
sessions: [
|
||||
{
|
||||
id: "session-1",
|
||||
start: "2026-10-08T16:00:00Z",
|
||||
end: "2026-10-08T17:00:00Z",
|
||||
timeZone: "America/Vancouver",
|
||||
},
|
||||
],
|
||||
},
|
||||
"Keep **Markdown**.\n",
|
||||
);
|
||||
const task = readTask(note.path, note.source)!;
|
||||
const moved = readTask(note.path, editTask(task, { status: "doing" }))!;
|
||||
assert.equal(moved.id, task.id);
|
||||
assert.equal(moved.body, task.body);
|
||||
assert.deepEqual(moved.plan, task.plan);
|
||||
assert.deepEqual(moved.sessions, task.sessions);
|
||||
assert.deepEqual(moved.due, task.due);
|
||||
assert.equal(moved.status, "doing");
|
||||
});
|
||||
test("metadata edits preserve unknown properties, comments, and the exact body", () => {
|
||||
const source =
|
||||
'\uFEFF---\r\nowner: Ada # keep this\r\nrunestone_pm:\r\n schema: 1\r\n id: stable\r\n kind: task\r\n status: todo # workflow\r\n future: {value: 12}\r\n plan:\r\n start: "2026-10-04"\r\n end: "2026-10-08"\r\n custom: untouched\r\n---\r\n# Body\r\n\r\n- [ ] Keep spacing \r\n';
|
||||
const original = readTask("Note.md", source)!;
|
||||
const next = editTask(original, {
|
||||
status: "doing",
|
||||
plan: { start: "2026-10-05", end: "2026-10-09" },
|
||||
});
|
||||
assert.equal(readTask("Note.md", next)!.body, original.body);
|
||||
assert.match(next, /owner: Ada # keep this/);
|
||||
assert.match(next, /# workflow/);
|
||||
assert.match(next, /future:/);
|
||||
assert.match(next, /custom: untouched/);
|
||||
assert.ok(next.startsWith("\uFEFF"));
|
||||
assert.ok(!/(?<!\r)\n/.test(next));
|
||||
});
|
||||
test("adding an existing note preserves its content and does not duplicate its identity", () => {
|
||||
const source = "---\ncategory: reference\n---\nOriginal body\n";
|
||||
const adopted = adoptNote("Existing.md", source),
|
||||
task = readTask("Existing.md", adopted)!;
|
||||
assert.equal(task.body, "Original body\n");
|
||||
assert.match(adopted, /category: reference/);
|
||||
assert.equal(adoptNote("Existing.md", adopted), adopted);
|
||||
});
|
||||
test("unsupported metadata and invalid dates are rejected without rewriting a note", () => {
|
||||
const note = newTask("Task", fields);
|
||||
assert.throws(
|
||||
() => readTask(note.path, note.source.replace("schema: 1", "schema: 2")),
|
||||
/unsupported/,
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
readTask(
|
||||
note.path,
|
||||
note.source.replace("status: todo", "status: unknown"),
|
||||
),
|
||||
/status/,
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
editTask(readTask(note.path, note.source)!, {
|
||||
due: { date: "2026-02-30" },
|
||||
}),
|
||||
/deadline/,
|
||||
);
|
||||
assert.throws(
|
||||
() => adoptNote("Bad.md", "---\nkey: 1\nkey: 2\n---\nBody"),
|
||||
/YAML/,
|
||||
);
|
||||
assert.throws(() => newTask("../escape", fields), /name/);
|
||||
assert.throws(() => newTask("CON", fields), /name/);
|
||||
assert.throws(
|
||||
() =>
|
||||
newTask("Task", {
|
||||
...fields,
|
||||
plan: { start: "2026-10-10", end: "2026-10-09" },
|
||||
}),
|
||||
/end/,
|
||||
);
|
||||
});
|
||||
test("date arithmetic preserves whole dates over leap years and daylight-saving boundaries", () => {
|
||||
assert.equal(addDays("2024-02-28", 1), "2024-02-29");
|
||||
assert.equal(addDays("2026-12-31", 1), "2027-01-01");
|
||||
assert.equal(dayDistance("2026-03-07", "2026-03-09"), 2);
|
||||
assert.equal(dayDistance("2026-10-31", "2026-11-02"), 2);
|
||||
assert.equal(validDate("2026-02-29"), false);
|
||||
});
|
||||
test("save and reload use one note, and archive retains its file", async () => {
|
||||
const { files, workspace } = memory();
|
||||
const store = new TaskStore(workspace);
|
||||
await store.create("Launch", fields, "Description");
|
||||
assert.equal([...files.keys()].filter(isHiddenCard).length, 1);
|
||||
const original = store.tasks[0];
|
||||
await store.save(original, { status: "done", archived: true });
|
||||
const reopened = new TaskStore(workspace);
|
||||
await reopened.reload();
|
||||
assert.equal(reopened.tasks[0].id, original.id);
|
||||
assert.equal(reopened.tasks[0].status, "done");
|
||||
assert.equal(reopened.tasks[0].archived, true);
|
||||
assert.equal([...files.keys()].filter(isHiddenCard).length, 1);
|
||||
});
|
||||
test("stale edits cannot overwrite external changes", async () => {
|
||||
const { workspace, files } = memory();
|
||||
const store = new TaskStore(workspace);
|
||||
await store.create("Task", fields, "Original");
|
||||
const original = store.tasks[0];
|
||||
const external = editTask(original, { body: "External change" });
|
||||
files.set(original.path, external);
|
||||
await assert.rejects(store.save(original, { status: "done" }), /changed/);
|
||||
assert.equal(files.get(original.path), external);
|
||||
});
|
||||
test("duplicate identities are excluded and blocked even when introduced after reload", async () => {
|
||||
const note = newTask("Task", fields);
|
||||
const { workspace, files } = memory({ [note.path]: note.source });
|
||||
const store = new TaskStore(workspace);
|
||||
await store.reload();
|
||||
const original = store.tasks[0];
|
||||
files.set("Copy.md", note.source);
|
||||
await assert.rejects(store.save(original, { status: "done" }), /duplicate/);
|
||||
assert.equal(store.tasks.length, 0);
|
||||
assert.match(store.issues[0], /Duplicate/);
|
||||
assert.equal(files.get(note.path), note.source);
|
||||
});
|
||||
test("duplicate card titles preserve both cards and disposal blocks new writes", async () => {
|
||||
const { workspace, files } = memory();
|
||||
const store = new TaskStore(workspace);
|
||||
await store.create("Task", fields, "Original");
|
||||
const first = store.tasks[0];
|
||||
await store.create("Task", fields, "Second card");
|
||||
assert.equal(store.tasks.length, 2);
|
||||
assert.equal(files.get(first.path), first.source);
|
||||
assert.equal(new Set(store.tasks.map((task) => task.id)).size, 2);
|
||||
store.dispose();
|
||||
await assert.rejects(store.create("Later", fields, ""), /closed/);
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
|
||||
import { newTask, readTask } from "../../../../src/lib/features/pm/storage/notes.ts";
|
||||
import { deletedCardsPath } from "../../../../src/lib/features/pm/storage/deleted-cards.ts";
|
||||
import { migrateCards } from "../../../../src/lib/features/pm/storage/cards.ts";
|
||||
import type { Workspace } from "../../../../src/lib/features/pm/model/model.ts";
|
||||
|
||||
function fixture() {
|
||||
const note = newTask("Delete me", { status: "todo", tags: [], sessions: [], archived: false,
|
||||
placements: { first: { listId: "todo" }, second: { listId: "doing" } } }, "Keep this source");
|
||||
const task = readTask("Delete me.md", note.source)!;
|
||||
const parent = newTask("Related", { status: "todo", tags: [], sessions: [], archived: false,
|
||||
links: [{ taskId: task.id, relation: "relates" }], subtasks: [{ id: "sub", taskId: task.id, title: task.title, done: false }] }, "");
|
||||
const files = new Map([[task.path, note.source], ["Related.md", parent.source]]);
|
||||
let fail = false;
|
||||
const workspace: Workspace = {
|
||||
async list(folder = "") { return [...files.keys()].filter(path => folder ? path.startsWith(`${folder}/`) : !path.startsWith(".")).map(path => ({ name: path.split("/").at(-1)!, rel_path: path, kind: "file" })); },
|
||||
async read(path) { if (!files.has(path)) throw Error("Missing"); return files.get(path)!; },
|
||||
async readOptional(path) { return files.get(path) ?? null; },
|
||||
async create(path, source) { if (fail || files.has(path)) throw Error("Write failed"); files.set(path, source); },
|
||||
async write(path, source, expected) { if (fail) throw Error("Write failed"); assert.equal(files.get(path), expected); files.set(path, source); },
|
||||
};
|
||||
return { task, files, workspace, setFailure() { fail = true; } };
|
||||
}
|
||||
|
||||
test("confirmed deletion removes legacy and migrated cards from all scopes and retains source records", async () => {
|
||||
for (const migrate of [false, true]) {
|
||||
const { workspace, files, task } = fixture();
|
||||
if (migrate) await migrateCards(workspace, [task]);
|
||||
const store = new TaskStore(workspace); await store.reload();
|
||||
const before = new Map(files);
|
||||
await store.deleteCard(store.tasks.find(item => item.id === task.id)!);
|
||||
assert.deepEqual(store.tasks.map(item => item.title), ["Related"]);
|
||||
for (const [path, source] of before) assert.equal(files.get(path), source);
|
||||
assert.deepEqual(JSON.parse(files.get(deletedCardsPath)!).ids, [task.id]);
|
||||
const fresh = new TaskStore(workspace); await fresh.reload();
|
||||
assert.equal(fresh.tasks.some(item => item.id === task.id), false);
|
||||
await assert.rejects(fresh.openSubtask(fresh.tasks[0].id, "sub"), /unavailable/);
|
||||
assert.equal(fresh.tasks[0].links![0].taskId, task.id);
|
||||
await assert.rejects(fresh.save(task, { archived: false }), /changed|duplicate/);
|
||||
}
|
||||
});
|
||||
|
||||
test("stale cards and failed deletion writes preserve the card", async () => {
|
||||
const stale = fixture(); const store = new TaskStore(stale.workspace); await store.reload();
|
||||
stale.files.set(stale.task.path, stale.task.source + "External edit\n");
|
||||
await assert.rejects(store.deleteCard(stale.task), /changed/);
|
||||
assert.equal(stale.files.has(deletedCardsPath), false);
|
||||
const failed = fixture(); const next = new TaskStore(failed.workspace); await next.reload();
|
||||
failed.setFailure(); await assert.rejects(next.deleteCard(failed.task), /Write failed/);
|
||||
await next.reload(); assert.equal(next.tasks.length, 2);
|
||||
});
|
||||
|
||||
test("damaged deletion records block card access instead of restoring deleted cards", async () => {
|
||||
const { workspace, files } = fixture();
|
||||
for (const source of ['{', '{"schema":2,"ids":[]}', '{"schema":1,"ids":[4]}']) {
|
||||
files.set(deletedCardsPath, source);
|
||||
const store = new TaskStore(workspace); await store.reload();
|
||||
assert.equal(store.tasks.length, 0);
|
||||
assert.ok(store.issues.some(issue => issue.startsWith("Deleted cards:")));
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
// The image data of description drafts: an image in an unsaved description survives a close, and a discard leaves no image data.
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { DescriptionDraft } from "../../../../src/lib/features/pm/storage/description-draft.ts";
|
||||
import { imageMarkdown, imagePath, saveImages } from "../../../../src/lib/features/pm/storage/images.ts";
|
||||
import { privateRulesPath } from "../../../../src/lib/features/pm/storage/persistence.ts";
|
||||
import { memoryWorkspace } from "./_memory.ts";
|
||||
|
||||
const one = "12345678-1234-1234-1234-123456789abc";
|
||||
const two = "87654321-1234-1234-1234-123456789abc";
|
||||
const data = "data:image/png;base64,aGVsbG8=";
|
||||
const other = "data:image/gif;base64,R0lGOD==";
|
||||
|
||||
/** A workspace that records the path of each write and creation, in order. */
|
||||
function recorded() {
|
||||
const workspace = memoryWorkspace({ [privateRulesPath]: "*\n" });
|
||||
const writes: string[] = [];
|
||||
const { write, create } = workspace;
|
||||
workspace.write = async (path, contents, expected) => { await write(path, contents, expected); writes.push(path); };
|
||||
workspace.create = async (path, contents) => { await create!(path, contents); writes.push(path); };
|
||||
return { workspace, writes };
|
||||
}
|
||||
|
||||
test("a draft from an earlier version, without an image record, still loads", async () => {
|
||||
const { workspace } = recorded();
|
||||
const draft = new DescriptionDraft(workspace, "task");
|
||||
workspace.files.set(draft.path, JSON.stringify({ schema: 1, body: `Old ${imageMarkdown("a.png", one)}` }) + "\n");
|
||||
const reopened = new DescriptionDraft(workspace, "task");
|
||||
assert.equal(await reopened.load(), `Old ${imageMarkdown("a.png", one)}`);
|
||||
assert.deepEqual(await reopened.loadImages(), new Map());
|
||||
await reopened.save("Newer text");
|
||||
assert.equal(workspace.files.has(reopened.imagesPath), false, "A draft without images makes no image record");
|
||||
});
|
||||
|
||||
test("the draft keeps the data of its unsaved images, and the image folder stays empty", async () => {
|
||||
const { workspace, writes } = recorded();
|
||||
const draft = new DescriptionDraft(workspace, "task");
|
||||
await draft.loadImages();
|
||||
const body = `Text\n${imageMarkdown("a.png", one)}`;
|
||||
await draft.save(body, new Map([[one, data]]));
|
||||
assert.deepEqual(writes, [draft.imagesPath, draft.path], "The image data comes before the reference");
|
||||
assert.equal([...workspace.files.keys()].some(path => path.startsWith(".runestone/pm/images/")), false);
|
||||
|
||||
// A text change does not write the image data again.
|
||||
await draft.save(`${body}\nMore`, new Map([[one, data]]));
|
||||
assert.deepEqual(writes, [draft.imagesPath, draft.path, draft.path]);
|
||||
|
||||
const reopened = new DescriptionDraft(workspace, "task");
|
||||
assert.equal(await reopened.load(), `${body}\nMore`);
|
||||
assert.deepEqual(await reopened.loadImages(), new Map([[one, data]]));
|
||||
// A later save writes the image file from the restored data.
|
||||
assert.deepEqual(await saveImages(workspace, body, await reopened.loadImages()), [one]);
|
||||
assert.match(workspace.files.get(imagePath(one))!, /data:image\/png;base64,aGVsbG8=/);
|
||||
});
|
||||
|
||||
test("a removed image keeps its data until the text without the reference is saved", async () => {
|
||||
const { workspace, writes } = recorded();
|
||||
const draft = new DescriptionDraft(workspace, "task");
|
||||
await draft.loadImages();
|
||||
await draft.save(`${imageMarkdown("a.png", one)}\n${imageMarkdown("b.gif", two)}`, new Map([[one, data], [two, other]]));
|
||||
writes.length = 0;
|
||||
await draft.save(imageMarkdown("a.png", one), new Map([[one, data]]));
|
||||
assert.deepEqual(writes, [draft.path, draft.imagesPath]);
|
||||
assert.deepEqual(await new DescriptionDraft(workspace, "task").loadImages(), new Map([[one, data]]));
|
||||
|
||||
// An image that replaces another one: the record holds both images while the text changes.
|
||||
writes.length = 0;
|
||||
await draft.save(imageMarkdown("b.gif", two), new Map([[two, other]]));
|
||||
assert.deepEqual(writes, [draft.imagesPath, draft.path, draft.imagesPath]);
|
||||
assert.deepEqual(await new DescriptionDraft(workspace, "task").loadImages(), new Map([[two, other]]));
|
||||
});
|
||||
|
||||
test("a discarded draft keeps no image data and writes no image file", async () => {
|
||||
const { workspace, writes } = recorded();
|
||||
const draft = new DescriptionDraft(workspace, "task");
|
||||
await draft.loadImages();
|
||||
await draft.save(imageMarkdown("a.png", one), new Map([[one, data]]));
|
||||
writes.length = 0;
|
||||
await draft.save(null, new Map([[one, data]]));
|
||||
assert.deepEqual(writes, [draft.path, draft.imagesPath], "The text goes first, so that no saved reference loses its data");
|
||||
assert.equal(await new DescriptionDraft(workspace, "task").load(), null);
|
||||
assert.equal(workspace.files.get(draft.imagesPath), JSON.stringify({ schema: 1, images: {} }) + "\n");
|
||||
assert.equal([...workspace.files.keys()].some(path => path.startsWith(".runestone/pm/images/")), false);
|
||||
});
|
||||
|
||||
test("an invalid image record stops the draft, and a stale writer cannot overwrite the images", async () => {
|
||||
const { workspace } = recorded();
|
||||
const draft = new DescriptionDraft(workspace, "task");
|
||||
for (const images of [null, [], { "../secret": data }, { [one]: "data:image/svg+xml;base64,PHN2Zz4=" }]) {
|
||||
workspace.files.set(draft.imagesPath, JSON.stringify({ schema: 1, images }));
|
||||
await assert.rejects(draft.loadImages(), /description draft is invalid/);
|
||||
}
|
||||
workspace.files.delete(draft.imagesPath);
|
||||
const first = new DescriptionDraft(workspace, "task"), second = new DescriptionDraft(workspace, "task");
|
||||
await first.loadImages();
|
||||
await second.loadImages();
|
||||
await first.save(imageMarkdown("a.png", one), new Map([[one, data]]));
|
||||
await assert.rejects(second.save(imageMarkdown("b.gif", two), new Map([[two, other]])), /exists/);
|
||||
assert.deepEqual(await new DescriptionDraft(workspace, "task").loadImages(), new Map([[one, data]]));
|
||||
});
|
||||
|
||||
test("an image save includes extra IDs, for example a card cover, and returns the saved IDs", async () => {
|
||||
const workspace = memoryWorkspace({ [privateRulesPath]: "*\n" });
|
||||
const pending = new Map([[one, data], [two, other]]);
|
||||
assert.deepEqual(await saveImages(workspace, "", pending, [], [two]), [two]);
|
||||
assert.equal(workspace.files.has(imagePath(one)), false);
|
||||
assert.equal(workspace.files.has(imagePath(two)), true);
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { headingEdit } from "../../../../src/lib/features/pm/model/description-format.ts";
|
||||
|
||||
function apply(value: string, start: number, end = start) {
|
||||
const edit = headingEdit(value, start, end);
|
||||
return { value: value.slice(0, edit.start) + edit.text + value.slice(edit.end), start: edit.selectionStart, end: edit.selectionEnd };
|
||||
}
|
||||
|
||||
test("Heading formats the caret line and preserves the caret inside its text", () => {
|
||||
assert.deepEqual(apply("Before\nTyped text\nAfter", 12), { value: "Before\n## Typed text\nAfter", start: 15, end: 15 });
|
||||
assert.deepEqual(apply("Typed text", 0), { value: "## Typed text", start: 3, end: 3 });
|
||||
assert.deepEqual(apply("Typed text", 10), { value: "## Typed text", start: 13, end: 13 });
|
||||
});
|
||||
|
||||
test("Heading preserves selected text and formats all selected lines", () => {
|
||||
assert.deepEqual(apply("One line\nTwo lines\nLast", 2, 12), { value: "## One line\n## Two lines\nLast", start: 5, end: 18 });
|
||||
assert.deepEqual(apply("One\nTwo", 0, 4), { value: "## One\nTwo", start: 3, end: 7 });
|
||||
});
|
||||
|
||||
test("Heading changes an existing heading without duplicate markers", () => {
|
||||
assert.deepEqual(apply("# Title", 7), { value: "## Title", start: 8, end: 8 });
|
||||
assert.deepEqual(apply("## Title", 5), { value: "## Title", start: 5, end: 5 });
|
||||
assert.deepEqual(apply("### Title", 1), { value: "## Title", start: 3, end: 3 });
|
||||
});
|
||||
|
||||
test("Heading leaves the caret after the marker on empty lines", () => {
|
||||
assert.deepEqual(apply("", 0), { value: "## ", start: 3, end: 3 });
|
||||
assert.deepEqual(apply("Text\n", 5), { value: "Text\n## ", start: 8, end: 8 });
|
||||
assert.deepEqual(apply("\nText", 0), { value: "## \nText", start: 3, end: 3 });
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
imageMarkdown,
|
||||
imageReferences,
|
||||
imagePath,
|
||||
parseImage,
|
||||
saveImages,
|
||||
maxImageBytes,
|
||||
} from "../../../../src/lib/features/pm/storage/images.ts";
|
||||
import type { Workspace } from "../../../../src/lib/features/pm/model/model.ts";
|
||||
const id = "12345678-1234-1234-1234-123456789abc";
|
||||
const data = "data:image/png;base64,aGVsbG8=";
|
||||
|
||||
test("image references preserve surrounding text and restrict private paths", () => {
|
||||
const markdown = imageMarkdown("shot [one]\n\\test.png", id);
|
||||
assert.equal(markdown, ``);
|
||||
const body = `Before\n${markdown}\nAfter`;
|
||||
assert.deepEqual(imageReferences(body), [
|
||||
{ id, name: "shot one test.png", markdown, index: 7 },
|
||||
]);
|
||||
assert.deepEqual(
|
||||
imageReferences(
|
||||
" ",
|
||||
),
|
||||
[],
|
||||
);
|
||||
assert.throws(() => imagePath("../../secret"), /invalid/);
|
||||
});
|
||||
test("saved image data rejects unsupported and executable sources", () => {
|
||||
assert.equal(parseImage(JSON.stringify({ schema: 1, data })), data);
|
||||
for (const value of [
|
||||
null,
|
||||
{},
|
||||
{ schema: 1, data: "https://example.com/image.png" },
|
||||
{ schema: 1, data: "data:image/svg+xml;base64,PHN2Zz4=" },
|
||||
{ schema: 1, data: "data:image/png;base64,***=" },
|
||||
])
|
||||
assert.throws(() => parseImage(JSON.stringify(value)));
|
||||
assert.throws(
|
||||
() => parseImage("x".repeat(Math.ceil(maxImageBytes / 3) * 4 + 257)),
|
||||
/50 MiB/,
|
||||
);
|
||||
});
|
||||
test("save writes only referenced images, protects existing files, and permits retry", async () => {
|
||||
const files = new Map<string, string>();
|
||||
const writes: string[] = [];
|
||||
const workspace: Workspace = {
|
||||
async list() {
|
||||
return [];
|
||||
},
|
||||
async read(path) {
|
||||
return files.get(path)!;
|
||||
},
|
||||
async readOptional(path) {
|
||||
return files.get(path) ?? null;
|
||||
},
|
||||
async create(path, source) {
|
||||
if (files.has(path)) throw new Error("Already exists");
|
||||
files.set(path, source);
|
||||
writes.push(path);
|
||||
},
|
||||
async write() {
|
||||
throw new Error("Unexpected overwrite");
|
||||
},
|
||||
};
|
||||
const pending = new Map([
|
||||
[id, data],
|
||||
["87654321-1234-1234-1234-123456789abc", data],
|
||||
]);
|
||||
const body = imageMarkdown("Screenshot", id);
|
||||
await saveImages(workspace, body, pending);
|
||||
assert.deepEqual(writes, [".runestone/pm/.gitignore", imagePath(id)]);
|
||||
await saveImages(workspace, body, pending);
|
||||
assert.equal(writes.length, 2);
|
||||
files.set(imagePath(id), "other image");
|
||||
await assert.rejects(saveImages(workspace, body, pending), /Already exists/);
|
||||
assert.equal(files.get(imagePath(id)), "other image");
|
||||
});
|
||||
|
||||
test("attachment metadata saves staged images without description references", async () => {
|
||||
const files = new Map<string, string>();
|
||||
const workspace: Workspace = {
|
||||
async list() { return []; },
|
||||
async read(path) { return files.get(path)!; },
|
||||
async readOptional(path) { return files.get(path) ?? null; },
|
||||
async create(path, source) { files.set(path, source); },
|
||||
async write() { throw new Error("Unexpected overwrite"); },
|
||||
};
|
||||
await saveImages(workspace, "", new Map([[id, data]]), [{ id, name: "Attachment.png" }]);
|
||||
assert.equal(parseImage(files.get(imagePath(id))!), data);
|
||||
});
|
||||
|
||||
test("image storage accepts exactly 50 MiB and rejects one extra byte", async () => {
|
||||
assert.equal(maxImageBytes, 50 * 1024 * 1024);
|
||||
const data = `data:image/png;base64,${Buffer.alloc(maxImageBytes).toString("base64")}`;
|
||||
const files = new Map<string, string>();
|
||||
const workspace: Workspace = {
|
||||
async list() { return []; }, async read(path) { return files.get(path)!; }, async readOptional(path) { return files.get(path) ?? null; },
|
||||
async write() { throw new Error("Unexpected overwrite"); },
|
||||
async create(path, source) { files.set(path, source); },
|
||||
};
|
||||
await saveImages(workspace, "", new Map([[id, data]]), [{ id, name: "large.png" }]);
|
||||
assert.equal(parseImage(files.get(imagePath(id))!), data);
|
||||
const tooLarge = `data:image/png;base64,${Buffer.alloc(maxImageBytes + 1).toString("base64")}`;
|
||||
assert.throws(() => parseImage(JSON.stringify({ schema: 1, data: tooLarge })), /50 MiB/);
|
||||
});
|
||||
@@ -0,0 +1,364 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
defaultLabels,
|
||||
labelsPath,
|
||||
parseLabels,
|
||||
validateLabels,
|
||||
} from "../../../../src/lib/features/pm/storage/labels.ts";
|
||||
import { newBoardSource, parseBoard } from "../../../../src/lib/features/pm/storage/board.ts";
|
||||
import { editTask, newTask, readTask } from "../../../../src/lib/features/pm/storage/notes.ts";
|
||||
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
|
||||
import {
|
||||
validateFields,
|
||||
type TaskFields,
|
||||
type Workspace,
|
||||
} from "../../../../src/lib/features/pm/model/model.ts";
|
||||
|
||||
const fields: TaskFields = {
|
||||
status: "todo",
|
||||
tags: [],
|
||||
sessions: [],
|
||||
archived: false,
|
||||
};
|
||||
function fixture() {
|
||||
const files = new Map<string, string>();
|
||||
const writes: string[] = [];
|
||||
const workspace: Workspace = {
|
||||
async list() {
|
||||
return [...files.keys()].map((path) => ({
|
||||
name: path.split("/").at(-1)!,
|
||||
rel_path: path,
|
||||
kind: "file",
|
||||
}));
|
||||
},
|
||||
async read(path) {
|
||||
if (!files.has(path)) throw new Error("Missing file");
|
||||
return files.get(path)!;
|
||||
},
|
||||
async readOptional(path) {
|
||||
return files.get(path) ?? null;
|
||||
},
|
||||
async create(path, source) {
|
||||
if (files.has(path)) throw new Error("File already exists");
|
||||
files.set(path, source);
|
||||
writes.push(path);
|
||||
},
|
||||
async write(path, source, expected) {
|
||||
if (files.get(path) !== expected) throw new Error("File changed");
|
||||
files.set(path, source);
|
||||
writes.push(path);
|
||||
},
|
||||
};
|
||||
return { files, writes, workspace, store: new TaskStore(workspace) };
|
||||
}
|
||||
|
||||
test("old notes and custom tags remain independent of saved labels", () => {
|
||||
const note = newTask(
|
||||
"Task",
|
||||
{ ...fields, tags: ["customer, success"], color: "pink" },
|
||||
"Keep **details**.\n",
|
||||
);
|
||||
const source = note.source.replace("---\n", "---\nowner: Ada # keep\n");
|
||||
const old = readTask(note.path, source)!;
|
||||
assert.equal(old.labels, undefined);
|
||||
const labeled = readTask(
|
||||
note.path,
|
||||
editTask(old, { labels: ["bug", "feature", "missing-label"] }),
|
||||
)!;
|
||||
assert.deepEqual(labeled.labels, ["bug", "feature", "missing-label"]);
|
||||
const moved = readTask(note.path, editTask(labeled, { status: "doing" }))!;
|
||||
assert.deepEqual(moved.labels, labeled.labels);
|
||||
const cleared = readTask(note.path, editTask(moved, { labels: [] }))!;
|
||||
assert.deepEqual(cleared.labels, []);
|
||||
assert.deepEqual(cleared.tags, old.tags);
|
||||
assert.equal(cleared.color, old.color);
|
||||
assert.equal(cleared.body, old.body);
|
||||
assert.match(cleared.source, /owner: Ada # keep/);
|
||||
for (const labels of [null, "bug", [1], [""], ["bug", "bug"], ["bad id"]])
|
||||
assert.throws(
|
||||
() => validateFields({ ...fields, labels } as TaskFields),
|
||||
/label IDs/,
|
||||
);
|
||||
});
|
||||
|
||||
test("one catalog serves every board and renames leave task files unchanged", async () => {
|
||||
const { files, workspace, writes } = fixture();
|
||||
const first = newBoardSource(),
|
||||
second = newBoardSource();
|
||||
files.set("First.md", first);
|
||||
files.set("Second.md", second);
|
||||
const a = new TaskStore(workspace, {
|
||||
id: parseBoard(first).id,
|
||||
path: "First.md",
|
||||
});
|
||||
const b = new TaskStore(workspace, {
|
||||
id: parseBoard(second).id,
|
||||
path: "Second.md",
|
||||
});
|
||||
await a.reload();
|
||||
assert.deepEqual(a.labels.value, defaultLabels());
|
||||
assert.equal(files.has(labelsPath), false);
|
||||
await a.create(
|
||||
"Shared label",
|
||||
{ ...fields, labels: ["bug"] },
|
||||
"Keep details.",
|
||||
);
|
||||
const task = a.tasks[0];
|
||||
await a.saveLabels(
|
||||
[
|
||||
...a.labels.value,
|
||||
{ id: "review", name: " Needs review ", color: "purple" },
|
||||
],
|
||||
a.labels.source,
|
||||
);
|
||||
await b.reload();
|
||||
assert.equal(b.labels.value.at(-1)!.name, "Needs review");
|
||||
assert.deepEqual(b.tasks[0].labels, ["bug"]);
|
||||
const changed = b.labels.value.map((label) =>
|
||||
label.id === "bug"
|
||||
? { ...label, name: "Defect", color: "orange" as const, archived: true }
|
||||
: label,
|
||||
);
|
||||
writes.length = 0;
|
||||
await b.saveLabels(changed, b.labels.source);
|
||||
await a.reload();
|
||||
assert.deepEqual(writes, [labelsPath]);
|
||||
assert.equal(a.labels.value[0].name, "Defect");
|
||||
assert.equal(a.labels.value[0].color, "orange");
|
||||
assert.equal(a.labels.value[0].archived, true);
|
||||
assert.equal(files.get(task.path), task.source);
|
||||
});
|
||||
|
||||
test("expanded palette colors persist in cards and shared labels", async () => {
|
||||
const { store, workspace } = fixture();
|
||||
const colors = [
|
||||
"amber",
|
||||
"lime",
|
||||
"teal",
|
||||
"cyan",
|
||||
"indigo",
|
||||
"magenta",
|
||||
"brown",
|
||||
"slate",
|
||||
"gray",
|
||||
] as const;
|
||||
await store.reload();
|
||||
await store.saveLabels(
|
||||
[
|
||||
...defaultLabels(),
|
||||
...colors.map((color) => ({ id: color, name: color, color })),
|
||||
],
|
||||
store.labels.source,
|
||||
);
|
||||
for (const color of colors)
|
||||
await store.create(
|
||||
`Palette ${color}`,
|
||||
{ ...fields, color, labels: [color] },
|
||||
"Keep these details.",
|
||||
);
|
||||
const reopened = new TaskStore(workspace);
|
||||
await reopened.reload();
|
||||
for (const color of colors) {
|
||||
const task = reopened.tasks.find(
|
||||
(task) => task.title === `Palette ${color}`,
|
||||
)!;
|
||||
assert.equal(task.color, color);
|
||||
assert.deepEqual(task.labels, [color]);
|
||||
assert.equal(task.body, "Keep these details.");
|
||||
assert.equal(
|
||||
reopened.labels.value.find((label) => label.id === color)!.color,
|
||||
color,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("catalog validation blocks duplicate names, bad colors, IDs, and archive states", () => {
|
||||
for (const labels of [
|
||||
null,
|
||||
{},
|
||||
[null],
|
||||
[{ id: "bug", name: "Bug", color: "url(bad)" }],
|
||||
[{ id: "bug", name: "\nBug", color: "red" }],
|
||||
[{ id: "bug", name: " ", color: "red" }],
|
||||
[{ id: "bug", name: "Bug", color: "red", archived: "yes" }],
|
||||
[
|
||||
...defaultLabels(),
|
||||
{ id: "other", name: " BUG ", color: "blue", archived: true },
|
||||
],
|
||||
[...defaultLabels(), { id: "bug", name: "Another", color: "blue" }],
|
||||
])
|
||||
assert.throws(() => validateLabels(labels));
|
||||
assert.throws(() => parseLabels('{"schema":2,"labels":[]}'), /schema/);
|
||||
assert.throws(() => parseLabels("broken json"), /saved labels file/);
|
||||
assert.deepEqual(parseLabels('{"schema":1,"labels":[]}').labels, []);
|
||||
});
|
||||
|
||||
test("concurrent catalog creation and stale edits cannot replace newer labels", async () => {
|
||||
const { store, workspace, files } = fixture();
|
||||
const other = new TaskStore(workspace);
|
||||
await store.reload();
|
||||
await other.reload();
|
||||
await store.saveLabels(defaultLabels(), store.labels.source);
|
||||
const created = files.get(labelsPath);
|
||||
await assert.rejects(
|
||||
other.saveLabels(defaultLabels(), other.labels.source),
|
||||
/already exists/,
|
||||
);
|
||||
assert.equal(files.get(labelsPath), created);
|
||||
await other.reload();
|
||||
const expected = other.labels.source;
|
||||
await store.saveLabels(
|
||||
store.labels.value.map((label) => ({ ...label, archived: true })),
|
||||
store.labels.source,
|
||||
);
|
||||
const updated = files.get(labelsPath);
|
||||
await assert.rejects(other.saveLabels(defaultLabels(), expected), /changed/);
|
||||
assert.equal(files.get(labelsPath), updated);
|
||||
await store.reload();
|
||||
await store.saveLabels([], store.labels.source);
|
||||
assert.deepEqual(store.labels.value, []);
|
||||
});
|
||||
|
||||
test("catalog read failures and invalid files leave task editing available without overwriting the catalog", async () => {
|
||||
const { store, files, workspace } = fixture();
|
||||
const task = newTask("Keep task", { ...fields, labels: ["unknown"] });
|
||||
files.set(task.path, task.source);
|
||||
files.set(labelsPath, "invalid json");
|
||||
await store.reload();
|
||||
assert.equal(store.tasks.length, 1);
|
||||
assert.match(store.issues.join(" "), /Saved labels/);
|
||||
assert.equal(store.labels.source, undefined);
|
||||
await assert.rejects(store.saveLabels(defaultLabels(), null), /unavailable/);
|
||||
await store.save(store.tasks[0], { status: "done" });
|
||||
assert.equal(files.get(labelsPath), "invalid json");
|
||||
assert.deepEqual(store.tasks[0].labels, ["unknown"]);
|
||||
workspace.readOptional = async () => {
|
||||
throw new Error("Permission denied");
|
||||
};
|
||||
await store.reload();
|
||||
assert.match(store.issues.join(" "), /Permission denied/);
|
||||
await assert.rejects(store.saveLabels(defaultLabels(), null), /unavailable/);
|
||||
});
|
||||
|
||||
test("catalog writes preserve unknown metadata and propagate filesystem errors", async () => {
|
||||
const { store, files, workspace } = fixture();
|
||||
const source = JSON.stringify({
|
||||
schema: 1,
|
||||
future: { keep: true },
|
||||
labels: defaultLabels().map((label) => ({ ...label, extra: "keep" })),
|
||||
});
|
||||
files.set(labelsPath, source);
|
||||
await store.reload();
|
||||
await store.saveLabels(store.labels.value, store.labels.source);
|
||||
const data = JSON.parse(files.get(labelsPath)!);
|
||||
assert.deepEqual(data.future, { keep: true });
|
||||
assert.equal(data.labels[0].extra, "keep");
|
||||
const before = files.get(labelsPath);
|
||||
workspace.write = async () => {
|
||||
throw new Error("Disk full");
|
||||
};
|
||||
await assert.rejects(
|
||||
store.saveLabels(defaultLabels(), store.labels.source),
|
||||
/Disk full/,
|
||||
);
|
||||
assert.equal(store.labels.source, before);
|
||||
assert.equal(files.get(labelsPath), before);
|
||||
});
|
||||
|
||||
test("a pending scan cannot replace saved label edits", async () => {
|
||||
const { store, workspace } = fixture();
|
||||
await store.reload();
|
||||
let release!: () => void, entered!: () => void;
|
||||
const gate = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const started = new Promise<void>((resolve) => {
|
||||
entered = resolve;
|
||||
});
|
||||
const read = workspace.readOptional!;
|
||||
let blocked = false;
|
||||
workspace.readOptional = async (path) => {
|
||||
if (path !== labelsPath || blocked) return read(path);
|
||||
blocked = true;
|
||||
const source = await read(path);
|
||||
entered();
|
||||
await gate;
|
||||
return source;
|
||||
};
|
||||
const pending = store.reload();
|
||||
await started;
|
||||
await store.saveLabels(
|
||||
[...defaultLabels(), { id: "new", name: "New label", color: "pink" }],
|
||||
null,
|
||||
);
|
||||
release();
|
||||
await pending;
|
||||
assert.equal(store.labels.value.at(-1)!.id, "new");
|
||||
assert.notEqual(store.labels.source, null);
|
||||
});
|
||||
|
||||
test("older workspaces can read catalogs through listing but cannot create without create support", async () => {
|
||||
const { store, workspace, files } = fixture();
|
||||
delete workspace.readOptional;
|
||||
delete workspace.create;
|
||||
await store.reload();
|
||||
await assert.rejects(
|
||||
store.saveLabels(defaultLabels(), null),
|
||||
/Update RuneStone/,
|
||||
);
|
||||
files.set(labelsPath, JSON.stringify({ schema: 1, labels: defaultLabels() }));
|
||||
await store.reload();
|
||||
assert.deepEqual(store.labels.value, defaultLabels());
|
||||
store.dispose();
|
||||
await assert.rejects(
|
||||
store.saveLabels(defaultLabels(), store.labels.source),
|
||||
/closed/,
|
||||
);
|
||||
});
|
||||
|
||||
test("deleting labels clears active, archived, unlisted, and shared cards while preserving unrelated data", async () => {
|
||||
const { store, files, workspace } = fixture();
|
||||
for (let index = 0; index < 4; index++) {
|
||||
const task = newTask(`Card ${index}`, {
|
||||
...fields, archived: index === 1, labels: ["bug", "feature", "unknown"], tags: ["bug"],
|
||||
placements: index === 2 ? {} : { a: { listId: "todo", order: "m" }, b: { listId: null } },
|
||||
}, "Keep **body**.");
|
||||
files.set(task.path, task.source);
|
||||
}
|
||||
await store.reload();
|
||||
await store.saveLabels(store.labels.value.filter(label => label.id !== "bug"), store.labels.source);
|
||||
const reopened = new TaskStore(workspace);
|
||||
await reopened.reload();
|
||||
assert.equal(reopened.tasks.length, 4);
|
||||
for (const task of reopened.tasks) {
|
||||
assert.deepEqual(task.labels, ["feature", "unknown"]);
|
||||
assert.deepEqual(task.tags, ["bug"]);
|
||||
assert.equal(task.body, "Keep **body**.");
|
||||
}
|
||||
assert.equal(reopened.tasks[1].archived, true);
|
||||
assert.deepEqual(reopened.tasks[0].placements, { a: { listId: "todo", order: "m" }, b: { listId: null } });
|
||||
assert.equal(reopened.labels.value.some(label => label.id === "bug"), false);
|
||||
});
|
||||
|
||||
test("failed label deletion keeps definitions and allows guarded retry", async () => {
|
||||
const { store, files, workspace } = fixture();
|
||||
for (const name of ["A", "B"]) {
|
||||
const task = newTask(name, { ...fields, labels: ["bug"] }, "Keep body");
|
||||
files.set(task.path, task.source);
|
||||
}
|
||||
await store.reload();
|
||||
const next = store.labels.value.filter(label => label.id !== "bug");
|
||||
const write = workspace.write;
|
||||
workspace.write = async (path, source, expected) => {
|
||||
if (path === store.tasks.find(task => task.title === "B")!.path) throw new Error("Disk full");
|
||||
return write(path, source, expected);
|
||||
};
|
||||
await assert.rejects(store.saveLabels(next, store.labels.source), /Disk full/);
|
||||
assert.equal(store.labels.value.some(label => label.id === "bug"), true);
|
||||
assert.deepEqual(store.tasks.find(task => task.title === "B")!.labels, ["bug"]);
|
||||
workspace.write = write;
|
||||
await store.saveLabels(next, store.labels.source);
|
||||
await store.reload();
|
||||
assert.equal(store.tasks.every(task => !task.labels?.includes("bug")), true);
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
// The legacy format: the native feature finds visible boards, task notes, and the root label file, and offers the
|
||||
// migration. The migration of the offer is the migration of the plugin, with its backups.
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { findLegacy, hasLegacy, mentionsProjectData } from "../../../../src/lib/features/pm/storage/legacy.ts";
|
||||
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
|
||||
import { boardMarkdown, catalogPath } from "../../../../src/lib/features/pm/storage/catalog.ts";
|
||||
import { defaultBoard } from "../../../../src/lib/features/pm/storage/board.ts";
|
||||
import { cardPath } from "../../../../src/lib/features/pm/storage/cards.ts";
|
||||
import { deletedCardsPath } from "../../../../src/lib/features/pm/storage/deleted-cards.ts";
|
||||
import { labelsPath, legacyLabelsPath } from "../../../../src/lib/features/pm/storage/labels.ts";
|
||||
import { newTask, readTask } from "../../../../src/lib/features/pm/storage/notes.ts";
|
||||
import { isHiddenCard } from "../../../../src/lib/features/pm/storage/persistence.ts";
|
||||
import { fields, hiddenWorkspace, memoryWorkspace } from "./_memory.ts";
|
||||
|
||||
const labels = JSON.stringify({ schema: 1, labels: [{ id: "bug", name: "Bug", color: "red" }] });
|
||||
|
||||
test("only notes that name runestone_pm in their properties count as Project Management data", () => {
|
||||
assert.equal(mentionsProjectData("---\nrunestone_pm:\n kind: task\n---\n"), true);
|
||||
assert.equal(mentionsProjectData(String.fromCharCode(0xfeff) + "---\r\ntitle: x\r\nrunestone_pm: {}\r\n---\r\n"), true);
|
||||
assert.equal(mentionsProjectData("# Plan\nrunestone_pm: in the body\n"), false);
|
||||
assert.equal(mentionsProjectData("---\ntitle: x\n---\nrunestone_pm: in the body\n"), false);
|
||||
assert.equal(mentionsProjectData("---\nother_runestone_pm: x\n---\n"), false);
|
||||
});
|
||||
|
||||
test("an empty workspace or a migrated workspace has nothing to offer", async () => {
|
||||
assert.equal(hasLegacy(await findLegacy(memoryWorkspace({ "Notes/Plain.md": "# Plain\n" }))), false);
|
||||
const workspace = hiddenWorkspace([{ id: "hidden", title: "Hidden" }]);
|
||||
assert.deepEqual(await findLegacy(workspace), { boards: [], cards: [], invalid: [], labels: false });
|
||||
});
|
||||
|
||||
test("visible boards, task notes, and the root label file are found without a parse of plain notes", async () => {
|
||||
const board = defaultBoard("visible-board");
|
||||
const workspace = memoryWorkspace({
|
||||
"Boards/Plan.md": boardMarkdown(board),
|
||||
"Tasks/Write.md": newTask("Write", fields(), "Body", "write").source,
|
||||
"Notes/Plain.md": "---\ntitle: [broken yaml\n---\nPlain note.\n",
|
||||
"Notes/Broken.md": "---\nrunestone_pm: [\n---\n",
|
||||
[legacyLabelsPath]: labels,
|
||||
});
|
||||
const content = await findLegacy(workspace);
|
||||
assert.deepEqual(content, { boards: ["Boards/Plan.md"], cards: ["Tasks/Write.md"], invalid: ["Notes/Broken.md"], labels: true });
|
||||
assert.equal(hasLegacy(content), true);
|
||||
});
|
||||
|
||||
test("migrated, deleted, and already saved data does not count again", async () => {
|
||||
const board = defaultBoard("old-board");
|
||||
const workspace = hiddenWorkspace([{ id: "copied", title: "Copied" }], {
|
||||
"Old.md": boardMarkdown(board),
|
||||
"Gone.md": boardMarkdown(defaultBoard("gone-board")),
|
||||
"Copied.md": newTask("Copied", fields(), "", "copied").source,
|
||||
"Deleted.md": newTask("Deleted", fields(), "", "deleted").source,
|
||||
[deletedCardsPath]: JSON.stringify({ schema: 1, ids: ["deleted"] }),
|
||||
[legacyLabelsPath]: labels,
|
||||
[labelsPath]: labels,
|
||||
});
|
||||
const catalog = JSON.parse(workspace.files.get(catalogPath)!);
|
||||
catalog.boards.push({ name: "Old", value: board });
|
||||
catalog.deletedBoardIds = ["gone-board"];
|
||||
workspace.files.set(catalogPath, JSON.stringify(catalog));
|
||||
assert.deepEqual(await findLegacy(workspace), { boards: [], cards: [], invalid: [], labels: false });
|
||||
});
|
||||
|
||||
test("the offer migrates every legacy board, task note, and the label file with backups, and changes no original", async () => {
|
||||
const board = defaultBoard("visible-board");
|
||||
const originals = {
|
||||
"Boards/Plan.md": boardMarkdown(board),
|
||||
"Tasks/Write.md": newTask("Write", fields({ placements: { "visible-board": { listId: "todo" } } }), "Body", "write").source,
|
||||
"Tasks/Read.md": newTask("Read", fields(), "", "read").source,
|
||||
[legacyLabelsPath]: labels,
|
||||
};
|
||||
const workspace = memoryWorkspace(originals);
|
||||
// The native view sees nothing before the migration.
|
||||
const hidden = new TaskStore(workspace, undefined, { legacy: false });
|
||||
await hidden.reload();
|
||||
assert.equal(hidden.tasks.length, 0);
|
||||
assert.equal(hidden.boards.length, 0);
|
||||
// The offer: a legacy store migrates all boards, the labels, and every visible task note.
|
||||
const legacy = new TaskStore(workspace, undefined, { legacy: true });
|
||||
await legacy.reload();
|
||||
const files = await legacy.migrateStorage(legacy.tasks.filter(task => !isHiddenCard(task.path)).map(task => task.id));
|
||||
legacy.dispose();
|
||||
assert.deepEqual(files.map(file => file.path).sort(), ["Boards/Plan.md", "Tasks/Read.md", "Tasks/Write.md", legacyLabelsPath].sort());
|
||||
for (const file of files) assert.equal(workspace.files.get(file.backup), file.source);
|
||||
for (const [path, source] of Object.entries(originals)) assert.equal(workspace.files.get(path), source, path);
|
||||
assert.equal(hasLegacy(await findLegacy(workspace)), false);
|
||||
await hidden.reload();
|
||||
assert.deepEqual(hidden.tasks.map(task => task.id).sort(), ["read", "write"]);
|
||||
assert.deepEqual(hidden.boards.map(item => [item.id, item.name]), [["visible-board", "Plan"]]);
|
||||
assert.deepEqual(hidden.labels.value.map(label => label.id), ["bug"]);
|
||||
});
|
||||
|
||||
test("Add existing note copies a plain note into a private card and leaves the note unchanged", async () => {
|
||||
const note = "---\ntags: [keep]\n---\n# Research\nDetails.\n";
|
||||
const workspace = hiddenWorkspace([], { "Notes/Research.md": note });
|
||||
const store = new TaskStore(workspace, { id: "board", path: "pm-board:board" }, { legacy: false });
|
||||
await store.reload();
|
||||
const card = await store.adopt("Notes/Research.md");
|
||||
assert.equal(workspace.files.get("Notes/Research.md"), note);
|
||||
assert.equal(card.path, cardPath(card.id));
|
||||
assert.equal(card.title, "Research");
|
||||
assert.equal(card.body, "# Research\nDetails.\n");
|
||||
assert.equal(card.placements?.board.listId, "todo");
|
||||
assert.match(workspace.files.get(card.path)!, /^tags: \[ keep \]$/m);
|
||||
assert.deepEqual(store.tasks.map(task => task.id), [card.id]);
|
||||
// A legacy task note migrates with a backup and keeps its ID.
|
||||
const legacyNote = newTask("Legacy", fields(), "Old body", "legacy-id").source;
|
||||
workspace.files.set("Notes/Legacy.md", legacyNote);
|
||||
const migrated = await store.adopt("Notes/Legacy.md");
|
||||
assert.equal(migrated.id, "legacy-id");
|
||||
assert.equal(migrated.path, cardPath("legacy-id"));
|
||||
assert.equal(workspace.files.get("Notes/Legacy.md"), legacyNote);
|
||||
assert.equal(workspace.files.get(".runestone/pm/backups/Notes/Legacy.md"), legacyNote);
|
||||
assert.equal(readTask(migrated.path, workspace.files.get(migrated.path)!)!.placements?.board.listId, "todo");
|
||||
// A second add of the same note finds the same card.
|
||||
assert.equal((await store.adopt("Notes/Legacy.md")).path, migrated.path);
|
||||
assert.equal(store.tasks.length, 2);
|
||||
});
|
||||
@@ -0,0 +1,514 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { newBoardSource, parseBoard, boardDocument } from "../../../../src/lib/features/pm/storage/board.ts";
|
||||
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
|
||||
import { newTask, readTask, adoptNote } from "../../../../src/lib/features/pm/storage/notes.ts";
|
||||
import type { Workspace, TaskFields } from "../../../../src/lib/features/pm/model/model.ts";
|
||||
|
||||
const fields: TaskFields = {
|
||||
status: "todo",
|
||||
tags: ["shared"],
|
||||
sessions: [
|
||||
{
|
||||
id: "session",
|
||||
start: "2026-10-08T16:00:00Z",
|
||||
end: "2026-10-08T17:00:00Z",
|
||||
timeZone: "America/Vancouver",
|
||||
},
|
||||
],
|
||||
due: { date: "2026-10-30" },
|
||||
plan: { start: "2026-10-05", end: "2026-10-31" },
|
||||
archived: false,
|
||||
};
|
||||
function fixture() {
|
||||
const first = newBoardSource(),
|
||||
second = newBoardSource();
|
||||
const files = new Map<string, string>([
|
||||
["Project/Launch.md", first],
|
||||
["Project/Personal.md", second],
|
||||
["Task.md", newTask("Task", fields, "Keep this description.").source],
|
||||
]);
|
||||
let fail = false;
|
||||
const writes: string[] = [];
|
||||
const workspace: Workspace = {
|
||||
async readOptional(path) {
|
||||
return files.get(path) ?? null;
|
||||
},
|
||||
async list(parent = "") {
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
const prefix = parent ? parent + "/" : "";
|
||||
if (!path.startsWith(prefix)) continue;
|
||||
const parts = path.slice(prefix.length).split("/");
|
||||
entries.set(parts[0], {
|
||||
name: parts[0],
|
||||
rel_path: prefix + parts[0],
|
||||
kind: parts.length > 1 ? "folder" : "file",
|
||||
});
|
||||
}
|
||||
return [...entries.values()];
|
||||
},
|
||||
async read(path) {
|
||||
const source = files.get(path);
|
||||
if (source === undefined) throw Error("Missing");
|
||||
return source;
|
||||
},
|
||||
async write(path, source, expected) {
|
||||
if (fail) throw Error("Disk failure");
|
||||
assert.equal(files.get(path), expected);
|
||||
writes.push(path);
|
||||
files.set(path, source);
|
||||
},
|
||||
async create(path, source) {
|
||||
if (files.has(path)) throw Error("Exists");
|
||||
files.set(path, source);
|
||||
},
|
||||
};
|
||||
const a = new TaskStore(workspace, {
|
||||
id: parseBoard(first).id,
|
||||
path: "Project/Launch.md",
|
||||
});
|
||||
const b = new TaskStore(workspace, {
|
||||
id: parseBoard(second).id,
|
||||
path: "Project/Personal.md",
|
||||
});
|
||||
const all = new TaskStore(workspace);
|
||||
return {
|
||||
files,
|
||||
workspace,
|
||||
a,
|
||||
b,
|
||||
all,
|
||||
writes,
|
||||
failWrites() {
|
||||
fail = true;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("a shared task synchronizes status lists and keeps one schedule", async () => {
|
||||
const { a, b, all, files, writes } = fixture();
|
||||
await a.adopt("Task.md");
|
||||
await b.adopt("Task.md");
|
||||
await a.reload();
|
||||
const original = a.tasks[0];
|
||||
writes.length = 0;
|
||||
await a.moveTask(original, "done");
|
||||
await b.reload();
|
||||
await all.reload();
|
||||
assert.deepEqual(writes, ["Task.md"]);
|
||||
assert.equal(a.board.listFor(a.scopedTasks[0])?.id, "done");
|
||||
assert.equal(b.board.listFor(b.scopedTasks[0])?.id, "done");
|
||||
assert.equal(b.scopedTasks[0].status, "done");
|
||||
assert.equal(all.scopedTasks.length, 1);
|
||||
assert.equal(all.scopedTasks[0].id, original.id);
|
||||
assert.deepEqual(all.scopedTasks[0].plan, fields.plan);
|
||||
assert.deepEqual(all.scopedTasks[0].sessions, fields.sessions);
|
||||
assert.deepEqual(all.scopedTasks[0].due, fields.due);
|
||||
assert.equal(all.scopedTasks[0].body, original.body);
|
||||
assert.equal(files.size, 3);
|
||||
await b.save(b.scopedTasks[0], { due: { date: "2026-11-01" } });
|
||||
await a.reload();
|
||||
assert.equal(a.scopedTasks[0].due?.date, "2026-11-01");
|
||||
});
|
||||
|
||||
test("leaving a Done list reopens completion and removal affects only one board", async () => {
|
||||
const { a, b, all } = fixture();
|
||||
await a.adopt("Task.md");
|
||||
await b.adopt("Task.md");
|
||||
await a.reload();
|
||||
await a.moveTask(a.tasks[0], "done");
|
||||
await a.changeBoard(() => a.board.add("This week", null));
|
||||
await a.moveTask(a.tasks[0], a.board.value.lists.at(-1)!.id);
|
||||
assert.equal(a.tasks[0].status, "todo");
|
||||
await a.removeFromBoard(a.tasks[0]);
|
||||
assert.equal(a.scopedTasks.length, 0);
|
||||
await b.reload();
|
||||
await all.reload();
|
||||
assert.equal(b.scopedTasks.length, 1);
|
||||
assert.equal(all.scopedTasks.length, 1);
|
||||
assert.equal(all.scopedTasks[0].archived, false);
|
||||
});
|
||||
|
||||
test("All tasks moves synchronize memberships in one write and append to destination lists", async () => {
|
||||
const { a, b, all, writes } = fixture();
|
||||
await a.adopt("Task.md");
|
||||
await b.adopt("Task.md");
|
||||
await a.create("Existing done", { ...fields, status: "done" }, "");
|
||||
await all.reload();
|
||||
const task = all.tasks.find((task) => task.title === "Task")!;
|
||||
writes.length = 0;
|
||||
await all.moveTask(task, "done");
|
||||
assert.deepEqual(writes, ["Task.md"]);
|
||||
for (const board of [a, b]) {
|
||||
await board.reload();
|
||||
const saved = board.scopedTasks.find((item) => item.id === task.id)!;
|
||||
assert.equal(saved.status, "done");
|
||||
assert.equal(board.board.listFor(saved)?.id, "done");
|
||||
assert.deepEqual(saved.sessions, task.sessions);
|
||||
assert.deepEqual(saved.plan, task.plan);
|
||||
assert.deepEqual(saved.due, task.due);
|
||||
assert.equal(saved.body, task.body);
|
||||
}
|
||||
assert.deepEqual(
|
||||
a.cardsInList("done").map((task) => task.title),
|
||||
["Existing done", "Task"],
|
||||
);
|
||||
assert.deepEqual(
|
||||
b.scopedTasks.map((task) => task.title),
|
||||
["Task"],
|
||||
);
|
||||
});
|
||||
|
||||
test("status changes use each board's designated list and preserve unmatched placements", async () => {
|
||||
const { a, b, all } = fixture();
|
||||
await a.adopt("Task.md");
|
||||
await b.adopt("Task.md");
|
||||
await a.changeBoard(() => a.board.add("Released", "done"));
|
||||
const destination = a.board.value.lists.at(-1)!.id;
|
||||
await a.changeBoard(() =>
|
||||
a.board.update((board) => {
|
||||
board.defaults.done = destination;
|
||||
}),
|
||||
);
|
||||
await b.changeBoard(() => b.board.remove("done"));
|
||||
await all.reload();
|
||||
const previous = all.tasks[0].placements![b.board.reference!.id];
|
||||
await all.save(all.tasks[0], { status: "done" });
|
||||
await a.reload();
|
||||
await b.reload();
|
||||
assert.equal(a.board.listFor(a.tasks[0])?.id, destination);
|
||||
assert.deepEqual(b.tasks[0].placements![b.board.reference!.id], previous);
|
||||
assert.equal(b.tasks[0].status, "done");
|
||||
});
|
||||
|
||||
test("status changes preserve absent memberships and unavailable board placements", async () => {
|
||||
const { a, b, all, files } = fixture();
|
||||
await a.adopt("Task.md");
|
||||
await all.reload();
|
||||
await all.moveTask(all.tasks[0], "doing");
|
||||
assert.equal(
|
||||
Object.hasOwn(all.tasks[0].placements!, b.board.reference!.id),
|
||||
false,
|
||||
);
|
||||
await a.reload();
|
||||
const previous = a.tasks[0].placements![a.board.reference!.id];
|
||||
files.delete("Project/Launch.md");
|
||||
await all.moveTask(all.tasks[0], "done");
|
||||
assert.deepEqual(all.tasks[0].placements![a.board.reference!.id], previous);
|
||||
});
|
||||
|
||||
test("failed All tasks moves preserve every placement and the shared status", async () => {
|
||||
const { a, b, all, files, failWrites } = fixture();
|
||||
await a.adopt("Task.md");
|
||||
await b.adopt("Task.md");
|
||||
await all.reload();
|
||||
const before = all.tasks[0];
|
||||
failWrites();
|
||||
await assert.rejects(all.moveTask(before, "done"), /Disk failure/);
|
||||
assert.equal(files.get("Task.md"), before.source);
|
||||
assert.deepEqual(all.tasks[0], before);
|
||||
});
|
||||
|
||||
test("board creation does not collect every workspace task", async () => {
|
||||
const { a, b } = fixture();
|
||||
await a.reload();
|
||||
await b.reload();
|
||||
assert.equal(a.scopedTasks.length, 0);
|
||||
await a.create("New", fields, "");
|
||||
await b.reload();
|
||||
assert.equal(a.scopedTasks.length, 1);
|
||||
assert.equal(b.scopedTasks.length, 0);
|
||||
assert.equal(a.board.listFor(a.scopedTasks[0])?.id, "todo");
|
||||
});
|
||||
|
||||
test("moving or deleting a board never moves or deletes its tasks", async () => {
|
||||
const { a, all, files } = fixture();
|
||||
await a.adopt("Task.md");
|
||||
const taskSource = files.get("Task.md");
|
||||
files.set("Elsewhere/Renamed.md", files.get("Project/Launch.md")!);
|
||||
files.delete("Project/Launch.md");
|
||||
await a.reload();
|
||||
assert.equal(a.board.reference?.path, "Elsewhere/Renamed.md");
|
||||
assert.equal(a.board.name, "Renamed");
|
||||
assert.equal(a.scopedTasks.length, 1);
|
||||
files.delete("Elsewhere/Renamed.md");
|
||||
await a.reload();
|
||||
await all.reload();
|
||||
assert.equal(a.board.available, false);
|
||||
assert.equal(all.scopedTasks.length, 1);
|
||||
assert.equal(files.get("Task.md"), taskSource);
|
||||
await assert.rejects(a.create("Lost", fields, ""), /unavailable/);
|
||||
});
|
||||
|
||||
test("invalid and duplicate boards do not block the workspace schedule", async () => {
|
||||
const { a, all, files } = fixture();
|
||||
files.set("Copy.md", files.get("Project/Launch.md")!);
|
||||
files.set(
|
||||
"Project/Personal.md",
|
||||
files.get("Project/Personal.md")!.replace("schema: 1", "schema: 99"),
|
||||
);
|
||||
await all.reload();
|
||||
await a.reload();
|
||||
assert.equal(all.tasks.length, 1);
|
||||
assert.equal(all.boards.length, 0);
|
||||
assert.equal(a.board.available, false);
|
||||
assert.ok(all.issues.some((issue) => issue.includes("Duplicate board ID")));
|
||||
assert.ok(all.issues.some((issue) => issue.includes("unsupported format")));
|
||||
});
|
||||
|
||||
test("failed placement writes preserve both membership and status", async () => {
|
||||
const { a, files, failWrites } = fixture();
|
||||
await a.adopt("Task.md");
|
||||
const source = files.get("Task.md");
|
||||
failWrites();
|
||||
await assert.rejects(a.moveTask(a.tasks[0], "done"), /Disk failure/);
|
||||
assert.equal(files.get("Task.md"), source);
|
||||
assert.equal(a.tasks[0].status, "todo");
|
||||
assert.equal(a.board.listFor(a.tasks[0])?.id, "todo");
|
||||
});
|
||||
|
||||
test("an open stale card cannot overwrite another board's edit", async () => {
|
||||
const { a, b, files } = fixture();
|
||||
await a.adopt("Task.md");
|
||||
await b.adopt("Task.md");
|
||||
await a.reload();
|
||||
const stale = a.tasks[0];
|
||||
await b.moveTask(b.tasks[0], "doing");
|
||||
const source = files.get("Task.md");
|
||||
await assert.rejects(a.moveTask(stale, "done"), /task changed/);
|
||||
assert.equal(files.get("Task.md"), source);
|
||||
});
|
||||
|
||||
test("board properties and prose survive edits and boards cannot become task notes", async () => {
|
||||
const { a, files } = fixture();
|
||||
const source =
|
||||
files
|
||||
.get("Project/Launch.md")!
|
||||
.replace("runestone_pm:", "owner: Ada # keep\nrunestone_pm:") +
|
||||
"Board description.\n";
|
||||
files.set("Project/Launch.md", source);
|
||||
await a.reload();
|
||||
await a.changeBoard(() => a.board.add("Review", null));
|
||||
const saved = files.get("Project/Launch.md")!;
|
||||
assert.ok(saved.includes("owner: Ada # keep"));
|
||||
assert.ok(saved.endsWith("Board description.\n"));
|
||||
assert.equal(readTask("Board.md", saved), null);
|
||||
assert.throws(() => adoptNote("Board.md", saved), /already contains Project Management data/);
|
||||
assert.equal(boardDocument("# A normal note", "Board.md"), null);
|
||||
});
|
||||
|
||||
test("renaming a board resolves its current path and preserves shared tasks and lists", async () => {
|
||||
const { a, b, all, files, writes } = fixture();
|
||||
await a.adopt("Task.md");
|
||||
await b.adopt("Task.md");
|
||||
await a.changeBoard(() => a.board.add("Review", null));
|
||||
const source = files.get("Project/Launch.md")!;
|
||||
const taskSource = files.get("Task.md");
|
||||
files.set("Moved/Launch.md", source);
|
||||
files.delete("Project/Launch.md");
|
||||
writes.length = 0;
|
||||
await a.renameBoard(" Release 1.2 ", async (document, name) => {
|
||||
assert.equal(document.path, "Moved/Launch.md");
|
||||
assert.equal(document.id, parseBoard(source).id);
|
||||
assert.equal(name, "Release 1.2");
|
||||
files.set("Moved/Release 1.2.md", files.get(document.path)!);
|
||||
files.delete(document.path);
|
||||
return "Moved/Release 1.2.md";
|
||||
});
|
||||
assert.equal(a.board.name, "Release 1.2");
|
||||
assert.equal(a.board.reference?.path, "Moved/Release 1.2.md");
|
||||
assert.equal(a.board.value.lists.at(-1)?.name, "Review");
|
||||
assert.equal(files.get("Moved/Release 1.2.md"), source);
|
||||
assert.equal(files.get("Task.md"), taskSource);
|
||||
assert.deepEqual(writes, []);
|
||||
await b.reload();
|
||||
await all.reload();
|
||||
assert.equal(a.scopedTasks.length, 1);
|
||||
assert.equal(b.scopedTasks.length, 1);
|
||||
assert.equal(all.scopedTasks.length, 1);
|
||||
await a.changeBoard(() => a.board.add("After rename", null));
|
||||
await a.moveTask(a.scopedTasks[0], "doing");
|
||||
assert.equal(a.board.listFor(a.scopedTasks[0])?.id, "doing");
|
||||
});
|
||||
|
||||
test("failed renames and unavailable boards preserve workspace files", async () => {
|
||||
const { a, all, files } = fixture();
|
||||
await a.reload();
|
||||
const before = [...files];
|
||||
await assert.rejects(
|
||||
a.renameBoard("Personal", async () => {
|
||||
throw Error("Exists");
|
||||
}),
|
||||
/Exists/,
|
||||
);
|
||||
assert.equal(a.board.reference?.path, "Project/Launch.md");
|
||||
assert.deepEqual([...files], before);
|
||||
const rename = async () => {
|
||||
assert.fail("Rename must not run");
|
||||
return "";
|
||||
};
|
||||
await assert.rejects(all.renameBoard("All", rename), /available board/);
|
||||
files.set("Copy.md", files.get("Project/Launch.md")!);
|
||||
await assert.rejects(a.renameBoard("Duplicate", rename), /available board/);
|
||||
files.delete("Copy.md");
|
||||
files.delete("Project/Launch.md");
|
||||
await assert.rejects(a.renameBoard("Missing", rename), /available board/);
|
||||
});
|
||||
|
||||
test("board transfers preserve metadata and other memberships in one card write", async () => {
|
||||
const { a, b, all, files, workspace, writes } = fixture();
|
||||
await a.adopt("Task.md");
|
||||
await b.adopt("Task.md");
|
||||
const destination = await a.createBoard("Destination");
|
||||
const target = new TaskStore(workspace, destination);
|
||||
await target.reload();
|
||||
await target.create("Already there", { ...fields, status: "doing" }, "");
|
||||
await a.reload();
|
||||
await a.save(a.tasks.find((task) => task.title === "Task")!, {
|
||||
priority: "high", color: "pink", labels: ["bug"], assignees: ["Ada"],
|
||||
customFields: [{ name: "Customer", value: "Keep" }],
|
||||
});
|
||||
files.set("Task.md", files.get("Task.md")!.replace("runestone_pm:", "owner: Ada # keep\nrunestone_pm:"));
|
||||
await a.reload();
|
||||
const before = a.tasks.find((task) => task.title === "Task")!;
|
||||
writes.length = 0;
|
||||
await a.transferTask(before, destination.id, "doing");
|
||||
assert.deepEqual(writes, [before.path]);
|
||||
assert.equal(a.scopedTasks.length, 0);
|
||||
await target.reload();
|
||||
await b.reload();
|
||||
await all.reload();
|
||||
const saved = target.tasks.find((task) => task.id === before.id)!;
|
||||
const { placements: _oldPlacements, source: _oldSource, ...oldDetails } = before;
|
||||
const { placements: _newPlacements, source: _newSource, ...newDetails } = saved;
|
||||
assert.deepEqual(newDetails, oldDetails);
|
||||
assert.deepEqual(saved.placements![b.board.reference!.id], before.placements![b.board.reference!.id]);
|
||||
assert.equal(Object.hasOwn(saved.placements!, a.board.reference!.id), false);
|
||||
assert.equal(saved.placements![destination.id].listId, "doing");
|
||||
assert.ok(saved.source.includes("owner: Ada # keep"));
|
||||
assert.deepEqual(target.cardsInList("doing").map((task) => task.title), ["Already there", "Task"]);
|
||||
assert.equal(b.scopedTasks.length, 1);
|
||||
assert.equal(all.tasks.filter((task) => task.id === before.id).length, 1);
|
||||
});
|
||||
|
||||
test("hidden cards transfer to existing memberships, custom lists, and Unlisted without copies", async () => {
|
||||
const { a, b, workspace, files } = fixture();
|
||||
await a.reload();
|
||||
await a.create("Private", fields, "");
|
||||
const privateCard = a.scopedTasks[0];
|
||||
assert.ok(privateCard.path.startsWith(".runestone/pm/cards/"));
|
||||
await a.save(privateCard, { placements: {
|
||||
...privateCard.placements,
|
||||
[b.board.reference!.id]: { listId: "todo", order: "a" },
|
||||
} });
|
||||
await b.reload();
|
||||
await b.changeBoard(() => b.board.add("Review", null));
|
||||
const reviewId = b.board.value.lists.at(-1)!.id;
|
||||
const before = a.tasks.find((task) => task.id === privateCard.id)!;
|
||||
const paths = [...files.keys()];
|
||||
await a.transferTask(before, b.board.reference!.id, reviewId);
|
||||
await b.reload();
|
||||
assert.equal(b.scopedTasks.length, 1);
|
||||
assert.equal(b.board.listFor(b.scopedTasks[0])?.id, reviewId);
|
||||
assert.equal(b.scopedTasks[0].body, privateCard.body);
|
||||
assert.deepEqual([...files.keys()], paths);
|
||||
const managed = await b.createBoard("Unlisted destination");
|
||||
await b.transferTask(b.scopedTasks[0], managed.id, null);
|
||||
const target = new TaskStore(workspace, managed);
|
||||
await target.reload();
|
||||
assert.equal(target.scopedTasks.length, 1);
|
||||
assert.equal(target.scopedTasks[0].placements![managed.id].listId, null);
|
||||
assert.equal(target.scopedTasks[0].status, "todo");
|
||||
});
|
||||
|
||||
test("transfers reject missing, duplicated, deleted, and archived destinations without card changes", async () => {
|
||||
for (const condition of ["missing", "duplicate", "deleted", "archived", "list"] as const) {
|
||||
const { a, b, files, workspace, writes } = fixture();
|
||||
await a.adopt("Task.md");
|
||||
const before = a.scopedTasks[0];
|
||||
let destination = b.board.reference!;
|
||||
if (condition === "missing") files.delete(destination.path);
|
||||
if (condition === "duplicate") files.set("Copy.md", files.get(destination.path)!);
|
||||
if (condition === "deleted") {
|
||||
await b.reload();
|
||||
await b.changeBoard(() => b.board.deleteBoard());
|
||||
}
|
||||
if (condition === "archived") {
|
||||
destination = await a.createBoard("Archived");
|
||||
const target = new TaskStore(workspace, destination);
|
||||
await target.reload();
|
||||
await target.changeBoard(() => target.board.manage({ archived: true }));
|
||||
}
|
||||
if (condition === "list") {
|
||||
await b.reload();
|
||||
await b.changeBoard(() => b.board.remove("doing"));
|
||||
}
|
||||
writes.length = 0;
|
||||
await assert.rejects(a.transferTask(before, destination.id, "doing"), /destination/);
|
||||
assert.equal(files.get(before.path), before.source, condition);
|
||||
assert.deepEqual(writes, [], condition);
|
||||
assert.deepEqual(a.scopedTasks[0], before, condition);
|
||||
}
|
||||
});
|
||||
|
||||
test("transfers require a current source membership and active source board", async () => {
|
||||
const { a, b, all, files } = fixture();
|
||||
await all.reload();
|
||||
await assert.rejects(all.transferTask(all.tasks[0], b.board.reference!.id, "todo"), /active board/);
|
||||
await a.reload();
|
||||
await assert.rejects(a.transferTask(a.tasks[0], b.board.reference!.id, "todo"), /no longer belongs/);
|
||||
await a.adopt("Task.md");
|
||||
const before = a.scopedTasks[0];
|
||||
await assert.rejects(a.transferTask(before, a.board.reference!.id, "todo"), /different destination/);
|
||||
files.delete(a.board.reference!.path);
|
||||
await assert.rejects(a.transferTask(before, b.board.reference!.id, "todo"), /active board/);
|
||||
assert.equal(files.get(before.path), before.source);
|
||||
});
|
||||
|
||||
test("stale cards and failed transfer writes preserve every membership", async () => {
|
||||
const { a, b, files, failWrites, writes } = fixture();
|
||||
await a.adopt("Task.md");
|
||||
const stale = a.scopedTasks[0];
|
||||
await b.reload();
|
||||
await b.save(b.tasks[0], { body: "An external edit." });
|
||||
const external = files.get(stale.path);
|
||||
await assert.rejects(a.transferTask(stale, b.board.reference!.id, "done"), /card changed/);
|
||||
assert.equal(files.get(stale.path), external);
|
||||
const current = a.scopedTasks[0];
|
||||
writes.length = 0;
|
||||
failWrites();
|
||||
await assert.rejects(a.transferTask(current, b.board.reference!.id, "done"), /Disk failure/);
|
||||
assert.equal(files.get(current.path), current.source);
|
||||
assert.deepEqual(a.scopedTasks[0], current);
|
||||
assert.deepEqual(writes, []);
|
||||
});
|
||||
|
||||
test("detail board changes save draft fields and membership atomically with stale-write protection", async () => {
|
||||
const { a, b, files, writes, failWrites } = fixture();
|
||||
await a.reload(); await a.adopt("Task.md"); await b.reload();
|
||||
const task = a.tasks[0]; const original = files.get(task.path);
|
||||
writes.length = 0;
|
||||
await a.saveToBoard(task, b.board.reference!.id, "doing", { body: "Draft preserved", priority: "highest" });
|
||||
assert.equal(writes.length, 1);
|
||||
const changed = readTask(task.path, files.get(task.path)!)!;
|
||||
assert.equal(changed.body, "Draft preserved"); assert.equal(changed.priority, "highest");
|
||||
assert.equal(changed.status, "doing"); assert.equal(changed.placements?.[a.board.reference!.id], undefined);
|
||||
assert.equal(changed.placements?.[b.board.reference!.id]?.listId, "doing");
|
||||
await assert.rejects(a.saveToBoard(task, b.board.reference!.id, "todo", { body: "Stale draft" }), /changed/);
|
||||
const saved = files.get(task.path); failWrites();
|
||||
await assert.rejects(b.saveToBoard(changed, a.board.reference!.id, "todo", { body: "Failed draft" }), /Disk failure/);
|
||||
assert.equal(files.get(task.path), saved); assert.notEqual(saved, original);
|
||||
});
|
||||
|
||||
test("pasted relative paths reuse one card and reject paths outside the workspace", async () => {
|
||||
const { a, files } = fixture(); await a.reload();
|
||||
const original = readTask("Task.md", files.get("Task.md")!)!;
|
||||
await a.createOrLink("./Task.md", { ...fields, listId: "doing" });
|
||||
assert.equal(a.tasks.length, 1); assert.equal(a.tasks[0].id, original.id);
|
||||
assert.equal(a.tasks[0].placements?.[a.board.reference!.id]?.listId, "doing");
|
||||
const before = new Map(files);
|
||||
for (const path of ["../Task.md", "D:/Task.md", "/Task.md", "https://example.com/Task.md"])
|
||||
await assert.rejects(a.createOrLink(path, fields), /relative Markdown path/);
|
||||
assert.deepEqual(files, before);
|
||||
});
|
||||
@@ -0,0 +1,187 @@
|
||||
// The main-bundle parts of the native Project Management feature: the catalog entry, the board view pattern of the
|
||||
// session, the settings and their first-start migration, and the board reader of Background and Settings.
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { featureEntry, featureOfOwner } from "../../../../src/lib/features/catalog.ts";
|
||||
import { FeatureSession } from "../../../../src/lib/features/session.ts";
|
||||
import { migrateFeatures, type LegacyPlugin } from "../../../../src/lib/features/migration.ts";
|
||||
import type { FeatureContext, FeatureInstance } from "../../../../src/lib/features/types.ts";
|
||||
import { boardOfView, boardViewId, PLANNING } from "../../../../src/lib/features/pm/views.ts";
|
||||
import { DEFAULT_PROJECT_MANAGEMENT, migrateProjectManagement, normalizeProjectManagement, readViewStates, VIEW_STATES_KEY, writeViewStates, type ProjectManagementMigrationHost, type ProjectManagementSettings } from "../../../../src/lib/features/pmSettings.ts";
|
||||
import { BOARD_CATALOG_PATH, parseBoardCatalog, readBoardCatalog, writeDefaultBoard } from "../../../../src/lib/features/pmBoards.ts";
|
||||
import { SETTINGS_SECTIONS, LEGACY_KEYS } from "../../../../src/lib/settings/store.ts";
|
||||
import { defaultBoard } from "../../../../src/lib/features/pm/storage/board.ts";
|
||||
import { parseCatalog } from "../../../../src/lib/features/pm/storage/catalog.ts";
|
||||
|
||||
function memoryStorage(initial: Record<string, string> = {}) {
|
||||
const values = new Map(Object.entries(initial));
|
||||
return { values, getItem: (key: string) => values.get(key) ?? null, setItem: (key: string, value: string) => { values.set(key, value); } };
|
||||
}
|
||||
|
||||
function context(log: string[] = []): FeatureContext {
|
||||
return {
|
||||
openView: id => { log.push(`open ${id}`); }, openFile: async () => {}, onWorkspaceChange: () => () => {},
|
||||
setViewTitle: (id, title) => { log.push(`title ${id} ${title}`); }, closeView: id => { log.push(`close ${id}`); },
|
||||
replaceView: (current, next) => { log.push(`replace ${current} ${next}`); },
|
||||
};
|
||||
}
|
||||
|
||||
test("Project Management keeps the plugin ID, is on by default, and follows its package", () => {
|
||||
const pm = featureEntry("pm");
|
||||
assert.equal(pm.owner, "runestone.pm");
|
||||
assert.equal(featureOfOwner("runestone.pm")?.id, "pm");
|
||||
assert.equal(pm.defaultOn, true);
|
||||
assert.equal(pm.followsPackage, true);
|
||||
assert.deepEqual(pm.views.map(view => [view.id, view.placement, view.launch]), [["planning", "editor", true]]);
|
||||
assert.deepEqual(pm.documentTypes, [], "The file tree reads no Markdown file for Project Management.");
|
||||
assert.equal((SETTINGS_SECTIONS as readonly string[]).includes("projectManagement"), true);
|
||||
assert.equal(LEGACY_KEYS.projectManagement, "runestone.project-management");
|
||||
});
|
||||
|
||||
test("board view IDs are the plugin IDs, and only valid board IDs match", () => {
|
||||
const id = "0c18bcdc-f41e-4a31-87f4-87c369f398c1";
|
||||
const view = boardViewId(id);
|
||||
assert.equal(view, "board-" + Buffer.from(id).toString("hex"));
|
||||
assert.equal(boardOfView(view), id);
|
||||
assert.equal(boardOfView(boardViewId("Plan ✓")), "Plan ✓");
|
||||
for (const other of [PLANNING, "board-", "board-6", "board-zz", "board-ff", "board-41-42", "graph"]) assert.equal(boardOfView(other), null, other);
|
||||
const pattern = featureEntry("pm").viewPatterns![0].match;
|
||||
assert.equal(pattern.test(view), true);
|
||||
assert.equal(pattern.test(PLANNING), false);
|
||||
assert.equal(pattern.test(view + "x"), false);
|
||||
});
|
||||
|
||||
test("the session answers for board views before the module loads, and gives them the board name later", async () => {
|
||||
let loads = 0;
|
||||
const log: string[] = [];
|
||||
const restored: [string, unknown][] = [];
|
||||
const mounted: string[] = [];
|
||||
const instance: FeatureInstance = {
|
||||
mount: view => { mounted.push(view); return () => {}; },
|
||||
launch: view => { log.push(`launch ${view}`); },
|
||||
restoreTabState: (view, state) => { restored.push([view, state]); },
|
||||
saveTabState: view => ({ view }),
|
||||
dispose() {},
|
||||
};
|
||||
const session = new FeatureSession(featureEntry("pm"), context(log), async () => { loads++; return { start: () => instance }; });
|
||||
const view = boardViewId("board-a");
|
||||
assert.equal(session.views.has(view), false);
|
||||
const pattern = session.patternView(view)!;
|
||||
assert.equal(pattern.placement, "editor");
|
||||
assert.equal(pattern.title, "Project Management");
|
||||
assert.equal(pattern.navigation, false);
|
||||
assert.equal(pattern.launcher, false);
|
||||
assert.equal(session.patternView(view), pattern, "One view for each ID");
|
||||
assert.equal(session.patternView("board-zz"), undefined);
|
||||
assert.equal(loads, 0, "No module load for a pattern view");
|
||||
assert.equal(session.setViewTitle(view, "Roadmap"), true);
|
||||
assert.equal(session.setViewTitle(view, "Roadmap"), false);
|
||||
assert.equal(session.setViewTitle("planning", "Other"), false, "A catalog view keeps its title");
|
||||
assert.equal(pattern.title, "Roadmap");
|
||||
// A tab transfer restores the state, which loads the module.
|
||||
await pattern.restoreTabState!({ search: "x" });
|
||||
assert.deepEqual(restored, [[view, { search: "x" }]]);
|
||||
assert.equal(loads, 1);
|
||||
assert.deepEqual(pattern.saveTabState!(), { view });
|
||||
const element = { replaceChildren() {} } as unknown as HTMLElement;
|
||||
const dispose = await session.mount(boardViewId("board-b"), element);
|
||||
assert.deepEqual(mounted, [boardViewId("board-b")]);
|
||||
await dispose();
|
||||
// The ribbon button launches `planning` through the feature, which chooses the default board.
|
||||
await session.launch("planning");
|
||||
assert.deepEqual(log, ["launch planning"]);
|
||||
await session.stop();
|
||||
assert.equal(session.patternView(boardViewId("board-c")), undefined, "An off feature makes no views");
|
||||
});
|
||||
|
||||
test("the settings keep 2, 3, or 5 priority levels", () => {
|
||||
assert.deepEqual(normalizeProjectManagement(undefined), DEFAULT_PROJECT_MANAGEMENT);
|
||||
assert.deepEqual(normalizeProjectManagement({ priorityLevels: 5, other: 1 }), { priorityLevels: 5 });
|
||||
assert.deepEqual(normalizeProjectManagement({ priorityLevels: 2 }), { priorityLevels: 2 });
|
||||
for (const value of [4, "5", null, 0]) assert.deepEqual(normalizeProjectManagement({ priorityLevels: value }), { priorityLevels: 3 });
|
||||
});
|
||||
|
||||
test("view states stay in localStorage, and a write keeps the states of other tabs", () => {
|
||||
const storage = memoryStorage({ [VIEW_STATES_KEY]: JSON.stringify({ planning: { view: "gantt" } }) });
|
||||
writeViewStates({ "board-61": { search: "bug" } }, storage);
|
||||
assert.deepEqual(readViewStates(storage), { planning: { view: "gantt" }, "board-61": { search: "bug" } });
|
||||
assert.deepEqual(readViewStates(memoryStorage({ [VIEW_STATES_KEY]: "not json" })), {});
|
||||
});
|
||||
|
||||
function pmHost(missing: boolean, storage = memoryStorage()) {
|
||||
const written: ProjectManagementSettings[] = [];
|
||||
const host: ProjectManagementMigrationHost & { written: ProjectManagementSettings[] } = {
|
||||
written, missing: () => missing, storage, write: async value => { written.push(value); },
|
||||
};
|
||||
return host;
|
||||
}
|
||||
|
||||
test("the first start makes the section and the view states from the kept plugin settings", async () => {
|
||||
const legacy: LegacyPlugin = { id: "runestone.pm", installed: true, enabled: true, settings: { priorityLevels: 5, viewStates: { planning: { view: "calendar" } }, other: true } };
|
||||
const host = pmHost(true);
|
||||
assert.deepEqual(await migrateProjectManagement(legacy, host), { priorityLevels: 5 });
|
||||
assert.deepEqual(host.written, [{ priorityLevels: 5 }]);
|
||||
assert.deepEqual(JSON.parse(host.storage.getItem(VIEW_STATES_KEY)!), { planning: { view: "calendar" } });
|
||||
// Existing view states in localStorage stay.
|
||||
const kept = pmHost(true, memoryStorage({ [VIEW_STATES_KEY]: "{\"planning\":{}}" }));
|
||||
await migrateProjectManagement(legacy, kept);
|
||||
assert.equal(kept.storage.getItem(VIEW_STATES_KEY), "{\"planning\":{}}");
|
||||
// Without plugin settings, the defaults apply. A present section stays.
|
||||
const fresh = pmHost(true);
|
||||
assert.deepEqual(await migrateProjectManagement(undefined, fresh), DEFAULT_PROJECT_MANAGEMENT);
|
||||
assert.equal(fresh.storage.getItem(VIEW_STATES_KEY), null);
|
||||
const present = pmHost(false);
|
||||
assert.equal(await migrateProjectManagement(legacy, present), null);
|
||||
assert.deepEqual(present.written, []);
|
||||
});
|
||||
|
||||
test("the feature migration asks for the Project Management package when the section is missing", async () => {
|
||||
const asked: string[][] = [];
|
||||
const switches: unknown[] = [];
|
||||
const host = { read: () => ({ git: true, background: true, terminal: true, pdf: true }), write: async (value: unknown) => { switches.push(value); },
|
||||
legacy: async (ids: string[]) => { asked.push(ids); return ids.map(id => ({ id, installed: true, enabled: false, settings: { priorityLevels: 2 } })); } };
|
||||
const background = { missing: () => false, hasImage: () => false, migrateFolder: async () => false, write: async () => {} };
|
||||
const terminal = { missing: () => false, legacy: () => null, write: async () => {} };
|
||||
const pm = pmHost(true);
|
||||
assert.deepEqual(await migrateFeatures(host, background, terminal, pm), ["pm"]);
|
||||
assert.deepEqual(asked, [["runestone.pm"]]);
|
||||
assert.deepEqual(switches, [{ git: true, background: true, terminal: true, pdf: true, pm: false }], "The switch follows the disabled package.");
|
||||
assert.deepEqual(pm.written, [{ priorityLevels: 2 }]);
|
||||
});
|
||||
|
||||
test("the board reader lists the boards of workspace.json without the feature code", async () => {
|
||||
const value = {
|
||||
schema: 1, defaultBoardId: "b", defaultBoardPath: "pm-board:b", future: { keep: true },
|
||||
boards: [{ name: "Roadmap", value: defaultBoard("a") }, { name: "Bugs", value: defaultBoard("b"), archived: true }, { name: "Copy", value: defaultBoard("a") }, { name: "No value" }],
|
||||
};
|
||||
const source = JSON.stringify(value);
|
||||
assert.deepEqual(parseBoardCatalog(source), { source, defaultBoardId: "b", boards: [{ id: "a", name: "Roadmap", archived: false }, { id: "b", name: "Bugs", archived: true }] });
|
||||
assert.deepEqual(parseBoardCatalog(null), { boards: [], defaultBoardId: null, source: null });
|
||||
assert.throws(() => parseBoardCatalog("{\"schema\":2,\"boards\":[]}"), /unsupported/);
|
||||
const reads: string[] = [];
|
||||
const catalog = await readBoardCatalog(async path => { reads.push(path); return source; });
|
||||
assert.deepEqual(reads, [BOARD_CATALOG_PATH]);
|
||||
assert.deepEqual(catalog.boards.map(board => board.id), ["a", "b"]);
|
||||
});
|
||||
|
||||
test("Settings saves the default board with a guarded write and keeps the other keys", async () => {
|
||||
const files = new Map([[BOARD_CATALOG_PATH, JSON.stringify({ schema: 1, boards: [{ name: "Roadmap", value: defaultBoard("a") }], future: 1 }, null, 2) + "\n"]]);
|
||||
const read = async (path: string) => files.get(path) ?? null;
|
||||
const write = async (path: string, contents: string, expected: string) => {
|
||||
if (files.get(path) !== expected) throw new Error("The file changed.");
|
||||
files.set(path, contents);
|
||||
};
|
||||
await writeDefaultBoard("a", read, write);
|
||||
const saved = JSON.parse(files.get(BOARD_CATALOG_PATH)!);
|
||||
assert.equal(saved.defaultBoardId, "a");
|
||||
assert.equal(saved.defaultBoardPath, "pm-board:a");
|
||||
assert.equal(saved.future, 1);
|
||||
// The feature code accepts the file.
|
||||
assert.equal(parseCatalog(files.get(BOARD_CATALOG_PATH)!).defaultBoardId, "a");
|
||||
await writeDefaultBoard(null, read, write);
|
||||
assert.equal(JSON.parse(files.get(BOARD_CATALOG_PATH)!).defaultBoardId, null);
|
||||
await assert.rejects(writeDefaultBoard("missing", read, write), /unavailable/);
|
||||
await assert.rejects(writeDefaultBoard("a", read, async () => { throw new Error("The file changed."); }), /changed/);
|
||||
// Without a catalog, All tasks needs no write.
|
||||
await writeDefaultBoard(null, async () => null, async () => { throw new Error("no write"); });
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { newTask, readTask, editTask, adoptNote } from "../../../../src/lib/features/pm/storage/notes.ts";
|
||||
import { DescriptionDraft } from "../../../../src/lib/features/pm/storage/description-draft.ts";
|
||||
import { defaultBoardPath } from "../../../../src/lib/features/pm/model/workspace-default.ts";
|
||||
import { defaultBoard } from "../../../../src/lib/features/pm/storage/board.ts";
|
||||
import { catalogPath, boardMarkdown } from "../../../../src/lib/features/pm/storage/catalog.ts";
|
||||
import type { Workspace } from "../../../../src/lib/features/pm/model/model.ts";
|
||||
|
||||
function fixture() {
|
||||
const files = new Map<string, string>();
|
||||
const workspace: Workspace = {
|
||||
async list() { throw new Error("No task scan expected"); },
|
||||
async read(path) { if (!files.has(path)) throw new Error("Missing"); return files.get(path)!; },
|
||||
async readOptional(path) { return files.get(path) ?? null; },
|
||||
async create(path, source) { if (files.has(path)) throw new Error("Exists"); files.set(path, source); },
|
||||
async write(path, source, expected) { if (files.get(path) !== expected) throw new Error("Conflict"); files.set(path, source); },
|
||||
};
|
||||
return { files, workspace };
|
||||
}
|
||||
const fields = { status: "todo" as const, tags: [], sessions: [], archived: false };
|
||||
test("new captures record immutable timestamps and existing legacy cards keep an unknown date", () => {
|
||||
const before = Date.now();
|
||||
const note = newTask("Timestamp", fields);
|
||||
const task = readTask(note.path, note.source)!;
|
||||
assert.ok(Date.parse(task.createdAt!) >= before && Date.parse(task.createdAt!) <= Date.now());
|
||||
const edited = readTask(task.path, editTask(task, { body: "Updated", status: "done", placements: { next: { listId: "done" } } }))!;
|
||||
assert.equal(edited.createdAt, task.createdAt);
|
||||
assert.throws(() => editTask(task, { createdAt: undefined }), /cannot change/);
|
||||
assert.throws(() => editTask(task, { createdAt: "2026-01-01T00:00:00Z" }), /cannot change/);
|
||||
assert.ok(Date.parse(readTask("Old.md", adoptNote("Old.md", "Original note"))!.createdAt!) >= before);
|
||||
const legacy = readTask(note.path, note.source.replace(/^ createdAt:.*\n/m, ""))!;
|
||||
assert.equal(readTask(legacy.path, editTask(legacy, { title: "Legacy edit" }))!.createdAt, undefined);
|
||||
assert.equal(adoptNote(legacy.path, legacy.source), legacy.source);
|
||||
});
|
||||
test("description drafts persist separately, cancel clears them, and stale writers cannot overwrite drafts", async () => {
|
||||
const { files, workspace } = fixture();
|
||||
const draft = new DescriptionDraft(workspace, "task");
|
||||
assert.equal(await draft.load(), null);
|
||||
await draft.save("Uncommitted text");
|
||||
const other = new DescriptionDraft(workspace, "task");
|
||||
assert.equal(await other.load(), "Uncommitted text");
|
||||
await draft.save("Newer draft");
|
||||
await assert.rejects(other.save("Stale draft"), /Conflict/);
|
||||
await draft.save(null);
|
||||
assert.equal(await new DescriptionDraft(workspace, "task").load(), null);
|
||||
assert.ok([...files.keys()].every(path => !path.includes("/cards/")));
|
||||
});
|
||||
test("default board resolves without scanning cards and keeps unavailable selections fixed", async () => {
|
||||
const { files, workspace } = fixture();
|
||||
const board = defaultBoard("chosen");
|
||||
const catalog = { schema: 1, boards: [{ name: "Chosen", value: board }], defaultBoardId: "chosen", unknown: "keep" };
|
||||
files.set(catalogPath, JSON.stringify(catalog));
|
||||
assert.equal(await defaultBoardPath(workspace), "pm-board:chosen");
|
||||
files.set(catalogPath, JSON.stringify({ ...catalog, boards: [] }));
|
||||
assert.equal(await defaultBoardPath(workspace), undefined);
|
||||
assert.equal(JSON.parse(files.get(catalogPath)!).defaultBoardId, "chosen");
|
||||
files.set("Legacy.md", boardMarkdown(board));
|
||||
files.set(catalogPath, JSON.stringify({ ...catalog, boards: [], defaultBoardPath: "Legacy.md" }));
|
||||
assert.equal(await defaultBoardPath(workspace), "Legacy.md");
|
||||
files.set(catalogPath, JSON.stringify({ ...catalog, boards: [], defaultBoardPath: "Legacy.md", deletedBoardIds: ["chosen"] }));
|
||||
assert.equal(await defaultBoardPath(workspace), undefined);
|
||||
});
|
||||
@@ -0,0 +1,142 @@
|
||||
// The hidden mode of the store (`legacy: false`): it reads only `.runestone/pm/`, and a save, a delete, a move,
|
||||
// or a watcher event reads only the changed files again.
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
|
||||
import { cardPath } from "../../../../src/lib/features/pm/storage/cards.ts";
|
||||
import { catalogPath } from "../../../../src/lib/features/pm/storage/catalog.ts";
|
||||
import { deletedCardsPath } from "../../../../src/lib/features/pm/storage/deleted-cards.ts";
|
||||
import { labelsPath } from "../../../../src/lib/features/pm/storage/labels.ts";
|
||||
import { editTask, newTask } from "../../../../src/lib/features/pm/storage/notes.ts";
|
||||
import { newBoardSource } from "../../../../src/lib/features/pm/storage/board.ts";
|
||||
import { privateRulesPath } from "../../../../src/lib/features/pm/storage/persistence.ts";
|
||||
import { fields, hiddenWorkspace } from "./_memory.ts";
|
||||
|
||||
const cards = [{ id: "a", title: "Card A" }, { id: "b", title: "Card B" }, { id: "c", title: "Card C" }];
|
||||
|
||||
test("the hidden mode reads only .runestone/pm and never a visible Markdown note", async () => {
|
||||
const workspace = hiddenWorkspace(cards, {
|
||||
"Notes/Task.md": newTask("Task", fields(), "", "visible").source,
|
||||
"Board.md": newBoardSource(),
|
||||
});
|
||||
const store = new TaskStore(workspace, { id: "board", path: "pm-board:board" }, { legacy: false });
|
||||
await store.reload();
|
||||
assert.equal(store.legacy, false);
|
||||
assert.deepEqual(store.issues, []);
|
||||
assert.deepEqual(store.tasks.map(task => task.id), ["a", "b", "c"]);
|
||||
assert.deepEqual(store.boards.map(board => board.id), ["board"]);
|
||||
assert.equal(workspace.markdownLists, 0);
|
||||
assert.ok(workspace.reads.every(path => path.startsWith(".runestone/pm/") || path === "runestone-pm-labels.json"), workspace.reads.join(", "));
|
||||
assert.equal(workspace.reads.some(path => path.endsWith(".md") && !path.startsWith(".runestone/")), false);
|
||||
// The legacy mode, for the migration and the skill helper, still reads the visible notes.
|
||||
const legacy = new TaskStore(workspace);
|
||||
await legacy.reload();
|
||||
assert.equal(legacy.legacy, true);
|
||||
assert.ok(legacy.tasks.some(task => task.id === "visible"));
|
||||
});
|
||||
|
||||
test("a save, a move, and a delete read only the changed card again", async () => {
|
||||
const workspace = hiddenWorkspace(cards);
|
||||
const store = new TaskStore(workspace, { id: "board", path: "pm-board:board" }, { legacy: false });
|
||||
await store.reload();
|
||||
const card = (id: string) => store.tasks.find(task => task.id === id)!;
|
||||
// Each write also checks the Git exclusion file of `.runestone/pm/`. It is not a reload.
|
||||
const reads = () => workspace.reads.filter(path => path !== privateRulesPath);
|
||||
|
||||
workspace.reads.length = 0;
|
||||
await store.save(card("a"), { body: "Changed" });
|
||||
assert.deepEqual(reads(), [cardPath("a")]);
|
||||
assert.equal(card("a").body, "Changed");
|
||||
|
||||
workspace.reads.length = 0;
|
||||
await store.moveTask(card("b"), "doing");
|
||||
assert.deepEqual(reads(), [cardPath("b")]);
|
||||
assert.equal(card("b").placements!.board.listId, "doing");
|
||||
assert.equal(card("b").status, "doing");
|
||||
|
||||
workspace.reads.length = 0;
|
||||
await store.deleteCard(card("c"));
|
||||
assert.deepEqual(reads().filter(path => path !== deletedCardsPath), [cardPath("c")]);
|
||||
assert.deepEqual(store.tasks.map(task => task.id), ["a", "b"]);
|
||||
assert.match(workspace.files.get(deletedCardsPath)!, /"c"/);
|
||||
});
|
||||
|
||||
test("a save still stops when another window changed the card", async () => {
|
||||
const workspace = hiddenWorkspace(cards);
|
||||
const store = new TaskStore(workspace, undefined, { legacy: false });
|
||||
await store.reload();
|
||||
const card = store.tasks.find(task => task.id === "a")!;
|
||||
workspace.files.set(cardPath("a"), editTask(card, { body: "Other window" }));
|
||||
await assert.rejects(store.save(card, { body: "This window" }), /changed/);
|
||||
assert.equal(store.tasks.find(task => task.id === "a")!.body, "Other window");
|
||||
});
|
||||
|
||||
test("watcher paths read only the changed files of .runestone/pm", async () => {
|
||||
const workspace = hiddenWorkspace(cards);
|
||||
const store = new TaskStore(workspace, { id: "board", path: "pm-board:board" }, { legacy: false });
|
||||
await store.reload();
|
||||
|
||||
// A change outside `.runestone/pm/`, or of images and drafts, reads nothing.
|
||||
workspace.reads.length = 0; workspace.lists.length = 0;
|
||||
await store.reloadPaths(["Notes/Plan.md", ".runestone/pm/images/x.json", ".runestone/pm/drafts/61.json", ".runestone/tabs.json"]);
|
||||
assert.deepEqual(workspace.reads, []);
|
||||
assert.deepEqual(workspace.lists, []);
|
||||
|
||||
// A new card from another window.
|
||||
workspace.files.set(cardPath("d"), newTask("Card D", fields({ title: "Card D", placements: { board: { listId: "done" } } }), "", "d").source);
|
||||
workspace.reads.length = 0;
|
||||
await store.reloadPaths([cardPath("d")]);
|
||||
assert.deepEqual(workspace.reads, [cardPath("d")]);
|
||||
assert.deepEqual(store.tasks.map(task => task.id), ["a", "b", "c", "d"]);
|
||||
|
||||
// A deleted card file.
|
||||
workspace.files.delete(cardPath("b"));
|
||||
workspace.reads.length = 0;
|
||||
await store.reloadPaths([cardPath("b")]);
|
||||
assert.deepEqual(workspace.reads, [cardPath("b"), cardPath("b")]);
|
||||
assert.deepEqual(store.tasks.map(task => task.id), ["a", "c", "d"]);
|
||||
|
||||
// A renamed board reads only the catalog.
|
||||
const catalog = JSON.parse(workspace.files.get(catalogPath)!);
|
||||
catalog.boards[0].name = "Renamed";
|
||||
workspace.files.set(catalogPath, JSON.stringify(catalog));
|
||||
workspace.reads.length = 0;
|
||||
await store.reloadPaths([catalogPath]);
|
||||
assert.deepEqual(workspace.reads, [catalogPath]);
|
||||
assert.equal(store.board.name, "Renamed");
|
||||
|
||||
// Labels and deleted cards each read their own file.
|
||||
workspace.files.set(labelsPath, JSON.stringify({ schema: 1, labels: [{ id: "x", name: "X", color: "red" }] }));
|
||||
workspace.files.set(deletedCardsPath, JSON.stringify({ schema: 1, ids: ["d"] }));
|
||||
workspace.reads.length = 0;
|
||||
await store.reloadPaths([labelsPath, deletedCardsPath]);
|
||||
assert.deepEqual(workspace.reads.sort(), [deletedCardsPath, labelsPath].sort());
|
||||
assert.deepEqual(store.labels.value.map(label => label.id), ["x"]);
|
||||
assert.deepEqual(store.tasks.map(task => task.id), ["a", "c"]);
|
||||
});
|
||||
|
||||
test("an invalid card from a watcher event hides all cards until it is valid again", async () => {
|
||||
const workspace = hiddenWorkspace(cards);
|
||||
const store = new TaskStore(workspace, undefined, { legacy: false });
|
||||
await store.reload();
|
||||
const valid = workspace.files.get(cardPath("a"))!;
|
||||
workspace.files.set(cardPath("a"), "---\nrunestone_pm: [\n---\n");
|
||||
await store.reloadPaths([cardPath("a")]);
|
||||
assert.deepEqual(store.tasks, []);
|
||||
assert.match(store.issues.join(" "), /\.runestone\/pm\/cards\/61\.md/);
|
||||
workspace.files.set(cardPath("a"), valid);
|
||||
await store.reloadPaths([cardPath("a")]);
|
||||
assert.deepEqual(store.issues, []);
|
||||
assert.equal(store.tasks.length, 3);
|
||||
});
|
||||
|
||||
test("a folder change, a marker change, or an unknown change reads everything again", async () => {
|
||||
const workspace = hiddenWorkspace(cards);
|
||||
const store = new TaskStore(workspace, undefined, { legacy: false });
|
||||
await store.reload();
|
||||
for (const paths of [[".runestone/pm/cards"], [".runestone/pm/cards/.gitignore"], [".runestone"], undefined]) {
|
||||
workspace.lists.length = 0;
|
||||
await store.reloadPaths(paths);
|
||||
assert.deepEqual(workspace.lists, [".runestone/pm/cards"], String(paths));
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,278 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
mkdtemp,
|
||||
readFile,
|
||||
writeFile,
|
||||
mkdir,
|
||||
readdir,
|
||||
rm,
|
||||
} from "node:fs/promises";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { tmpdir } from "node:os";
|
||||
import { resolve, join, dirname } from "node:path";
|
||||
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
|
||||
import { newTask, readTask, editTask } from "../../../../src/lib/features/pm/storage/notes.ts";
|
||||
import { cardPath } from "../../../../src/lib/features/pm/storage/cards.ts";
|
||||
import { cardOrder } from "../../../../src/lib/features/pm/storage/order.ts";
|
||||
import {
|
||||
privateRulesPath,
|
||||
cardsMarker,
|
||||
isHiddenCard,
|
||||
} from "../../../../src/lib/features/pm/storage/persistence.ts";
|
||||
import { catalogPath } from "../../../../src/lib/features/pm/storage/catalog.ts";
|
||||
import { defaultLabels, labelsPath } from "../../../../src/lib/features/pm/storage/labels.ts";
|
||||
import type { Workspace, TaskFields } from "../../../../src/lib/features/pm/model/model.ts";
|
||||
|
||||
const fields: TaskFields = {
|
||||
status: "todo",
|
||||
tags: ["keep"],
|
||||
labels: ["bug"],
|
||||
archived: false,
|
||||
sessions: [],
|
||||
due: { date: "2026-10-30" },
|
||||
plan: { start: "2026-10-07", end: "2026-10-10" },
|
||||
placements: { board: { listId: "todo" } },
|
||||
};
|
||||
async function fixture(t: test.TestContext) {
|
||||
const root = await mkdtemp(join(tmpdir(), "runestone-pm-private-"));
|
||||
t.after(async () => {
|
||||
assert.ok(
|
||||
resolve(root).startsWith(resolve(tmpdir(), "runestone-pm-private-")),
|
||||
);
|
||||
await rm(root, { recursive: true, force: true });
|
||||
});
|
||||
const file = (path: string) => {
|
||||
const absolute = resolve(root, path);
|
||||
assert.ok(
|
||||
absolute === root ||
|
||||
absolute.startsWith(root + "/") ||
|
||||
absolute.startsWith(root + "\\"),
|
||||
);
|
||||
return absolute;
|
||||
};
|
||||
const workspace: Workspace = {
|
||||
async readOptional(path) {
|
||||
try {
|
||||
return await readFile(file(path), "utf8");
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
async read(path) {
|
||||
return readFile(file(path), "utf8");
|
||||
},
|
||||
async list(path = "") {
|
||||
return (await readdir(file(path), { withFileTypes: true }))
|
||||
.filter((entry) => ![".git", ".runestone"].includes(entry.name))
|
||||
.map((entry) => ({
|
||||
name: entry.name,
|
||||
rel_path: (path ? path + "/" : "") + entry.name,
|
||||
kind: entry.isDirectory() ? "folder" : "file",
|
||||
}));
|
||||
},
|
||||
async create(path, source) {
|
||||
await mkdir(dirname(file(path)), { recursive: true });
|
||||
await writeFile(file(path), source, { flag: "wx" });
|
||||
},
|
||||
async write(path, source, expected) {
|
||||
assert.equal(await workspace.read(path), expected, "Changed on disk");
|
||||
await writeFile(file(path), source);
|
||||
},
|
||||
};
|
||||
const git = (...args: string[]) =>
|
||||
execFileSync("git", args, {
|
||||
cwd: root,
|
||||
encoding: "utf8",
|
||||
windowsHide: true,
|
||||
}).trim();
|
||||
return { root, file, workspace, git, store: new TaskStore(workspace) };
|
||||
}
|
||||
|
||||
test("new cards and other Project Management data stay outside navigation and normal Git staging", async (t) => {
|
||||
const { store, workspace, git } = await fixture(t);
|
||||
git("init", "--quiet");
|
||||
await workspace.create!("README.md", "Shared project\n");
|
||||
await store.createBoard("Board");
|
||||
await store.create("Card: / duplicate?", fields, "Private details");
|
||||
await store.create("Card: / duplicate?", fields, "Second card");
|
||||
await store.saveLabels(defaultLabels(), store.labels.source);
|
||||
await store.reload();
|
||||
assert.equal(store.tasks.length, 2);
|
||||
assert.equal(new Set(store.tasks.map((task) => task.id)).size, 2);
|
||||
assert.ok(store.tasks.every((task) => isHiddenCard(task.path)));
|
||||
assert.deepEqual(
|
||||
(await workspace.list()).map((entry) => entry.name),
|
||||
["README.md"],
|
||||
);
|
||||
assert.equal(await workspace.readOptional!(".gitignore"), null);
|
||||
for (const path of [
|
||||
catalogPath,
|
||||
labelsPath,
|
||||
privateRulesPath,
|
||||
cardsMarker,
|
||||
...store.tasks.map((task) => task.path),
|
||||
])
|
||||
assert.equal(git("check-ignore", "--", path), path);
|
||||
git("add", ".");
|
||||
assert.equal(git("ls-files"), "README.md");
|
||||
});
|
||||
|
||||
test("Git protection is installed before data writes and failures preserve privacy", async (t) => {
|
||||
const { store, workspace } = await fixture(t);
|
||||
const create = workspace.create!;
|
||||
const writes: string[] = [];
|
||||
workspace.create = async (path, source) => {
|
||||
writes.push(path);
|
||||
if (path === privateRulesPath)
|
||||
throw new Error("Cannot create Git exclusion");
|
||||
await create(path, source);
|
||||
};
|
||||
await assert.rejects(store.create("Private", fields, ""), /Git exclusion/);
|
||||
assert.deepEqual(writes, [privateRulesPath]);
|
||||
workspace.create = async (path, source) => {
|
||||
writes.push(path);
|
||||
await create(path, source);
|
||||
};
|
||||
writes.length = 0;
|
||||
await store.create("Private", fields, "");
|
||||
assert.deepEqual(writes, [
|
||||
privateRulesPath,
|
||||
cardsMarker,
|
||||
store.tasks[0].path,
|
||||
]);
|
||||
});
|
||||
|
||||
test("selected legacy cards migrate with exact backups, stable order, and no changes to linked notes", async (t) => {
|
||||
const { store, workspace, file, git } = await fixture(t);
|
||||
git("init", "--quiet");
|
||||
const original = newTask("Existing", fields, "Preserve **body**.\n");
|
||||
const source = original.source.replace("---\n", "---\nowner: Ada # retain\n");
|
||||
await workspace.create!(original.path, source);
|
||||
const linked = newTask("Shared", fields, "Keep as a note");
|
||||
await workspace.create!("Docs/Shared.md", linked.source);
|
||||
git("add", ".");
|
||||
await store.reload();
|
||||
const before = store.tasks.find((task) => task.title === "Existing")!;
|
||||
const stale = new TaskStore(workspace);
|
||||
await stale.reload();
|
||||
const report = await store.migrateStorage([before.id]);
|
||||
assert.equal(report.length, 1);
|
||||
const current = store.tasks.find((task) => task.id === before.id)!;
|
||||
assert.equal(current.path, cardPath(before.id));
|
||||
assert.equal(current.title, before.title);
|
||||
assert.equal(current.body, before.body);
|
||||
for (const key of [
|
||||
"status",
|
||||
"tags",
|
||||
"labels",
|
||||
"due",
|
||||
"plan",
|
||||
"sessions",
|
||||
"archived",
|
||||
] as const)
|
||||
assert.deepEqual(current[key], before[key]);
|
||||
assert.equal(cardOrder(current, "board"), cardOrder(before, "board"));
|
||||
assert.equal(cardOrder(current), cardOrder(before));
|
||||
assert.equal(await workspace.read(original.path), source);
|
||||
assert.equal(await workspace.read(report[0].backup), source);
|
||||
assert.equal(await workspace.read("Docs/Shared.md"), linked.source);
|
||||
assert.match(current.source, /owner: Ada # retain/);
|
||||
await assert.rejects(stale.save(before, { status: "done" }), /changed/);
|
||||
await store.save(current, { title: "Private: edited", status: "doing" });
|
||||
await store.migrateStorage([before.id]);
|
||||
assert.equal(
|
||||
store.tasks.find((task) => task.id === before.id)!.title,
|
||||
"Private: edited",
|
||||
);
|
||||
await rm(file(original.path));
|
||||
await store.reload();
|
||||
assert.equal(store.tasks.length, 2);
|
||||
assert.equal(
|
||||
store.tasks.find((task) => task.id === before.id)!.status,
|
||||
"doing",
|
||||
);
|
||||
git("add", "-A");
|
||||
assert.equal(git("ls-files"), "Docs/Shared.md");
|
||||
});
|
||||
|
||||
test("partial card migration resumes without replacing newer hidden edits", async (t) => {
|
||||
const { workspace, store } = await fixture(t);
|
||||
for (const title of ["A", "B"]) {
|
||||
const note = newTask(title, fields);
|
||||
await workspace.create!(note.path, note.source);
|
||||
}
|
||||
await store.reload();
|
||||
const ids = store.tasks.map((task) => task.id);
|
||||
const blocked = cardPath(ids[1]);
|
||||
const create = workspace.create!;
|
||||
workspace.create = async (path, source) => {
|
||||
if (path === blocked) throw new Error("Disk full");
|
||||
await create(path, source);
|
||||
};
|
||||
await assert.rejects(store.migrateStorage(ids), /Disk full/);
|
||||
await store.reload();
|
||||
assert.equal(store.tasks.length, 2);
|
||||
const first = store.tasks.find((task) => task.id === ids[0])!;
|
||||
await store.save(first, { body: "Later edit" });
|
||||
workspace.create = create;
|
||||
await store.migrateStorage(ids);
|
||||
assert.ok(store.tasks.every((task) => isHiddenCard(task.path)));
|
||||
assert.equal(
|
||||
store.tasks.find((task) => task.id === ids[0])!.body,
|
||||
"Later edit",
|
||||
);
|
||||
});
|
||||
|
||||
test("changed originals block further migration and stale saves without losing either version", async (t) => {
|
||||
const { workspace, store } = await fixture(t);
|
||||
const note = newTask("A", fields);
|
||||
await workspace.create!(note.path, note.source);
|
||||
await store.reload();
|
||||
const id = store.tasks[0].id;
|
||||
await store.migrateStorage([id]);
|
||||
const hidden = store.tasks[0];
|
||||
await workspace.write(
|
||||
note.path,
|
||||
editTask(readTask(note.path, note.source)!, { body: "Outside edit" }),
|
||||
note.source,
|
||||
);
|
||||
await assert.rejects(store.save(hidden, { status: "done" }), /changed/);
|
||||
await assert.rejects(store.migrateStorage(), /issues/);
|
||||
assert.equal(await workspace.read(hidden.path), hidden.source);
|
||||
});
|
||||
|
||||
test("migration retains long filename titles and an existing Project Management ignore file", async (t) => {
|
||||
const { workspace, store } = await fixture(t);
|
||||
const note = newTask("A", fields);
|
||||
const path = "Legacy/" + "a".repeat(130) + ".md";
|
||||
await workspace.create!(path, note.source);
|
||||
await workspace.create!(
|
||||
privateRulesPath,
|
||||
"# Personal rules\ncache/\n!keep.json\n",
|
||||
);
|
||||
await store.reload();
|
||||
await store.migrateStorage([store.tasks[0].id]);
|
||||
assert.equal(store.tasks[0].title, "a".repeat(130));
|
||||
assert.equal(
|
||||
await workspace.read(privateRulesPath),
|
||||
"# Personal rules\ncache/\n!keep.json\n# RuneStone Project Management local data\n*\n",
|
||||
);
|
||||
});
|
||||
|
||||
test("an invalid hidden card cannot fall back to editing its old visible note", async (t) => {
|
||||
const { workspace, store } = await fixture(t);
|
||||
const note = newTask("A", fields);
|
||||
await workspace.create!(note.path, note.source);
|
||||
await store.reload();
|
||||
const legacy = store.tasks[0];
|
||||
await store.migrateStorage([legacy.id]);
|
||||
const hidden = store.tasks[0];
|
||||
await workspace.write(hidden.path, "broken data", hidden.source);
|
||||
await store.reload();
|
||||
assert.equal(store.tasks.length, 0);
|
||||
assert.match(store.issues.join(" "), /hidden card ID/);
|
||||
await assert.rejects(store.save(legacy, { status: "done" }), /changed/);
|
||||
assert.equal(await workspace.read(note.path), note.source);
|
||||
});
|
||||
@@ -0,0 +1,195 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
|
||||
import { cardPath } from "../../../../src/lib/features/pm/storage/cards.ts";
|
||||
import { newTask, editTask } from "../../../../src/lib/features/pm/storage/notes.ts";
|
||||
import { newBoardSource, parseBoard } from "../../../../src/lib/features/pm/storage/board.ts";
|
||||
import { cardsMarker, privateRulesPath } from "../../../../src/lib/features/pm/storage/persistence.ts";
|
||||
import { mapConcurrent, scanConcurrency } from "../../../../src/lib/features/pm/storage/scan.ts";
|
||||
import type { Workspace } from "../../../../src/lib/features/pm/model/model.ts";
|
||||
|
||||
test("native discovery avoids directory bridge calls and retains save conflicts", async () => {
|
||||
const boardSource = newBoardSource();
|
||||
const boardId = parseBoard(boardSource).id;
|
||||
const id = crypto.randomUUID();
|
||||
const taskPath = cardPath(id);
|
||||
const original = newTask(id, {
|
||||
title: "Latency card", status: "todo", tags: [], sessions: [], archived: false,
|
||||
placements: { [boardId]: { listId: "todo" } },
|
||||
}, "Original details", id).source;
|
||||
const files = new Map([["Board.md", boardSource], [taskPath, original], [cardsMarker, "*\n"], [privateRulesPath, "*\n"]]);
|
||||
let scans = 0, lists = 0, writes = 0;
|
||||
let scanFailure = false;
|
||||
const workspace: Workspace = {
|
||||
async listMarkdown() {
|
||||
scans++;
|
||||
if (scanFailure) throw new Error("Directory unavailable");
|
||||
return [...files.keys()].filter(path => !path.startsWith(".") && path.endsWith(".md"));
|
||||
},
|
||||
async list(path) {
|
||||
lists++;
|
||||
assert.equal(path, ".runestone/pm/cards", "Visible folders must use the native listing");
|
||||
return [{ name: taskPath.split("/").at(-1)!, rel_path: taskPath, kind: "file" }];
|
||||
},
|
||||
async read(path) { const value = files.get(path); assert.notEqual(value, undefined); return value!; },
|
||||
async readOptional(path) { return files.get(path) ?? null; },
|
||||
async create() { throw new Error("Unexpected create"); },
|
||||
async write(path, source, expected) { assert.equal(files.get(path), expected); writes++; files.set(path, source); },
|
||||
};
|
||||
const store = new TaskStore(workspace, { id: boardId, path: "Board.md" });
|
||||
await store.reload();
|
||||
await store.moveTask(store.tasks[0], "doing");
|
||||
await store.save(store.tasks[0], { body: "Updated details" });
|
||||
assert.equal(scans, 3);
|
||||
assert.equal(lists, 3);
|
||||
assert.equal(writes, 2);
|
||||
const stale = store.tasks[0];
|
||||
const external = editTask(stale, { body: "External details" });
|
||||
files.set(taskPath, external);
|
||||
await assert.rejects(store.save(stale, { body: "Stale details" }), /changed/);
|
||||
const current = store.tasks[0];
|
||||
files.set("Copy.md", current.source);
|
||||
await assert.rejects(store.moveTask(current, "done"), /duplicate/);
|
||||
files.delete("Copy.md");
|
||||
await store.reload();
|
||||
scanFailure = true;
|
||||
await assert.rejects(store.save(store.tasks[0], { body: "Blocked details" }), /Directory unavailable/);
|
||||
assert.equal(files.get(taskPath), external);
|
||||
assert.equal(writes, 2);
|
||||
});
|
||||
|
||||
test("load, move, and detail saves overlap bounded reads without weakening conflict checks", async (t) => {
|
||||
const source = newBoardSource();
|
||||
const boardId = parseBoard(source).id;
|
||||
const files = new Map([
|
||||
["Board.md", source],
|
||||
[cardsMarker, "*\n"],
|
||||
[privateRulesPath, "*\n"],
|
||||
]);
|
||||
for (let index = 0; index < 32; index++) {
|
||||
files.set(`Notes${index % 4}/Note${index}.md`, "An ordinary note.");
|
||||
const id = crypto.randomUUID();
|
||||
files.set(
|
||||
cardPath(id),
|
||||
newTask(
|
||||
id,
|
||||
{
|
||||
title: `Card ${index}`,
|
||||
status: "todo",
|
||||
tags: [],
|
||||
sessions: [],
|
||||
archived: false,
|
||||
placements: { [boardId]: { listId: "todo" } },
|
||||
},
|
||||
"Original details",
|
||||
id,
|
||||
).source,
|
||||
);
|
||||
}
|
||||
let active = 0,
|
||||
peak = 0,
|
||||
reads = 0;
|
||||
const readDelay = 15;
|
||||
const workspace: Workspace = {
|
||||
async list(parent = "") {
|
||||
const entries = new Map();
|
||||
const prefix = parent ? `${parent}/` : "";
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix)) continue;
|
||||
const parts = path.slice(prefix.length).split("/");
|
||||
entries.set(parts[0], {
|
||||
name: parts[0],
|
||||
rel_path: prefix + parts[0],
|
||||
kind: parts.length > 1 ? "folder" : "file",
|
||||
});
|
||||
}
|
||||
return [...entries.values()];
|
||||
},
|
||||
async read(path) {
|
||||
reads++;
|
||||
peak = Math.max(peak, ++active);
|
||||
try {
|
||||
await delay(readDelay);
|
||||
const value = files.get(path);
|
||||
if (value === undefined) throw new Error("Missing note");
|
||||
return value;
|
||||
} finally {
|
||||
active--;
|
||||
}
|
||||
},
|
||||
async readOptional(path) {
|
||||
return files.get(path) ?? null;
|
||||
},
|
||||
async write(path, source, expected) {
|
||||
assert.equal(files.get(path), expected);
|
||||
files.set(path, source);
|
||||
},
|
||||
async create(path, source) {
|
||||
assert.equal(files.has(path), false);
|
||||
files.set(path, source);
|
||||
},
|
||||
};
|
||||
const store = new TaskStore(workspace, { id: boardId, path: "Board.md" });
|
||||
for (const [name, action] of [
|
||||
["load", () => store.reload()],
|
||||
["move", () => store.moveTask(store.tasks[0], "doing")],
|
||||
["edit", () => store.save(store.tasks[0], { body: "Updated details" })],
|
||||
] as const) {
|
||||
peak = reads = 0;
|
||||
const started = performance.now();
|
||||
await action();
|
||||
const elapsed = performance.now() - started;
|
||||
assert.equal(reads, 65);
|
||||
assert.equal(peak, scanConcurrency);
|
||||
assert.equal(active, 0);
|
||||
// The serial delay alone is 975 ms. Keep generous headroom for busy runners.
|
||||
assert.ok(elapsed < reads * readDelay * 0.75, `${name} took ${elapsed} ms`);
|
||||
t.diagnostic(
|
||||
`${name}: ${reads} reads, peak ${peak}, ${Math.round(elapsed)} ms (serial delay ${reads * readDelay} ms)`,
|
||||
);
|
||||
}
|
||||
assert.equal(store.tasks[0].body, "Updated details");
|
||||
assert.equal(store.tasks[0].status, "doing");
|
||||
const cached = store.tasks[1];
|
||||
await store.reload();
|
||||
assert.equal(
|
||||
store.tasks.find((task) => task.id === cached.id),
|
||||
cached,
|
||||
);
|
||||
|
||||
const stale = store.tasks[0];
|
||||
const external = editTask(stale, { body: "External details" });
|
||||
files.set(stale.path, external);
|
||||
await assert.rejects(store.save(stale, { body: "Stale details" }), /changed/);
|
||||
assert.equal(files.get(stale.path), external);
|
||||
const current = store.tasks.find((task) => task.id === stale.id)!;
|
||||
files.set("Notes0/Copied card.md", current.source);
|
||||
await assert.rejects(store.moveTask(current, "done"), /duplicate/);
|
||||
assert.equal(files.get(current.path), external);
|
||||
});
|
||||
|
||||
test("parallel scanning retains input order and drains pending work on failure", async () => {
|
||||
let active = 0;
|
||||
await assert.rejects(
|
||||
mapConcurrent([0, 1, 2, 3], async (value) => {
|
||||
active++;
|
||||
try {
|
||||
await delay(value === 0 ? 1 : 20);
|
||||
if (value === 0) throw new Error("Directory unavailable");
|
||||
return value;
|
||||
} finally {
|
||||
active--;
|
||||
}
|
||||
}),
|
||||
/Directory unavailable/,
|
||||
);
|
||||
assert.equal(active, 0);
|
||||
assert.deepEqual(
|
||||
await mapConcurrent([0, 1, 2, 3], async (value) => {
|
||||
await delay(4 - value);
|
||||
return value;
|
||||
}),
|
||||
[0, 1, 2, 3],
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,330 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
|
||||
import { newBoardSource, parseBoard, BoardStore } from "../../../../src/lib/features/pm/storage/board.ts";
|
||||
import {
|
||||
catalogPath,
|
||||
createBoard,
|
||||
readCatalog,
|
||||
boardKey,
|
||||
parseCatalog,
|
||||
} from "../../../../src/lib/features/pm/storage/catalog.ts";
|
||||
import { migrateStorage } from "../../../../src/lib/features/pm/storage/migration.ts";
|
||||
import { labelsPath, legacyLabelsPath } from "../../../../src/lib/features/pm/storage/labels.ts";
|
||||
import { newTask } from "../../../../src/lib/features/pm/storage/notes.ts";
|
||||
import type { Workspace } from "../../../../src/lib/features/pm/model/model.ts";
|
||||
|
||||
function fixture() {
|
||||
const source = newBoardSource() + "Keep the board description.\n";
|
||||
const id = parseBoard(source).id;
|
||||
const task = newTask(
|
||||
"Keep task",
|
||||
{
|
||||
status: "doing",
|
||||
tags: ["tag"],
|
||||
labels: ["bug"],
|
||||
archived: false,
|
||||
sessions: [],
|
||||
placements: { [id]: { listId: "doing", order: "a" } },
|
||||
},
|
||||
"Keep task body.",
|
||||
);
|
||||
const files = new Map([
|
||||
["Project/Launch.md", source],
|
||||
[task.path, task.source],
|
||||
[
|
||||
legacyLabelsPath,
|
||||
JSON.stringify({
|
||||
schema: 1,
|
||||
extra: "keep",
|
||||
labels: [{ id: "bug", name: "Defect", color: "red" }],
|
||||
}),
|
||||
],
|
||||
]);
|
||||
let fail = "";
|
||||
const workspace: Workspace = {
|
||||
async readOptional(path) {
|
||||
return files.get(path) ?? null;
|
||||
},
|
||||
async read(path) {
|
||||
if (!files.has(path)) throw new Error("Missing file");
|
||||
return files.get(path)!;
|
||||
},
|
||||
async list(parent = "") {
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
const prefix = parent ? parent + "/" : "";
|
||||
if (!path.startsWith(prefix) || path.startsWith(".")) continue;
|
||||
const parts = path.slice(prefix.length).split("/");
|
||||
entries.set(parts[0], {
|
||||
name: parts[0],
|
||||
rel_path: prefix + parts[0],
|
||||
kind: parts.length > 1 ? "folder" : "file",
|
||||
});
|
||||
}
|
||||
return [...entries.values()];
|
||||
},
|
||||
async create(path, source) {
|
||||
if (path === fail) throw new Error("Disk failure");
|
||||
if (files.has(path)) throw new Error("Exists");
|
||||
files.set(path, source);
|
||||
},
|
||||
async write(path, source, expected) {
|
||||
if (path === fail) throw new Error("Disk failure");
|
||||
if (files.get(path) !== expected) throw new Error("Conflict");
|
||||
files.set(path, source);
|
||||
},
|
||||
};
|
||||
return {
|
||||
files,
|
||||
workspace,
|
||||
id,
|
||||
task,
|
||||
source,
|
||||
setFailure(path: string) {
|
||||
fail = path;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("migration backs up exact originals, preserves cards and survives removal of visible metadata", async () => {
|
||||
const { files, workspace, id, task, source } = fixture();
|
||||
const originalLabels = files.get(legacyLabelsPath)!;
|
||||
const store = new TaskStore(workspace, { id, path: "Project/Launch.md" });
|
||||
const report = await store.migrateStorage();
|
||||
assert.equal(report.length, 2);
|
||||
for (const file of report)
|
||||
assert.equal(files.get(file.backup), files.get(file.path));
|
||||
assert.equal(files.get("Project/Launch.md"), source);
|
||||
assert.equal(files.get(task.path), task.source);
|
||||
assert.equal(store.board.reference?.path, boardKey(id));
|
||||
assert.equal(store.scopedTasks.length, 1);
|
||||
assert.equal(store.scopedTasks[0].placements?.[id].order, "a");
|
||||
assert.equal(store.labels.value[0].name, "Defect");
|
||||
await store.board.edit("doing", "Building", "doing");
|
||||
await store.reload();
|
||||
await store.saveLabels(
|
||||
[{ id: "bug", name: "Issue", color: "blue" }],
|
||||
store.labels.source,
|
||||
);
|
||||
await store.migrateStorage();
|
||||
assert.equal(store.board.value.lists[1].name, "Building");
|
||||
assert.equal(store.labels.value[0].name, "Issue");
|
||||
assert.equal(files.get(legacyLabelsPath), originalLabels);
|
||||
files.delete("Project/Launch.md");
|
||||
files.delete(legacyLabelsPath);
|
||||
const reopened = new TaskStore(workspace, { id, path: boardKey(id) });
|
||||
await reopened.reload();
|
||||
assert.equal(reopened.scopedTasks[0].id, store.tasks[0].id);
|
||||
assert.equal(reopened.labels.value[0].name, "Issue");
|
||||
assert.equal(reopened.board.value.lists[1].name, "Building");
|
||||
assert.equal(reopened.issues.length, 0);
|
||||
});
|
||||
|
||||
test("a label write failure can resume after boards commit without duplicating data", async () => {
|
||||
const { files, workspace, setFailure } = fixture();
|
||||
const store = new TaskStore(workspace);
|
||||
setFailure(labelsPath);
|
||||
await assert.rejects(store.migrateStorage(), /Disk failure/);
|
||||
assert.equal((await readCatalog(workspace)).value.boards.length, 1);
|
||||
assert.ok(files.has(legacyLabelsPath));
|
||||
setFailure("");
|
||||
await store.migrateStorage();
|
||||
assert.equal((await readCatalog(workspace)).value.boards.length, 1);
|
||||
assert.ok(files.has(labelsPath));
|
||||
});
|
||||
|
||||
test("backup failure prevents migration publication", async () => {
|
||||
const { files, workspace, setFailure } = fixture();
|
||||
setFailure(".runestone/pm/backups/Project/Launch.md");
|
||||
await assert.rejects(
|
||||
new TaskStore(workspace).migrateStorage(),
|
||||
/Disk failure/,
|
||||
);
|
||||
assert.equal(files.has(catalogPath), false);
|
||||
assert.equal(files.has(labelsPath), false);
|
||||
});
|
||||
|
||||
test("a legacy editor cannot write its original board after another view migrates it", async () => {
|
||||
const { files, workspace, id, source } = fixture();
|
||||
const stale = new BoardStore(workspace, { id, path: "Project/Launch.md" });
|
||||
await stale.reload();
|
||||
await new TaskStore(workspace).migrateStorage();
|
||||
await assert.rejects(stale.add("Old edit", null), /hidden storage/);
|
||||
assert.equal(files.get("Project/Launch.md"), source);
|
||||
await stale.reload();
|
||||
assert.equal(stale.reference?.path, boardKey(id));
|
||||
await stale.add("New edit", null);
|
||||
assert.equal(
|
||||
(await readCatalog(workspace)).value.boards[0].value.lists.at(-1)?.name,
|
||||
"New edit",
|
||||
);
|
||||
});
|
||||
|
||||
test("invalid or duplicate originals and conflicting labels block migration without writes", async () => {
|
||||
for (const kind of [
|
||||
"duplicate",
|
||||
"invalid-labels",
|
||||
"hidden-labels",
|
||||
"future",
|
||||
]) {
|
||||
const { files, workspace, source } = fixture();
|
||||
if (kind === "duplicate") files.set("Duplicate.md", source);
|
||||
if (kind === "invalid-labels") files.set(legacyLabelsPath, "broken");
|
||||
if (kind === "hidden-labels")
|
||||
files.set(labelsPath, files.get(legacyLabelsPath)!);
|
||||
if (kind === "future") files.set(catalogPath, '{"schema":99,"boards":[]}');
|
||||
const before = new Map(files);
|
||||
await assert.rejects(new TaskStore(workspace).migrateStorage());
|
||||
assert.deepEqual(files, before);
|
||||
}
|
||||
});
|
||||
|
||||
test("changed legacy files or damaged backups never receive a successful migration check", async () => {
|
||||
for (const path of [
|
||||
"Project/Launch.md",
|
||||
".runestone/pm/backups/Project/Launch.md",
|
||||
legacyLabelsPath,
|
||||
]) {
|
||||
const { files, workspace } = fixture();
|
||||
const store = new TaskStore(workspace);
|
||||
await store.migrateStorage();
|
||||
files.set(path, files.get(path)! + "\n");
|
||||
const before = new Map(files);
|
||||
await assert.rejects(store.migrateStorage());
|
||||
assert.deepEqual(files, before);
|
||||
}
|
||||
});
|
||||
|
||||
test("hidden boards rename, archive, restore, and reject stale writes without changing task notes", async () => {
|
||||
const { files, workspace, task } = fixture();
|
||||
const reference = await createBoard(workspace, "New board");
|
||||
const store = new TaskStore(workspace, reference);
|
||||
await store.reload();
|
||||
await store.renameBoard("Release");
|
||||
const stale = new BoardStore(workspace, reference);
|
||||
await stale.reload();
|
||||
await store.board.manage({ archived: true });
|
||||
await assert.rejects(stale.add("Review", null), /changed/);
|
||||
await store.reload();
|
||||
assert.equal(store.board.editable, false);
|
||||
await assert.rejects(
|
||||
store.create(
|
||||
"No card",
|
||||
{ status: "todo", tags: [], sessions: [], archived: false },
|
||||
"",
|
||||
),
|
||||
/Restore/,
|
||||
);
|
||||
await store.board.manage({ archived: false });
|
||||
await store.reload();
|
||||
assert.equal(store.board.name, "Release");
|
||||
assert.equal(store.board.editable, true);
|
||||
assert.equal(files.get(task.path), task.source);
|
||||
await assert.rejects(createBoard(workspace, "release"), /already exists/);
|
||||
});
|
||||
|
||||
test("hidden data is isolated by workspace and unknown catalog fields survive edits", async () => {
|
||||
const a = fixture(),
|
||||
b = fixture();
|
||||
const reference = await createBoard(a.workspace, "Private");
|
||||
const value = JSON.parse(a.files.get(catalogPath)!);
|
||||
value.futureMapping = { externalId: "remote-1" };
|
||||
a.files.set(catalogPath, JSON.stringify(value));
|
||||
const board = new BoardStore(a.workspace, reference);
|
||||
await board.reload();
|
||||
await board.add("Review", null);
|
||||
assert.deepEqual(
|
||||
JSON.parse(a.files.get(catalogPath)!).futureMapping,
|
||||
value.futureMapping,
|
||||
);
|
||||
assert.equal((await readCatalog(b.workspace)).value.boards.length, 0);
|
||||
});
|
||||
|
||||
test("deleting a board preserves cards, other boards, and unknown catalog fields", async () => {
|
||||
for (const archived of [false, true]) {
|
||||
const { files, workspace, task, id } = fixture();
|
||||
const reference = await createBoard(workspace, "Accidental board");
|
||||
const initial = JSON.parse(files.get(catalogPath)!);
|
||||
initial.futureMapping = { keep: "value" };
|
||||
initial.boards[0].archived = archived;
|
||||
files.set(catalogPath, JSON.stringify(initial));
|
||||
const store = new TaskStore(workspace, reference);
|
||||
await store.reload();
|
||||
await store.changeBoard(() => store.board.deleteBoard());
|
||||
assert.equal(store.board.available, false);
|
||||
assert.equal(store.board.editable, false);
|
||||
assert.equal(files.get(task.path), task.source);
|
||||
const all = new TaskStore(workspace);
|
||||
await all.reload();
|
||||
assert.deepEqual(all.boards.map((board) => board.id), [id]);
|
||||
assert.equal(all.tasks[0].placements?.[id].listId, "doing");
|
||||
const catalog = (await readCatalog(workspace)).value;
|
||||
assert.deepEqual(catalog.boards, []);
|
||||
assert.deepEqual(catalog.deletedBoardIds, [reference.id]);
|
||||
assert.deepEqual(catalog.futureMapping, initial.futureMapping);
|
||||
await assert.rejects(store.board.deleteBoard(), /available/);
|
||||
}
|
||||
});
|
||||
|
||||
test("deleted legacy and migrated boards stay deleted after reload and migration", async () => {
|
||||
for (const migrated of [false, true]) {
|
||||
const { files, workspace, id, source, task } = fixture();
|
||||
const store = new TaskStore(workspace, { id, path: "Project/Launch.md" });
|
||||
await store.reload();
|
||||
const original = store.boards[0];
|
||||
const stale = new BoardStore(workspace, { id, path: "Project/Launch.md" });
|
||||
await stale.reload();
|
||||
if (migrated) await store.migrateStorage();
|
||||
await store.changeBoard(() => store.board.deleteBoard());
|
||||
assert.equal(files.get("Project/Launch.md"), source);
|
||||
assert.equal(files.get(task.path), task.source);
|
||||
if (migrated) assert.equal(files.get(".runestone/pm/backups/Project/Launch.md"), source);
|
||||
await assert.rejects(stale.add("Stale list", null), /deleted/);
|
||||
await assert.rejects(stale.reload(), /deleted/);
|
||||
assert.equal(stale.available, false);
|
||||
await assert.rejects(migrateStorage(workspace, [original]), /deleted/);
|
||||
const all = new TaskStore(workspace);
|
||||
await all.reload();
|
||||
assert.equal(all.boards.length, 0);
|
||||
assert.equal(all.legacyBoards.length, 0);
|
||||
assert.equal(all.tasks.length, 1);
|
||||
await all.migrateStorage();
|
||||
await all.reload();
|
||||
assert.equal(all.boards.length, 0);
|
||||
assert.equal(all.issues.length, 0);
|
||||
}
|
||||
});
|
||||
|
||||
test("changed boards and failed catalog writes block deletion", async () => {
|
||||
for (const managed of [false, true]) {
|
||||
const { files, workspace, id, setFailure } = fixture();
|
||||
const reference = managed ? await createBoard(workspace, "New") : { id, path: "Project/Launch.md" };
|
||||
const board = new BoardStore(workspace, reference);
|
||||
await board.reload();
|
||||
const path = managed ? catalogPath : reference.path;
|
||||
files.set(path, files.get(path)! + "\n");
|
||||
const before = new Map(files);
|
||||
await assert.rejects(board.deleteBoard(), /changed/);
|
||||
assert.deepEqual(files, before);
|
||||
await board.reload();
|
||||
setFailure(catalogPath);
|
||||
await assert.rejects(board.deleteBoard(), /Disk failure/);
|
||||
assert.equal(board.available, true);
|
||||
assert.equal((await readCatalog(workspace)).value.deletedBoardIds, undefined);
|
||||
}
|
||||
});
|
||||
|
||||
test("a legacy board cannot be deleted from a stale view after migration", async () => {
|
||||
const { workspace, id } = fixture();
|
||||
const stale = new BoardStore(workspace, { id, path: "Project/Launch.md" });
|
||||
await stale.reload();
|
||||
await new TaskStore(workspace).migrateStorage();
|
||||
await assert.rejects(stale.deleteBoard(), /hidden storage/);
|
||||
assert.equal((await readCatalog(workspace)).value.boards.length, 1);
|
||||
});
|
||||
|
||||
test("invalid deletion records fail closed", () => {
|
||||
for (const deletedBoardIds of ["id", [null], [""], ["id", "id"]])
|
||||
assert.throws(() => parseCatalog(JSON.stringify({ schema: 1, boards: [], deletedBoardIds })), /deleted board/);
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
|
||||
import { newTask, readTask } from "../../../../src/lib/features/pm/storage/notes.ts";
|
||||
import type { Workspace } from "../../../../src/lib/features/pm/model/model.ts";
|
||||
|
||||
test("subtask promotion retains checklist data and retries without duplicate cards", async () => {
|
||||
const parent = newTask("Parent", { status: "todo", tags: [], sessions: [], archived: false,
|
||||
subtasks: [{ id: "child", title: "Child", done: true }], priority: "high" }, "Keep the description");
|
||||
const files = new Map([["Parent.md", parent.source]]);
|
||||
const parentId = readTask("Parent.md", parent.source)!.id;
|
||||
let fail = true;
|
||||
const workspace: Workspace = {
|
||||
async list(folder = "") { return [...files.keys()].filter(path => folder ? path.startsWith(`${folder}/`) : !path.startsWith(".")).map(path => ({ name: path.split("/").at(-1)!, rel_path: path, kind: "file" })); },
|
||||
async read(path) { if (!files.has(path)) throw Error("Missing"); return files.get(path)!; },
|
||||
async readOptional(path) { return files.get(path) ?? null; },
|
||||
async create(path, source) { if (files.has(path)) throw Error("Exists"); files.set(path, source); },
|
||||
async write(path, source, expected) { if (fail) throw Error("Write failed"); assert.equal(files.get(path), expected); files.set(path, source); },
|
||||
};
|
||||
const store = new TaskStore(workspace);
|
||||
await store.reload();
|
||||
await assert.rejects(store.openSubtask(parentId, "child"), /Write failed/);
|
||||
fail = false;
|
||||
const child = await store.openSubtask(parentId, "child");
|
||||
assert.equal(child.title, "Child"); assert.equal(child.status, "done"); assert.equal(child.priority, undefined);
|
||||
assert.equal(store.tasks.length, 2);
|
||||
const saved = readTask("Parent.md", files.get("Parent.md")!)!;
|
||||
assert.equal(saved.subtasks![0].taskId, child.id);
|
||||
assert.equal(saved.body, "Keep the description"); assert.equal(saved.priority, "high");
|
||||
assert.equal((await store.openSubtask(parentId, "child")).id, child.id);
|
||||
assert.equal(store.tasks.length, 2);
|
||||
});
|
||||
@@ -0,0 +1,149 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { watchBackground, type BackgroundFrame, type PMBackgroundApi } from "../../../../src/lib/features/pm/model/transient-background.ts";
|
||||
|
||||
const frame = (url: string): BackgroundFrame => ({ url, overlay: 0, position: "center", size: "cover" });
|
||||
function fixture() {
|
||||
const frames = new Map<string, BackgroundFrame>();
|
||||
const listeners = new Set<(target: string) => void>();
|
||||
// The shape of `backgroundHub` in `src/lib/plugins/backgrounds.ts`.
|
||||
const api: PMBackgroundApi = {
|
||||
get: target => frames.get(target) ?? null,
|
||||
subscribe(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; },
|
||||
};
|
||||
const set = (target: string, value: BackgroundFrame | null) => {
|
||||
if (value) frames.set(target, value); else frames.delete(target);
|
||||
for (const listener of listeners) listener(target);
|
||||
};
|
||||
return { api, set, listeners };
|
||||
}
|
||||
|
||||
test("slides override saved images and removal restores them without writes", async () => {
|
||||
const { api, set, listeners } = fixture();
|
||||
const seen: (BackgroundFrame | null)[] = [];
|
||||
let savedReads = 0;
|
||||
const watcher = watchBackground("pm-board:one", api, async () => { savedReads++; return frame("saved"); }, value => seen.push(value));
|
||||
await watcher.refresh();
|
||||
set("pm-board:one", frame("slide"));
|
||||
assert.equal(seen.at(-1)?.url, "slide");
|
||||
assert.equal(savedReads, 1);
|
||||
set("pm-board:one", null);
|
||||
await Promise.resolve();
|
||||
assert.equal(seen.at(-1)?.url, "saved");
|
||||
watcher.dispose();
|
||||
watcher.dispose();
|
||||
assert.equal(listeners.size, 0);
|
||||
});
|
||||
|
||||
test("pending saved reads cannot replace a new slide or change a closed mount", async () => {
|
||||
const { api, set } = fixture();
|
||||
let resolve!: (value: BackgroundFrame) => void;
|
||||
const pending = new Promise<BackgroundFrame>(done => { resolve = done; });
|
||||
const seen: (BackgroundFrame | null)[] = [];
|
||||
const watcher = watchBackground("pm-all", api, () => pending, value => seen.push(value));
|
||||
const refresh = watcher.refresh();
|
||||
set("pm-all", frame("slide"));
|
||||
resolve(frame("stale"));
|
||||
await refresh;
|
||||
assert.deepEqual(seen.map(value => value?.url), ["slide"]);
|
||||
set("pm-all", null);
|
||||
watcher.dispose();
|
||||
await Promise.resolve();
|
||||
await watcher.refresh();
|
||||
assert.equal(seen.length, 1);
|
||||
});
|
||||
|
||||
test("late failures cannot clear a slide", async () => {
|
||||
const { api, set } = fixture();
|
||||
let reject!: (error: Error) => void;
|
||||
const pending = new Promise<BackgroundFrame>( (_resolve, fail) => { reject = fail; });
|
||||
const seen: (BackgroundFrame | null)[] = [];
|
||||
const watcher = watchBackground("pm-all", api, () => pending, value => seen.push(value));
|
||||
const refresh = watcher.refresh();
|
||||
set("pm-all", frame("slide"));
|
||||
reject(new Error("Missing image"));
|
||||
await refresh;
|
||||
assert.deepEqual(seen.map(value => value?.url), ["slide"]);
|
||||
watcher.dispose();
|
||||
});
|
||||
|
||||
test("split mounts subscribe separately and filter board and all-task targets", async () => {
|
||||
const { api, set, listeners } = fixture();
|
||||
const seen = [[], [], []] as (BackgroundFrame | null)[][];
|
||||
const mounts = ["pm-board:one", "pm-board:two", "pm-all"].map((target, index) =>
|
||||
watchBackground(target, api, async () => null, value => seen[index].push(value)));
|
||||
set("pm-board:one", frame("one"));
|
||||
assert.deepEqual(seen.map(values => values.length), [1, 0, 0]);
|
||||
mounts[0].dispose();
|
||||
set("pm-board:two", frame("two"));
|
||||
set("pm-all", frame("all"));
|
||||
assert.deepEqual(seen.map(values => values.at(-1)?.url), ["one", "two", "all"]);
|
||||
mounts[1].dispose(); mounts[2].dispose();
|
||||
assert.equal(listeners.size, 0);
|
||||
});
|
||||
|
||||
test("all-board slides override saved boards and specific slides retain priority", async () => {
|
||||
const { api, set } = fixture();
|
||||
const seen: (BackgroundFrame | null)[] = [];
|
||||
const watcher = watchBackground("pm-board:one", api, async () => frame("saved"), value => seen.push(value));
|
||||
await watcher.refresh();
|
||||
set("pm-all", frame("all"));
|
||||
assert.equal(seen.at(-1)?.url, "all");
|
||||
set("pm-board:one", frame("specific"));
|
||||
set("pm-all", frame("next-all"));
|
||||
assert.equal(seen.at(-1)?.url, "specific");
|
||||
set("pm-board:one", null);
|
||||
assert.equal(seen.at(-1)?.url, "next-all");
|
||||
set("pm-all", null);
|
||||
await Promise.resolve();
|
||||
assert.equal(seen.at(-1)?.url, "saved");
|
||||
watcher.dispose();
|
||||
});
|
||||
|
||||
test("older hosts use saved images and failures clear the background", async () => {
|
||||
const seen: (BackgroundFrame | null)[] = [];
|
||||
let fails = false;
|
||||
const watcher = watchBackground("pm-all", undefined, async () => {
|
||||
if (fails) throw new Error("Missing image");
|
||||
return frame("saved");
|
||||
}, value => seen.push(value));
|
||||
await watcher.refresh(); fails = true; await watcher.refresh();
|
||||
assert.deepEqual(seen.map(value => value?.url ?? null), ["saved", null]);
|
||||
watcher.dispose();
|
||||
});
|
||||
|
||||
test("shared app slides use one host layer and react to either target changing", async () => {
|
||||
const { api, set } = fixture();
|
||||
const seen: (BackgroundFrame | null)[] = [];
|
||||
const watcher = watchBackground("pm-board:one", api, async () => frame("saved"), value => seen.push(value));
|
||||
set("pm-all", frame("shared"));
|
||||
assert.equal(seen.at(-1)?.url, "shared");
|
||||
set("app", frame("shared"));
|
||||
assert.equal(seen.at(-1), null);
|
||||
set("app", frame("next"));
|
||||
assert.equal(seen.at(-1)?.url, "shared");
|
||||
set("pm-all", frame("next"));
|
||||
assert.equal(seen.at(-1), null);
|
||||
set("pm-board:one", frame("specific"));
|
||||
assert.equal(seen.at(-1)?.url, "specific");
|
||||
set("pm-board:one", null);
|
||||
assert.equal(seen.at(-1), null);
|
||||
set("app", null);
|
||||
assert.equal(seen.at(-1)?.url, "next");
|
||||
watcher.dispose();
|
||||
});
|
||||
|
||||
test("different image appearance and transitions keep an independent PM layer", () => {
|
||||
const { api, set } = fixture();
|
||||
const seen: (BackgroundFrame | null)[] = [];
|
||||
const watcher = watchBackground("pm-all", api, async () => null, value => seen.push(value));
|
||||
set("app", frame("same"));
|
||||
for (const difference of [{ blurredUrl: "blob:blur" }, { overlay: 0.4 }, { size: "contain" as const }, { position: "top left" as const },
|
||||
{ previous: frame("old"), transitionMs: 500 }]) {
|
||||
set("pm-all", { ...frame("same"), ...difference });
|
||||
assert.equal(seen.at(-1)?.url, "same");
|
||||
}
|
||||
set("app", { ...frame("same"), previous: frame("old"), transitionMs: 500 });
|
||||
assert.equal(seen.at(-1), null);
|
||||
watcher.dispose();
|
||||
});
|
||||
@@ -0,0 +1,275 @@
|
||||
// The Terminal feature: the catalog entry, the shell commands and tasks, the shortcuts, the session lifecycle,
|
||||
// the theme map, the settings section, and the first-start migration of the plugin settings.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { featureEntry, featureOfOwner } from "../../../src/lib/features/catalog.ts";
|
||||
import { migrateFeatures } from "../../../src/lib/features/migration.ts";
|
||||
import { TERMINAL_KEYS, TERMINAL_SHORTCUTS, terminalShortcut, type TerminalAction } from "../../../src/lib/features/terminalKeys.ts";
|
||||
import { DEFAULT_TERMINAL, migrateTerminal, normalizeTerminal, type TerminalMigrationHost, type TerminalSettings } from "../../../src/lib/features/terminalSettings.ts";
|
||||
import { directoryCommand, fileCommand, parseTasks, pickProfile, quoteShell, remember, type ShellProfile } from "../../../src/lib/features/terminal/model.ts";
|
||||
import { TerminalSessions, type PtyRequest, type PtyTransport } from "../../../src/lib/features/terminal/sessions.ts";
|
||||
import { SELECTION_ALPHA, TERMINAL_TOKENS, terminalColors } from "../../../src/lib/features/terminal/theme.ts";
|
||||
import { ANSI_COLORS } from "../../../src/lib/theme/roles.ts";
|
||||
import { SETTINGS_SECTIONS, LEGACY_KEYS } from "../../../src/lib/settings/store.ts";
|
||||
import type { ProjectManagementMigrationHost } from "../../../src/lib/features/pmSettings.ts";
|
||||
|
||||
/** A Project Management host with a section already present. */
|
||||
function presentProjectManagement(): ProjectManagementMigrationHost {
|
||||
return { missing: () => false, write: async () => { throw new Error("not asked"); }, storage: { getItem: () => null, setItem: () => {} } };
|
||||
}
|
||||
|
||||
test("Terminal keeps the ID of the Terminal plugin and follows its package", () => {
|
||||
const terminal = featureEntry("terminal");
|
||||
assert.equal(terminal.owner, "runestone.terminal");
|
||||
assert.equal(featureOfOwner("runestone.terminal")?.id, "terminal");
|
||||
assert.equal(terminal.defaultOn, true);
|
||||
assert.equal(terminal.followsPackage, true);
|
||||
assert.deepEqual(terminal.views, []);
|
||||
assert.deepEqual(terminal.commands, []);
|
||||
});
|
||||
|
||||
test("paths are shell-quoted without evaluating metacharacters", () => {
|
||||
assert.equal(directoryCommand("C:\\a'b\\$notes", "powershell"), "Set-Location -LiteralPath 'C:\\a''b\\$notes'");
|
||||
assert.equal(quoteShell("/tmp/it's $(bad)", "bash"), "'/tmp/it'\\''s $(bad)'");
|
||||
assert.equal(directoryCommand("C:\\two words", "cmd"), 'cd /d "C:\\two words"');
|
||||
assert.equal(directoryCommand("C:\\two words", "node"), 'process.chdir("C:\\\\two words")');
|
||||
assert.equal(directoryCommand("C:\\two words", "bash"), "cd -- 'C:/two words'");
|
||||
assert.throws(() => quoteShell("C:\\%PATH%", "cmd"), /PowerShell/);
|
||||
assert.throws(() => fileCommand("a\nwhoami.py", "powershell"), /line breaks/);
|
||||
});
|
||||
|
||||
test("run file selects a runner and refuses documents that do not run", () => {
|
||||
assert.equal(fileCommand("D:\\project\\hello world.py", "powershell"), "python 'D:\\project\\hello world.py'");
|
||||
assert.equal(fileCommand("/project/app.mjs", "bash"), "node '/project/app.mjs'");
|
||||
assert.equal(fileCommand("D:\\tools\\app.exe", "powershell"), "& 'D:\\tools\\app.exe'");
|
||||
assert.equal(fileCommand("D:\\tools\\build.cmd", "cmd"), 'cmd /c "D:\\tools\\build.cmd"');
|
||||
assert.throws(() => fileCommand("notes.md", "powershell"), /cannot run this file type/);
|
||||
assert.throws(() => fileCommand("app.js", "node"), /Node\.js REPL/);
|
||||
});
|
||||
|
||||
test("the tasks file must be valid before the panel offers a task", () => {
|
||||
assert.deepEqual(parseTasks('{"tasks":[{"label":"Test","command":"npm test","profile":"pwsh"}]}'), [{ label: "Test", command: "npm test", profile: "pwsh" }]);
|
||||
for (const text of ["{}", "null", '{"tasks":[null]}', '{"tasks":[{"label":"x","command":" "}]}', '{"tasks":[{"label":"x","command":"echo hi","profile":4}]}']) assert.throws(() => parseTasks(text), text);
|
||||
});
|
||||
|
||||
test("history puts the newest value first, has no duplicates, and keeps 100 values", () => {
|
||||
assert.deepEqual(remember(["one", "two"], "two"), ["two", "one"]);
|
||||
assert.equal(remember(Array.from({ length: 100 }, (_, i) => String(i)), "new").length, 100);
|
||||
assert.deepEqual(remember(["one"], " "), ["one"]);
|
||||
});
|
||||
|
||||
test("a new terminal takes the default profile, then the first shell that is not Node.js", () => {
|
||||
const profiles: ShellProfile[] = [{ id: "node", title: "JavaScript Debug Terminal", kind: "node" }, { id: "powershell", title: "PowerShell", kind: "powershell" }, { id: "cmd", title: "Command Prompt", kind: "cmd" }];
|
||||
assert.equal(pickProfile(profiles, "cmd")?.id, "cmd");
|
||||
assert.equal(pickProfile(profiles, "")?.id, "powershell");
|
||||
assert.equal(pickProfile(profiles, "missing")?.id, "powershell");
|
||||
assert.equal(pickProfile([profiles[0]], "")?.id, "node");
|
||||
assert.equal(pickProfile([], ""), undefined);
|
||||
});
|
||||
|
||||
/** A key event for a written combination such as "Mod+Shift+`". Mod is Ctrl. */
|
||||
function press(combination: string) {
|
||||
const parts = combination.split("+");
|
||||
const key = parts.pop()!;
|
||||
const has = (name: string) => parts.includes(name);
|
||||
const code = key === "`" ? "Backquote" : /^\d$/.test(key) ? `Digit${key}` : key.length === 1 ? `Key${key.toUpperCase()}` : key;
|
||||
return { ctrlKey: has("Mod") || has("Ctrl"), metaKey: false, altKey: has("Alt"), shiftKey: has("Shift"), code, key: key.length === 1 ? key.toLowerCase() : key };
|
||||
}
|
||||
|
||||
test("physical key shortcuts tell new, split, window, and hide apart", () => {
|
||||
const key = { ctrlKey: true, metaKey: false, altKey: false, shiftKey: true, code: "Backquote", key: "~" };
|
||||
assert.equal(terminalShortcut(key), "new");
|
||||
assert.equal(terminalShortcut({ ...key, altKey: true }), "window");
|
||||
assert.equal(terminalShortcut({ ...key, code: "Digit5", key: "%" }), "split");
|
||||
assert.equal(terminalShortcut({ ...key, shiftKey: false, code: "KeyJ", key: "j" }), "toggle");
|
||||
assert.equal(terminalShortcut({ ...key, shiftKey: false, code: "KeyC", key: "c" }), null);
|
||||
assert.equal(terminalShortcut({ ...key, ctrlKey: false, metaKey: true, shiftKey: false }), "toggle", "Cmd works as Ctrl on macOS.");
|
||||
assert.equal(terminalShortcut({ ...key, ctrlKey: false }), null);
|
||||
// Each combination that menus and Help show gives its own action.
|
||||
for (const [action, combination] of Object.entries(TERMINAL_KEYS)) assert.equal(terminalShortcut(press(combination)), action as TerminalAction, combination);
|
||||
assert.ok(TERMINAL_SHORTCUTS.every(row => row.label && row.keys && !/Ctrl/.test(row.keys)), "Help rows use Mod, so macOS shows Cmd.");
|
||||
});
|
||||
|
||||
/** A fake host. `hold()` makes the next open wait for `release()`. */
|
||||
function fakeTransport() {
|
||||
const calls: string[] = [];
|
||||
const outputs = new Map<string, { data: (bytes: Uint8Array) => void; exit: (code: number | null) => void }>();
|
||||
let holding: Promise<void> = Promise.resolve();
|
||||
let release: () => void = () => {};
|
||||
let failClose = false;
|
||||
const transport: PtyTransport = {
|
||||
open: async (request: PtyRequest, data, exit) => {
|
||||
calls.push(`open:${request.id}:${request.profile ?? ""}:${request.directory ?? ""}`);
|
||||
outputs.set(request.id, { data, exit });
|
||||
await holding;
|
||||
},
|
||||
write: async (id, data) => { calls.push(`write:${id}:${data}`); },
|
||||
resize: async (id, cols, rows) => { calls.push(`resize:${id}:${cols}x${rows}`); },
|
||||
close: async id => { calls.push(`close:${id}`); if (failClose) throw new Error("close failed"); },
|
||||
profiles: async () => [{ id: "pwsh", title: "PowerShell 7", kind: "powershell" }],
|
||||
openWindow: async () => { calls.push("window"); },
|
||||
dictation: async () => { calls.push("dictation"); },
|
||||
};
|
||||
return {
|
||||
transport, calls, outputs,
|
||||
hold() { holding = new Promise(resolve => { release = resolve; }); },
|
||||
release: () => release(),
|
||||
failClose(value: boolean) { failClose = value; },
|
||||
};
|
||||
}
|
||||
const text = (bytes: Uint8Array) => new TextDecoder().decode(bytes);
|
||||
const options = (output: string[] = [], exits: (number | null)[] = []) => ({ cwd: "C:\\work", cols: 80, rows: 24, onData: (data: Uint8Array) => output.push(text(data)), onExit: (code: number | null) => exits.push(code) });
|
||||
|
||||
test("sessions deliver their own output, write, resize, and close once", async () => {
|
||||
const host = fakeTransport();
|
||||
const sessions = new TerminalSessions(host.transport);
|
||||
assert.deepEqual(await sessions.profiles(), [{ id: "pwsh", title: "PowerShell 7", kind: "powershell" }]);
|
||||
const output: string[] = [];
|
||||
await sessions.open("a", { ...options(output), profile: "pwsh", directory: "C:\\work\\src" });
|
||||
await sessions.open("b", options());
|
||||
assert.deepEqual(host.calls.slice(0, 2), ["open:a:pwsh:C:\\work\\src", "open:b::"]);
|
||||
host.outputs.get("a")!.data(new TextEncoder().encode("ready"));
|
||||
await sessions.write("a", "dir\r");
|
||||
await sessions.resize("a", 100, 30);
|
||||
assert.deepEqual(output, ["ready"]);
|
||||
assert.deepEqual(host.calls.slice(-2), ["write:a:dir\r", "resize:a:100x30"]);
|
||||
await assert.rejects(sessions.open("a", options()), /already running/);
|
||||
await Promise.all([sessions.close("a"), sessions.close("a")]);
|
||||
assert.equal(host.calls.filter(call => call === "close:a").length, 1);
|
||||
await assert.rejects(sessions.write("a", "x"), /not running/);
|
||||
host.outputs.get("a")!.data(new TextEncoder().encode("late"));
|
||||
assert.deepEqual(output, ["ready"], "A closed pane gets no more output.");
|
||||
await assert.rejects(sessions.open("a", options()), /closed/);
|
||||
await assert.rejects(sessions.write("missing", "x"), /not running/);
|
||||
await sessions.openWindow();
|
||||
await sessions.dictation();
|
||||
assert.deepEqual(host.calls.slice(-2), ["window", "dictation"]);
|
||||
});
|
||||
|
||||
test("a close waits for the start of its shell, and a closed pane cannot start", async () => {
|
||||
const host = fakeTransport();
|
||||
const sessions = new TerminalSessions(host.transport);
|
||||
host.hold();
|
||||
const start = sessions.open("starting", options());
|
||||
const close = sessions.close("starting");
|
||||
assert.equal(sessions.close("starting"), close, "A second close returns the same promise.");
|
||||
await Promise.resolve();
|
||||
assert.deepEqual(host.calls, ["open:starting::"]);
|
||||
host.release();
|
||||
await Promise.all([start, close]);
|
||||
assert.deepEqual(host.calls, ["open:starting::", "close:starting"]);
|
||||
await sessions.close("not-started");
|
||||
await assert.rejects(sessions.open("not-started", options()), /closed/);
|
||||
assert.equal(host.calls.length, 2);
|
||||
});
|
||||
|
||||
test("an exited shell needs no close, and a failed close can be tried again", async () => {
|
||||
const host = fakeTransport();
|
||||
const sessions = new TerminalSessions(host.transport);
|
||||
const exits: (number | null)[] = [];
|
||||
await sessions.open("exits", options([], exits));
|
||||
host.outputs.get("exits")!.exit(3);
|
||||
host.outputs.get("exits")!.exit(4);
|
||||
assert.deepEqual(exits, [3], "The exit reaches the pane one time.");
|
||||
await assert.rejects(sessions.write("exits", "x"), /not running/);
|
||||
await sessions.close("exits");
|
||||
assert.equal(host.calls.includes("close:exits"), false);
|
||||
await sessions.open("writer", options());
|
||||
host.failClose(true);
|
||||
await assert.rejects(sessions.close("writer"), /close failed/);
|
||||
host.failClose(false);
|
||||
await sessions.close("writer");
|
||||
assert.equal(host.calls.filter(call => call === "close:writer").length, 2);
|
||||
});
|
||||
|
||||
test("closeAll stops every shell, also one that is starting, and later calls fail", async () => {
|
||||
const host = fakeTransport();
|
||||
const sessions = new TerminalSessions(host.transport);
|
||||
await sessions.open("one", options());
|
||||
host.hold();
|
||||
const late = sessions.open("late", options());
|
||||
const stopping = sessions.closeAll();
|
||||
assert.equal(sessions.signal.aborted, true);
|
||||
host.release();
|
||||
await late;
|
||||
await stopping;
|
||||
assert.deepEqual(host.calls.filter(call => call.startsWith("close:")).sort(), ["close:late", "close:one"]);
|
||||
await assert.rejects(sessions.open("again", options()), /This feature is off/);
|
||||
await assert.rejects(sessions.profiles(), /This feature is off/);
|
||||
await assert.rejects(sessions.openWindow(), /This feature is off/);
|
||||
});
|
||||
|
||||
test("the terminal colors come from the theme tokens, with the 16 ANSI colors from --rs-ansi-*", () => {
|
||||
const asked: [string, number][] = [];
|
||||
const theme = terminalColors((css, maxAlpha) => { asked.push([css, maxAlpha]); return css; });
|
||||
assert.equal(theme.background, "#00000000", "The panel surface shows through the terminal.");
|
||||
assert.equal(theme.foreground, "var(--rs-text)");
|
||||
assert.equal(theme.cursor, "var(--rs-accent)");
|
||||
assert.equal(theme.cursorAccent, "var(--rs-bg)");
|
||||
assert.equal(theme.selectionBackground, "var(--rs-selection)");
|
||||
assert.deepEqual(asked.find(([css]) => css === "var(--rs-selection)"), ["var(--rs-selection)", SELECTION_ALPHA]);
|
||||
assert.equal(SELECTION_ALPHA, 165);
|
||||
for (const color of ANSI_COLORS) {
|
||||
const bright = `bright${color[0].toUpperCase()}${color.slice(1)}` as keyof typeof theme;
|
||||
assert.equal(theme[color], `var(--rs-ansi-${color})`);
|
||||
assert.equal(theme[bright], `var(--rs-ansi-bright-${color})`);
|
||||
}
|
||||
assert.equal(TERMINAL_TOKENS.filter(item => item.token.startsWith("var(--rs-ansi-")).length, 16);
|
||||
assert.ok(asked.filter(([css]) => css !== "var(--rs-selection)").every(([, alpha]) => alpha === 255), "Only the selection has an alpha cap.");
|
||||
});
|
||||
|
||||
test("the terminal settings section has valid values and its own old key", () => {
|
||||
assert.ok((SETTINGS_SECTIONS as readonly string[]).includes("terminal"));
|
||||
assert.equal(LEGACY_KEYS.terminal, "runestone.terminal");
|
||||
assert.deepEqual(normalizeTerminal(undefined), DEFAULT_TERMINAL);
|
||||
assert.deepEqual(normalizeTerminal(["x"]), DEFAULT_TERMINAL);
|
||||
assert.deepEqual(normalizeTerminal({ defaultProfile: "cmd", fontSize: 40, scrollback: 5, cursorBlink: false, future: 1 }),
|
||||
{ defaultProfile: "cmd", fontSize: 28, scrollback: 100, cursorBlink: false });
|
||||
assert.deepEqual(normalizeTerminal({ defaultProfile: 3, fontSize: 2, scrollback: 250000, cursorBlink: "no" }),
|
||||
{ defaultProfile: "", fontSize: 9, scrollback: 100000, cursorBlink: true });
|
||||
assert.equal(normalizeTerminal({ fontSize: 14.6 }).fontSize, 15);
|
||||
assert.equal(normalizeTerminal({ fontSize: Number.NaN }).fontSize, 13);
|
||||
});
|
||||
|
||||
function terminalHost(missing: boolean, legacy: string | null | (() => never)): TerminalMigrationHost & { written: TerminalSettings[] } {
|
||||
const written: TerminalSettings[] = [];
|
||||
return { written, missing: () => missing, legacy: () => typeof legacy === "function" ? legacy() : legacy, write: async value => { written.push(value); } };
|
||||
}
|
||||
|
||||
test("the first start copies the plugin settings into the terminal section once", async () => {
|
||||
const plugin = JSON.stringify({ defaultProfile: "git-bash", fontSize: 16, scrollback: 2000, cursorBlink: false });
|
||||
const copy = terminalHost(true, plugin);
|
||||
assert.deepEqual(await migrateTerminal(copy), { defaultProfile: "git-bash", fontSize: 16, scrollback: 2000, cursorBlink: false });
|
||||
assert.deepEqual(copy.written, [{ defaultProfile: "git-bash", fontSize: 16, scrollback: 2000, cursorBlink: false }]);
|
||||
const present = terminalHost(false, plugin);
|
||||
assert.equal(await migrateTerminal(present), null);
|
||||
assert.deepEqual(present.written, [], "An existing section stays.");
|
||||
const none = terminalHost(true, null);
|
||||
assert.equal(await migrateTerminal(none), null);
|
||||
assert.deepEqual(none.written, [], "Without the old key, the defaults apply and nothing is written.");
|
||||
const damaged = terminalHost(true, "{not json");
|
||||
assert.deepEqual(await migrateTerminal(damaged), DEFAULT_TERMINAL);
|
||||
const blocked = terminalHost(true, () => { throw new Error("storage is blocked"); });
|
||||
assert.equal(await migrateTerminal(blocked), null);
|
||||
});
|
||||
|
||||
test("the feature migration copies the terminal settings also when the package report fails", async () => {
|
||||
const error = console.error;
|
||||
console.error = () => {};
|
||||
try {
|
||||
const terminal = terminalHost(true, JSON.stringify({ fontSize: 20 }));
|
||||
const background = { missing: () => false, hasImage: () => false, migrateFolder: async () => false, write: async () => {} };
|
||||
const host = { read: () => undefined, write: async () => { throw new Error("not asked"); }, legacy: async () => { throw new Error("no host"); } };
|
||||
assert.deepEqual(await migrateFeatures(host, background, terminal, presentProjectManagement()), []);
|
||||
assert.deepEqual(terminal.written, [{ ...DEFAULT_TERMINAL, fontSize: 20 }]);
|
||||
} finally { console.error = error; }
|
||||
});
|
||||
|
||||
test("the terminal switch follows the enabled state of an installed Terminal plugin", async () => {
|
||||
const writes: unknown[] = [];
|
||||
const host = { read: () => ({ git: true, background: true, pdf: true, pm: true }), write: async (value: unknown) => { writes.push(value); },
|
||||
legacy: async (ids: string[]) => ids.map(id => ({ id, installed: true, enabled: false, settings: null })) };
|
||||
const background = { missing: () => false, hasImage: () => false, migrateFolder: async () => false, write: async () => {} };
|
||||
assert.deepEqual(await migrateFeatures(host, background, terminalHost(false, null), presentProjectManagement()), ["terminal"]);
|
||||
assert.deepEqual(writes, [{ git: true, background: true, pdf: true, pm: true, terminal: false }]);
|
||||
});
|
||||
Reference in New Issue
Block a user