Guard family-data failures and verify workspace recovery and focus boundaries

This commit is contained in:
Nick Beckley 2026-11-26 23:56:43 +00:00
parent 0189b5db1e
commit bf80f525bc
5 changed files with 173 additions and 12 deletions

View File

@ -50,6 +50,7 @@ const fs = require("fs"),
}
if (different) changed++;
}
assert(maxDifference <= 1, name + " screenshot intensity changed");
assert(changed <= 12, name + " screenshot changed: " + changed + " pixels");
results.push({
name,

View File

@ -216,6 +216,73 @@ const { chromium } = require("playwright"),
expected,
"project-specific membership, positions, pin, viewport and divider restored",
);
// Rejected family reads cannot release pins, change the preset or overwrite a saved view.
await c.route("**/RelationshipMap/Family?*", (r) =>
r.fulfill({
status: 403,
json: { message: "Synthetic denied family read" },
}),
);
await p.locator(".rw-display > summary").click();
await p.locator("#rwPreset").selectOption("family");
await p.keyboard.press("Escape");
await ready();
assert.deepEqual(await view(), expected);
assert.equal(await p.locator("#rwPreset").inputValue(), "custom");
const original = await p.evaluate(
(key) => localStorage.getItem(key),
expected.key,
),
unavailable = JSON.stringify({
...JSON.parse(original),
preset: "family",
layout: "family",
});
await p.evaluate(({ key, data }) => localStorage.setItem(key, data), {
key: expected.key,
data: unavailable,
});
await p.addInitScript(
({ key, data }) => {
if (sessionStorage.getItem("main-test-family-seed") !== "done") {
localStorage.setItem(key, data);
sessionStorage.setItem("main-test-family-seed", "done");
}
},
{ key: expected.key, data: unavailable },
);
await p.reload();
await ready();
await p.waitForTimeout(350);
assert.equal(
await p.evaluate((key) => localStorage.getItem(key), expected.key),
unavailable,
"failed restore retains exact saved preferences",
);
assert.equal(
await p.evaluate(
() =>
window.PlotDirectorRelationshipWorkspace.cy.nodes(":visible").length,
),
0,
"unavailable family data is not shown as a Story tree",
);
assert.match(
await p.locator("#rwStatus").innerText(),
/could not be loaded/,
);
await p.goto("http://127.0.0.1:5238/fixture?page=calendar-test");
assert.equal(
await p.evaluate((key) => localStorage.getItem(key), expected.key),
unavailable,
"pagehide cannot overwrite failed restore",
);
await p.evaluate(({ key, data }) => localStorage.setItem(key, data), {
key: expected.key,
data: original,
});
await open(7);
assert.deepEqual(await view(), expected);
await c.addCookies([
{ name: "fixture-user", value: "5", url: "http://127.0.0.1:5238" },
]);

View File

@ -14,7 +14,15 @@ fs.mkdirSync(out, { recursive: true });
(async () => {
let context, page, cdp;
const errors = [],
calls = { directory: 0, state: 0, family: 0, assign: 0, undo: 0, save: 0 },
calls = {
directory: 0,
state: 0,
family: 0,
assign: 0,
undo: 0,
save: 0,
focusWrites: 0,
},
values = new Map(),
previous = new Map();
let fail = 0;
@ -25,6 +33,15 @@ fs.mkdirSync(out, { recursive: true });
viewport: { width: 1920, height: 1080 },
});
page = context.pages()[0];
context.on("request", (r) => {
if (
r.method() === "POST" &&
/\/NarrativeFocus\/(?:Shared\/Publish|Set)$/.test(
new URL(r.url()).pathname,
)
)
calls.focusWrites++;
});
await context.route("https://cdn.jsdelivr.net/**", (r) =>
r.fulfill({
contentType: "application/javascript",
@ -249,9 +266,9 @@ fs.mkdirSync(out, { recursive: true });
await control.selectOption(value);
if (!installed)
await control.evaluate((n) => (n.closest("details").open = false));
await ready();
if (!(await page.locator("dialog[open]").count()))
await page.keyboard.press("Escape");
await ready();
}
async function shot(name) {
await page.screenshot({ path: `${out}/${mode}-${name}.png` });
@ -702,6 +719,54 @@ fs.mkdirSync(out, { recursive: true });
.getByRole("menuitem", { name: "Remove from diagram", exact: true })
.waitFor();
await page.keyboard.press("Escape");
// Scene Explorer is local; only its explicit promotion invokes the established focus setter.
const promotionTarget = await page.evaluate(() => {
const focus = window.PlotDirectorNarrativeFocus,
target = focus.state.positions.find((p) => p.sceneID);
if (!target) throw Error("Fixture requires a known focus scene");
window.mainPromotions = [];
focus.set = async (target) => {
mainPromotions.push(target);
return true;
};
return target;
});
before = await state();
await page
.getByLabel("Scene to visualise", { exact: true })
.selectOption(String(promotionTarget.sceneID));
await page.waitForTimeout(350);
await ready();
assert.equal(
await page.evaluate(() => mainPromotions.length),
0,
"local scene exploration never invokes global setter",
);
await unchanged(before, "Scene Explorer selection");
assert(
await page.evaluate(() => {
const w = window.PlotDirectorRelationshipWorkspace;
return w.mainCommands.records().every((r) => {
const e = w.cy.$id("r-" + r.characterRelationshipID);
return (
e.source().data("characterID") === r.characterAID &&
e.target().data("characterID") === r.characterBID &&
e.hasClass(r.cssClass) &&
e.data("label") === r.relationshipTypeName
);
});
}),
"historical refresh retains author-family endpoints, categories and labels",
);
await page
.getByRole("button", { name: "Set Current Focus Here", exact: true })
.click();
assert.equal(await page.evaluate(() => mainPromotions.length), 1);
assert.equal(
await page.evaluate(() => mainPromotions[0].sceneID),
promotionTarget.sceneID,
);
calls.explicitPromotion = 1;
// Seven themes and representative widths, no horizontal overflow.
for (const width of [1280, 1920, 2560, 3840, 800, 390, 1920]) {
await page.setViewportSize({ width, height: 1080 });
@ -729,6 +794,7 @@ fs.mkdirSync(out, { recursive: true });
? "dark"
: "light";
}, theme);
await ready();
await shot("theme-" + theme);
}
await page.waitForTimeout(400);
@ -740,6 +806,11 @@ fs.mkdirSync(out, { recursive: true });
await launch(true);
await open();
await unchanged(before, "persistent Chromium/PWA restart");
assert.equal(
calls.focusWrites,
0,
"diagram operations made no shared-focus write requests",
);
assert.deepEqual(errors, []);
fs.writeFileSync(
`${out}/${mode}-acceptance.json`,

View File

@ -48,12 +48,16 @@
for (const [id, label] of LAYOUTS)
layoutControl.add(new Option(label, id));
let initialised = false,
viewUnavailable = false,
pendingCommands = 0;
function command(task) {
pendingCommands++;
return Promise.resolve()
.then(task)
.catch((error) => toast.error(error.message))
.catch((error) => {
syncControls();
toast.error(error.message);
})
.finally(() => pendingCommands--);
}
function setPreset(next) {
@ -167,10 +171,18 @@
}));
}
function snapshot() {
const ps = {};
if (viewUnavailable) {
try {
const retained = localStorage.getItem(storageKey);
if (retained) return JSON.parse(retained);
} catch {}
if (saved) return copy(saved);
}
const ps = Object.fromEntries(positions);
cy.nodes().forEach((n) => {
const id = n.data("characterID");
if (known(id)) ps[id] = { ...n.position() };
if (known(id) && !viewUnavailable && !familyPromise)
ps[id] = { ...n.position() };
});
return {
members: [...members],
@ -194,6 +206,7 @@
function remember() {
clearTimeout(saveTimer);
saveTimer = setTimeout(() => {
if (viewUnavailable || familyPromise) return;
try {
localStorage.setItem(storageKey, JSON.stringify(snapshot()));
} catch {}
@ -523,15 +536,18 @@
referenceRecords = current;
}
async function applyFocus(centre = false) {
if (isFamily() && !family) {
if (isFamily() && !family && (preset !== "custom" || members.size)) {
status.textContent = "Loading author-reference family facts…";
try {
await loadFamily();
} catch (error) {
status.textContent = error.message;
return;
viewUnavailable = true;
if (!initialised) cy.elements().hide();
return false;
}
}
viewUnavailable = false;
updateMembership();
if (isFamily())
cy.nodes().style({ width: 180, height: 66, padding: 0 });
@ -656,7 +672,7 @@
remember();
}
function pin(id = a.getFocus()) {
if (!known(id) || !members.has(id)) return;
if (!known(id) || !members.has(id) || !node(id).visible()) return;
checkpoint();
pins.has(id) ? pins.delete(id) : pins.add(id);
positions.set(id, { ...node(id).position() });
@ -665,6 +681,7 @@
}
async function performPreset(next) {
if (!PRESETS.some(([id]) => id === next)) return;
if (next === "family") await loadFamily();
checkpoint();
layoutEpoch++;
if (preset === "custom") rememberCustom();
@ -818,14 +835,14 @@
}
if (!LAYOUTS.some(([id]) => id === kind)) return;
if (kind === "family") {
await loadFamily();
const choice = await pinChoice();
if (choice === "cancel") return;
if (options.checkpoint !== false) checkpoint();
if (choice === "release") pins.clear();
await loadFamily();
} else if (options.checkpoint !== false) checkpoint();
layout = kind;
await applyFocus(false);
if ((await applyFocus(false)) === false) return;
syncControls();
const epoch = ++layoutEpoch,
arrangementStarted = performance.now();
@ -2177,6 +2194,7 @@
wire(window.PlotDirectorPresenceConnection);
function flush() {
clearTimeout(saveTimer);
if (viewUnavailable || familyPromise) return;
try {
localStorage.setItem(storageKey, JSON.stringify(snapshot()));
} catch {}
@ -2192,7 +2210,10 @@
}
syncControls();
syncPalettes();
await applyFocus(false);
if ((await applyFocus(false)) === false) {
initialised = true;
return;
}
if (saved) {
if (Number.isFinite(saved.zoom)) cy.zoom(saved.zoom);
if (Number.isFinite(saved.pan?.x) && Number.isFinite(saved.pan?.y))
@ -2239,6 +2260,7 @@
refreshPaletteTitles,
restyle() {
refreshIndicators();
updateLabels();
scheduleRoutes();
},
get familyMode() {

View File

@ -350,7 +350,7 @@
}
const visible = cy.nodes(':visible');
if(!enhancement)visible.forEach((n,i) => { if (!restored?.positions?.[n.id()] && n.position().x === 0 && n.position().y === 0) n.position({ x: 200 + i % 6 * 190, y: 150 + Math.floor(i/6)*100 }); });
status.textContent = `${point.textContent}: ${model.relationships.length} relationships.`;
if(!enhancement)status.textContent = `${point.textContent}: ${model.relationships.length} relationships.`;
if(enhancement)enhancement.refreshDetail();else if (focus) renderCharacterDetail();
else clearDetail();
} catch (error) { if (error.name !== 'AbortError') { stateLoaded = false; status.textContent = error.message; } }